@aceshooting/lyra-ui 30.9.0 → 31.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (283) hide show
  1. package/CHANGELOG.md +361 -335
  2. package/dist/ai/adapters/ag-ui.js +1 -1
  3. package/dist/autoloader-cdn.js +1 -1
  4. package/dist/components/agent-tools/activity-feed/activity-feed.class.js +1 -1
  5. package/dist/components/agent-tools/budget-meter/budget-meter.class.d.ts +12 -1
  6. package/dist/components/agent-tools/budget-meter/budget-meter.class.js +4 -4
  7. package/dist/components/agent-tools/compare-panel/compare-panel.class.js +1 -1
  8. package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +1 -1
  9. package/dist/components/agent-tools/thinking-panel/thinking-panel.class.js +1 -1
  10. package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.class.js +1 -1
  11. package/dist/components/charts/chart/box-plot.class.js +2 -2
  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 +2 -2
  17. package/dist/components/conversation/chat-composer/chat-composer.class.d.ts +26 -11
  18. package/dist/components/conversation/chat-composer/chat-composer.class.js +11 -9
  19. package/dist/components/conversation/chat-composer/chat-composer.styles.js +1 -1
  20. package/dist/components/conversation/chat-message/chat-message.class.d.ts +27 -3
  21. package/dist/components/conversation/chat-message/chat-message.class.js +14 -12
  22. package/dist/components/conversation/chat-message/chat-message.styles.js +1 -1
  23. package/dist/components/conversation/chat-viewport/chat-viewport.class.d.ts +29 -2
  24. package/dist/components/conversation/chat-viewport/chat-viewport.class.js +2 -2
  25. package/dist/components/conversation/chat-viewport/chat-viewport.styles.js +1 -1
  26. package/dist/components/conversation/code-block/code-block-shared.js +1 -1
  27. package/dist/components/conversation/markdown/markdown-base.class.d.ts +1 -1
  28. package/dist/components/conversation/markdown/markdown-base.class.js +1 -1
  29. package/dist/components/conversation/markdown/markdown-code-header.js +1 -1
  30. package/dist/components/conversation/markdown/markdown-core.class.d.ts +10 -0
  31. package/dist/components/conversation/markdown/markdown-core.class.js +1 -1
  32. package/dist/components/conversation/markdown/markdown-shared.d.ts +7 -2
  33. package/dist/components/conversation/markdown/markdown-shared.js +3 -3
  34. package/dist/components/conversation/markdown/markdown.class.d.ts +10 -0
  35. package/dist/components/conversation/markdown/markdown.class.js +1 -1
  36. package/dist/components/conversation/message-feedback/message-feedback.class.d.ts +11 -3
  37. package/dist/components/conversation/message-feedback/message-feedback.class.js +12 -6
  38. package/dist/components/conversation/message-feedback/message-feedback.styles.js +1 -1
  39. package/dist/components/conversation/message-parts/message-parts.class.js +1 -1
  40. package/dist/components/conversation/prompt-input/prompt-input.class.d.ts +8 -4
  41. package/dist/components/conversation/prompt-input/prompt-input.class.js +3 -2
  42. package/dist/components/conversation/push-to-talk/push-to-talk.class.js +1 -1
  43. package/dist/components/conversation/streaming-text/streaming-text-base.class.d.ts +4 -0
  44. package/dist/components/conversation/streaming-text/streaming-text-base.class.js +1 -1
  45. package/dist/components/conversation/streaming-text/streaming-text-core.class.d.ts +1 -1
  46. package/dist/components/conversation/streaming-text/streaming-text-core.class.js +1 -0
  47. package/dist/components/conversation/streaming-text/streaming-text.class.d.ts +1 -1
  48. package/dist/components/conversation/streaming-text/streaming-text.class.js +1 -0
  49. package/dist/components/conversation/suggestion-chips/suggestion-chips.class.d.ts +17 -3
  50. package/dist/components/conversation/suggestion-chips/suggestion-chips.class.js +3 -3
  51. package/dist/components/conversation/suggestion-chips/suggestion-chips.d.ts +1 -1
  52. package/dist/components/conversation/suggestion-chips/suggestion-chips.js +1 -1
  53. package/dist/components/conversation/suggestion-chips/suggestion-chips.styles.js +1 -1
  54. package/dist/components/conversation/thread-list/thread-list.class.d.ts +1 -1
  55. package/dist/components/conversation/thread-list/thread-list.class.js +3 -3
  56. package/dist/components/conversation/transcript-feed/transcript-feed.class.js +1 -1
  57. package/dist/components/data/data-grid/data-grid.class.d.ts +10 -10
  58. package/dist/components/data/data-grid/data-grid.class.js +1 -1
  59. package/dist/components/data/document-library/document-library-cursor.js +1 -0
  60. package/dist/components/data/document-library/document-library-types.d.ts +20 -0
  61. package/dist/components/data/document-library/document-library.class.d.ts +37 -26
  62. package/dist/components/data/document-library/document-library.class.js +20 -11
  63. package/dist/components/data/document-library/document-library.styles.js +1 -1
  64. package/dist/components/data/file-tree/file-tree.class.js +1 -1
  65. package/dist/components/data/flow-canvas/flow-canvas.class.d.ts +1 -1
  66. package/dist/components/data/flow-canvas/flow-canvas.class.js +2 -2
  67. package/dist/components/data/heatmap/heatmap.class.d.ts +1 -1
  68. package/dist/components/data/heatmap/heatmap.class.js +1 -1
  69. package/dist/components/data/pagination/pagination.class.js +1 -1
  70. package/dist/components/data/table/table.class.d.ts +31 -2
  71. package/dist/components/data/table/table.class.js +3 -3
  72. package/dist/components/data/table/table.styles.js +1 -1
  73. package/dist/components/data/timeline/timeline-cluster.js +1 -1
  74. package/dist/components/data/timeline/timeline-item.class.d.ts +10 -3
  75. package/dist/components/data/timeline/timeline-item.class.js +16 -12
  76. package/dist/components/data/timeline/timeline-item.styles.js +1 -1
  77. package/dist/components/data/timeline/timeline.class.d.ts +14 -2
  78. package/dist/components/data/timeline/timeline.class.js +9 -5
  79. package/dist/components/data/tree/tree-item.class.js +1 -1
  80. package/dist/components/data/tree/tree.class.d.ts +2 -0
  81. package/dist/components/data/tree/tree.class.js +1 -1
  82. package/dist/components/forms/button/button.class.d.ts +8 -6
  83. package/dist/components/forms/button/button.class.js +2 -2
  84. package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
  85. package/dist/components/forms/color-picker/color-core.js +1 -1
  86. package/dist/components/forms/combobox/combobox.class.d.ts +20 -12
  87. package/dist/components/forms/combobox/combobox.class.js +2 -2
  88. package/dist/components/forms/date-picker/date-input.class.d.ts +1 -1
  89. package/dist/components/forms/date-picker/date-input.class.js +1 -1
  90. package/dist/components/forms/icon-button/icon-button.class.d.ts +4 -2
  91. package/dist/components/forms/icon-button/icon-button.class.js +2 -2
  92. package/dist/components/forms/input/input-shared.js +2 -2
  93. package/dist/components/forms/input/number-input-locale.js +1 -0
  94. package/dist/components/forms/input/number-input.class.d.ts +19 -2
  95. package/dist/components/forms/input/number-input.class.js +2 -2
  96. package/dist/components/forms/locale-picker/locale-picker.class.d.ts +3 -3
  97. package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
  98. package/dist/components/layout/app-rail-group/app-rail-group.class.js +1 -1
  99. package/dist/components/layout/details/accordion-item.class.js +1 -1
  100. package/dist/components/layout/dock-panel/dock-panel.class.d.ts +1 -1
  101. package/dist/components/layout/dock-panel/dock-panel.class.js +1 -1
  102. package/dist/components/layout/menu/menu.class.js +1 -1
  103. package/dist/components/layout/multi-split/multi-split.class.js +1 -1
  104. package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.js +1 -1
  105. package/dist/components/layout/page/page.class.d.ts +3 -3
  106. package/dist/components/layout/page/page.class.js +1 -1
  107. package/dist/components/layout/segmented/segmented.class.d.ts +20 -7
  108. package/dist/components/layout/segmented/segmented.class.js +34 -24
  109. package/dist/components/layout/segmented/segmented.styles.js +1 -1
  110. package/dist/components/layout/stepper/stepper.styles.js +1 -1
  111. package/dist/components/layout/tab-group/tab-group.class.d.ts +8 -1
  112. package/dist/components/layout/tab-group/tab-group.class.js +1 -1
  113. package/dist/components/layout/tab-group/tab.class.d.ts +7 -1
  114. package/dist/components/layout/tab-group/tab.class.js +1 -1
  115. package/dist/components/layout/virtual-list/virtual-list.class.d.ts +2 -2
  116. package/dist/components/layout/virtual-list/virtual-list.class.js +1 -1
  117. package/dist/components/media/animated-image/animated-image.class.js +1 -1
  118. package/dist/components/media/attachment-chip/attachment-chip.class.d.ts +21 -14
  119. package/dist/components/media/attachment-chip/attachment-chip.class.js +1 -1
  120. package/dist/components/media/attachment-trigger/attachment-trigger.class.d.ts +36 -12
  121. package/dist/components/media/attachment-trigger/attachment-trigger.class.js +3 -3
  122. package/dist/components/media/drop-zone/drop-zone.class.d.ts +23 -5
  123. package/dist/components/media/drop-zone/drop-zone.class.js +2 -2
  124. package/dist/components/media/drop-zone/drop-zone.styles.js +1 -1
  125. package/dist/components/media/file-icon/file-icon.class.js +1 -1
  126. package/dist/components/media/flag/flag-url-resolver.js +1 -1
  127. package/dist/components/media/image-viewer/image-viewer.class.d.ts +2 -2
  128. package/dist/components/media/image-viewer/image-viewer.class.js +1 -1
  129. package/dist/components/media/map/map-anchor-controller.js +1 -1
  130. package/dist/components/media/map/map-canvas-target.js +1 -0
  131. package/dist/components/media/map/map-owned-features.js +1 -1
  132. package/dist/components/media/map/map-scene-elevated-lines.js +2 -2
  133. package/dist/components/media/map/map-scene-render-controller.js +1 -1
  134. package/dist/components/media/map/map.class.d.ts +15 -6
  135. package/dist/components/media/map/map.class.js +4 -4
  136. package/dist/components/media/map/map.styles.js +1 -1
  137. package/dist/components/media/pan-zoom/pan-zoom.class.js +1 -1
  138. package/dist/components/media/sequence-playback/sequence-playback.class.d.ts +21 -9
  139. package/dist/components/media/sequence-playback/sequence-playback.class.js +7 -6
  140. package/dist/components/media/sequence-playback/sequence-playback.styles.js +1 -1
  141. package/dist/components/media/video/video.class.d.ts +3 -3
  142. package/dist/components/media/video/video.class.js +3 -1
  143. package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
  144. package/dist/components/overlays/chip/chip.class.js +1 -1
  145. package/dist/components/overlays/overlay/dropdown.class.js +1 -1
  146. package/dist/components/overlays/overlay/overlay.styles.js +1 -1
  147. package/dist/components/overlays/overlay/tooltip.class.d.ts +5 -1
  148. package/dist/components/overlays/overlay/tooltip.class.js +3 -3
  149. package/dist/components/retrieval/embedding-explorer/embedding-explorer-engine.js +1 -1
  150. package/dist/components/retrieval/graph/graph-node-renderer.js +1 -1
  151. package/dist/components/retrieval/graph/graph-spatial-controller.js +1 -1
  152. package/dist/components/retrieval/graph/graph.class.d.ts +1 -1
  153. package/dist/components/retrieval/graph/graph.class.js +1 -1
  154. package/dist/components/retrieval/ingestion-queue/ingestion-queue-presentation.d.ts +11 -0
  155. package/dist/components/retrieval/ingestion-queue/ingestion-queue-presentation.js +1 -0
  156. package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.d.ts +18 -7
  157. package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.js +13 -26
  158. package/dist/components/retrieval/ingestion-queue/ingestion-queue.styles.js +1 -1
  159. package/dist/components/retrieval/mind-map/mind-map.class.js +1 -1
  160. package/dist/components/retrieval/neighbor-list/neighbor-list.class.d.ts +1 -1
  161. package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +3 -3
  162. package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +1 -1
  163. package/dist/components/utility/diff-view/diff-view.class.d.ts +5 -5
  164. package/dist/components/utility/diff-view/diff-view.class.js +1 -1
  165. package/dist/components/utility/icon/icon.class.js +1 -1
  166. package/dist/components/utility/json-viewer/json-viewer.class.d.ts +16 -1
  167. package/dist/components/utility/json-viewer/json-viewer.class.js +4 -4
  168. package/dist/components/utility/json-viewer/json-viewer.styles.js +1 -1
  169. package/dist/components/utility/known-date/known-date.class.js +1 -1
  170. package/dist/components/utility/mention-popover/mention-popover.class.js +1 -1
  171. package/dist/components/viewers/archive-viewer/archive-viewer.class.js +1 -1
  172. package/dist/components/viewers/calendar-viewer/calendar-viewer.class.js +1 -1
  173. package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
  174. package/dist/components/viewers/csv-viewer/csv-viewer.class.js +1 -1
  175. package/dist/components/viewers/dataset-viewer/dataset-viewer.class.js +1 -1
  176. package/dist/components/viewers/document-preview/document-preview.class.js +2 -2
  177. package/dist/components/viewers/docx-viewer/docx-viewer.class.d.ts +1 -1
  178. package/dist/components/viewers/docx-viewer/docx-viewer.class.js +2 -2
  179. package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
  180. package/dist/components/viewers/email-viewer/email-viewer.class.d.ts +1 -1
  181. package/dist/components/viewers/email-viewer/email-viewer.class.js +2 -2
  182. package/dist/components/viewers/html-viewer/html-viewer.class.js +1 -1
  183. package/dist/components/viewers/include/include.class.js +1 -1
  184. package/dist/components/viewers/model-viewer/model-viewer.class.js +1 -1
  185. package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +2 -2
  186. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.d.ts +2 -2
  187. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +2 -2
  188. package/dist/components/viewers/pptx-viewer/pptx-viewer.class.js +1 -1
  189. package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.js +1 -1
  190. package/dist/components/viewers/svg-viewer/svg-viewer.class.js +1 -1
  191. package/dist/components/viewers/table-viewer-shared.js +4 -4
  192. package/dist/components/viewers/xml-viewer/xml-viewer.class.js +2 -2
  193. package/dist/data-sources.d.ts +10 -0
  194. package/dist/events.d.ts +9 -4
  195. package/dist/framework-types.d.ts +1 -1
  196. package/dist/internal/anchored-overlay-runtime.js +1 -1
  197. package/dist/internal/catalog-picker.js +1 -1
  198. package/dist/internal/default-strings/conversation.generated.js +1 -1
  199. package/dist/internal/default-strings/data.generated.js +1 -1
  200. package/dist/internal/default-strings/retrieval.generated.js +1 -1
  201. package/dist/internal/document-tokens.js +2 -2
  202. package/dist/internal/drop-session-controller.js +1 -1
  203. package/dist/internal/engine-3d.js +1 -1
  204. package/dist/internal/icon-only-content.js +1 -1
  205. package/dist/internal/layered-layout.js +1 -1
  206. package/dist/internal/localization-types.d.ts +1 -1
  207. package/dist/internal/localization.js +1 -1
  208. package/dist/internal/lyra-element.js +2 -2
  209. package/dist/internal/map-custom-layer-controller.js +1 -1
  210. package/dist/internal/media-panorama.js +1 -1
  211. package/dist/internal/native-modal-context.js +1 -1
  212. package/dist/internal/overlay-manager.js +1 -1
  213. package/dist/internal/overlay-order.js +1 -1
  214. package/dist/internal/overlay-stack.js +1 -1
  215. package/dist/internal/package-metadata.js +1 -1
  216. package/dist/internal/runtime-diagnostics.js +1 -0
  217. package/dist/internal/safe-url.js +1 -1
  218. package/dist/internal/scoped-definitions.generated.js +1 -1
  219. package/dist/internal/scroll-overflow.js +1 -1
  220. package/dist/internal/source-cursor-controller.js +1 -0
  221. package/dist/internal/source-cursor-projection.js +1 -0
  222. package/dist/internal/source-page-scope.js +1 -1
  223. package/dist/internal/source-window-controller.js +1 -1
  224. package/dist/internal/text-quote.js +1 -1
  225. package/dist/internal/viewer-search.js +1 -1
  226. package/dist/lyra.d.ts +1 -1
  227. package/dist/sequence-time-binding.js +1 -1
  228. package/dist/simulation-clock.js +1 -1
  229. package/dist/styles/reservations.css +1 -1
  230. package/dist/styles/reservations.styles.js +1 -1
  231. package/dist/testing/happy-dom-shims.js +1 -1
  232. package/dist/theme/theme-bootstrap.js +1 -1
  233. package/dist/theme/theme.js +1 -1
  234. package/dist/utilities/overlay-manager.d.ts +2 -0
  235. package/llms/components/lr-attachment-chip.md +27 -12
  236. package/llms/components/lr-attachment-trigger.md +27 -7
  237. package/llms/components/lr-budget-meter.md +31 -0
  238. package/llms/components/lr-button.md +6 -4
  239. package/llms/components/lr-chat-composer.md +26 -9
  240. package/llms/components/lr-chat-message.md +44 -3
  241. package/llms/components/lr-chat-viewport.md +39 -2
  242. package/llms/components/lr-combobox.md +27 -1
  243. package/llms/components/lr-data-grid.md +2 -0
  244. package/llms/components/lr-dialog.md +10 -0
  245. package/llms/components/lr-diff-view.md +6 -0
  246. package/llms/components/lr-document-library.md +90 -6
  247. package/llms/components/lr-drop-zone.md +26 -2
  248. package/llms/components/lr-graph.md +5 -0
  249. package/llms/components/lr-icon-button.md +2 -1
  250. package/llms/components/lr-ingestion-queue.md +76 -8
  251. package/llms/components/lr-json-viewer.md +51 -0
  252. package/llms/components/lr-lite-chart.md +2 -1
  253. package/llms/components/lr-locale-picker.md +5 -0
  254. package/llms/components/lr-map.md +33 -0
  255. package/llms/components/lr-markdown-core.md +2 -1
  256. package/llms/components/lr-markdown.md +20 -4
  257. package/llms/components/lr-menu.md +3 -1
  258. package/llms/components/lr-message-feedback.md +38 -3
  259. package/llms/components/lr-number-input.md +28 -1
  260. package/llms/components/lr-page.md +4 -2
  261. package/llms/components/lr-prompt-input.md +6 -3
  262. package/llms/components/lr-segmented.md +30 -10
  263. package/llms/components/lr-sequence-playback.md +47 -12
  264. package/llms/components/lr-streaming-text-core.md +3 -2
  265. package/llms/components/lr-streaming-text.md +4 -1
  266. package/llms/components/lr-suggestion-chips.md +28 -5
  267. package/llms/components/lr-tab-group.md +13 -1
  268. package/llms/components/lr-tab.md +5 -0
  269. package/llms/components/lr-table.md +25 -4
  270. package/llms/components/lr-timeline-item.md +1 -1
  271. package/llms/components/lr-timeline.md +38 -4
  272. package/llms/components/lr-tooltip.md +3 -1
  273. package/llms/components/lr-tree.md +4 -0
  274. package/llms/components/lr-virtual-list.md +4 -1
  275. package/llms/peers.md +2 -2
  276. package/llms/shared/events-and-types.md +61 -2
  277. package/llms/shared/forms-and-accessibility.md +46 -4
  278. package/llms/shared/imports-and-registration.md +154 -110
  279. package/llms/shared/testing-and-utilities.md +5 -1
  280. package/llms/shared.md +266 -117
  281. package/locales.json +1 -1
  282. package/package.json +22 -21
  283. package/registrations.json +1 -1
@@ -1,5 +1,9 @@
1
- import{__decorate}from"tslib";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html}from"lit";import{property,state}from"lit/decorators.js";import{applyComposedFocusRepair,captureComposedFocusRepair,collectComposedFocusTargets}from"../../../internal/focus-navigation.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{literalSetConverter}from"../../../internal/converters.js";import{tag}from"../../../internal/prefix.js";import{observeScrollOverflow,SCROLL_OVERFLOW_ATTRIBUTE}from"../../../internal/scroll-overflow.js";import{isUsableActiveElement,safeDeepActiveElement}from"../../../internal/active-element.js";import{OBSERVE_TIMELINE_ITEM_TIMESTAMP,SET_TIMELINE_CLUSTER_PRESENTATION,isTimelineClusterItemContract,timeValueChanged}from"./timeline-cluster.js";import{scrollOverflowFadeStyles}from"../../../internal/scroll-overflow.styles.js";import{styles}from"./timeline.styles.js";import{LYRA_DEFAULT_timeline,LYRA_DEFAULT_timelineClusterCount}from"../../../internal/default-strings/data.generated.js";const TIMELINE_ORIENTATION=literalSetConverter(["vertical","horizontal"],"vertical");function safelyContainsActive(container,candidate){if(!isUsableActiveElement(candidate))return!1;try{return container.contains(candidate)}catch{return!1}}const TIMELINE_SCALE=literalSetConverter(["flow","time"],"flow"),TIMELINE_COLLISION=literalSetConverter(["overlap","stack","cluster"],"overlap"),EMPTY_TIMELINE_CLUSTERS=Object.freeze([]),CLUSTER_HIDDEN_ATTRIBUTE="data-lr-timeline-cluster-hidden",TIMELINE_COLLISION_THRESHOLD=.015;function timelineEpochMs(raw){if(raw==null)return null;const ms=(raw instanceof Date?raw:typeof raw=="number"?new Date(raw):new Date(String(raw))).getTime();return Number.isFinite(ms)?ms:null}function itemEpochMs(element){return timelineEpochMs(element.timestamp)}class LyraTimeline extends LyraElement{constructor(){super(...arguments),this._orientation="vertical",this._scale="flow",this._collision="overlap",this.slottedCount=0,this.collisionClusters=EMPTY_TIMELINE_CLUSTERS,this.managedClusterHiddenItems=new Set,this.managedClusterRepresentatives=new Set,this.clusterActivations=new Map,this.timestampObservedItems=new Set,this.focusRepairGeneration=0,this.timePositionedItems=new Set,this.overflowObservedItems=new Set,this.overflowItemsPending=!0,this.geometryObservedItems=new Set,this.itemGeometry=new Map,this.scrollOverflow=observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part="base"]'),()=>{this.scheduleTimeExtentMeasurement(),this.scale==="time"&&this.collision==="cluster"&&this.scheduleClusterMeasurement(),this.syncScrollTabStop()}),this.onSlotChange=()=>{this.cachedTimelineItems=void 0,this.overflowItemsPending=!0,this.invalidateTimeGeometry();const current=new Set(this.timelineItems());for(const item of this.overflowObservedItems)current.has(item)||this.overflowObservedItems.delete(item);this.updateBrowserDerivedState(()=>{this.slottedCount=current.size,this.applyTimeScale(),this.syncItemObservations()})},this.onTimelineItemTimestampChange=()=>{this.isConnected&&this.scheduleAfterUpdate(()=>this.applyTimeScale(),"timeline-item-timestamps")}}static{this.defaultStrings={...super.defaultStrings,timeline:LYRA_DEFAULT_timeline,timelineClusterCount:LYRA_DEFAULT_timelineClusterCount}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-cluster-activate"])}static{this.identityEventDetailProperties=Object.freeze({"lr-cluster-activate":Object.freeze(["items"])})}static{this.styles=[LyraElement.styles,scrollOverflowFadeStyles,styles]}get orientation(){return this._orientation}set orientation(value){const normalized=TIMELINE_ORIENTATION.normalizeReflected(this,"orientation",value),previous=this._orientation;previous!==normalized&&(this._orientation=normalized,this.requestUpdate("orientation",previous))}get scale(){return this._scale}set scale(value){const normalized=TIMELINE_SCALE.normalizeReflected(this,"scale",value),previous=this._scale;previous!==normalized&&(this._scale=normalized,this.requestUpdate("scale",previous))}get collision(){return this._collision}set collision(value){const normalized=TIMELINE_COLLISION.normalizeReflected(this,"collision",value),previous=this._collision;previous!==normalized&&(this._collision=normalized,this.requestUpdate("collision",previous))}requestUpdate(...args){args[0]===void 0&&this.itemGeometry?.clear(),super.requestUpdate(...args)}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.scheduleAfterUpdate(()=>this.applyTimeScale(),"timeline-clusters")}disconnectedCallback(){this.cancelClusterMeasurement(),this.cancelTimeExtentMeasurement(),this.focusRepairGeneration+=1,this.restoreClusterPresentation(),this.restoreClusterVisibility(),this.syncTimestampObservers([]),this.cachedTimelineItems=void 0,this.overflowObservedItems.clear(),this.overflowItemsPending=!0,this.stopTimeGeometryObserver(),this.collisionClusters.length>0&&(this.collisionClusters=EMPTY_TIMELINE_CLUSTERS),super.disconnectedCallback()}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.slottedCount=Array.from(this.children).filter(element=>!element.getAttribute("slot")&&element.localName===tag("timeline-item")).length),this.hasUpdated?(changed.has("scale")||changed.has("collision")||changed.has("rangeStart")||changed.has("rangeEnd"))&&this.applyTimeScale():this.seedFirstRenderState(()=>this.applyTimeScale())}updated(changed){super.updated(changed),(changed.size===0||[...changed.keys()].some(key=>key!=="accessibleLabel"))&&this.invalidateTimeGeometry(),(this.overflowItemsPending||changed.has("scale")||changed.has("orientation"))&&this.syncItemObservations(),this.syncScrollTabStop(),this.scheduleTimeExtentMeasurement(),(changed.has("collisionClusters")||changed.has("orientation"))&&this.collisionClusters.length>0&&this.scheduleAfterUpdate(()=>this.applyTimeScale(),"timeline-cluster-measurement"),this.collisionClusters.length>0&&this.syncClusterPresentations(this.collisionClusters)}syncScrollTabStop(){const base=this.renderRoot.querySelector('[part="base"]');if(!base)return;const reachableOnlyByScrolling=this.orientation==="horizontal"&&base.hasAttribute(SCROLL_OVERFLOW_ATTRIBUTE);base.setAttribute("tabindex",reachableOnlyByScrolling?"0":"-1")}countTimelineItems(slot){return slot.assignedElements({flatten:!0}).filter(element=>element.localName===tag("timeline-item")).length}firstUpdated(changed){super.firstUpdated(changed),this.scheduleAfterUpdate(()=>this.updateBrowserDerivedState(()=>{const slot=this.shadowRoot.querySelector("slot");this.cachedTimelineItems=void 0,this.overflowItemsPending=!0,this.slottedCount=this.countTimelineItems(slot),this.applyTimeScale(),this.syncItemObservations()}),"timeline-first-slot-reconciliation")}get itemCount(){return this.slottedCount}syncTimestampObservers(items){const current=new Set(items);for(const item of this.timestampObservedItems)current.has(item)||(isTimelineClusterItemContract(item)&&item[OBSERVE_TIMELINE_ITEM_TIMESTAMP](this.onTimelineItemTimestampChange,!1),this.timestampObservedItems.delete(item));for(const item of current)this.timestampObservedItems.has(item)||isTimelineClusterItemContract(item)&&(item[OBSERVE_TIMELINE_ITEM_TIMESTAMP](this.onTimelineItemTimestampChange,!0),this.timestampObservedItems.add(item))}timelineItems(){return this.cachedTimelineItems??=this.collectTimelineItems()}collectTimelineItems(){const slot=this.shadowRoot?.querySelector("slot");return(slot?slot.assignedElements({flatten:!0}):Array.from(this.children).filter(element=>!element.getAttribute("slot"))).filter(element=>element.localName===tag("timeline-item"))}timeRange(stamps){const pinnedStart=timelineEpochMs(this.rangeStart),pinnedEnd=timelineEpochMs(this.rangeEnd);if(pinnedStart!==null&&pinnedEnd!==null&&pinnedEnd>pinnedStart)return[pinnedStart,pinnedEnd];let lo=1/0,hi=-1/0;for(const stamp of stamps)stamp!==null&&(stamp<lo&&(lo=stamp),stamp>hi&&(hi=stamp));return hi>lo?[lo,hi]:null}applyTimeScale(){if(this.scheduleTimeExtentMeasurement(),this.scale!=="time"){this.overflowItemsPending=!0,this.timestampObservedItems.size&&this.syncTimestampObservers([]);for(const item of this.timePositionedItems)item.style.removeProperty("--_lr-timeline-item-offset"),item.style.removeProperty("--_lr-timeline-item-lane");this.timePositionedItems.clear(),this.applyCollisionClusters([]);return}this.invalidateTimeGeometry();const items=this.timelineItems(),currentItems=new Set(items);this.syncTimestampObservers(items);const clusterThreshold=this.collision==="cluster"?this.clusterCollisionThreshold():TIMELINE_COLLISION_THRESHOLD;for(const previous of this.timePositionedItems)currentItems.has(previous)||(previous.style.removeProperty("--_lr-timeline-item-offset"),previous.style.removeProperty("--_lr-timeline-item-lane"));this.timePositionedItems.clear();for(const item of items)this.timePositionedItems.add(item);const stamps=items.map(item=>itemEpochMs(item)),range=this.timeRange(stamps),lastIndex=Math.max(1,items.length-1),offsets=new Array(items.length).fill(0);items.forEach((item,index)=>{const stamp=stamps[index]??null,ratio=range&&stamp!==null?(stamp-range[0])/(range[1]-range[0]):this.collision==="cluster"&&stamp!==null?0:index/lastIndex,clamped=Math.min(1,Math.max(0,ratio));offsets[index]=clamped,item.style.setProperty("--_lr-timeline-item-offset",`${clamped*100}%`)}),this.applyCollisionLanes(items,offsets),this.applyCollisionClusters(this.collision==="cluster"?this.buildCollisionClusters(items,offsets,clusterThreshold):[])}applyCollisionLanes(items,offsets){if(this.collision!=="stack"){for(const item of items)item.style.removeProperty("--_lr-timeline-item-lane");return}const order=items.map((_,index)=>index).sort((a,b)=>(offsets[a]??0)-(offsets[b]??0)),laneTails=[],lanes=new Array(items.length).fill(0);for(const index of order){const offset=offsets[index]??0;let lane=laneTails.findIndex(tail=>offset-tail>=TIMELINE_COLLISION_THRESHOLD);lane===-1&&(lane=laneTails.length),laneTails[lane]=offset,lanes[index]=lane}items.forEach((item,index)=>{item.style.setProperty("--_lr-timeline-item-lane",String(lanes[index]??0))})}buildCollisionClusters(items,offsets,threshold){const order=items.map((_,index)=>index).sort((a,b)=>(offsets[a]??0)-(offsets[b]??0)||a-b),clusters=[];let window=[],windowStart=0;const flush=()=>{if(window.length<2){window=[];return}const memberIndexes=[...window].sort((a,b)=>a-b);clusters.push({offset:windowStart,items:memberIndexes.map(index=>items[index])}),window=[]};for(const index of order){const offset=offsets[index]??0;window.length>0&&offset-windowStart>=threshold&&flush(),window.length===0&&(windowStart=offset),window.push(index)}return flush(),clusters}clusterCollisionThreshold(){const base=this.renderRoot.querySelector('[part="base"]');if(!base)return TIMELINE_COLLISION_THRESHOLD;const axisExtent=this.orientation==="horizontal"?base.clientWidth:base.clientHeight;if(!Number.isFinite(axisExtent)||axisExtent<=0)return TIMELINE_COLLISION_THRESHOLD;let markerExtent=0;for(const item of this.managedClusterRepresentatives){const marker=item.shadowRoot?.querySelector('[part="cluster"]');if(!marker)continue;const rect=marker.getBoundingClientRect();markerExtent=Math.max(markerExtent,this.orientation==="horizontal"?rect.width:rect.height)}return!Number.isFinite(markerExtent)||markerExtent<=0?TIMELINE_COLLISION_THRESHOLD:Math.max(TIMELINE_COLLISION_THRESHOLD,markerExtent/axisExtent)}scheduleTimeExtentMeasurement(){const view=this.ownerDocument?.defaultView;view&&(this.timeExtentFrame!==void 0&&this.timeExtentView===view||(this.cancelTimeExtentMeasurement(),this.timeExtentView=view,this.timeExtentFrame=view.requestAnimationFrame(()=>{if(this.timeExtentFrame=void 0,this.timeExtentView=void 0,!this.isConnected||this.ownerDocument.defaultView!==view)return;const base=this.renderRoot.querySelector('[part="base"]');if(!base)return;let overhang=0;if(this.scale==="time"&&this.orientation!=="horizontal"){const bottom=base.getBoundingClientRect().bottom;for(const item of this.timelineItems()){const geometry=this.timeItemGeometry(item,bottom);overhang=Math.max(overhang,geometry.bottom)}}const trailing=`${Math.ceil(overhang)}px`;if(base.style.getPropertyValue("--_lr-timeline-trailing-extent")!==trailing&&base.style.setProperty("--_lr-timeline-trailing-extent",trailing),this.scale!=="time"||this.orientation!=="horizontal"||this.collision==="cluster"){base.style.removeProperty("--_lr-timeline-content-height");return}let extent=0;for(const item of this.timelineItems())extent=Math.max(extent,this.timeItemGeometry(item,0).extent);const height=`${extent+Math.max(0,base.offsetHeight-base.clientHeight)}px`;base.style.getPropertyValue("--_lr-timeline-content-height")!==height&&base.style.setProperty("--_lr-timeline-content-height",height)})))}syncItemObservations(){if(this.syncTimeGeometryObserver(),this.overflowItemsPending){const added=this.timelineItems().filter(item=>!this.overflowObservedItems.has(item));if(added.length&&this.scale!=="time"){this.scrollOverflow.observeExtra(added);for(const item of added)this.overflowObservedItems.add(item)}this.overflowItemsPending=!1}}invalidateTimeGeometry(item){item?this.itemGeometry.delete(item):this.itemGeometry.clear()}timeItemGeometry(item,baseBottom){let geometry=this.itemGeometry.get(item);return geometry||(geometry=item.getClientRects().length?{bottom:this.orientation==="horizontal"?0:item.getBoundingClientRect().bottom-baseBottom,extent:this.orientation==="horizontal"?item.offsetTop+item.offsetHeight+1:0}:{bottom:0,extent:0},this.itemGeometry.set(item,geometry)),geometry}stopTimeGeometryObserver(){this.timeGeometryObserver?.disconnect(),this.timeGeometryObserver=void 0,this.timeGeometryBase=void 0,this.timeGeometryView=void 0,this.geometryObservedItems.clear(),this.itemGeometry.clear()}syncTimeGeometryObserver(){const view=this.ownerDocument?.defaultView,base=this.renderRoot.querySelector('[part="base"]');if(this.scale!=="time"||!this.isConnected||!view||!base){this.stopTimeGeometryObserver();return}if(view!==this.timeGeometryView||base!==this.timeGeometryBase){this.stopTimeGeometryObserver();const Observer=view.ResizeObserver;if(!Observer)return;const observer=new Observer(entries=>{if(!(this.timeGeometryObserver!==observer||this.ownerDocument.defaultView!==view)){for(const entry of entries)this.invalidateTimeGeometry(entry.target===base?void 0:entry.target);this.scrollOverflow.measure(),this.syncScrollTabStop(),this.scheduleTimeExtentMeasurement(),this.collision==="cluster"&&this.scheduleClusterMeasurement()}});this.timeGeometryObserver=observer,this.timeGeometryBase=base,this.timeGeometryView=view,observer.observe(base)}const items=new Set(this.timelineItems());for(const previous of this.geometryObservedItems)items.has(previous)||(this.timeGeometryObserver?.unobserve(previous),this.geometryObservedItems.delete(previous),this.itemGeometry.delete(previous));for(const item of items)this.geometryObservedItems.has(item)||(this.timeGeometryObserver?.observe(item),this.geometryObservedItems.add(item))}cancelTimeExtentMeasurement(){this.timeExtentFrame!==void 0&&this.timeExtentView&&this.timeExtentView.cancelAnimationFrame(this.timeExtentFrame),this.timeExtentFrame=void 0,this.timeExtentView=void 0}scheduleClusterMeasurement(){const view=this.ownerDocument.defaultView;view&&(this.clusterMeasurementFrame!==void 0&&this.clusterMeasurementView===view||(this.cancelClusterMeasurement(),this.clusterMeasurementView=view,this.clusterMeasurementFrame=view.requestAnimationFrame(()=>{this.clusterMeasurementFrame=void 0,this.clusterMeasurementView=void 0,this.isConnected&&this.ownerDocument.defaultView===view&&this.scale==="time"&&this.collision==="cluster"&&this.applyTimeScale()})))}cancelClusterMeasurement(){this.clusterMeasurementFrame!==void 0&&this.clusterMeasurementView&&this.clusterMeasurementView.cancelAnimationFrame(this.clusterMeasurementFrame),this.clusterMeasurementFrame=void 0,this.clusterMeasurementView=void 0}sameClusters(left,right){return left.length===right.length&&left.every((cluster,index)=>cluster.offset===right[index]?.offset&&cluster.items.length===right[index]?.items.length&&cluster.items.every((item,itemIndex)=>item===right[index]?.items[itemIndex]))}captureClusterFocusRepair(clusters){const active=safeDeepActiveElement(this.ownerDocument);if(!active)return;const focusedItem=this.timelineItems().find(item=>item===active||safelyContainsActive(item,active)||safeDeepActiveElement(item.shadowRoot)===active);if(!focusedItem)return;const wasRepresentative=this.managedClusterRepresentatives.has(focusedItem),nextCluster=clusters.find(cluster=>cluster.items.includes(focusedItem)),nextRepresentative=nextCluster?.items[0],mode=nextCluster?"cluster":"item";if(mode==="cluster"&&wasRepresentative&&nextRepresentative===focusedItem||mode==="item"&&!wasRepresentative)return;const base=this.renderRoot.querySelector('[part="base"]');let snapshot;try{snapshot=captureComposedFocusRepair(focusedItem,base)}catch{return}if(snapshot)return{item:mode==="cluster"?nextRepresentative:focusedItem,mode,snapshot}}scheduleClusterFocusRepair(repair){const generation=++this.focusRepairGeneration;repair&&repair.item.updateComplete.then(()=>{if(generation!==this.focusRepairGeneration||!this.isConnected)return;const base=this.renderRoot.querySelector('[part="base"]'),target=repair.mode==="cluster"?repair.item.shadowRoot?.querySelector('[part="cluster"]')??null:collectComposedFocusTargets(repair.item).elements[0]??base;try{applyComposedFocusRepair(repair.snapshot,target)}catch{}})}applyCollisionClusters(clusters){const frozen=Object.freeze(clusters.map(cluster=>Object.freeze({offset:cluster.offset,items:Object.freeze([...cluster.items])}))),changed=!this.sameClusters(this.collisionClusters,frozen),focusRepair=changed?this.captureClusterFocusRepair(frozen):void 0,representatives=new Set(frozen.map(cluster=>cluster.items[0])),hiddenItems=new Set(frozen.flatMap(cluster=>cluster.items.filter(item=>!representatives.has(item))));for(const item of this.managedClusterHiddenItems){if(hiddenItems.has(item)){item.hasAttribute(CLUSTER_HIDDEN_ATTRIBUTE)||item.setAttribute(CLUSTER_HIDDEN_ATTRIBUTE,"");continue}item.getAttribute(CLUSTER_HIDDEN_ATTRIBUTE)===""&&item.removeAttribute(CLUSTER_HIDDEN_ATTRIBUTE),this.managedClusterHiddenItems.delete(item)}for(const item of hiddenItems)this.managedClusterHiddenItems.has(item)||item.hasAttribute(CLUSTER_HIDDEN_ATTRIBUTE)||(item.setAttribute(CLUSTER_HIDDEN_ATTRIBUTE,""),this.managedClusterHiddenItems.add(item));if(changed){this.restoreClusterPresentation();for(const cluster of frozen){const representative=cluster.items[0];this.clusterActivations.set(representative,()=>this.activateCluster(cluster.items)),this.managedClusterRepresentatives.add(representative)}this.collisionClusters=frozen,this.syncClusterPresentations(frozen),this.scheduleClusterFocusRepair(focusRepair)}for(const cluster of frozen)cluster.items[0].style.setProperty("--_lr-timeline-item-offset",`${cluster.offset*100}%`)}syncClusterPresentations(clusters){for(const cluster of clusters){const representative=cluster.items[0],activate=this.clusterActivations.get(representative);if(!activate)continue;const countText=getNumberFormat(this.effectiveLocale).format(cluster.items.length);isTimelineClusterItemContract(representative)&&representative[SET_TIMELINE_CLUSTER_PRESENTATION]({accessibleLabel:this.localize("timelineClusterCount",void 0,{count:countText}),countText,activate})}}restoreClusterPresentation(){for(const item of this.managedClusterRepresentatives)isTimelineClusterItemContract(item)&&item[SET_TIMELINE_CLUSTER_PRESENTATION](void 0);this.managedClusterRepresentatives.clear(),this.clusterActivations.clear()}restoreClusterVisibility(){for(const item of this.managedClusterHiddenItems)item.getAttribute(CLUSTER_HIDDEN_ATTRIBUTE)===""&&item.removeAttribute(CLUSTER_HIDDEN_ATTRIBUTE);this.managedClusterHiddenItems.clear()}activateCluster(items){const snapshot=this.ownerDocument.defaultView?.Array.from(items)??[...items];this.emit("lr-cluster-activate",Object.freeze({items:Object.freeze(snapshot)}))}render(){return html`
2
- <div part="base" role="list" tabindex="-1" aria-label=${this.accessibleLabel==null?this.localize("timeline"):this.accessibleLabel}>
3
- <slot @slotchange=${this.onSlotChange}></slot>
4
- </div>
5
- `}}__decorate([property({reflect:!0,converter:TIMELINE_ORIENTATION})],LyraTimeline.prototype,"orientation",null),__decorate([property({reflect:!0,converter:TIMELINE_SCALE})],LyraTimeline.prototype,"scale",null),__decorate([property({reflect:!0,converter:TIMELINE_COLLISION})],LyraTimeline.prototype,"collision",null),__decorate([property({attribute:!1,hasChanged:timeValueChanged})],LyraTimeline.prototype,"rangeStart",void 0),__decorate([property({attribute:!1,hasChanged:timeValueChanged})],LyraTimeline.prototype,"rangeEnd",void 0),__decorate([property({attribute:"aria-label"})],LyraTimeline.prototype,"accessibleLabel",void 0),__decorate([state()],LyraTimeline.prototype,"slottedCount",void 0),__decorate([state()],LyraTimeline.prototype,"collisionClusters",void 0);export{LyraTimeline};
1
+ import{__decorate}from"tslib";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html}from"lit";import{property,state}from"lit/decorators.js";import{applyComposedFocusRepair,captureComposedFocusRepair,collectComposedFocusTargets}from"../../../internal/focus-navigation.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{literalSetConverter}from"../../../internal/converters.js";import{tag}from"../../../internal/prefix.js";import{observeScrollOverflow,SCROLL_OVERFLOW_ATTRIBUTE}from"../../../internal/scroll-overflow.js";import{isUsableActiveElement,safeDeepActiveElement}from"../../../internal/active-element.js";import{OBSERVE_TIMELINE_ITEM_TIMESTAMP,SET_TIMELINE_CLUSTER_PRESENTATION,SET_TIMELINE_ITEM_ORDINAL,TIMELINE_ITEM_ORDINAL_OF,isTimelineClusterItemContract,isTimelineOrdinalItem,timeValueChanged}from"./timeline-cluster.js";import{finiteInteger}from"../../../internal/numbers.js";import{scrollOverflowFadeStyles}from"../../../internal/scroll-overflow.styles.js";import{styles}from"./timeline.styles.js";import{LYRA_DEFAULT_timeline,LYRA_DEFAULT_timelineClusterCount}from"../../../internal/default-strings/data.generated.js";const TIMELINE_ORIENTATION=literalSetConverter(["vertical","horizontal"],"vertical");function safelyContainsActive(container,candidate){if(!isUsableActiveElement(candidate))return!1;try{return container.contains(candidate)}catch{return!1}}const TIMELINE_SCALE=literalSetConverter(["flow","time"],"flow"),TIMELINE_COLLISION=literalSetConverter(["overlap","stack","cluster"],"overlap"),EMPTY_TIMELINE_CLUSTERS=Object.freeze([]),CLUSTER_HIDDEN_ATTRIBUTE="data-lr-timeline-cluster-hidden",TIMELINE_COLLISION_THRESHOLD=.015;function timelineEpochMs(raw){if(raw==null)return null;const ms=(raw instanceof Date?raw:typeof raw=="number"?new Date(raw):new Date(String(raw))).getTime();return Number.isFinite(ms)?ms:null}function itemEpochMs(element){return timelineEpochMs(element.timestamp)}class LyraTimeline extends LyraElement{constructor(){super(...arguments),this._orientation="vertical",this._scale="flow",this._collision="overlap",this.ordered=!1,this.start=1,this.slottedCount=0,this.collisionClusters=EMPTY_TIMELINE_CLUSTERS,this.managedClusterHiddenItems=new Set,this.managedClusterRepresentatives=new Set,this.clusterActivations=new Map,this.timestampObservedItems=new Set,this.numberedItems=new Set,this.focusRepairGeneration=0,this.timePositionedItems=new Set,this.overflowObservedItems=new Set,this.overflowItemsPending=!0,this.geometryObservedItems=new Set,this.itemGeometry=new Map,this.scrollOverflow=observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part="base"]'),()=>{this.scheduleTimeExtentMeasurement(),this.scale==="time"&&this.collision==="cluster"&&this.scheduleClusterMeasurement(),this.syncScrollTabStop()}),this.onSlotChange=()=>{this.cachedTimelineItems=void 0,this.overflowItemsPending=!0,this.invalidateTimeGeometry();const current=new Set(this.timelineItems());for(const item of this.overflowObservedItems)current.has(item)||this.overflowObservedItems.delete(item);this.updateBrowserDerivedState(()=>{this.slottedCount=current.size,this.applyTimeScale(),this.syncItemObservations()}),this.syncOrdinals()},this.onTimelineItemTimestampChange=()=>{this.isConnected&&this.scheduleAfterUpdate(()=>this.applyTimeScale(),"timeline-item-timestamps")}}static{this.defaultStrings={...super.defaultStrings,timeline:LYRA_DEFAULT_timeline,timelineClusterCount:LYRA_DEFAULT_timelineClusterCount}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-cluster-activate"])}static{this.identityEventDetailProperties=Object.freeze({"lr-cluster-activate":Object.freeze(["items"])})}static{this.styles=[LyraElement.styles,scrollOverflowFadeStyles,styles]}get orientation(){return this._orientation}set orientation(value){const normalized=TIMELINE_ORIENTATION.normalizeReflected(this,"orientation",value),previous=this._orientation;previous!==normalized&&(this._orientation=normalized,this.requestUpdate("orientation",previous))}get scale(){return this._scale}set scale(value){const normalized=TIMELINE_SCALE.normalizeReflected(this,"scale",value),previous=this._scale;previous!==normalized&&(this._scale=normalized,this.requestUpdate("scale",previous))}get collision(){return this._collision}set collision(value){const normalized=TIMELINE_COLLISION.normalizeReflected(this,"collision",value),previous=this._collision;previous!==normalized&&(this._collision=normalized,this.requestUpdate("collision",previous))}requestUpdate(...args){args[0]===void 0&&this.itemGeometry?.clear(),super.requestUpdate(...args)}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.scheduleAfterUpdate(()=>{this.applyTimeScale(),this.syncOrdinals()},"timeline-clusters")}disconnectedCallback(){this.cancelClusterMeasurement(),this.cancelTimeExtentMeasurement(),this.focusRepairGeneration+=1,this.restoreClusterPresentation(),this.restoreClusterVisibility(),this.syncTimestampObservers([]),this.cachedTimelineItems=void 0,this.syncOrdinals(),this.overflowObservedItems.clear(),this.overflowItemsPending=!0,this.stopTimeGeometryObserver(),this.collisionClusters.length>0&&(this.collisionClusters=EMPTY_TIMELINE_CLUSTERS),super.disconnectedCallback()}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.slottedCount=Array.from(this.children).filter(element=>!element.getAttribute("slot")&&element.localName===tag("timeline-item")).length),this.hasUpdated?(changed.has("scale")||changed.has("collision")||changed.has("rangeStart")||changed.has("rangeEnd"))&&this.applyTimeScale():this.seedFirstRenderState(()=>this.applyTimeScale())}updated(changed){super.updated(changed),(changed.size===0||[...changed.keys()].some(key=>key!=="accessibleLabel"))&&this.invalidateTimeGeometry(),(this.overflowItemsPending||changed.has("scale")||changed.has("orientation"))&&this.syncItemObservations(),(changed.has("ordered")||changed.has("start"))&&this.syncOrdinals(),this.syncScrollTabStop(),this.scheduleTimeExtentMeasurement(),(changed.has("collisionClusters")||changed.has("orientation"))&&this.collisionClusters.length>0&&this.scheduleAfterUpdate(()=>this.applyTimeScale(),"timeline-cluster-measurement"),this.collisionClusters.length>0&&this.syncClusterPresentations(this.collisionClusters)}syncScrollTabStop(){const base=this.renderRoot.querySelector('[part="base"]');if(!base)return;const reachableOnlyByScrolling=this.orientation==="horizontal"&&base.hasAttribute(SCROLL_OVERFLOW_ATTRIBUTE);base.setAttribute("tabindex",reachableOnlyByScrolling?"0":"-1")}countTimelineItems(slot){return slot.assignedElements({flatten:!0}).filter(element=>element.localName===tag("timeline-item")).length}firstUpdated(changed){super.firstUpdated(changed),this.scheduleAfterUpdate(()=>this.updateBrowserDerivedState(()=>{const slot=this.shadowRoot.querySelector("slot");this.cachedTimelineItems=void 0,this.overflowItemsPending=!0,this.slottedCount=this.countTimelineItems(slot),this.applyTimeScale(),this.syncItemObservations(),this.syncOrdinals()}),"timeline-first-slot-reconciliation")}get itemCount(){return this.slottedCount}get firstOrdinal(){return finiteInteger(this.start,1)}syncOrdinals(){const items=this.isConnected?this.timelineItems():[],current=new Set(items);for(const item of this.numberedItems)current.has(item)||(isTimelineOrdinalItem(item)&&item[SET_TIMELINE_ITEM_ORDINAL](void 0),this.numberedItems.delete(item));const first=this.firstOrdinal;items.forEach((item,index)=>{isTimelineOrdinalItem(item)&&(item[SET_TIMELINE_ITEM_ORDINAL](this.ordered?first+index:void 0),this.ordered?this.numberedItems.add(item):this.numberedItems.delete(item))})}[TIMELINE_ITEM_ORDINAL_OF](item){if(this.scale==="time"&&this.onTimelineItemTimestampChange(),!this.ordered)return;const index=this.timelineItems().indexOf(item);if(!(index<0))return this.numberedItems.add(item),this.firstOrdinal+index}syncTimestampObservers(items){const current=new Set(items);for(const item of this.timestampObservedItems)current.has(item)||(isTimelineClusterItemContract(item)&&item[OBSERVE_TIMELINE_ITEM_TIMESTAMP](this.onTimelineItemTimestampChange,!1),this.timestampObservedItems.delete(item));for(const item of current)this.timestampObservedItems.has(item)||isTimelineClusterItemContract(item)&&(item[OBSERVE_TIMELINE_ITEM_TIMESTAMP](this.onTimelineItemTimestampChange,!0),this.timestampObservedItems.add(item))}timelineItems(){return this.cachedTimelineItems??=this.collectTimelineItems()}collectTimelineItems(){const slot=this.shadowRoot?.querySelector("slot");return(slot?slot.assignedElements({flatten:!0}):Array.from(this.children).filter(element=>!element.getAttribute("slot"))).filter(element=>element.localName===tag("timeline-item"))}timeRange(stamps){const pinnedStart=timelineEpochMs(this.rangeStart),pinnedEnd=timelineEpochMs(this.rangeEnd);if(pinnedStart!==null&&pinnedEnd!==null&&pinnedEnd>pinnedStart)return[pinnedStart,pinnedEnd];let lo=1/0,hi=-1/0;for(const stamp of stamps)stamp!==null&&(stamp<lo&&(lo=stamp),stamp>hi&&(hi=stamp));return hi>lo?[lo,hi]:null}applyTimeScale(){if(this.scheduleTimeExtentMeasurement(),this.scale!=="time"){this.overflowItemsPending=!0,this.timestampObservedItems.size&&this.syncTimestampObservers([]);for(const item of this.timePositionedItems)item.style.removeProperty("--_lr-timeline-item-offset"),item.style.removeProperty("--_lr-timeline-item-lane");this.timePositionedItems.clear(),this.applyCollisionClusters([]);return}this.invalidateTimeGeometry();const items=this.timelineItems(),currentItems=new Set(items);this.syncTimestampObservers(items);const clusterThreshold=this.collision==="cluster"?this.clusterCollisionThreshold():TIMELINE_COLLISION_THRESHOLD;for(const previous of this.timePositionedItems)currentItems.has(previous)||(previous.style.removeProperty("--_lr-timeline-item-offset"),previous.style.removeProperty("--_lr-timeline-item-lane"));this.timePositionedItems.clear();for(const item of items)this.timePositionedItems.add(item);const stamps=items.map(item=>itemEpochMs(item)),range=this.timeRange(stamps),lastIndex=Math.max(1,items.length-1),offsets=new Array(items.length).fill(0);items.forEach((item,index)=>{const stamp=stamps[index]??null,ratio=range&&stamp!==null?(stamp-range[0])/(range[1]-range[0]):this.collision==="cluster"&&stamp!==null?0:index/lastIndex,clamped=Math.min(1,Math.max(0,ratio));offsets[index]=clamped,item.style.setProperty("--_lr-timeline-item-offset",`${clamped*100}%`)}),this.applyCollisionLanes(items,offsets),this.applyCollisionClusters(this.collision==="cluster"?this.buildCollisionClusters(items,offsets,clusterThreshold):[])}applyCollisionLanes(items,offsets){if(this.collision!=="stack"){for(const item of items)item.style.removeProperty("--_lr-timeline-item-lane");return}const order=items.map((_,index)=>index).sort((a,b)=>(offsets[a]??0)-(offsets[b]??0)),laneTails=[],lanes=new Array(items.length).fill(0);for(const index of order){const offset=offsets[index]??0;let lane=laneTails.findIndex(tail=>offset-tail>=TIMELINE_COLLISION_THRESHOLD);lane===-1&&(lane=laneTails.length),laneTails[lane]=offset,lanes[index]=lane}items.forEach((item,index)=>{item.style.setProperty("--_lr-timeline-item-lane",String(lanes[index]??0))})}buildCollisionClusters(items,offsets,threshold){const order=items.map((_,index)=>index).sort((a,b)=>(offsets[a]??0)-(offsets[b]??0)||a-b),clusters=[];let window=[],windowStart=0;const flush=()=>{if(window.length<2){window=[];return}const memberIndexes=[...window].sort((a,b)=>a-b);clusters.push({offset:windowStart,items:memberIndexes.map(index=>items[index])}),window=[]};for(const index of order){const offset=offsets[index]??0;window.length>0&&offset-windowStart>=threshold&&flush(),window.length===0&&(windowStart=offset),window.push(index)}return flush(),clusters}clusterCollisionThreshold(){const base=this.renderRoot.querySelector('[part="base"]');if(!base)return TIMELINE_COLLISION_THRESHOLD;const axisExtent=this.orientation==="horizontal"?base.clientWidth:base.clientHeight;if(!Number.isFinite(axisExtent)||axisExtent<=0)return TIMELINE_COLLISION_THRESHOLD;let markerExtent=0;for(const item of this.managedClusterRepresentatives){const marker=item.shadowRoot?.querySelector('[part="cluster"]');if(!marker)continue;const rect=marker.getBoundingClientRect();markerExtent=Math.max(markerExtent,this.orientation==="horizontal"?rect.width:rect.height)}return!Number.isFinite(markerExtent)||markerExtent<=0?TIMELINE_COLLISION_THRESHOLD:Math.max(TIMELINE_COLLISION_THRESHOLD,markerExtent/axisExtent)}scheduleTimeExtentMeasurement(){const view=this.ownerDocument?.defaultView;view&&(this.timeExtentFrame!==void 0&&this.timeExtentView===view||(this.cancelTimeExtentMeasurement(),this.timeExtentView=view,this.timeExtentFrame=view.requestAnimationFrame(()=>{if(this.timeExtentFrame=void 0,this.timeExtentView=void 0,!this.isConnected||this.ownerDocument.defaultView!==view)return;const base=this.renderRoot.querySelector('[part="base"]');if(!base)return;let overhang=0;if(this.scale==="time"&&this.orientation!=="horizontal"){const bottom=base.getBoundingClientRect().bottom;for(const item of this.timelineItems()){const geometry=this.timeItemGeometry(item,bottom);overhang=Math.max(overhang,geometry.bottom)}}const trailing=`${Math.ceil(overhang)}px`;if(base.style.getPropertyValue("--_lr-timeline-trailing-extent")!==trailing&&base.style.setProperty("--_lr-timeline-trailing-extent",trailing),this.scale!=="time"||this.orientation!=="horizontal"||this.collision==="cluster"){base.style.removeProperty("--_lr-timeline-content-height");return}let extent=0;for(const item of this.timelineItems())extent=Math.max(extent,this.timeItemGeometry(item,0).extent);const height=`${extent+Math.max(0,base.offsetHeight-base.clientHeight)}px`;base.style.getPropertyValue("--_lr-timeline-content-height")!==height&&base.style.setProperty("--_lr-timeline-content-height",height)})))}syncItemObservations(){if(this.syncTimeGeometryObserver(),this.overflowItemsPending){const added=this.timelineItems().filter(item=>!this.overflowObservedItems.has(item));if(added.length&&this.scale!=="time"){this.scrollOverflow.observeExtra(added);for(const item of added)this.overflowObservedItems.add(item)}this.overflowItemsPending=!1}}invalidateTimeGeometry(item){item?this.itemGeometry.delete(item):this.itemGeometry.clear()}timeItemGeometry(item,baseBottom){let geometry=this.itemGeometry.get(item);return geometry||(geometry=item.getClientRects().length?{bottom:this.orientation==="horizontal"?0:item.getBoundingClientRect().bottom-baseBottom,extent:this.orientation==="horizontal"?item.offsetTop+item.offsetHeight+1:0}:{bottom:0,extent:0},this.itemGeometry.set(item,geometry)),geometry}stopTimeGeometryObserver(){this.timeGeometryObserver?.disconnect(),this.timeGeometryObserver=void 0,this.timeGeometryBase=void 0,this.timeGeometryView=void 0,this.geometryObservedItems.clear(),this.itemGeometry.clear()}syncTimeGeometryObserver(){const view=this.ownerDocument?.defaultView,base=this.renderRoot.querySelector('[part="base"]');if(this.scale!=="time"||!this.isConnected||!view||!base){this.stopTimeGeometryObserver();return}if(view!==this.timeGeometryView||base!==this.timeGeometryBase){this.stopTimeGeometryObserver();const Observer=view.ResizeObserver;if(!Observer)return;const observer=new Observer(entries=>{if(!(this.timeGeometryObserver!==observer||this.ownerDocument.defaultView!==view)){for(const entry of entries)this.invalidateTimeGeometry(entry.target===base?void 0:entry.target);this.scrollOverflow.measure(),this.syncScrollTabStop(),this.scheduleTimeExtentMeasurement(),this.collision==="cluster"&&this.scheduleClusterMeasurement()}});this.timeGeometryObserver=observer,this.timeGeometryBase=base,this.timeGeometryView=view,observer.observe(base)}const items=new Set(this.timelineItems());for(const previous of this.geometryObservedItems)items.has(previous)||(this.timeGeometryObserver?.unobserve(previous),this.geometryObservedItems.delete(previous),this.itemGeometry.delete(previous));for(const item of items)this.geometryObservedItems.has(item)||(this.timeGeometryObserver?.observe(item),this.geometryObservedItems.add(item))}cancelTimeExtentMeasurement(){this.timeExtentFrame!==void 0&&this.timeExtentView&&this.timeExtentView.cancelAnimationFrame(this.timeExtentFrame),this.timeExtentFrame=void 0,this.timeExtentView=void 0}scheduleClusterMeasurement(){const view=this.ownerDocument.defaultView;view&&(this.clusterMeasurementFrame!==void 0&&this.clusterMeasurementView===view||(this.cancelClusterMeasurement(),this.clusterMeasurementView=view,this.clusterMeasurementFrame=view.requestAnimationFrame(()=>{this.clusterMeasurementFrame=void 0,this.clusterMeasurementView=void 0,this.isConnected&&this.ownerDocument.defaultView===view&&this.scale==="time"&&this.collision==="cluster"&&this.applyTimeScale()})))}cancelClusterMeasurement(){this.clusterMeasurementFrame!==void 0&&this.clusterMeasurementView&&this.clusterMeasurementView.cancelAnimationFrame(this.clusterMeasurementFrame),this.clusterMeasurementFrame=void 0,this.clusterMeasurementView=void 0}sameClusters(left,right){return left.length===right.length&&left.every((cluster,index)=>cluster.offset===right[index]?.offset&&cluster.items.length===right[index]?.items.length&&cluster.items.every((item,itemIndex)=>item===right[index]?.items[itemIndex]))}captureClusterFocusRepair(clusters){const active=safeDeepActiveElement(this.ownerDocument);if(!active)return;const focusedItem=this.timelineItems().find(item=>item===active||safelyContainsActive(item,active)||safeDeepActiveElement(item.shadowRoot)===active);if(!focusedItem)return;const wasRepresentative=this.managedClusterRepresentatives.has(focusedItem),nextCluster=clusters.find(cluster=>cluster.items.includes(focusedItem)),nextRepresentative=nextCluster?.items[0],mode=nextCluster?"cluster":"item";if(mode==="cluster"&&wasRepresentative&&nextRepresentative===focusedItem||mode==="item"&&!wasRepresentative)return;const base=this.renderRoot.querySelector('[part="base"]');let snapshot;try{snapshot=captureComposedFocusRepair(focusedItem,base)}catch{return}if(snapshot)return{item:mode==="cluster"?nextRepresentative:focusedItem,mode,snapshot}}scheduleClusterFocusRepair(repair){const generation=++this.focusRepairGeneration;repair&&repair.item.updateComplete.then(()=>{if(generation!==this.focusRepairGeneration||!this.isConnected)return;const base=this.renderRoot.querySelector('[part="base"]'),target=repair.mode==="cluster"?repair.item.shadowRoot?.querySelector('[part="cluster"]')??null:collectComposedFocusTargets(repair.item).elements[0]??base;try{applyComposedFocusRepair(repair.snapshot,target)}catch{}})}applyCollisionClusters(clusters){const frozen=Object.freeze(clusters.map(cluster=>Object.freeze({offset:cluster.offset,items:Object.freeze([...cluster.items])}))),changed=!this.sameClusters(this.collisionClusters,frozen),focusRepair=changed?this.captureClusterFocusRepair(frozen):void 0,representatives=new Set(frozen.map(cluster=>cluster.items[0])),hiddenItems=new Set(frozen.flatMap(cluster=>cluster.items.filter(item=>!representatives.has(item))));for(const item of this.managedClusterHiddenItems){if(hiddenItems.has(item)){item.hasAttribute(CLUSTER_HIDDEN_ATTRIBUTE)||item.setAttribute(CLUSTER_HIDDEN_ATTRIBUTE,"");continue}item.getAttribute(CLUSTER_HIDDEN_ATTRIBUTE)===""&&item.removeAttribute(CLUSTER_HIDDEN_ATTRIBUTE),this.managedClusterHiddenItems.delete(item)}for(const item of hiddenItems)this.managedClusterHiddenItems.has(item)||item.hasAttribute(CLUSTER_HIDDEN_ATTRIBUTE)||(item.setAttribute(CLUSTER_HIDDEN_ATTRIBUTE,""),this.managedClusterHiddenItems.add(item));if(changed){this.restoreClusterPresentation();for(const cluster of frozen){const representative=cluster.items[0];this.clusterActivations.set(representative,()=>this.activateCluster(cluster.items)),this.managedClusterRepresentatives.add(representative)}this.collisionClusters=frozen,this.syncClusterPresentations(frozen),this.scheduleClusterFocusRepair(focusRepair)}for(const cluster of frozen)cluster.items[0].style.setProperty("--_lr-timeline-item-offset",`${cluster.offset*100}%`)}syncClusterPresentations(clusters){for(const cluster of clusters){const representative=cluster.items[0],activate=this.clusterActivations.get(representative);if(!activate)continue;const countText=getNumberFormat(this.effectiveLocale).format(cluster.items.length);isTimelineClusterItemContract(representative)&&representative[SET_TIMELINE_CLUSTER_PRESENTATION]({accessibleLabel:this.localize("timelineClusterCount",void 0,{count:countText}),countText,activate})}}restoreClusterPresentation(){for(const item of this.managedClusterRepresentatives)isTimelineClusterItemContract(item)&&item[SET_TIMELINE_CLUSTER_PRESENTATION](void 0);this.managedClusterRepresentatives.clear(),this.clusterActivations.clear()}restoreClusterVisibility(){for(const item of this.managedClusterHiddenItems)item.getAttribute(CLUSTER_HIDDEN_ATTRIBUTE)===""&&item.removeAttribute(CLUSTER_HIDDEN_ATTRIBUTE);this.managedClusterHiddenItems.clear()}activateCluster(items){const snapshot=this.ownerDocument.defaultView?.Array.from(items)??[...items];this.emit("lr-cluster-activate",Object.freeze({items:Object.freeze(snapshot)}))}render(){const label=this.accessibleLabel==null?this.localize("timeline"):this.accessibleLabel;return this.ordered?html`
2
+ <ol part="base" role="list" tabindex="-1" aria-label=${label}>
3
+ <slot @slotchange=${this.onSlotChange}></slot>
4
+ </ol>
5
+ `:html`
6
+ <div part="base" role="list" tabindex="-1" aria-label=${label}>
7
+ <slot @slotchange=${this.onSlotChange}></slot>
8
+ </div>
9
+ `}}__decorate([property({reflect:!0,converter:TIMELINE_ORIENTATION})],LyraTimeline.prototype,"orientation",null),__decorate([property({reflect:!0,converter:TIMELINE_SCALE})],LyraTimeline.prototype,"scale",null),__decorate([property({reflect:!0,converter:TIMELINE_COLLISION})],LyraTimeline.prototype,"collision",null),__decorate([property({type:Boolean,reflect:!0})],LyraTimeline.prototype,"ordered",void 0),__decorate([property({type:Number})],LyraTimeline.prototype,"start",void 0),__decorate([property({attribute:!1,hasChanged:timeValueChanged})],LyraTimeline.prototype,"rangeStart",void 0),__decorate([property({attribute:!1,hasChanged:timeValueChanged})],LyraTimeline.prototype,"rangeEnd",void 0),__decorate([property({attribute:"aria-label"})],LyraTimeline.prototype,"accessibleLabel",void 0),__decorate([state()],LyraTimeline.prototype,"slottedCount",void 0),__decorate([state()],LyraTimeline.prototype,"collisionClusters",void 0);export{LyraTimeline};
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{deepActiveElementIn}from"../../../internal/active-element.js";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AccessibleTextController}from"../../../internal/accessible-text-controller.js";import{tag}from"../../../internal/prefix.js";import{hasRealContent,isAccessibilityVisible,nextId}from"../../../internal/a11y.js";import{composedAccessibilityText}from"../../../internal/accessibility-visibility.js";import{chevronIcon}from"../../../internal/icons.js";import{parseCssTimeToken}from"../../../internal/css-motion-time.js";import{finiteDuration}from"../../../internal/numbers.js";import{setCustomState}from"../../../internal/custom-states.js";import{attachInternalsSafely}from"../../../internal/element-internals.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{cascadeUpdateComplete}from"./update-cascade.js";import{styles}from"./tree-item.styles.js";import{fromInteractiveDescendant,treeItemMotionPreference,treeItemOwnerContext}from"./tree-owner-controller.js";import{TREE_MAX_RENDER_DEPTH}from"./tree-types.js";const CHILDREN_SLOT="children",TREE_ITEM_EXPORT_PARTS=["base","tree-item","row","toggle","icon","content","label","description","badge","group","item","item--disabled","item--expanded","item--indeterminate","item--selected","indentation","expand-button","spinner","spinner__base","children","checkbox","checkbox__base","checkbox__control","checkbox__control--checked","checkbox__control--indeterminate","checkbox__checked-icon","checkbox__indeterminate-icon","checkbox__label"].join(", ");class LyraTreeItem extends LyraElement{constructor(){super(...arguments),this.itemInternals=attachInternalsSafely(this),this.managedItemAriaLabel=null,this.writingItemAriaLabel=!1,this.label="",this.disabled=!1,this.selected=!1,this.expanded=!1,this.lazy=!1,this._loading=!1,this.lifecycleGeneration=0,this.lazyGeneration=0,this._collapsing=!1,this.labelTextObserver=new AccessibleTextController(this,[],()=>{this.assignChildSlots(),this.requestUpdate(),this._loading&&this.actualChildItems().length>0&&this.finishLazyLoad(this.lazyGeneration)},["slot"]),this.handleLabelSlotChange=event=>{const target=event.target;target?.nodeType!==1||target.localName!=="slot"||target.getRootNode()!==this.renderRoot&&!this.labelForwardingSlots().includes(target)||(this.labelTextObserver.bind(),this.requestUpdate())},this.slottedLabel=!1,this.slottedChildren=!1,this.onOwnedFocus=event=>{event.composedPath()[0]===this&&deepActiveElementIn(this.ownerDocument)===this&&this.ownerContext.focusOwner?.(this)},this.onToggleMouseDown=e=>{e.preventDefault(),!this.isDisabled&&this.focus()},this.onTogglePointerDown=event=>{const toggle=event.currentTarget;toggle?.nodeType===1&&(toggle.setAttribute("data-pressed",""),toggle.setPointerCapture(event.pointerId))},this.onTogglePointerEnd=event=>{const toggle=event.currentTarget;toggle?.nodeType===1&&(toggle.removeAttribute("data-pressed"),toggle.hasPointerCapture(event.pointerId)&&toggle.releasePointerCapture(event.pointerId))},this.onRowClick=event=>{const row=event.currentTarget;fromInteractiveDescendant(event,target=>target===row)||this.select()}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-expand","lr-after-expand","lr-collapse","lr-after-collapse","lr-lazy-change","lr-lazy-load"])}static{this.identityEventDetailProperties=Object.freeze({"lr-expand":Object.freeze(["item"]),"lr-after-expand":Object.freeze(["item"]),"lr-collapse":Object.freeze(["item"]),"lr-after-collapse":Object.freeze(["item"]),"lr-lazy-change":Object.freeze(["item"]),"lr-lazy-load":Object.freeze(["item"])})}static{this.styles=[LyraElement.styles,styles]}attributeChangedCallback(name,oldValue,value){super.attributeChangedCallback(name,oldValue,value),name==="aria-label"&&!this.writingItemAriaLabel&&(this.managedItemAriaLabel=null)}get item(){return this._item}set item(value){const old=this._item;if(old===value)return;this._item=value,this.labelTextObserver.setEnabled(!value),(value?.selected!==void 0||old?.id!==value?.id)&&(this.selected=!!value?.selected),this.lazy=!!value?.lazy;const hasResolvedChildren=!!value?.children?.length;this._loading&&(hasResolvedChildren||!this.lazy)&&this.finishLazyLoad(this.lazyGeneration,hasResolvedChildren),this.requestUpdate("item",old)}get loading(){return this._loading}get indeterminate(){return this.ownerContext.indeterminate}get ownerContext(){return treeItemOwnerContext(this)}get nodeId(){return this.item?this.item.id:this.generatedId??=nextId("tree-item")}get isDisabled(){return this.item?!!(this.item.disabled||this.hasDuplicateDataId):this.disabled}get hasDuplicateDataId(){const context=this.ownerContext.identity,item=this.item;return!!(context&&item&&context.collisionIds.has(item.id)&&context.ownerPaths.get(item.id)!==context.path)}get nodeLabel(){const ariaLabel=this.getAttribute("aria-label");return ariaLabel!==null?ariaLabel:this.item?this.item.accessibleLabel||this.item.label:this.slottedLabelText||this.label}syncItemAriaLabel(){const current=this.getAttribute("aria-label");if(this.managedItemAriaLabel===null&&current!==null)return;const item=this.item;let next=item?.accessibleLabel||null;if(item&&!this.hasAttribute("aria-labelledby")&&!next?.trim()&&!item.label.trim()&&!item.description?.trim()&&!item.badges?.some(badge=>badge.label?.trim()||badge.text.trim())&&(next=item.id),next===null){if(this.managedItemAriaLabel!==null&&current===this.managedItemAriaLabel){this.writingItemAriaLabel=!0;try{this.removeAttribute("aria-label")}finally{this.writingItemAriaLabel=!1}}this.managedItemAriaLabel=null;return}if(current!==next){this.writingItemAriaLabel=!0;try{this.setAttribute("aria-label",next)}finally{this.writingItemAriaLabel=!1}}this.managedItemAriaLabel=next}childItems(){return this.item?[...this.shadowRoot?.querySelectorAll(tag("tree-item"))??[]]:[...this.children].filter(child=>this.isChildItem(child))}getChildrenItems({includeDisabled=!0}={}){const children=this.childItems();return includeDisabled?children:children.filter(child=>!child.isDisabled)}isChildItem(node){return node.nodeType===1&&node.localName===tag("tree-item")}isDeclarativeLabelNode(node){if(this.isChildItem(node))return!1;if(node.nodeType!==1)return!0;const slotName=node.getAttribute("slot");return slotName===null||slotName===""}labelForwardingSlots(){return Array.from(this.querySelectorAll("slot")).filter(slot=>{let top=slot;for(;top.parentNode&&top.parentNode!==this;)top=top.parentNode;return top.parentNode===this&&this.isDeclarativeLabelNode(top)})}get slottedLabelText(){return composedAccessibilityText(this.declarativeLabelRoots(),{requireRendered:!1,shouldPruneNode:node=>{if(this.contains(node))return!1;const target=node.nodeType===1?node:node.parentElement;return target===null||!isAccessibilityVisible(target)},skipRootAncestorValidation:!0}).replace(/\s+/g," ").trim()}declarativeLabelRoots(){const childNodes=this.childNodes;return childNodes?Array.from(childNodes).filter(node=>this.isDeclarativeLabelNode(node)):[]}declarativeLabelNodes(){const renderRoot=this.renderRoot;if(!renderRoot)return[];const slot=renderRoot.querySelector("slot:not([name])");return slot?slot.assignedNodes({flatten:!0}):this.declarativeLabelRoots().flatMap(node=>{if(node.nodeType!==1||node.localName!=="slot")return[node];const forwardingSlot=node;return forwardingSlot.assignedNodes().length>0?forwardingSlot.assignedNodes({flatten:!0}):Array.from(forwardingSlot.childNodes)})}get hasSlottedLabel(){return hasRealContent(this.declarativeLabelNodes())}assignChildSlots(){for(const child of this.children)this.isChildItem(child)&&child.getAttribute("slot")!==CHILDREN_SLOT&&child.setAttribute("slot",CHILDREN_SLOT)}sampleLightDomState(){this.slottedLabel=this.hasSlottedLabel,this.slottedChildren=!this.item&&this.hasChildren}connectedCallback(){super.connectedCallback(),this.assignChildSlots(),this.hasUpdated&&this.sampleLightDomState(),this.addEventListener("slotchange",this.handleLabelSlotChange),this.addEventListener("focusin",this.onOwnedFocus)}disconnectedCallback(){this.removeEventListener("slotchange",this.handleLabelSlotChange),this.removeEventListener("focusin",this.onOwnedFocus),this.lifecycleGeneration++,this.lazyGeneration++,this.cancelLifecycleTimer(),this._loading=!1,this.lazy&&(this.expanded=!1),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.labelTextObserver.adopted()}actualChildItems(){return this.childItems()}get hasChildren(){const context=this.ownerContext;return context.depth>=TREE_MAX_RENDER_DEPTH?!1:this.item?!!(this.lazy||this.item.children?.length&&!context.ancestry.includes(this.item)):this.lazy||this.childItems().length>0}willUpdate(changed){super.willUpdate(changed),this.hasUpdated&&changed.size>0&&[...changed.keys()].every(key=>key==="selected"||key==="expanded"||key==="disabled"||key==="_loading"||key==="_collapsing")&&this.labelTextObserver.preserveBindingForNextUpdate(),this.assignChildSlots(),this.hasUpdated?this.sampleLightDomState():this.seedFirstRenderState(()=>this.sampleLightDomState()),(changed.has("item")||changed.has("disabled"))&&this.isDisabled&&this.expanded&&(this.expanded=!1),(changed.has("item")||changed.has("disabled"))&&this.isDisabled&&this._loading&&this.cancelLazyLoad(!0),changed.has("lazy")&&this._loading&&!this.lazy&&this.finishLazyLoad(this.lazyGeneration,this.actualChildItems().length>0),this.setAttribute("role","treeitem");const context=this.ownerContext;this.setAttribute("aria-level",String(context.depth+1)),this.setAttribute("aria-setsize",String(context.setSize)),this.setAttribute("aria-posinset",String(context.posInSet)),this.hasChildren?this.setAttribute("aria-expanded",String(this.expanded)):this.removeAttribute("aria-expanded"),this.syncItemAriaLabel(),this.multipleSelection?(this.setAttribute("aria-checked",context.indeterminate?"mixed":String(this.selected)),this.removeAttribute("aria-selected")):(this.removeAttribute("aria-checked"),context.ownsSelection||!this.item||this.item.selected!==void 0?this.setAttribute("aria-selected",String(this.selected)):this.removeAttribute("aria-selected")),this.setAttribute("aria-disabled",String(this.isDisabled)),this._loading?this.setAttribute("aria-busy","true"):this.removeAttribute("aria-busy"),this.tabIndex=!this.isDisabled&&this.nodeId===(context.activeNodeId?context.activeNodeId():context.activeId)?0:-1,setCustomState(this.itemInternals,"disabled",this.isDisabled),setCustomState(this.itemInternals,"expanded",this.expanded),setCustomState(this.itemInternals,"indeterminate",context.indeterminate),setCustomState(this.itemInternals,"selected",this.selected)}updated(changed){super.updated(changed),(changed.has("expanded")||changed.has("item"))&&this.ownerContext.syncOwner?.()}expand(){if(!(this.isDisabled||this._loading||this.expanded)){if(this.lazy){this.beginLazyLoad();return}this.hasChildren&&this.commitExpanded(!0)}}commitExpanded(expanded){this.expanded!==expanded&&(this.lifecycleGeneration++,this.cancelLifecycleTimer(),this._collapsing=!expanded,this.expanded=expanded,this.emit(expanded?"lr-expand":"lr-collapse",{item:this}),this.emit("lr-node-toggle",{nodeId:this.nodeId,expanded}),this.scheduleAfterEvent(expanded,this.lifecycleGeneration))}beginLazyLoad(){if(this._loading||this.isDisabled)return;this._loading=!0;const generation=++this.lazyGeneration;this.emit("lr-lazy-change",{item:this,loading:!0}),this.emit("lr-lazy-load",{item:this,generation})}finishLazyLoad(generation,hasResolvedChildren=this.actualChildItems().length>0){!this._loading||generation!==this.lazyGeneration||(this._loading=!1,this.emit("lr-lazy-change",{item:this,loading:!1}),!(!this.isConnected||this.isDisabled||!hasResolvedChildren)&&this.commitExpanded(!0))}cancelLazyLoad(emitChange){this._loading&&(this.lazyGeneration++,this._loading=!1,emitChange&&this.emit("lr-lazy-change",{item:this,loading:!1}))}scheduleAfterEvent(expanded,generation){const owner=this.ownerDocument.defaultView;if(!owner)return;const reducedMotion=treeItemMotionPreference(this);this.updateComplete.then(()=>{if(generation!==this.lifecycleGeneration||!this.isConnected||this.expanded!==expanded||this.ownerDocument.defaultView!==owner)return;const animationNode=this.renderRoot.querySelector('[part="children"]'),duration=this.motionDuration(expanded,owner,reducedMotion),finish=()=>{if(this.cancelLifecycleTimer(),!(generation!==this.lifecycleGeneration||!this.isConnected||this.expanded!==expanded||this.ownerDocument.defaultView!==owner)){if(!expanded&&this._collapsing){this._collapsing=!1,this.updateComplete.then(()=>{generation===this.lifecycleGeneration&&this.isConnected&&!this.expanded&&!this._collapsing&&this.ownerDocument.defaultView===owner&&this.emit("lr-after-collapse",{item:this})});return}this.emit("lr-after-expand",{item:this})}},computedAnimation=animationNode&&duration>0?owner.getComputedStyle(animationNode).animationName:"none";if(!animationNode||duration===0||computedAnimation==="none"){finish();return}const listener=event=>{event.target===animationNode&&finish()};animationNode.addEventListener("animationend",listener),this.lifecycleAnimation={node:animationNode,listener};const timer={owner,handle:0};timer.handle=owner.setTimeout(finish,duration),this.lifecycleTimer=timer})}cancelLifecycleTimer(){const animation=this.lifecycleAnimation;animation&&(this.lifecycleAnimation=void 0,animation.node.removeEventListener("animationend",animation.listener));const timer=this.lifecycleTimer;timer&&(this.lifecycleTimer=void 0,timer.owner.clearTimeout(timer.handle))}motionDuration(expanded,owner,reduced=prefersReducedMotion(this)){if(reduced)return 0;const property2=expanded?"--show-duration":"--hide-duration",ownStyle=owner.getComputedStyle(this),raw=ownStyle.getPropertyValue(property2).trim()||ownStyle.getPropertyValue("--lr-duration-base").trim();return finiteDuration(parseCssTimeToken(raw)?.ms??0,0)}collapse(){this.isDisabled||!this.hasChildren||!this.expanded||this.commitExpanded(!1)}select(){this.isDisabled||(this.emit("lr-node-select",{nodeId:this.nodeId}),this.focus())}click(){if(this.isDisabled)return;const row=this.renderRoot.querySelector('[part="row"]');row?row.click():this.select()}async getUpdateComplete(){const result=await super.getUpdateComplete(),context=this.ownerContext;return context.ownsSelection&&context.depth<TREE_MAX_RENDER_DEPTH&&await cascadeUpdateComplete(this.childItems()),result}get multipleSelection(){const selection=this.ownerContext.selection;return selection==="multiple"||selection==="leaf-multiple"}itemPartNames(){return["item",this.isDisabled?"item--disabled":"",this.expanded?"item--expanded":"",this.indeterminate?"item--indeterminate":"",this.selected?"item--selected":""].filter(Boolean).join(" ")}inheritedIcon(source){if(!source)return nothing;const clone=source.cloneNode(!0);return clone.removeAttribute("slot"),clone.removeAttribute("id"),clone.setAttribute("aria-hidden","true"),clone}renderDisclosureIcon(){const slotName=this.expanded?"expand-icon":"collapse-icon",context=this.ownerContext,inherited=this.inheritedIcon(this.expanded?context.expandIcon:context.collapseIcon);return html`<slot name=${slotName}>${inherited===nothing?chevronIcon():inherited}</slot>`}renderSpinner(){return html`<span part="spinner" aria-hidden="true"><span part="spinner__base"></span></span>`}renderCheckbox(){if(!this.multipleSelection)return nothing;const controlParts=["checkbox__control",this.selected?"checkbox__control--checked":"",this.indeterminate?"checkbox__control--indeterminate":""].filter(Boolean).join(" ");return html`
1
+ import{__decorate}from"tslib";import{deepActiveElementIn}from"../../../internal/active-element.js";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AccessibleTextController}from"../../../internal/accessible-text-controller.js";import{tag}from"../../../internal/prefix.js";import{hasRealContent,isAccessibilityVisible,nextId}from"../../../internal/a11y.js";import{composedAccessibilityText}from"../../../internal/accessibility-visibility.js";import{chevronIcon}from"../../../internal/icons.js";import{parseCssTimeToken}from"../../../internal/css-motion-time.js";import{finiteDuration}from"../../../internal/numbers.js";import{setCustomState}from"../../../internal/custom-states.js";import{attachInternalsSafely}from"../../../internal/element-internals.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{cascadeUpdateComplete}from"./update-cascade.js";import{styles}from"./tree-item.styles.js";import{fromInteractiveDescendant,treeItemMotionPreference,treeItemOwnerContext}from"./tree-owner-controller.js";import{TREE_MAX_RENDER_DEPTH}from"./tree-types.js";const CHILDREN_SLOT="children",TREE_ITEM_EXPORT_PARTS=["base","tree-item","row","toggle","icon","content","label","description","badge","group","item","item--disabled","item--expanded","item--indeterminate","item--selected","indentation","expand-button","spinner","spinner__base","children","checkbox","checkbox__base","checkbox__control","checkbox__control--checked","checkbox__control--indeterminate","checkbox__checked-icon","checkbox__indeterminate-icon","checkbox__label"].join(", ");class LyraTreeItem extends LyraElement{constructor(){super(...arguments),this.itemInternals=attachInternalsSafely(this),this.managedItemAriaLabel=null,this.writingItemAriaLabel=!1,this.label="",this.disabled=!1,this.selected=!1,this.expanded=!1,this.lazy=!1,this._loading=!1,this.lifecycleGeneration=0,this.lazyGeneration=0,this._collapsing=!1,this.labelTextObserver=new AccessibleTextController(this,[],()=>{this.assignChildSlots(),this.requestUpdate(),this._loading&&this.actualChildItems().length>0&&this.finishLazyLoad(this.lazyGeneration)},["slot"]),this.handleLabelSlotChange=event=>{const target=event.target;target?.nodeType!==1||target.localName!=="slot"||target.getRootNode()!==this.renderRoot&&!this.labelForwardingSlots().includes(target)||(this.labelTextObserver.bind(),this.requestUpdate())},this.slottedLabel=!1,this.slottedChildren=!1,this.onOwnedFocus=event=>{event.composedPath()[0]===this&&deepActiveElementIn(this.ownerDocument)===this&&this.ownerContext.focusOwner?.(this)},this.onToggleMouseDown=e=>{e.preventDefault(),!this.isDisabled&&this.focus()},this.onTogglePointerDown=event=>{const toggle=event.currentTarget;toggle?.nodeType===1&&(toggle.setAttribute("data-pressed",""),toggle.setPointerCapture(event.pointerId))},this.onTogglePointerEnd=event=>{const toggle=event.currentTarget;toggle?.nodeType===1&&(toggle.removeAttribute("data-pressed"),toggle.hasPointerCapture(event.pointerId)&&toggle.releasePointerCapture(event.pointerId))},this.onRowClick=event=>{const row=event.currentTarget;fromInteractiveDescendant(event,target=>target===row)||this.select()}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-expand","lr-after-expand","lr-collapse","lr-after-collapse","lr-lazy-change","lr-lazy-load"])}static{this.identityEventDetailProperties=Object.freeze({"lr-expand":Object.freeze(["item"]),"lr-after-expand":Object.freeze(["item"]),"lr-collapse":Object.freeze(["item"]),"lr-after-collapse":Object.freeze(["item"]),"lr-lazy-change":Object.freeze(["item"]),"lr-lazy-load":Object.freeze(["item"])})}static{this.styles=[LyraElement.styles,styles]}attributeChangedCallback(name,oldValue,value){super.attributeChangedCallback(name,oldValue,value),name==="aria-label"&&!this.writingItemAriaLabel&&(this.managedItemAriaLabel=null)}get item(){return this._item}set item(value){const old=this._item;if(old===value)return;this._item=value,this.labelTextObserver.setEnabled(!value),(value?.selected!==void 0||old?.id!==value?.id)&&(this.selected=!!value?.selected),this.lazy=!!value?.lazy;const hasResolvedChildren=!!value?.children?.length;this._loading&&(hasResolvedChildren||!this.lazy)&&this.finishLazyLoad(this.lazyGeneration,hasResolvedChildren),this.requestUpdate("item",old)}get loading(){return this._loading}get indeterminate(){return this.ownerContext.indeterminate}get ownerContext(){return treeItemOwnerContext(this)}get nodeId(){return this.item?this.item.id:this.generatedId??=nextId("tree-item")}get isDisabled(){return this.item?!!(this.item.disabled||this.hasDuplicateDataId):this.disabled}get hasDuplicateDataId(){const context=this.ownerContext.identity,item=this.item;return!!(context&&item&&context.collisionIds.has(item.id)&&context.ownerPaths.get(item.id)!==context.path)}get nodeLabel(){const ariaLabel=this.getAttribute("aria-label");return ariaLabel!==null?ariaLabel:this.item?this.item.accessibleLabel||this.item.label:this.slottedLabelText||this.label}syncItemAriaLabel(){const current=this.getAttribute("aria-label");if(this.managedItemAriaLabel===null&&current!==null)return;const item=this.item;let next=item?.accessibleLabel||null;if(item&&!this.hasAttribute("aria-labelledby")&&!next?.trim()&&!item.label.trim()&&!item.description?.trim()&&!item.badges?.some(badge=>badge.label?.trim()||badge.text.trim())&&(next=item.id),next===null){if(this.managedItemAriaLabel!==null&&current===this.managedItemAriaLabel){this.writingItemAriaLabel=!0;try{this.removeAttribute("aria-label")}finally{this.writingItemAriaLabel=!1}}this.managedItemAriaLabel=null;return}if(current!==next){this.writingItemAriaLabel=!0;try{this.setAttribute("aria-label",next)}finally{this.writingItemAriaLabel=!1}}this.managedItemAriaLabel=next}childItems(){return this.item?[...this.shadowRoot?.querySelectorAll(tag("tree-item"))??[]]:[...this.children].filter(child=>this.isChildItem(child))}getChildrenItems({includeDisabled=!0}={}){const children=this.childItems();return includeDisabled?children:children.filter(child=>!child.isDisabled)}isChildItem(node){return node.nodeType===1&&node.localName===tag("tree-item")}isDeclarativeLabelNode(node){if(this.isChildItem(node))return!1;if(node.nodeType!==1)return!0;const slotName=node.getAttribute("slot");return slotName===null||slotName===""}labelForwardingSlots(){return Array.from(this.querySelectorAll("slot")).filter(slot=>{let top=slot;for(;top.parentNode&&top.parentNode!==this;)top=top.parentNode;return top.parentNode===this&&this.isDeclarativeLabelNode(top)})}get slottedLabelText(){return composedAccessibilityText(this.declarativeLabelRoots(),{requireRendered:!1,shouldPruneNode:node=>{if(this.contains(node))return!1;const target=node.nodeType===1?node:node.parentElement;return target===null||!isAccessibilityVisible(target)},skipRootAncestorValidation:!0}).replace(/\s+/g," ").trim()}declarativeLabelRoots(){const childNodes=this.childNodes;return childNodes?Array.from(childNodes).filter(node=>this.isDeclarativeLabelNode(node)):[]}declarativeLabelNodes(){const renderRoot=this.renderRoot;if(!renderRoot)return[];const slot=renderRoot.querySelector("slot:not([name])");return slot?slot.assignedNodes({flatten:!0}):this.declarativeLabelRoots().flatMap(node=>{if(node.nodeType!==1||node.localName!=="slot")return[node];const forwardingSlot=node;return forwardingSlot.assignedNodes().length>0?forwardingSlot.assignedNodes({flatten:!0}):Array.from(forwardingSlot.childNodes)})}get hasSlottedLabel(){return hasRealContent(this.declarativeLabelNodes())}assignChildSlots(){for(const child of this.children)this.isChildItem(child)&&child.getAttribute("slot")!==CHILDREN_SLOT&&child.setAttribute("slot",CHILDREN_SLOT)}sampleLightDomState(){this.slottedLabel=this.hasSlottedLabel,this.slottedChildren=!this.item&&this.hasChildren}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.sampleLightDomState(),this.addEventListener("slotchange",this.handleLabelSlotChange),this.addEventListener("focusin",this.onOwnedFocus)}disconnectedCallback(){this.removeEventListener("slotchange",this.handleLabelSlotChange),this.removeEventListener("focusin",this.onOwnedFocus),this.lifecycleGeneration++,this.lazyGeneration++,this.cancelLifecycleTimer(),this._loading=!1,this.lazy&&(this.expanded=!1),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.labelTextObserver.adopted()}actualChildItems(){return this.childItems()}get hasChildren(){const context=this.ownerContext;return context.depth>=TREE_MAX_RENDER_DEPTH?!1:this.item?!!(this.lazy||this.item.children?.length&&!context.ancestry.includes(this.item)):this.lazy||this.childItems().length>0}willUpdate(changed){super.willUpdate(changed),this.hasUpdated&&changed.size>0&&[...changed.keys()].every(key=>key==="selected"||key==="expanded"||key==="disabled"||key==="_loading"||key==="_collapsing")&&this.labelTextObserver.preserveBindingForNextUpdate(),this.assignChildSlots(),this.hasUpdated?this.sampleLightDomState():this.seedFirstRenderState(()=>this.sampleLightDomState()),(changed.has("item")||changed.has("disabled"))&&this.isDisabled&&this.expanded&&(this.expanded=!1),(changed.has("item")||changed.has("disabled"))&&this.isDisabled&&this._loading&&this.cancelLazyLoad(!0),changed.has("lazy")&&this._loading&&!this.lazy&&this.finishLazyLoad(this.lazyGeneration,this.actualChildItems().length>0),this.setAttribute("role","treeitem");const context=this.ownerContext;this.setAttribute("aria-level",String(context.depth+1)),this.setAttribute("aria-setsize",String(context.setSize)),this.setAttribute("aria-posinset",String(context.posInSet)),this.hasChildren?this.setAttribute("aria-expanded",String(this.expanded)):this.removeAttribute("aria-expanded"),this.syncItemAriaLabel(),this.multipleSelection?(this.setAttribute("aria-checked",context.indeterminate?"mixed":String(this.selected)),this.removeAttribute("aria-selected")):(this.removeAttribute("aria-checked"),context.ownsSelection||!this.item||this.item.selected!==void 0?this.setAttribute("aria-selected",String(this.selected)):this.removeAttribute("aria-selected")),this.setAttribute("aria-disabled",String(this.isDisabled)),this._loading?this.setAttribute("aria-busy","true"):this.removeAttribute("aria-busy"),this.tabIndex=!this.isDisabled&&this.nodeId===(context.activeNodeId?context.activeNodeId():context.activeId)?0:-1,setCustomState(this.itemInternals,"disabled",this.isDisabled),setCustomState(this.itemInternals,"expanded",this.expanded),setCustomState(this.itemInternals,"indeterminate",context.indeterminate),setCustomState(this.itemInternals,"selected",this.selected)}updated(changed){super.updated(changed),(changed.has("expanded")||changed.has("item"))&&this.ownerContext.syncOwner?.()}expand(){if(!(this.isDisabled||this._loading||this.expanded)){if(this.lazy){this.beginLazyLoad();return}this.hasChildren&&this.commitExpanded(!0)}}commitExpanded(expanded){this.expanded!==expanded&&(this.lifecycleGeneration++,this.cancelLifecycleTimer(),this._collapsing=!expanded,this.expanded=expanded,this.emit(expanded?"lr-expand":"lr-collapse",{item:this}),this.emit("lr-node-toggle",{nodeId:this.nodeId,expanded}),this.scheduleAfterEvent(expanded,this.lifecycleGeneration))}beginLazyLoad(){if(this._loading||this.isDisabled)return;this._loading=!0;const generation=++this.lazyGeneration;this.emit("lr-lazy-change",{item:this,loading:!0}),this.emit("lr-lazy-load",{item:this,generation})}finishLazyLoad(generation,hasResolvedChildren=this.actualChildItems().length>0){!this._loading||generation!==this.lazyGeneration||(this._loading=!1,this.emit("lr-lazy-change",{item:this,loading:!1}),!(!this.isConnected||this.isDisabled||!hasResolvedChildren)&&this.commitExpanded(!0))}cancelLazyLoad(emitChange){this._loading&&(this.lazyGeneration++,this._loading=!1,emitChange&&this.emit("lr-lazy-change",{item:this,loading:!1}))}scheduleAfterEvent(expanded,generation){const owner=this.ownerDocument.defaultView;if(!owner)return;const reducedMotion=treeItemMotionPreference(this);this.updateComplete.then(()=>{if(generation!==this.lifecycleGeneration||!this.isConnected||this.expanded!==expanded||this.ownerDocument.defaultView!==owner)return;const animationNode=this.renderRoot.querySelector('[part="children"]'),duration=this.motionDuration(expanded,owner,reducedMotion),finish=()=>{if(this.cancelLifecycleTimer(),!(generation!==this.lifecycleGeneration||!this.isConnected||this.expanded!==expanded||this.ownerDocument.defaultView!==owner)){if(!expanded&&this._collapsing){this._collapsing=!1,this.updateComplete.then(()=>{generation===this.lifecycleGeneration&&this.isConnected&&!this.expanded&&!this._collapsing&&this.ownerDocument.defaultView===owner&&this.emit("lr-after-collapse",{item:this})});return}this.emit("lr-after-expand",{item:this})}},computedAnimation=animationNode&&duration>0?owner.getComputedStyle(animationNode).animationName:"none";if(!animationNode||duration===0||computedAnimation==="none"){finish();return}const listener=event=>{event.target===animationNode&&finish()};animationNode.addEventListener("animationend",listener),this.lifecycleAnimation={node:animationNode,listener};const timer={owner,handle:0};timer.handle=owner.setTimeout(finish,duration),this.lifecycleTimer=timer})}cancelLifecycleTimer(){const animation=this.lifecycleAnimation;animation&&(this.lifecycleAnimation=void 0,animation.node.removeEventListener("animationend",animation.listener));const timer=this.lifecycleTimer;timer&&(this.lifecycleTimer=void 0,timer.owner.clearTimeout(timer.handle))}motionDuration(expanded,owner,reduced=prefersReducedMotion(this)){if(reduced)return 0;const property2=expanded?"--show-duration":"--hide-duration",ownStyle=owner.getComputedStyle(this),raw=ownStyle.getPropertyValue(property2).trim()||ownStyle.getPropertyValue("--lr-duration-base").trim();return finiteDuration(parseCssTimeToken(raw)?.ms??0,0)}collapse(){this.isDisabled||!this.hasChildren||!this.expanded||this.commitExpanded(!1)}select(){this.isDisabled||(this.emit("lr-node-select",{nodeId:this.nodeId}),this.focus())}click(){if(this.isDisabled)return;const row=this.renderRoot.querySelector('[part="row"]');row?row.click():this.select()}async getUpdateComplete(){const result=await super.getUpdateComplete(),context=this.ownerContext;return context.ownsSelection&&context.depth<TREE_MAX_RENDER_DEPTH&&await cascadeUpdateComplete(this.childItems()),result}get multipleSelection(){const selection=this.ownerContext.selection;return selection==="multiple"||selection==="leaf-multiple"}itemPartNames(){return["item",this.isDisabled?"item--disabled":"",this.expanded?"item--expanded":"",this.indeterminate?"item--indeterminate":"",this.selected?"item--selected":""].filter(Boolean).join(" ")}inheritedIcon(source){if(!source)return nothing;const clone=source.cloneNode(!0);return clone.removeAttribute("slot"),clone.removeAttribute("id"),clone.setAttribute("aria-hidden","true"),clone}renderDisclosureIcon(){const slotName=this.expanded?"expand-icon":"collapse-icon",context=this.ownerContext,inherited=this.inheritedIcon(this.expanded?context.expandIcon:context.collapseIcon);return html`<slot name=${slotName}>${inherited===nothing?chevronIcon():inherited}</slot>`}renderSpinner(){return html`<span part="spinner" aria-hidden="true"><span part="spinner__base"></span></span>`}renderCheckbox(){if(!this.multipleSelection)return nothing;const controlParts=["checkbox__control",this.selected?"checkbox__control--checked":"",this.indeterminate?"checkbox__control--indeterminate":""].filter(Boolean).join(" ");return html`
2
2
  <span
3
3
  part="checkbox"
4
4
  aria-hidden="true"
@@ -80,6 +80,8 @@ export type TreeSource=LyraHierarchySource<LyraTreeNodeData,LyraHierarchyQuery>;
80
80
  export declare class LyraTree extends LyraElement<LyraTreeEventMap>{protected static collectionSupport:import("../../../internal/lyra-element.js").LyraCollectionSupport;protected static readonly immutableEventDetails:readonly string[];protected static readonly identityEventDetailProperties:Readonly<{'lr-selection-change':readonly string[];}>;static styles:import("lit").CSSResultGroup[];private _treeSource;private sourceMode;private sourcePaintVersion;private sourceAnnouncement?;private readonly sourceAnnouncer;private readonly hierarchy;
81
81
  /** Immutable provider preorder. Wins over legacy inputs while defined; unset restores them.
82
82
  * At most 301 rows mount, with four 100-row pages and one focused row retained.
83
+ * Row names include label, description and badge text unless accessibleLabel overrides them;
84
+ * otherwise unnamed rows use their stable id.
83
85
  * Reassign or call requestUpdate() after changing the provider revision.
84
86
  * @default undefined */
85
87
  get treeSource():TreeSource|undefined;set treeSource(value:TreeSource|undefined);
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{HierarchySourceController,hierarchyField,hierarchyKey,hierarchyText}from"../../../internal/hierarchy-source-controller.js";import{hierarchySourceView}from"../../../internal/hierarchy-source-view.js";import{hierarchySourceStyles}from"../../../internal/hierarchy-source-view.styles.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{inheritedPreference,preferenceMediaMatches}from"../../../internal/preferences.js";import{finiteCount}from"../../../internal/numbers.js";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{tag}from"../../../internal/prefix.js";import{resolveListMove}from"../../../internal/list-navigation.js";import{styles}from"./tree.styles.js";import{cascadeUpdateComplete}from"./update-cascade.js";import{configureTreeItemOwner,withTreeItemMotionPreference,fromInteractiveDescendant,setTreeItemSelection,treeItemOwnerContext}from"./tree-owner-controller.js";import"./tree-item.class.js";import{TREE_MAX_RENDER_DEPTH,TREE_MAX_RENDER_NODES}from"./tree-types.js";import{composedParentElement,deepActiveElementIn}from"../../../internal/active-element.js";import{LYRA_DEFAULT_treeLimit}from"../../../internal/default-strings/data.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_expand,LYRA_DEFAULT_loading,LYRA_DEFAULT_noData,LYRA_DEFAULT_retry,LYRA_DEFAULT_treeNodeMoved,LYRA_DEFAULT_treeSourceError,LYRA_DEFAULT_treeSourceSummary}from"../../../internal/default-strings/shared.generated.js";const TREE_SELECTIONS=new Set(["single","multiple","leaf","leaf-multiple"]),TREE_BADGE_LIMIT=100,TREE_MAX_INSPECTED_POSITIONS=1e4,EMPTY_TREE_DATA=Object.freeze([]);function ownValue(record,key){try{const descriptor=Object.getOwnPropertyDescriptor(record,key);return descriptor&&"value"in descriptor?descriptor.value:void 0}catch{return}}function arrayLength(value){if(!Array.isArray(value))return 0;try{return Math.max(0,Math.min(Number.MAX_SAFE_INTEGER,Math.trunc(value.length)))}catch{return 0}}function normalizeBadges(value){if(!Array.isArray(value))return{truncated:value!==void 0};const badges=[],length=arrayLength(value);for(let index=0;index<Math.min(length,TREE_BADGE_LIMIT);index++){const raw=ownValue(value,String(index));if(!raw||typeof raw!="object"||Array.isArray(raw))continue;const text=ownValue(raw,"text");if(typeof text!="string")continue;const rawTone=ownValue(raw,"tone"),tone=rawTone==="brand"||rawTone==="success"||rawTone==="warning"||rawTone==="danger"?rawTone:"neutral",rawLabel=ownValue(raw,"label");badges.push(Object.freeze({text,tone,...typeof rawLabel=="string"?{label:rawLabel}:{}}))}return{badges:Object.freeze(badges),truncated:length>TREE_BADGE_LIMIT}}function sameIcon(left,right){if(Object.is(left,right))return!0;const a=left,b=right;if(!a||!b||typeof a!="object"||typeof b!="object"||a._$litType$===void 0||a._$litType$!==b._$litType$||a.strings!==b.strings)return!1;const leftValues=a.values??[],rightValues=b.values??[];return leftValues.length===rightValues.length&&leftValues.every((value,index)=>Object.is(value,rightValues[index]))}function sameBadges(left,right){return left===right?!0:!left||!right||left.length!==right.length?!1:left.every((badge,index)=>{const other=right[index];return badge.text===other.text&&badge.tone===other.tone&&badge.label===other.label})}function sameTreeNode(next,previous){if(next.id!==previous.id||next.label!==previous.label||next.selected!==previous.selected||next.disabled!==previous.disabled||next.lazy!==previous.lazy||next.description!==previous.description||next.accessibleLabel!==previous.accessibleLabel||!sameIcon(next.icon,previous.icon)||!sameBadges(next.badges,previous.badges))return!1;const children=next.children,previousChildren=previous.children;return!children||!previousChildren?children===void 0&&previousChildren===void 0:children.length===previousChildren.length&&children.every((child,index)=>child===previousChildren[index])}function indexTreeNodes(nodes){const byId=new Map,stack=[...nodes];for(;stack.length>0;){const node=stack.pop();byId.set(node.id,node),node.children&&stack.push(...node.children)}return byId}function normalizeTreeData(input,previous=EMPTY_TREE_DATA,limit=TREE_MAX_RENDER_NODES){if(!Array.isArray(input))return{data:EMPTY_TREE_DATA,declaredChildrenAtPath:new Map,declaredRootCount:0,truncated:input!=null,limitReached:!1};const root=[],declaredChildrenAtPath=new Map,created=[],rootLength=arrayLength(input);let truncated=!1,limitReached=!1,accepted=0,inspected=0;const seenIds=new Set,identityFilteredCollections=new Set,jobs=[{source:input,index:0,length:rootLength,target:root,parentPath:"",depth:0,ancestors:new Set}];for(;jobs.length>0;){const job=jobs[jobs.length-1];if(job.index>=job.length){jobs.pop();continue}if(accepted>=limit||inspected>=TREE_MAX_INSPECTED_POSITIONS){truncated=!0,limitReached=accepted>=limit;break}const raw=ownValue(job.source,String(job.index++));if(inspected++,inspected===TREE_MAX_INSPECTED_POSITIONS&&(truncated=!0),!raw||typeof raw!="object"||Array.isArray(raw)){truncated=!0,identityFilteredCollections.add(job.target);continue}const id=ownValue(raw,"id"),label=ownValue(raw,"label");if(typeof id!="string"||id.trim()===""||seenIds.has(id)||typeof label!="string"){truncated=!0,identityFilteredCollections.add(job.target);continue}seenIds.add(id);const node={id,label},selected=ownValue(raw,"selected"),disabled=ownValue(raw,"disabled"),lazy=ownValue(raw,"lazy");typeof selected=="boolean"&&(node.selected=selected),typeof disabled=="boolean"&&(node.disabled=disabled),typeof lazy=="boolean"&&(node.lazy=lazy);const icon=ownValue(raw,"icon");icon!==void 0&&(node.icon=icon);const description=ownValue(raw,"description");typeof description=="string"&&(node.description=description);const accessibleLabel=ownValue(raw,"accessibleLabel");typeof accessibleLabel=="string"&&(node.accessibleLabel=accessibleLabel);const normalizedBadges=normalizeBadges(ownValue(raw,"badges"));normalizedBadges.badges?.length&&(node.badges=normalizedBadges.badges),truncated||=normalizedBadges.truncated;const ownIndex=job.target.length,path=job.parentPath===""?String(ownIndex):`${job.parentPath}/${ownIndex}`;job.target.push(node),created.push(node),accepted++;const rawChildren=ownValue(raw,"children"),childCount=arrayLength(rawChildren);if(childCount===0)continue;if(declaredChildrenAtPath.set(path,childCount),job.depth>=TREE_MAX_RENDER_DEPTH||job.ancestors.has(raw)){truncated=!0;continue}const children=[];node.children=children;const ancestors=new Set(job.ancestors);ancestors.add(raw),jobs.push({source:rawChildren,index:0,length:childCount,target:children,parentPath:path,depth:job.depth+1,ancestors})}const previousById=previous.length>0?indexTreeNodes(previous):void 0,resolved=new Map,resolve=node=>resolved.get(node)??node;for(let index=created.length-1;index>=0;index--){const node=created[index];if(node.children){for(let child=0;child<node.children.length;child++)node.children[child]=resolve(node.children[child]);Object.freeze(node.children)}Object.freeze(node);const prior=previousById?.get(node.id);prior&&!(node.children&&identityFilteredCollections.has(node.children))&&sameTreeNode(node,prior)&&resolved.set(node,prior)}for(let index=0;index<root.length;index++)root[index]=resolve(root[index]);const normalizedJobs=root.map((node,index)=>({node,path:String(index)}));for(;normalizedJobs.length>0;){const{node,path}=normalizedJobs.pop(),children=node.children??[];identityFilteredCollections.has(children)&&declaredChildrenAtPath.set(path,children.length);for(let index=children.length-1;index>=0;index--)normalizedJobs.push({node:children[index],path:`${path}/${index}`})}return{data:Object.freeze(root),declaredChildrenAtPath,declaredRootCount:identityFilteredCollections.has(root)?root.length:rootLength,truncated,limitReached}}function isInertWithin(node,root){for(let current=node;current&&current!==root;current=current.parentElement)if(current.hasAttribute("inert"))return!0;return!1}class LyraTree extends LyraElement{constructor(){super(...arguments),this._treeSource=void 0,this.sourceMode=!1,this.sourcePaintVersion=0,this.sourceAnnouncer=new AnnouncementSinkController(this),this.hierarchy=new HierarchySourceController(this,{normalize:(value,key)=>this.normalizeSourceValue(value,key),onChange:()=>{const previous=this.sourcePaintVersion++;this.requestUpdate("sourcePaintVersion",previous)},accepted:(action,_row,state2)=>{action.type==="select"&&this.emit("lr-source-selection-change",Object.freeze({key:action.key,selected:action.selected,scope:action.scope,state:state2}))}}),this._data=EMPTY_TREE_DATA,this.lastDataInput=void 0,this.lastDataLimit=0,this.declaredChildrenAtPath=new Map,this.declaredRootCount=0,this._dataTruncated=!1,this._limitReached=!1,this.label="",this.maxNodes=1e3,this.reorderable=!1,this._selection="single",this._activeId=null,this.readActiveId=()=>this._activeId,this.hasAuthoredItems=!1,this.pendingFocusId=null,this.generatedNodes=new WeakSet,this.dataIdOwnerPaths=new Map,this.dataIdCollisions=new Set,this.selectionSyncPending=!0,this.dataSyncPending=!1,this.inertMutationPending=!1,this.dirtyConfigureRoots=new Set,this.lastFocusedNodeId=null,this.onTreeFocusIn=e=>{const path=e.composedPath(),owner=path.find(target=>target.localName===tag("tree"));if(owner&&owner!==this)return;const item=path.find(target=>target.nodeType===1&&target.localName===tag("tree-item"));item&&this.onItemFocus(item)},this.onItemFocus=element=>{const item=element;this.isNavigable(item)&&(this.lastFocusedNodeId=item.nodeId,this.setActiveNode(item))},this.contextSyncPending=!0,this.bulkExpansions=0,this.syncGeneration=0,this.syncRequested=!1,this.syncRunning=!1,this.requestContextSync=()=>{this.contextSyncPending=!0,this.scheduleTreeSync()},this.onChildrenChanged=()=>{if(this.treeSource!==void 0)return;const wasAuthored=this.hasAuthoredItems;this.refreshAuthoredItems(),wasAuthored&&!this.hasAuthoredItems&&(this.dataSyncPending=!0),this.selectionSyncPending=!0,this.requestUpdate()},this.childObserverGeneration=0,this.onChildMutations=allRecords=>{const records=allRecords.filter(record=>record.type!=="attributes"||record.oldValue!==null!==record.target.hasAttribute(record.attributeName??""));if(records.length!==0){if(records.some(record=>record.attributeName==="inert")&&(this.inertMutationPending=!0),records.every(record=>record.type==="attributes")){const itemTag=tag("tree-item");for(const record of records){const target=record.target;if(!(target instanceof Element)||target.localName!==itemTag)continue;const root=this.rootTreeItemAncestor(target);root&&this.dirtyConfigureRoots.add(root)}}else this.dirtyConfigureRoots.clear();this.onChildrenChanged()}},this.onNodeActivate=e=>{const node=this.eventNode(e);if(!node||node.isDisabled)return;this.selectionSyncPending=!0,this.bulkExpansions>0?this.syncRequested=!0:this.requestUpdate();const expanded=e.detail?.expanded===!0;(this.focusIsWithin(node)||!expanded&&this.activeId!==node.nodeId&&this.subtreeHasId(node,this.activeId))&&this.setActiveNode(node)},this.onNodeSelect=event=>{const node=this.eventNode(event);!node||node.isDisabled||(this.setActiveNode(node),this.updateSelectionFrom(node)&&this.emit("lr-selection-change",Object.freeze({selection:this.selectedItems})))},this.onTreeKeyDown=e=>{const itemTag=tag("tree-item");if(fromInteractiveDescendant(e,target=>target.localName===itemTag))return;const visible=this.visibleNodeElements();if(visible.length===0)return;const currentIndex=visible.findIndex(n=>n.nodeId===this.activeId),current=currentIndex>=0?visible[currentIndex]:visible[0];if(!current)return;if(this.reorderable&&(e.ctrlKey||e.metaKey)&&(e.key==="ArrowUp"||e.key==="ArrowDown")){e.preventDefault(),this.requestReorder(current,e.key==="ArrowDown"?1:-1);return}if(e.altKey)return;const rtl=this.effectiveDirection==="rtl",expandKey=rtl?"ArrowLeft":"ArrowRight",collapseKey=rtl?"ArrowRight":"ArrowLeft",moved=resolveListMove(e.key,{count:visible.length,current:Math.max(currentIndex,0),orientation:"vertical",wrap:!1,clamp:!0});if(moved!==null){e.preventDefault(),this.focusNode(visible[moved]);return}switch(e.key){case expandKey:if(e.preventDefault(),!current.hasChildren)break;if(!current.expanded)current.expand();else{const child=visible[currentIndex+1];child&&treeItemOwnerContext(child).depth>treeItemOwnerContext(current).depth&&this.focusNode(child)}break;case collapseKey:if(e.preventDefault(),current.hasChildren&&current.expanded)current.collapse();else for(let i=currentIndex-1;i>=0;i--){const sibling=visible[i];if(sibling&&treeItemOwnerContext(sibling).depth<treeItemOwnerContext(current).depth){this.focusNode(sibling);break}}break;case"Enter":case" ":e.preventDefault(),current.select();break;default:return}}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,expand:LYRA_DEFAULT_expand,loading:LYRA_DEFAULT_loading,noData:LYRA_DEFAULT_noData,retry:LYRA_DEFAULT_retry,treeLimit:LYRA_DEFAULT_treeLimit,treeNodeMoved:LYRA_DEFAULT_treeNodeMoved,treeSourceError:LYRA_DEFAULT_treeSourceError,treeSourceSummary:LYRA_DEFAULT_treeSourceSummary}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-selection-change"])}static{this.identityEventDetailProperties=Object.freeze({"lr-selection-change":Object.freeze(["selection"])})}static{this.styles=[LyraElement.styles,styles,hierarchySourceStyles]}get treeSource(){return this._treeSource}set treeSource(value){const previous=this._treeSource;this._treeSource=value,this.hierarchy?.update(value,this.effectiveLocale,!0),this.requestUpdate("treeSource",previous)}revealSourceKey(key){return this.treeSource===void 0?Promise.resolve(!1):this.hierarchy.reveal(key)}normalizeSourceValue(value,key){const id=hierarchyKey(hierarchyField(value,"id"));if(id!==key)throw new TypeError("Hierarchy domain key mismatch");const label=hierarchyText(hierarchyField(value,"label")),description=hierarchyText(hierarchyField(value,"description")),accessibleLabel=hierarchyText(hierarchyField(value,"accessibleLabel")),normalized=normalizeBadges(hierarchyField(value,"badges"));let units=label.length+description.length+accessibleLabel.length;for(const badge of normalized.badges??[])units+=badge.text.length+(badge.label?.length??0);if(normalized.truncated||units>65536)throw new RangeError("Hierarchy display value exceeds its row budget");return Object.freeze({id,label,description,accessibleLabel,icon:hierarchyField(value,"icon"),badges:normalized.badges})}announceSource(){const status=this.hierarchy.error?this.localize("treeSourceError"):this.hierarchy.loading?this.localize("loading"):this.sourceSummary();this.sourceAnnouncement!==void 0&&status!==this.sourceAnnouncement&&this.sourceAnnouncer.announce(status),this.sourceAnnouncement=status,this.hierarchy.rowsObserved&&this.sourceAnnouncer.transition("source-rows",this.hierarchy.rowError?"error":"ready",this.hierarchy.rowError?this.localize("treeSourceError"):"")}sourceSummary(){const projection=this.hierarchy.projection;return projection?this.localize("treeSourceSummary",void 0,{visible:getNumberFormat(this.effectiveLocale).format(projection.rows.count),total:getNumberFormat(this.effectiveLocale).format(projection.total)}):""}get data(){return this._data}set data(value){if((value===this._data||value===this.lastDataInput)&&this.lastDataLimit===this.effectiveMaxNodes)return;this.lastDataInput=value,this.lastDataLimit=this.effectiveMaxNodes,this.hasUpdated&&this.selectionBeforeRefresh===void 0&&(this.selectionBeforeRefresh=this.selectedItems.map(item=>item.nodeId));const previous=this._data,normalized=normalizeTreeData(value,this._data,this.effectiveMaxNodes);this._data=normalized.data,this.declaredChildrenAtPath=normalized.declaredChildrenAtPath,this.declaredRootCount=normalized.declaredRootCount,this._dataTruncated=normalized.truncated,this._limitReached=normalized.limitReached,this.requestUpdate("data",previous)}get dataTruncated(){return this._dataTruncated}get effectiveMaxNodes(){return Math.max(1,Math.min(1e4,finiteCount(this.maxNodes,1e3)))}get selection(){return this._selection}set selection(value){const old=this._selection,normalized=TREE_SELECTIONS.has(value)?value:"single";old!==normalized&&(this._selection=normalized,this.selectionSyncPending=!0,this.requestUpdate("selection",old))}get activeId(){return this._activeId}set activeId(value){value!==this._activeId&&(this.activeNode&&(this.activeNode.tabIndex=-1),this.activeNode=void 0,this._activeId=value)}setActiveNode(node){this.activeId=node?.nodeId??null,this.activeNode!==node&&this.activeNode&&(this.activeNode.tabIndex=-1),this.activeNode=node,node&&(node.tabIndex=this.isNavigable(node)?0:-1)}get nodeWalkLimit(){return this.hasAuthoredItems?Number.POSITIVE_INFINITY:this.effectiveMaxNodes}get nodeElements(){return[...this.querySelectorAll(`:scope > ${tag("tree-item")}`)]}childrenOf(node){return node.childItems()}isNavigable(node){return!node.isDisabled&&!isInertWithin(node,this)}allNodeElements(){const result=[],seen=new Set,stack=this.nodeElements.map(node=>({node,depth:0})).reverse();for(;stack.length>0&&result.length<this.nodeWalkLimit;){const{node,depth}=stack.pop();if(seen.has(node)||(seen.add(node),result.push(node),depth>=TREE_MAX_RENDER_DEPTH))continue;const children=this.childrenOf(node);for(let index=children.length-1;index>=0;index--)stack.push({node:children[index],depth:depth+1})}return result}get selectedItems(){return this.treeSource!==void 0?Object.freeze([]):Object.freeze(this.allNodeElements().filter(node=>node.selected))}iconSource(name){return this.querySelector(`:scope > [slot="${name}"]`)}applyTreeContext(){const expandIcon=this.iconSource("expand-icon"),collapseIcon=this.iconSource("collapse-icon"),roots=this.nodeElements,rootCount=this.hasAuthoredItems?roots.length:this.declaredRootCount,stack=[];for(let index=roots.length-1;index>=0;index--)stack.push({node:roots[index],ancestry:[],depth:0,setSize:rootCount,posInSet:index+1,identity:this.hasAuthoredItems?void 0:this.treeIdentityAt(String(index))});const seen=new Set;for(;stack.length>0&&seen.size<this.nodeWalkLimit;){const frame=stack.pop();if(seen.has(frame.node)||(seen.add(frame.node),frame.node.nodeId===this.activeId&&this.setActiveNode(frame.node),configureTreeItemOwner(frame.node,{...treeItemOwnerContext(frame.node),activeId:null,activeNodeId:this.readActiveId,ancestry:frame.ancestry,depth:frame.depth,setSize:frame.setSize,posInSet:frame.posInSet,selection:this.selection,ownsSelection:!0,identity:frame.identity,expandIcon,collapseIcon,syncOwner:this.requestContextSync,focusOwner:this.onItemFocus}),frame.depth>=TREE_MAX_RENDER_DEPTH))continue;const children=this.childrenOf(frame.node),declaredCount=frame.identity?.declaredChildrenAtPath.get(frame.identity.path)??frame.node.item?.children?.length??children.length,childAncestry=frame.node.item?[...frame.ancestry,frame.node.item]:frame.ancestry;for(let index=children.length-1;index>=0;index--){const identity=frame.identity?{path:`${frame.identity.path}/${index}`,ownerPaths:frame.identity.ownerPaths,collisionIds:frame.identity.collisionIds,declaredChildrenAtPath:frame.identity.declaredChildrenAtPath}:void 0;stack.push({node:children[index],ancestry:childAncestry,depth:frame.depth+1,setSize:declaredCount,posInSet:index+1,identity})}}}selectableInSingleMode(node){return!node.isDisabled&&(this.selection!=="leaf"||!node.hasChildren)}normalizeSingleSelection(){let kept=!1;for(const node of this.allNodeElements()){const selected=!kept&&node.selected&&this.selectableInSingleMode(node);this.setSelection(node,selected,!1),selected&&(kept=!0)}}setBranchSelection(node,selected,leavesOnly){const stack=[{node,depth:treeItemOwnerContext(node).depth}],seen=new Set;for(;stack.length>0&&seen.size<this.nodeWalkLimit;){const{node:current,depth}=stack.pop();if(seen.has(current)||current.isDisabled)continue;seen.add(current);const children=this.childrenOf(current).filter(child=>!child.isDisabled);if(!leavesOnly||children.length===0?this.setSelection(current,leavesOnly&&current.hasChildren?!1:selected,!1):this.setSelection(current,!1,!1),depth<TREE_MAX_RENDER_DEPTH)for(let index=children.length-1;index>=0;index--)stack.push({node:children[index],depth:depth+1})}}deriveMultipleSelection(node,leavesOnly){const states=new Map,stack=[{item:node,visited:!1,depth:0}],queued=new Set;for(;stack.length>0;){const entry=stack.pop();if(entry.visited){const current=entry.item;if(current.isDisabled){this.setSelection(current,!1,!1),states.set(current,"ignored");continue}const children2=this.childrenOf(current).filter(child=>!child.isDisabled);if(children2.length===0){leavesOnly&&current.hasChildren?(this.setSelection(current,!1,!1),states.set(current,"none")):(this.setSelection(current,current.selected,!1),states.set(current,current.selected?"all":"none"));continue}const childStates=children2.map(child=>states.get(child)??"ignored").filter(state2=>state2!=="ignored");if(childStates.length===0){this.setSelection(current,!1,!1),states.set(current,"none");continue}const all=childStates.every(state2=>state2==="all"),none=childStates.every(state2=>state2==="none");this.setSelection(current,all,!all&&!none),states.set(current,all?"all":none?"none":"some");continue}if(queued.size>=this.nodeWalkLimit||queued.has(entry.item)||(queued.add(entry.item),stack.push({...entry,visited:!0}),entry.depth>=TREE_MAX_RENDER_DEPTH))continue;const children=this.childrenOf(entry.item);for(let index=children.length-1;index>=0;index--)queued.has(children[index])||stack.push({item:children[index],visited:!1,depth:entry.depth+1})}return states.get(node)??"none"}normalizeMultipleSelection(){const leavesOnly=this.selection==="leaf-multiple";for(const node of this.allNodeElements())node.selected&&this.childrenOf(node).length>0&&this.setBranchSelection(node,!0,leavesOnly);for(const root of this.nodeElements)this.deriveMultipleSelection(root,leavesOnly)}normalizeSelection(){this.selection==="single"||this.selection==="leaf"?this.normalizeSingleSelection():this.normalizeMultipleSelection()}setSelection(node,selected,indeterminate){this.selectionBefore&&!this.selectionBefore.has(node)&&this.selectionBefore.set(node,[node.selected,node.indeterminate]),setTreeItemSelection(node,selected,indeterminate)}updateSelectionFrom(node){if(node.isDisabled||(this.selection==="single"||this.selection==="leaf")&&!this.selectableInSingleMode(node))return!1;const before=new Map;this.selectionBefore=before;try{if(this.selection==="single"||this.selection==="leaf")for(const candidate of this.allNodeElements())this.setSelection(candidate,candidate===node,!1);else{const select=node.indeterminate||!node.selected;this.setBranchSelection(node,select,this.selection==="leaf-multiple");for(const root of this.nodeElements)this.deriveMultipleSelection(root,this.selection==="leaf-multiple")}}finally{this.selectionBefore=void 0}for(const[candidate,[selected,indeterminate]]of before)if(candidate.selected!==selected||candidate.indeterminate!==indeterminate)return!0;return!1}refreshAuthoredItems(){const nodes=this.nodeElements;for(const node of nodes)node.hasAttribute("slot")&&node.removeAttribute("slot");const authored=nodes.some(node=>!this.generatedNodes.has(node));if(authored)for(const node of nodes)this.generatedNodes.has(node)&&node.remove();this.hasAuthoredItems=authored}visibleNodeElements(){const acc=[],seen=new Set,stack=this.nodeElements.map(node=>({node,depth:0})).reverse();for(;stack.length>0&&acc.length<this.nodeWalkLimit;){const{node,depth}=stack.pop();if(seen.has(node)||(seen.add(node),!this.isNavigable(node))||(acc.push(node),!node.expanded||depth>=TREE_MAX_RENDER_DEPTH))continue;const children=this.childrenOf(node);for(let index=children.length-1;index>=0;index--)stack.push({node:children[index],depth:depth+1})}return acc}findItem(items,id){const stack=[...items].reverse(),seen=new Set;for(;stack.length>0;){const item=stack.pop();if(!seen.has(item)){if(seen.add(item),item.id===id)return item;if(item.children)for(let i=item.children.length-1;i>=0;i--){const child=item.children[i];child&&stack.push(child)}}}}isDuplicateDataPath(item,path){return this.dataIdCollisions.has(item.id)&&this.dataIdOwnerPaths.get(item.id)!==path}rebuildDataIdentity(){const ownerPaths=new Map,collisionIds=new Set,ancestry=new Set,stack=[{items:this.data,index:0,parentPath:"",depth:0}];for(;stack.length>0;){const frame=stack[stack.length-1];if(frame.index>=frame.items.length){frame.owner&&ancestry.delete(frame.owner),stack.pop();continue}const index=frame.index++,item=frame.items[index];if(!item)continue;const path=frame.parentPath===""?String(index):`${frame.parentPath}/${index}`;ownerPaths.has(item.id)?collisionIds.add(item.id):ownerPaths.set(item.id,path),!(frame.depth>=TREE_MAX_RENDER_DEPTH||ancestry.has(item)||!item.children?.length)&&(ancestry.add(item),stack.push({items:item.children,index:0,parentPath:path,depth:frame.depth+1,owner:item}))}this.dataIdOwnerPaths=ownerPaths,this.dataIdCollisions=collisionIds}treeIdentityAt(path){return{path,ownerPaths:this.dataIdOwnerPaths,collisionIds:this.dataIdCollisions,declaredChildrenAtPath:this.declaredChildrenAtPath}}firstEnabledId(items){for(let index=0;index<items.length;index++){const item=items[index];if(!(!item||item.disabled||this.isDuplicateDataPath(item,String(index))))return item.id}return null}isEnabledReachableId(items,id){const stack=items.map((item,index)=>({item,path:String(index)})).reverse(),seen=new Set;for(;stack.length>0;){const{item,path}=stack.pop();if(!seen.has(item)&&(seen.add(item),!(item.disabled||this.isDuplicateDataPath(item,path)))){if(item.id===id)return!0;if(item.children)for(let i=item.children.length-1;i>=0;i--){const child=item.children[i];child&&stack.push({item:child,path:`${path}/${i}`})}}}return!1}findRenderedSiblings(node){const root=node.getRootNode(),shadowHost="host"in root?root.host:null,shadowParent=shadowHost?.localName===tag("tree-item")?shadowHost:null,lightParent=node.parentElement?.localName===tag("tree-item")?node.parentElement:null,parentItem=shadowParent??lightParent,siblings=parentItem?parentItem.childItems():this.nodeElements,index=siblings.indexOf(node);if(!(index<0))return{parent:parentItem,siblings,index}}deepFocusedNode(){const active=deepActiveElementIn(this.ownerDocument);if(!active||active.localName!==tag("tree-item"))return null;const node=active;return this.visibleNodeElements().some(n=>n.nodeId===node.nodeId)?node:null}resolveActiveFromDom(){const inertMutation=this.inertMutationPending;this.inertMutationPending=!1;const visible=this.visibleNodeElements(),current=visible.find(node=>node.nodeId===this.activeId);if(current){this.setActiveNode(current);return}const displaced=this.activeId;if(this.setActiveNode(visible[0]),!inertMutation||this.activeId==null||displaced==null||displaced!==this.lastFocusedNodeId)return;const ownerDocument=this.ownerDocument,active=deepActiveElementIn(ownerDocument),strandedOnDisplaced=active?.nodeType===1&&active.localName===tag("tree-item")&&active.nodeId===displaced;active!==null&&active!==ownerDocument.body&&!strandedOnDisplaced||(this.pendingFocusId=this.activeId)}requestUpdate(name,oldValue){name===void 0&&this._treeSource!==void 0&&this.hierarchy?.update(this._treeSource,this.effectiveLocale,!0),super.requestUpdate(name,oldValue)}willUpdate(changed){if(super.willUpdate(changed),this.hierarchy.update(this.treeSource,this.effectiveLocale),this.treeSource!==void 0){if(!this.sourceMode){this.sourceMode=!0,this.resetChildObserver(),this.pendingFocusId=null,this.pendingReorder=void 0,this.selectionBeforeRefresh=void 0,this.syncRequested=!1,this.syncGeneration++,this.syncRunning=!1,this.syncTask=void 0;for(const node of this.nodeElements)this.generatedNodes.has(node)&&node.remove()}return}if(this.sourceMode&&(this.sourceMode=!1,this.sourceAnnouncement=void 0,this.dataSyncPending=!0,this.selectionSyncPending=!0,this.armChildObserver()),changed.has("maxNodes")&&this.hasUpdated&&!changed.has("data")&&(this.data=this.data),this.refreshAuthoredItems(),(changed.has("data")||changed.has("selection"))&&(this.selectionSyncPending=!0),this.hasAuthoredItems){this.resolveActiveFromDom();return}if(changed.has("data")||this.dataSyncPending){this.dataSyncPending=!1;const focused=this.deepFocusedNode(),focusedId=focused?.nodeId??null;this.rebuildDataIdentity(),this.syncNodes();const activeItem=this.activeId?this.findItem(this.data,this.activeId):void 0;(!this.activeId||!activeItem||activeItem.disabled||!this.isEnabledReachableId(this.data,this.activeId))&&(this.activeId=this.firstEnabledId(this.data)),this.pendingFocusId=focused==null?null:focusedId!=null&&this.findItem(this.data,focusedId)?focusedId:this.activeId}this.inertMutationPending&&this.resolveActiveFromDom()}firstUpdated(changed){super.firstUpdated(changed),hostAriaLabel(this)==null&&!this.label&&devWarnOnce("lyra-tree-missing-accessible-name","<lr-tree> has no accessible name: set `label` or a host `aria-label`.")}updated(changed){if(super.updated(changed),this.treeSource!==void 0){this.announceSource();return}const targeted=changed.size===0&&this.hasAuthoredItems&&this.dirtyConfigureRoots.size>0;if(targeted){const nodes=this.nodeElements,count=nodes.length,positions=this.dirtyConfigureRoots.size>1?new Map(nodes.map((node,index)=>[node,index])):void 0;for(const node of this.dirtyConfigureRoots){const i=positions?positions.get(node)??-1:nodes.indexOf(node);i<0||configureTreeItemOwner(node,{...treeItemOwnerContext(node),activeId:null,activeNodeId:this.readActiveId,ancestry:[],depth:0,setSize:count,posInSet:i+1,selection:this.selection,ownsSelection:!0,identity:void 0,expandIcon:this.iconSource("expand-icon"),collapseIcon:this.iconSource("collapse-icon"),syncOwner:this.requestContextSync,focusOwner:this.onItemFocus})}}else if(changed.has("activeId")||changed.has("data")||this.hasAuthoredItems){const nodes=this.nodeElements,count=this.hasAuthoredItems?nodes.length:this.declaredRootCount;nodes.forEach((node,i)=>{configureTreeItemOwner(node,{...treeItemOwnerContext(node),activeId:null,activeNodeId:this.readActiveId,ancestry:[],depth:0,setSize:count,posInSet:i+1,selection:this.selection,ownsSelection:!0,identity:this.hasAuthoredItems?void 0:this.treeIdentityAt(String(i)),expandIcon:this.iconSource("expand-icon"),collapseIcon:this.iconSource("collapse-icon"),syncOwner:this.requestContextSync,focusOwner:this.onItemFocus})})}targeted||(this.contextSyncPending=!0),this.dirtyConfigureRoots.clear(),this.scheduleTreeSync()}scheduleTreeSync(){this.treeSource===void 0&&(this.syncRequested=!0,!(this.syncRunning||this.bulkExpansions>0)&&(this.syncRunning=!0,this.syncTask=this.runTreeSync()))}async runTreeSync(){const generation=this.syncGeneration;try{for(;this.syncRequested&&(this.syncRequested=!1,await super.getUpdateComplete(),!(this.treeSource!==void 0||generation!==this.syncGeneration||(await cascadeUpdateComplete(this.nodeElements),this.treeSource!==void 0||generation!==this.syncGeneration)||(this.contextSyncPending&&(this.contextSyncPending=!1,this.applyTreeContext()),this.selectionSyncPending&&(this.selectionSyncPending=!1,this.normalizeSelection()),await cascadeUpdateComplete(this.nodeElements),this.treeSource!==void 0||generation!==this.syncGeneration)));)this.reportRefreshSelectionChange(),this.confirmPendingReorder(),this.restorePendingFocus()}finally{generation===this.syncGeneration&&(this.syncRunning=!1)}}rootTreeItemAncestor(node){const itemTag=tag("tree-item");let current=node;for(;current&&current.parentElement&&current.parentElement!==this;)current=current.parentElement;return current&&current.parentElement===this&&current.localName===itemTag?current:null}connectedCallback(){super.connectedCallback(),this.armChildObserver()}armChildObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected||this.treeSource!==void 0||this.childObserver&&this.childObserverDocument===ownerDocument)return;this.resetChildObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.childObserverGeneration,observer=new MutationObserverCtor(records=>{this.childObserver!==observer||this.childObserverDocument!==ownerDocument||this.childObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.onChildMutations(records)});this.childObserver=observer,this.childObserverDocument=ownerDocument,observer.observe(this,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0,attributeFilter:["selected","disabled","inert","lazy"]})}disconnectedCallback(){super.disconnectedCallback(),this.sourceAnnouncement=void 0,this.pendingReorder=void 0,this.activeNode=void 0,this.resetChildObserver()}adoptedCallback(){super.adoptedCallback(),this.hierarchy.adopted(),this.resetChildObserver()}resetChildObserver(){this.childObserverGeneration+=1,this.childObserver?.disconnect(),this.childObserver=void 0,this.childObserverDocument=void 0}syncNodes(){const existingById=new Map;for(const node of this.nodeElements){if(!node.item)continue;const matches=existingById.get(node.item.id)??[];matches.push(node),existingById.set(node.item.id,matches)}let previousSibling=null;for(let index=0;index<this.data.length;index++){const item=this.data[index];let node=existingById.get(item.id)?.shift();node||(node=this.ownerDocument.createElement(tag("tree-item")),this.generatedNodes.add(node)),node.item=item,configureTreeItemOwner(node,{...treeItemOwnerContext(node),ancestry:[],depth:0,setSize:this.declaredRootCount,posInSet:index+1,selection:this.selection,ownsSelection:!0,identity:this.treeIdentityAt(String(index)),expandIcon:this.iconSource("expand-icon"),collapseIcon:this.iconSource("collapse-icon"),syncOwner:this.requestContextSync,focusOwner:this.onItemFocus});const targetPosition=previousSibling?previousSibling.nextElementSibling:this.firstElementChild;targetPosition!==node&&this.insertBefore(node,targetPosition),previousSibling=node}for(const nodes of existingById.values())for(const node of nodes)node.remove()}focusNode(node){node&&(this.setActiveNode(node),node.focus())}subtreeHasId(root,id){if(id==null)return!1;const stack=this.childrenOf(root).map(item=>({item,depth:treeItemOwnerContext(root).depth+1}));for(let visited=0;stack.length>0&&visited<this.nodeWalkLimit;visited++){const{item,depth}=stack.pop();if(!(depth>TREE_MAX_RENDER_DEPTH)){if(item.nodeId===id)return!0;depth<TREE_MAX_RENDER_DEPTH&&stack.push(...this.childrenOf(item).map(child=>({item:child,depth:depth+1})))}}return!1}focusIsWithin(node){for(let current=deepActiveElementIn(this.ownerDocument);current;current=composedParentElement(current)){if(current===node)return!0;if(current===this)return!1}return!1}eventNode(e){const path=e.composedPath(),origin=path[0];if(origin?.nodeType===1&&origin.localName===tag("tree-item")){const treeTag=tag("tree");for(const target of path){if(target===this)return origin;if(target.localName===treeTag)return}return}const id=e.detail?.nodeId;return this.allNodeElements().find(candidate=>candidate.nodeId===id)}async getUpdateComplete(){let result=await super.getUpdateComplete();if(this.treeSource!==void 0)return result;for(;this.syncRunning||this.isUpdatePending;)this.syncRunning&&await this.syncTask,result=await super.getUpdateComplete();return this.treeSource===void 0&&await cascadeUpdateComplete(this.nodeElements),result}reportRefreshSelectionChange(){const before=this.selectionBeforeRefresh;if(before===void 0||this.isUpdatePending)return;this.selectionBeforeRefresh=void 0;const selection=this.selectedItems;selection.length===before.length&&selection.every((item,index)=>item.nodeId===before[index])||this.emit("lr-selection-change",Object.freeze({selection}))}restorePendingFocus(){if(this.pendingFocusId==null)return;const id=this.pendingFocusId;this.pendingFocusId=null;const visible=this.visibleNodeElements();(visible.find(n=>n.nodeId===id)??visible.find(n=>n.nodeId===this.activeId))?.focus()}requestReorder(node,delta){const id=node.nodeId,found=this.findRenderedSiblings(node);if(!found)return;const{parent,siblings,index}=found,total=siblings.length,toIndex=index+delta;toIndex<0||toIndex>=total||(this.pendingReorder={node,parent,originalSiblings:[...siblings],targetSibling:siblings[toIndex],fromIndex:index,toIndex},this.emit("lr-reorder",{nodeId:id,parentNodeId:parent?.nodeId??null,fromIndex:index,toIndex}))}confirmPendingReorder(){const pending=this.pendingReorder;if(!pending)return;const found=this.findRenderedSiblings(pending.node);if(!found){this.pendingReorder=void 0;return}(found.siblings.length!==pending.originalSiblings.length||found.siblings.some((node,index)=>node!==pending.originalSiblings[index]))&&(this.pendingReorder=void 0,!(found.parent!==pending.parent||found.index!==pending.toIndex||found.siblings[pending.fromIndex]!==pending.targetSibling)&&this.liveRegion?.announce(this.localize("treeNodeMoved",void 0,{label:pending.node.nodeLabel,index:this.formatCount(found.index+1),total:this.formatCount(found.siblings.length)}),{force:!0}))}async expandAll(){if(this.treeSource!==void 0)return;let level=this.nodeElements.map(node=>({node,depth:0}));const seen=new Set,systemReduced=preferenceMediaMatches(this.ownerDocument.defaultView,"(prefers-reduced-motion: reduce)");this.bulkExpansions+=1;try{for(;level.length>0&&seen.size<this.nodeWalkLimit;){const current=[];for(const entry of level){const{node}=entry;if(!(seen.has(node)||seen.size>=this.nodeWalkLimit)){if(seen.add(node),current.push(entry),node.isDisabled)node.expanded=!1;else if(node.hasChildren){const reduced=systemReduced||inheritedPreference(node,"data-lr-motion","reduce")==="reduce";withTreeItemMotionPreference(node,reduced,()=>node.expand())}}}await Promise.all(current.map(({node})=>node.updateComplete)),level=[];for(const{node,depth}of current)depth<TREE_MAX_RENDER_DEPTH&&level.push(...this.childrenOf(node).map(child=>({node:child,depth:depth+1})))}}finally{this.bulkExpansions-=1}this.bulkExpansions===0&&this.syncRequested&&this.scheduleTreeSync(),await this.updateComplete}async collapseAll(){if(this.treeSource!==void 0)return;const focused=this.deepFocusedNode(),topLevel=this.nodeElements,nodes=this.allNodeElements();for(let index=nodes.length-1;index>=0;index--){const node=nodes[index];node.isDisabled?node.expanded=!1:node.collapse()}(this.hasAuthoredItems?topLevel.some(node=>this.isNavigable(node)&&node.nodeId===this.activeId):this.data.some(item=>!item.disabled&&item.id===this.activeId))||(this.activeId=this.hasAuthoredItems?topLevel.find(node=>this.isNavigable(node))?.nodeId??null:this.firstEnabledId(this.data)),focused&&(this.pendingFocusId=this.activeId),await cascadeUpdateComplete(topLevel)}render(){return this.treeSource!==void 0?hierarchySourceView(this.hierarchy,{label:hostAriaLabel(this)??this.label,rtl:this.effectiveDirection==="rtl",multiple:this.selection==="multiple"||this.selection==="leaf-multiple",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.accessibleLabel||value.label||value.description||value.id,content:value=>html`${value.icon??nothing}${value.label}${value.description?html`<span>${value.description}</span>`:nothing}${value.badges?.map(badge=>html`<span aria-label=${badge.label||nothing}>${badge.text}</span>`)}`,select:row=>{if((this.selection==="leaf"||this.selection==="leaf-multiple")&&row.childCount>0)return;const multiple=this.selection==="multiple"||this.selection==="leaf-multiple";this.hierarchy.project({type:"select",key:row.key,selected:multiple?!row.selected:!0,scope:multiple&&row.childCount>0?"subtree":"item"},!0,row)}}):html`
1
+ import{__decorate}from"tslib";import{HierarchySourceController,hierarchyField,hierarchyKey,hierarchyText}from"../../../internal/hierarchy-source-controller.js";import{hierarchySourceView}from"../../../internal/hierarchy-source-view.js";import{hierarchySourceStyles}from"../../../internal/hierarchy-source-view.styles.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{inheritedPreference,preferenceMediaMatches}from"../../../internal/preferences.js";import{finiteCount}from"../../../internal/numbers.js";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{tag}from"../../../internal/prefix.js";import{resolveListMove}from"../../../internal/list-navigation.js";import{styles}from"./tree.styles.js";import{cascadeUpdateComplete}from"./update-cascade.js";import{configureTreeItemOwner,withTreeItemMotionPreference,fromInteractiveDescendant,setTreeItemSelection,treeItemOwnerContext}from"./tree-owner-controller.js";import"./tree-item.class.js";import{TREE_MAX_RENDER_DEPTH,TREE_MAX_RENDER_NODES}from"./tree-types.js";import{composedParentElement,deepActiveElementIn}from"../../../internal/active-element.js";import{LYRA_DEFAULT_treeLimit}from"../../../internal/default-strings/data.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_expand,LYRA_DEFAULT_loading,LYRA_DEFAULT_noData,LYRA_DEFAULT_retry,LYRA_DEFAULT_treeNodeMoved,LYRA_DEFAULT_treeSourceError,LYRA_DEFAULT_treeSourceSummary}from"../../../internal/default-strings/shared.generated.js";const TREE_SELECTIONS=new Set(["single","multiple","leaf","leaf-multiple"]),TREE_BADGE_LIMIT=100,TREE_MAX_INSPECTED_POSITIONS=1e4,EMPTY_TREE_DATA=Object.freeze([]);function ownValue(record,key){try{const descriptor=Object.getOwnPropertyDescriptor(record,key);return descriptor&&"value"in descriptor?descriptor.value:void 0}catch{return}}function arrayLength(value){if(!Array.isArray(value))return 0;try{return Math.max(0,Math.min(Number.MAX_SAFE_INTEGER,Math.trunc(value.length)))}catch{return 0}}function normalizeBadges(value){if(!Array.isArray(value))return{truncated:value!==void 0};const badges=[],length=arrayLength(value);for(let index=0;index<Math.min(length,TREE_BADGE_LIMIT);index++){const raw=ownValue(value,String(index));if(!raw||typeof raw!="object"||Array.isArray(raw))continue;const text=ownValue(raw,"text");if(typeof text!="string")continue;const rawTone=ownValue(raw,"tone"),tone=rawTone==="brand"||rawTone==="success"||rawTone==="warning"||rawTone==="danger"?rawTone:"neutral",rawLabel=ownValue(raw,"label");badges.push(Object.freeze({text,tone,...typeof rawLabel=="string"?{label:rawLabel}:{}}))}return{badges:Object.freeze(badges),truncated:length>TREE_BADGE_LIMIT}}function sameIcon(left,right){if(Object.is(left,right))return!0;const a=left,b=right;if(!a||!b||typeof a!="object"||typeof b!="object"||a._$litType$===void 0||a._$litType$!==b._$litType$||a.strings!==b.strings)return!1;const leftValues=a.values??[],rightValues=b.values??[];return leftValues.length===rightValues.length&&leftValues.every((value,index)=>Object.is(value,rightValues[index]))}function sameBadges(left,right){return left===right?!0:!left||!right||left.length!==right.length?!1:left.every((badge,index)=>{const other=right[index];return badge.text===other.text&&badge.tone===other.tone&&badge.label===other.label})}function sameTreeNode(next,previous){if(next.id!==previous.id||next.label!==previous.label||next.selected!==previous.selected||next.disabled!==previous.disabled||next.lazy!==previous.lazy||next.description!==previous.description||next.accessibleLabel!==previous.accessibleLabel||!sameIcon(next.icon,previous.icon)||!sameBadges(next.badges,previous.badges))return!1;const children=next.children,previousChildren=previous.children;return!children||!previousChildren?children===void 0&&previousChildren===void 0:children.length===previousChildren.length&&children.every((child,index)=>child===previousChildren[index])}function indexTreeNodes(nodes){const byId=new Map,stack=[...nodes];for(;stack.length>0;){const node=stack.pop();byId.set(node.id,node),node.children&&stack.push(...node.children)}return byId}function normalizeTreeData(input,previous=EMPTY_TREE_DATA,limit=TREE_MAX_RENDER_NODES){if(!Array.isArray(input))return{data:EMPTY_TREE_DATA,declaredChildrenAtPath:new Map,declaredRootCount:0,truncated:input!=null,limitReached:!1};const root=[],declaredChildrenAtPath=new Map,created=[],rootLength=arrayLength(input);let truncated=!1,limitReached=!1,accepted=0,inspected=0;const seenIds=new Set,identityFilteredCollections=new Set,jobs=[{source:input,index:0,length:rootLength,target:root,parentPath:"",depth:0,ancestors:new Set}];for(;jobs.length>0;){const job=jobs[jobs.length-1];if(job.index>=job.length){jobs.pop();continue}if(accepted>=limit||inspected>=TREE_MAX_INSPECTED_POSITIONS){truncated=!0,limitReached=accepted>=limit;break}const raw=ownValue(job.source,String(job.index++));if(inspected++,inspected===TREE_MAX_INSPECTED_POSITIONS&&(truncated=!0),!raw||typeof raw!="object"||Array.isArray(raw)){truncated=!0,identityFilteredCollections.add(job.target);continue}const id=ownValue(raw,"id"),label=ownValue(raw,"label");if(typeof id!="string"||id.trim()===""||seenIds.has(id)||typeof label!="string"){truncated=!0,identityFilteredCollections.add(job.target);continue}seenIds.add(id);const node={id,label},selected=ownValue(raw,"selected"),disabled=ownValue(raw,"disabled"),lazy=ownValue(raw,"lazy");typeof selected=="boolean"&&(node.selected=selected),typeof disabled=="boolean"&&(node.disabled=disabled),typeof lazy=="boolean"&&(node.lazy=lazy);const icon=ownValue(raw,"icon");icon!==void 0&&(node.icon=icon);const description=ownValue(raw,"description");typeof description=="string"&&(node.description=description);const accessibleLabel=ownValue(raw,"accessibleLabel");typeof accessibleLabel=="string"&&(node.accessibleLabel=accessibleLabel);const normalizedBadges=normalizeBadges(ownValue(raw,"badges"));normalizedBadges.badges?.length&&(node.badges=normalizedBadges.badges),truncated||=normalizedBadges.truncated;const ownIndex=job.target.length,path=job.parentPath===""?String(ownIndex):`${job.parentPath}/${ownIndex}`;job.target.push(node),created.push(node),accepted++;const rawChildren=ownValue(raw,"children"),childCount=arrayLength(rawChildren);if(childCount===0)continue;if(declaredChildrenAtPath.set(path,childCount),job.depth>=TREE_MAX_RENDER_DEPTH||job.ancestors.has(raw)){truncated=!0;continue}const children=[];node.children=children;const ancestors=new Set(job.ancestors);ancestors.add(raw),jobs.push({source:rawChildren,index:0,length:childCount,target:children,parentPath:path,depth:job.depth+1,ancestors})}const previousById=previous.length>0?indexTreeNodes(previous):void 0,resolved=new Map,resolve=node=>resolved.get(node)??node;for(let index=created.length-1;index>=0;index--){const node=created[index];if(node.children){for(let child=0;child<node.children.length;child++)node.children[child]=resolve(node.children[child]);Object.freeze(node.children)}Object.freeze(node);const prior=previousById?.get(node.id);prior&&!(node.children&&identityFilteredCollections.has(node.children))&&sameTreeNode(node,prior)&&resolved.set(node,prior)}for(let index=0;index<root.length;index++)root[index]=resolve(root[index]);const normalizedJobs=root.map((node,index)=>({node,path:String(index)}));for(;normalizedJobs.length>0;){const{node,path}=normalizedJobs.pop(),children=node.children??[];identityFilteredCollections.has(children)&&declaredChildrenAtPath.set(path,children.length);for(let index=children.length-1;index>=0;index--)normalizedJobs.push({node:children[index],path:`${path}/${index}`})}return{data:Object.freeze(root),declaredChildrenAtPath,declaredRootCount:identityFilteredCollections.has(root)?root.length:rootLength,truncated,limitReached}}function isInertWithin(node,root){for(let current=node;current&&current!==root;current=current.parentElement)if(current.hasAttribute("inert"))return!0;return!1}class LyraTree extends LyraElement{constructor(){super(...arguments),this._treeSource=void 0,this.sourceMode=!1,this.sourcePaintVersion=0,this.sourceAnnouncer=new AnnouncementSinkController(this),this.hierarchy=new HierarchySourceController(this,{normalize:(value,key)=>this.normalizeSourceValue(value,key),onChange:()=>{const previous=this.sourcePaintVersion++;this.requestUpdate("sourcePaintVersion",previous)},accepted:(action,_row,state2)=>{action.type==="select"&&this.emit("lr-source-selection-change",Object.freeze({key:action.key,selected:action.selected,scope:action.scope,state:state2}))}}),this._data=EMPTY_TREE_DATA,this.lastDataInput=void 0,this.lastDataLimit=0,this.declaredChildrenAtPath=new Map,this.declaredRootCount=0,this._dataTruncated=!1,this._limitReached=!1,this.label="",this.maxNodes=1e3,this.reorderable=!1,this._selection="single",this._activeId=null,this.readActiveId=()=>this._activeId,this.hasAuthoredItems=!1,this.pendingFocusId=null,this.generatedNodes=new WeakSet,this.dataIdOwnerPaths=new Map,this.dataIdCollisions=new Set,this.selectionSyncPending=!0,this.dataSyncPending=!1,this.inertMutationPending=!1,this.dirtyConfigureRoots=new Set,this.lastFocusedNodeId=null,this.onTreeFocusIn=e=>{const path=e.composedPath(),owner=path.find(target=>target.localName===tag("tree"));if(owner&&owner!==this)return;const item=path.find(target=>target.nodeType===1&&target.localName===tag("tree-item"));item&&this.onItemFocus(item)},this.onItemFocus=element=>{const item=element;this.isNavigable(item)&&(this.lastFocusedNodeId=item.nodeId,this.setActiveNode(item))},this.contextSyncPending=!0,this.bulkExpansions=0,this.syncGeneration=0,this.syncRequested=!1,this.syncRunning=!1,this.requestContextSync=()=>{this.contextSyncPending=!0,this.scheduleTreeSync()},this.onChildrenChanged=()=>{if(this.treeSource!==void 0)return;const wasAuthored=this.hasAuthoredItems;this.refreshAuthoredItems(),wasAuthored&&!this.hasAuthoredItems&&(this.dataSyncPending=!0),this.selectionSyncPending=!0,this.requestUpdate()},this.childObserverGeneration=0,this.onChildMutations=allRecords=>{const records=allRecords.filter(record=>record.type!=="attributes"||record.oldValue!==null!==record.target.hasAttribute(record.attributeName??""));if(records.length!==0){if(records.some(record=>record.attributeName==="inert")&&(this.inertMutationPending=!0),records.every(record=>record.type==="attributes")){const itemTag=tag("tree-item");for(const record of records){const target=record.target;if(!(target instanceof Element)||target.localName!==itemTag)continue;const root=this.rootTreeItemAncestor(target);root&&this.dirtyConfigureRoots.add(root)}}else this.dirtyConfigureRoots.clear();this.onChildrenChanged()}},this.onNodeActivate=e=>{const node=this.eventNode(e);if(!node||node.isDisabled)return;this.selectionSyncPending=!0,this.bulkExpansions>0?this.syncRequested=!0:this.requestUpdate();const expanded=e.detail?.expanded===!0;(this.focusIsWithin(node)||!expanded&&this.activeId!==node.nodeId&&this.subtreeHasId(node,this.activeId))&&this.setActiveNode(node)},this.onNodeSelect=event=>{const node=this.eventNode(event);!node||node.isDisabled||(this.setActiveNode(node),this.updateSelectionFrom(node)&&this.emit("lr-selection-change",Object.freeze({selection:this.selectedItems})))},this.onTreeKeyDown=e=>{const itemTag=tag("tree-item");if(fromInteractiveDescendant(e,target=>target.localName===itemTag))return;const visible=this.visibleNodeElements();if(visible.length===0)return;const currentIndex=visible.findIndex(n=>n.nodeId===this.activeId),current=currentIndex>=0?visible[currentIndex]:visible[0];if(!current)return;if(this.reorderable&&(e.ctrlKey||e.metaKey)&&(e.key==="ArrowUp"||e.key==="ArrowDown")){e.preventDefault(),this.requestReorder(current,e.key==="ArrowDown"?1:-1);return}if(e.altKey)return;const rtl=this.effectiveDirection==="rtl",expandKey=rtl?"ArrowLeft":"ArrowRight",collapseKey=rtl?"ArrowRight":"ArrowLeft",moved=resolveListMove(e.key,{count:visible.length,current:Math.max(currentIndex,0),orientation:"vertical",wrap:!1,clamp:!0});if(moved!==null){e.preventDefault(),this.focusNode(visible[moved]);return}switch(e.key){case expandKey:if(e.preventDefault(),!current.hasChildren)break;if(!current.expanded)current.expand();else{const child=visible[currentIndex+1];child&&treeItemOwnerContext(child).depth>treeItemOwnerContext(current).depth&&this.focusNode(child)}break;case collapseKey:if(e.preventDefault(),current.hasChildren&&current.expanded)current.collapse();else for(let i=currentIndex-1;i>=0;i--){const sibling=visible[i];if(sibling&&treeItemOwnerContext(sibling).depth<treeItemOwnerContext(current).depth){this.focusNode(sibling);break}}break;case"Enter":case" ":e.preventDefault(),current.select();break;default:return}}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,expand:LYRA_DEFAULT_expand,loading:LYRA_DEFAULT_loading,noData:LYRA_DEFAULT_noData,retry:LYRA_DEFAULT_retry,treeLimit:LYRA_DEFAULT_treeLimit,treeNodeMoved:LYRA_DEFAULT_treeNodeMoved,treeSourceError:LYRA_DEFAULT_treeSourceError,treeSourceSummary:LYRA_DEFAULT_treeSourceSummary}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-selection-change"])}static{this.identityEventDetailProperties=Object.freeze({"lr-selection-change":Object.freeze(["selection"])})}static{this.styles=[LyraElement.styles,styles,hierarchySourceStyles]}get treeSource(){return this._treeSource}set treeSource(value){const previous=this._treeSource;this._treeSource=value,this.hierarchy?.update(value,this.effectiveLocale,!0),this.requestUpdate("treeSource",previous)}revealSourceKey(key){return this.treeSource===void 0?Promise.resolve(!1):this.hierarchy.reveal(key)}normalizeSourceValue(value,key){const id=hierarchyKey(hierarchyField(value,"id"));if(id!==key)throw new TypeError("Hierarchy domain key mismatch");const label=hierarchyText(hierarchyField(value,"label")),description=hierarchyText(hierarchyField(value,"description")),accessibleLabel=hierarchyText(hierarchyField(value,"accessibleLabel")),normalized=normalizeBadges(hierarchyField(value,"badges"));let units=label.length+description.length+accessibleLabel.length;for(const badge of normalized.badges??[])units+=badge.text.length+(badge.label?.length??0);if(normalized.truncated||units>65536)throw new RangeError("Hierarchy display value exceeds its row budget");return Object.freeze({id,label,description,accessibleLabel,icon:hierarchyField(value,"icon"),badges:normalized.badges})}announceSource(){const status=this.hierarchy.error?this.localize("treeSourceError"):this.hierarchy.loading?this.localize("loading"):this.sourceSummary();this.sourceAnnouncement!==void 0&&status!==this.sourceAnnouncement&&this.sourceAnnouncer.announce(status),this.sourceAnnouncement=status,this.hierarchy.rowsObserved&&this.sourceAnnouncer.transition("source-rows",this.hierarchy.rowError?"error":"ready",this.hierarchy.rowError?this.localize("treeSourceError"):"")}sourceSummary(){const projection=this.hierarchy.projection;return projection?this.localize("treeSourceSummary",void 0,{visible:getNumberFormat(this.effectiveLocale).format(projection.rows.count),total:getNumberFormat(this.effectiveLocale).format(projection.total)}):""}get data(){return this._data}set data(value){if((value===this._data||value===this.lastDataInput)&&this.lastDataLimit===this.effectiveMaxNodes)return;this.lastDataInput=value,this.lastDataLimit=this.effectiveMaxNodes,this.hasUpdated&&this.selectionBeforeRefresh===void 0&&(this.selectionBeforeRefresh=this.selectedItems.map(item=>item.nodeId));const previous=this._data,normalized=normalizeTreeData(value,this._data,this.effectiveMaxNodes);this._data=normalized.data,this.declaredChildrenAtPath=normalized.declaredChildrenAtPath,this.declaredRootCount=normalized.declaredRootCount,this._dataTruncated=normalized.truncated,this._limitReached=normalized.limitReached,this.requestUpdate("data",previous)}get dataTruncated(){return this._dataTruncated}get effectiveMaxNodes(){return Math.max(1,Math.min(1e4,finiteCount(this.maxNodes,1e3)))}get selection(){return this._selection}set selection(value){const old=this._selection,normalized=TREE_SELECTIONS.has(value)?value:"single";old!==normalized&&(this._selection=normalized,this.selectionSyncPending=!0,this.requestUpdate("selection",old))}get activeId(){return this._activeId}set activeId(value){value!==this._activeId&&(this.activeNode&&(this.activeNode.tabIndex=-1),this.activeNode=void 0,this._activeId=value)}setActiveNode(node){this.activeId=node?.nodeId??null,this.activeNode!==node&&this.activeNode&&(this.activeNode.tabIndex=-1),this.activeNode=node,node&&(node.tabIndex=this.isNavigable(node)?0:-1)}get nodeWalkLimit(){return this.hasAuthoredItems?Number.POSITIVE_INFINITY:this.effectiveMaxNodes}get nodeElements(){return[...this.querySelectorAll(`:scope > ${tag("tree-item")}`)]}childrenOf(node){return node.childItems()}isNavigable(node){return!node.isDisabled&&!isInertWithin(node,this)}allNodeElements(){const result=[],seen=new Set,stack=this.nodeElements.map(node=>({node,depth:0})).reverse();for(;stack.length>0&&result.length<this.nodeWalkLimit;){const{node,depth}=stack.pop();if(seen.has(node)||(seen.add(node),result.push(node),depth>=TREE_MAX_RENDER_DEPTH))continue;const children=this.childrenOf(node);for(let index=children.length-1;index>=0;index--)stack.push({node:children[index],depth:depth+1})}return result}get selectedItems(){return this.treeSource!==void 0?Object.freeze([]):Object.freeze(this.allNodeElements().filter(node=>node.selected))}iconSource(name){return this.querySelector(`:scope > [slot="${name}"]`)}applyTreeContext(){const expandIcon=this.iconSource("expand-icon"),collapseIcon=this.iconSource("collapse-icon"),roots=this.nodeElements,rootCount=this.hasAuthoredItems?roots.length:this.declaredRootCount,stack=[];for(let index=roots.length-1;index>=0;index--)stack.push({node:roots[index],ancestry:[],depth:0,setSize:rootCount,posInSet:index+1,identity:this.hasAuthoredItems?void 0:this.treeIdentityAt(String(index))});const seen=new Set;for(;stack.length>0&&seen.size<this.nodeWalkLimit;){const frame=stack.pop();if(seen.has(frame.node)||(seen.add(frame.node),frame.node.nodeId===this.activeId&&this.setActiveNode(frame.node),configureTreeItemOwner(frame.node,{...treeItemOwnerContext(frame.node),activeId:null,activeNodeId:this.readActiveId,ancestry:frame.ancestry,depth:frame.depth,setSize:frame.setSize,posInSet:frame.posInSet,selection:this.selection,ownsSelection:!0,identity:frame.identity,expandIcon,collapseIcon,syncOwner:this.requestContextSync,focusOwner:this.onItemFocus}),frame.depth>=TREE_MAX_RENDER_DEPTH))continue;const children=this.childrenOf(frame.node),declaredCount=frame.identity?.declaredChildrenAtPath.get(frame.identity.path)??frame.node.item?.children?.length??children.length,childAncestry=frame.node.item?[...frame.ancestry,frame.node.item]:frame.ancestry;for(let index=children.length-1;index>=0;index--){const identity=frame.identity?{path:`${frame.identity.path}/${index}`,ownerPaths:frame.identity.ownerPaths,collisionIds:frame.identity.collisionIds,declaredChildrenAtPath:frame.identity.declaredChildrenAtPath}:void 0;stack.push({node:children[index],ancestry:childAncestry,depth:frame.depth+1,setSize:declaredCount,posInSet:index+1,identity})}}}selectableInSingleMode(node){return!node.isDisabled&&(this.selection!=="leaf"||!node.hasChildren)}normalizeSingleSelection(){let kept=!1;for(const node of this.allNodeElements()){const selected=!kept&&node.selected&&this.selectableInSingleMode(node);this.setSelection(node,selected,!1),selected&&(kept=!0)}}setBranchSelection(node,selected,leavesOnly){const stack=[{node,depth:treeItemOwnerContext(node).depth}],seen=new Set;for(;stack.length>0&&seen.size<this.nodeWalkLimit;){const{node:current,depth}=stack.pop();if(seen.has(current)||current.isDisabled)continue;seen.add(current);const children=this.childrenOf(current).filter(child=>!child.isDisabled);if(!leavesOnly||children.length===0?this.setSelection(current,leavesOnly&&current.hasChildren?!1:selected,!1):this.setSelection(current,!1,!1),depth<TREE_MAX_RENDER_DEPTH)for(let index=children.length-1;index>=0;index--)stack.push({node:children[index],depth:depth+1})}}deriveMultipleSelection(node,leavesOnly){const states=new Map,stack=[{item:node,visited:!1,depth:0}],queued=new Set;for(;stack.length>0;){const entry=stack.pop();if(entry.visited){const current=entry.item;if(current.isDisabled){this.setSelection(current,!1,!1),states.set(current,"ignored");continue}const children2=this.childrenOf(current).filter(child=>!child.isDisabled);if(children2.length===0){leavesOnly&&current.hasChildren?(this.setSelection(current,!1,!1),states.set(current,"none")):(this.setSelection(current,current.selected,!1),states.set(current,current.selected?"all":"none"));continue}const childStates=children2.map(child=>states.get(child)??"ignored").filter(state2=>state2!=="ignored");if(childStates.length===0){this.setSelection(current,!1,!1),states.set(current,"none");continue}const all=childStates.every(state2=>state2==="all"),none=childStates.every(state2=>state2==="none");this.setSelection(current,all,!all&&!none),states.set(current,all?"all":none?"none":"some");continue}if(queued.size>=this.nodeWalkLimit||queued.has(entry.item)||(queued.add(entry.item),stack.push({...entry,visited:!0}),entry.depth>=TREE_MAX_RENDER_DEPTH))continue;const children=this.childrenOf(entry.item);for(let index=children.length-1;index>=0;index--)queued.has(children[index])||stack.push({item:children[index],visited:!1,depth:entry.depth+1})}return states.get(node)??"none"}normalizeMultipleSelection(){const leavesOnly=this.selection==="leaf-multiple";for(const node of this.allNodeElements())node.selected&&this.childrenOf(node).length>0&&this.setBranchSelection(node,!0,leavesOnly);for(const root of this.nodeElements)this.deriveMultipleSelection(root,leavesOnly)}normalizeSelection(){this.selection==="single"||this.selection==="leaf"?this.normalizeSingleSelection():this.normalizeMultipleSelection()}setSelection(node,selected,indeterminate){this.selectionBefore&&!this.selectionBefore.has(node)&&this.selectionBefore.set(node,[node.selected,node.indeterminate]),setTreeItemSelection(node,selected,indeterminate)}updateSelectionFrom(node){if(node.isDisabled||(this.selection==="single"||this.selection==="leaf")&&!this.selectableInSingleMode(node))return!1;const before=new Map;this.selectionBefore=before;try{if(this.selection==="single"||this.selection==="leaf")for(const candidate of this.allNodeElements())this.setSelection(candidate,candidate===node,!1);else{const select=node.indeterminate||!node.selected;this.setBranchSelection(node,select,this.selection==="leaf-multiple");for(const root of this.nodeElements)this.deriveMultipleSelection(root,this.selection==="leaf-multiple")}}finally{this.selectionBefore=void 0}for(const[candidate,[selected,indeterminate]]of before)if(candidate.selected!==selected||candidate.indeterminate!==indeterminate)return!0;return!1}refreshAuthoredItems(){const nodes=this.nodeElements;for(const node of nodes)node.hasAttribute("slot")&&node.removeAttribute("slot");const authored=nodes.some(node=>!this.generatedNodes.has(node));if(authored)for(const node of nodes)this.generatedNodes.has(node)&&node.remove();this.hasAuthoredItems=authored}visibleNodeElements(){const acc=[],seen=new Set,stack=this.nodeElements.map(node=>({node,depth:0})).reverse();for(;stack.length>0&&acc.length<this.nodeWalkLimit;){const{node,depth}=stack.pop();if(seen.has(node)||(seen.add(node),!this.isNavigable(node))||(acc.push(node),!node.expanded||depth>=TREE_MAX_RENDER_DEPTH))continue;const children=this.childrenOf(node);for(let index=children.length-1;index>=0;index--)stack.push({node:children[index],depth:depth+1})}return acc}findItem(items,id){const stack=[...items].reverse(),seen=new Set;for(;stack.length>0;){const item=stack.pop();if(!seen.has(item)){if(seen.add(item),item.id===id)return item;if(item.children)for(let i=item.children.length-1;i>=0;i--){const child=item.children[i];child&&stack.push(child)}}}}isDuplicateDataPath(item,path){return this.dataIdCollisions.has(item.id)&&this.dataIdOwnerPaths.get(item.id)!==path}rebuildDataIdentity(){const ownerPaths=new Map,collisionIds=new Set,ancestry=new Set,stack=[{items:this.data,index:0,parentPath:"",depth:0}];for(;stack.length>0;){const frame=stack[stack.length-1];if(frame.index>=frame.items.length){frame.owner&&ancestry.delete(frame.owner),stack.pop();continue}const index=frame.index++,item=frame.items[index];if(!item)continue;const path=frame.parentPath===""?String(index):`${frame.parentPath}/${index}`;ownerPaths.has(item.id)?collisionIds.add(item.id):ownerPaths.set(item.id,path),!(frame.depth>=TREE_MAX_RENDER_DEPTH||ancestry.has(item)||!item.children?.length)&&(ancestry.add(item),stack.push({items:item.children,index:0,parentPath:path,depth:frame.depth+1,owner:item}))}this.dataIdOwnerPaths=ownerPaths,this.dataIdCollisions=collisionIds}treeIdentityAt(path){return{path,ownerPaths:this.dataIdOwnerPaths,collisionIds:this.dataIdCollisions,declaredChildrenAtPath:this.declaredChildrenAtPath}}firstEnabledId(items){for(let index=0;index<items.length;index++){const item=items[index];if(!(!item||item.disabled||this.isDuplicateDataPath(item,String(index))))return item.id}return null}isEnabledReachableId(items,id){const stack=items.map((item,index)=>({item,path:String(index)})).reverse(),seen=new Set;for(;stack.length>0;){const{item,path}=stack.pop();if(!seen.has(item)&&(seen.add(item),!(item.disabled||this.isDuplicateDataPath(item,path)))){if(item.id===id)return!0;if(item.children)for(let i=item.children.length-1;i>=0;i--){const child=item.children[i];child&&stack.push({item:child,path:`${path}/${i}`})}}}return!1}findRenderedSiblings(node){const root=node.getRootNode(),shadowHost="host"in root?root.host:null,shadowParent=shadowHost?.localName===tag("tree-item")?shadowHost:null,lightParent=node.parentElement?.localName===tag("tree-item")?node.parentElement:null,parentItem=shadowParent??lightParent,siblings=parentItem?parentItem.childItems():this.nodeElements,index=siblings.indexOf(node);if(!(index<0))return{parent:parentItem,siblings,index}}deepFocusedNode(){const active=deepActiveElementIn(this.ownerDocument);if(!active||active.localName!==tag("tree-item"))return null;const node=active;return this.visibleNodeElements().some(n=>n.nodeId===node.nodeId)?node:null}resolveActiveFromDom(){const inertMutation=this.inertMutationPending;this.inertMutationPending=!1;const visible=this.visibleNodeElements(),current=visible.find(node=>node.nodeId===this.activeId);if(current){this.setActiveNode(current);return}const displaced=this.activeId;if(this.setActiveNode(visible[0]),!inertMutation||this.activeId==null||displaced==null||displaced!==this.lastFocusedNodeId)return;const ownerDocument=this.ownerDocument,active=deepActiveElementIn(ownerDocument),strandedOnDisplaced=active?.nodeType===1&&active.localName===tag("tree-item")&&active.nodeId===displaced;active!==null&&active!==ownerDocument.body&&!strandedOnDisplaced||(this.pendingFocusId=this.activeId)}requestUpdate(name,oldValue){name===void 0&&this._treeSource!==void 0&&this.hierarchy?.update(this._treeSource,this.effectiveLocale,!0),super.requestUpdate(name,oldValue)}willUpdate(changed){if(super.willUpdate(changed),this.hierarchy.update(this.treeSource,this.effectiveLocale),this.treeSource!==void 0){if(!this.sourceMode){this.sourceMode=!0,this.resetChildObserver(),this.pendingFocusId=null,this.pendingReorder=void 0,this.selectionBeforeRefresh=void 0,this.syncRequested=!1,this.syncGeneration++,this.syncRunning=!1,this.syncTask=void 0;for(const node of this.nodeElements)this.generatedNodes.has(node)&&node.remove()}return}if(this.sourceMode&&(this.sourceMode=!1,this.sourceAnnouncement=void 0,this.dataSyncPending=!0,this.selectionSyncPending=!0,this.armChildObserver()),changed.has("maxNodes")&&this.hasUpdated&&!changed.has("data")&&(this.data=this.data),this.refreshAuthoredItems(),(changed.has("data")||changed.has("selection"))&&(this.selectionSyncPending=!0),this.hasAuthoredItems){this.resolveActiveFromDom();return}if(changed.has("data")||this.dataSyncPending){this.dataSyncPending=!1;const focused=this.deepFocusedNode(),focusedId=focused?.nodeId??null;this.rebuildDataIdentity(),this.syncNodes();const activeItem=this.activeId?this.findItem(this.data,this.activeId):void 0;(!this.activeId||!activeItem||activeItem.disabled||!this.isEnabledReachableId(this.data,this.activeId))&&(this.activeId=this.firstEnabledId(this.data)),this.pendingFocusId=focused==null?null:focusedId!=null&&this.findItem(this.data,focusedId)?focusedId:this.activeId}this.inertMutationPending&&this.resolveActiveFromDom()}firstUpdated(changed){super.firstUpdated(changed),hostAriaLabel(this)==null&&!this.label&&devWarnOnce("lyra-tree-missing-accessible-name","<lr-tree> has no accessible name: set `label` or a host `aria-label`.")}updated(changed){if(super.updated(changed),this.treeSource!==void 0){this.announceSource();return}const targeted=changed.size===0&&this.hasAuthoredItems&&this.dirtyConfigureRoots.size>0;if(targeted){const nodes=this.nodeElements,count=nodes.length,positions=this.dirtyConfigureRoots.size>1?new Map(nodes.map((node,index)=>[node,index])):void 0;for(const node of this.dirtyConfigureRoots){const i=positions?positions.get(node)??-1:nodes.indexOf(node);i<0||configureTreeItemOwner(node,{...treeItemOwnerContext(node),activeId:null,activeNodeId:this.readActiveId,ancestry:[],depth:0,setSize:count,posInSet:i+1,selection:this.selection,ownsSelection:!0,identity:void 0,expandIcon:this.iconSource("expand-icon"),collapseIcon:this.iconSource("collapse-icon"),syncOwner:this.requestContextSync,focusOwner:this.onItemFocus})}}else if(changed.has("activeId")||changed.has("data")||this.hasAuthoredItems){const nodes=this.nodeElements,count=this.hasAuthoredItems?nodes.length:this.declaredRootCount;nodes.forEach((node,i)=>{configureTreeItemOwner(node,{...treeItemOwnerContext(node),activeId:null,activeNodeId:this.readActiveId,ancestry:[],depth:0,setSize:count,posInSet:i+1,selection:this.selection,ownsSelection:!0,identity:this.hasAuthoredItems?void 0:this.treeIdentityAt(String(i)),expandIcon:this.iconSource("expand-icon"),collapseIcon:this.iconSource("collapse-icon"),syncOwner:this.requestContextSync,focusOwner:this.onItemFocus})})}targeted||(this.contextSyncPending=!0),this.dirtyConfigureRoots.clear(),this.scheduleTreeSync()}scheduleTreeSync(){this.treeSource===void 0&&(this.syncRequested=!0,!(this.syncRunning||this.bulkExpansions>0)&&(this.syncRunning=!0,this.syncTask=this.runTreeSync()))}async runTreeSync(){const generation=this.syncGeneration;try{for(;this.syncRequested&&(this.syncRequested=!1,await super.getUpdateComplete(),!(this.treeSource!==void 0||generation!==this.syncGeneration||(await cascadeUpdateComplete(this.nodeElements),this.treeSource!==void 0||generation!==this.syncGeneration)||(this.contextSyncPending&&(this.contextSyncPending=!1,this.applyTreeContext()),this.selectionSyncPending&&(this.selectionSyncPending=!1,this.normalizeSelection()),await cascadeUpdateComplete(this.nodeElements),this.treeSource!==void 0||generation!==this.syncGeneration)));)this.reportRefreshSelectionChange(),this.confirmPendingReorder(),this.restorePendingFocus()}finally{generation===this.syncGeneration&&(this.syncRunning=!1)}}rootTreeItemAncestor(node){const itemTag=tag("tree-item");let current=node;for(;current&&current.parentElement&&current.parentElement!==this;)current=current.parentElement;return current&&current.parentElement===this&&current.localName===itemTag?current:null}connectedCallback(){super.connectedCallback(),this.armChildObserver()}armChildObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected||this.treeSource!==void 0||this.childObserver&&this.childObserverDocument===ownerDocument)return;this.resetChildObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.childObserverGeneration,observer=new MutationObserverCtor(records=>{this.childObserver!==observer||this.childObserverDocument!==ownerDocument||this.childObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.onChildMutations(records)});this.childObserver=observer,this.childObserverDocument=ownerDocument,observer.observe(this,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0,attributeFilter:["selected","disabled","inert","lazy"]})}disconnectedCallback(){super.disconnectedCallback(),this.sourceAnnouncement=void 0,this.pendingReorder=void 0,this.activeNode=void 0,this.resetChildObserver()}adoptedCallback(){super.adoptedCallback(),this.hierarchy.adopted(),this.resetChildObserver()}resetChildObserver(){this.childObserverGeneration+=1,this.childObserver?.disconnect(),this.childObserver=void 0,this.childObserverDocument=void 0}syncNodes(){const existingById=new Map;for(const node of this.nodeElements){if(!node.item)continue;const matches=existingById.get(node.item.id)??[];matches.push(node),existingById.set(node.item.id,matches)}let previousSibling=null;for(let index=0;index<this.data.length;index++){const item=this.data[index];let node=existingById.get(item.id)?.shift();node||(node=this.ownerDocument.createElement(tag("tree-item")),this.generatedNodes.add(node)),node.item=item,configureTreeItemOwner(node,{...treeItemOwnerContext(node),ancestry:[],depth:0,setSize:this.declaredRootCount,posInSet:index+1,selection:this.selection,ownsSelection:!0,identity:this.treeIdentityAt(String(index)),expandIcon:this.iconSource("expand-icon"),collapseIcon:this.iconSource("collapse-icon"),syncOwner:this.requestContextSync,focusOwner:this.onItemFocus});const targetPosition=previousSibling?previousSibling.nextElementSibling:this.firstElementChild;targetPosition!==node&&this.insertBefore(node,targetPosition),previousSibling=node}for(const nodes of existingById.values())for(const node of nodes)node.remove()}focusNode(node){node&&(this.setActiveNode(node),node.focus())}subtreeHasId(root,id){if(id==null)return!1;const stack=this.childrenOf(root).map(item=>({item,depth:treeItemOwnerContext(root).depth+1}));for(let visited=0;stack.length>0&&visited<this.nodeWalkLimit;visited++){const{item,depth}=stack.pop();if(!(depth>TREE_MAX_RENDER_DEPTH)){if(item.nodeId===id)return!0;depth<TREE_MAX_RENDER_DEPTH&&stack.push(...this.childrenOf(item).map(child=>({item:child,depth:depth+1})))}}return!1}focusIsWithin(node){for(let current=deepActiveElementIn(this.ownerDocument);current;current=composedParentElement(current)){if(current===node)return!0;if(current===this)return!1}return!1}eventNode(e){const path=e.composedPath(),origin=path[0];if(origin?.nodeType===1&&origin.localName===tag("tree-item")){const treeTag=tag("tree");for(const target of path){if(target===this)return origin;if(target.localName===treeTag)return}return}const id=e.detail?.nodeId;return this.allNodeElements().find(candidate=>candidate.nodeId===id)}async getUpdateComplete(){let result=await super.getUpdateComplete();if(this.treeSource!==void 0)return result;for(;this.syncRunning||this.isUpdatePending;)this.syncRunning&&await this.syncTask,result=await super.getUpdateComplete();return this.treeSource===void 0&&await cascadeUpdateComplete(this.nodeElements),result}reportRefreshSelectionChange(){const before=this.selectionBeforeRefresh;if(before===void 0||this.isUpdatePending)return;this.selectionBeforeRefresh=void 0;const selection=this.selectedItems;selection.length===before.length&&selection.every((item,index)=>item.nodeId===before[index])||this.emit("lr-selection-change",Object.freeze({selection}))}restorePendingFocus(){if(this.pendingFocusId==null)return;const id=this.pendingFocusId;this.pendingFocusId=null;const visible=this.visibleNodeElements();(visible.find(n=>n.nodeId===id)??visible.find(n=>n.nodeId===this.activeId))?.focus()}requestReorder(node,delta){const id=node.nodeId,found=this.findRenderedSiblings(node);if(!found)return;const{parent,siblings,index}=found,total=siblings.length,toIndex=index+delta;toIndex<0||toIndex>=total||(this.pendingReorder={node,parent,originalSiblings:[...siblings],targetSibling:siblings[toIndex],fromIndex:index,toIndex},this.emit("lr-reorder",{nodeId:id,parentNodeId:parent?.nodeId??null,fromIndex:index,toIndex}))}confirmPendingReorder(){const pending=this.pendingReorder;if(!pending)return;const found=this.findRenderedSiblings(pending.node);if(!found){this.pendingReorder=void 0;return}(found.siblings.length!==pending.originalSiblings.length||found.siblings.some((node,index)=>node!==pending.originalSiblings[index]))&&(this.pendingReorder=void 0,!(found.parent!==pending.parent||found.index!==pending.toIndex||found.siblings[pending.fromIndex]!==pending.targetSibling)&&this.liveRegion?.announce(this.localize("treeNodeMoved",void 0,{label:pending.node.nodeLabel,index:this.formatCount(found.index+1),total:this.formatCount(found.siblings.length)}),{force:!0}))}async expandAll(){if(this.treeSource!==void 0)return;let level=this.nodeElements.map(node=>({node,depth:0}));const seen=new Set,systemReduced=preferenceMediaMatches(this.ownerDocument.defaultView,"(prefers-reduced-motion: reduce)");this.bulkExpansions+=1;try{for(;level.length>0&&seen.size<this.nodeWalkLimit;){const current=[];for(const entry of level){const{node}=entry;if(!(seen.has(node)||seen.size>=this.nodeWalkLimit)){if(seen.add(node),current.push(entry),node.isDisabled)node.expanded=!1;else if(node.hasChildren){const reduced=systemReduced||inheritedPreference(node,"data-lr-motion","reduce")==="reduce";withTreeItemMotionPreference(node,reduced,()=>node.expand())}}}await Promise.all(current.map(({node})=>node.updateComplete)),level=[];for(const{node,depth}of current)depth<TREE_MAX_RENDER_DEPTH&&level.push(...this.childrenOf(node).map(child=>({node:child,depth:depth+1})))}}finally{this.bulkExpansions-=1}this.bulkExpansions===0&&this.syncRequested&&this.scheduleTreeSync(),await this.updateComplete}async collapseAll(){if(this.treeSource!==void 0)return;const focused=this.deepFocusedNode(),topLevel=this.nodeElements,nodes=this.allNodeElements();for(let index=nodes.length-1;index>=0;index--){const node=nodes[index];node.isDisabled?node.expanded=!1:node.collapse()}(this.hasAuthoredItems?topLevel.some(node=>this.isNavigable(node)&&node.nodeId===this.activeId):this.data.some(item=>!item.disabled&&item.id===this.activeId))||(this.activeId=this.hasAuthoredItems?topLevel.find(node=>this.isNavigable(node))?.nodeId??null:this.firstEnabledId(this.data)),focused&&(this.pendingFocusId=this.activeId),await cascadeUpdateComplete(topLevel)}render(){return this.treeSource!==void 0?hierarchySourceView(this.hierarchy,{label:hostAriaLabel(this)??this.label,rtl:this.effectiveDirection==="rtl",multiple:this.selection==="multiple"||this.selection==="leaf-multiple",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.accessibleLabel||[value.label,value.description,...(value.badges??[]).map(badge=>badge.label?.trim()?badge.label:badge.text)].filter(text=>text?.trim()).join(" ")||value.id,content:value=>html`${value.icon??nothing}${value.label}${value.description?html` <span>${value.description}</span>`:nothing}${value.badges?.map(badge=>html` <span role=${badge.label?.trim()?"img":nothing} aria-label=${badge.label?.trim()?badge.label:nothing}>${badge.text}</span>`)}`,select:row=>{if((this.selection==="leaf"||this.selection==="leaf-multiple")&&row.childCount>0)return;const multiple=this.selection==="multiple"||this.selection==="leaf-multiple";this.hierarchy.project({type:"select",key:row.key,selected:multiple?!row.selected:!0,scope:multiple&&row.childCount>0?"subtree":"item"},!0,row)}}):html`
2
2
  <div
3
3
  part="base tree"
4
4
  role="tree"
@@ -32,8 +32,9 @@ export type ButtonFormMethod='get'|'post'|'dialog';export interface LyraButtonEv
32
32
  * transient native button rather than this host. With none of those properties set, submission
33
33
  * stays a plain `requestSubmit()` with a `null` submitter.
34
34
  *
35
- * When `href` is set to a safe link URL (`http:`/`https:`/`blob:`/`mailto:`/relative — see
36
- * `safeLinkHref`, or `safeDownloadHref` which drops `mailto:` when `download` is set) the root
35
+ * When `href` is set to a safe link URL (`http:`/`https:`/`blob:`/`mailto:`/`tel:`/`sms:`/relative —
36
+ * see `safeActionLinkHref`, or `safeDownloadHref` which drops `mailto:`, `tel:` and `sms:` when
37
+ * `download` is set) the root
37
38
  * renders as a real `<a part="base" href=…>` instead — for a link styled
38
39
  * as a button (e.g. a CTA). Native navigation is then the anchor's own activation, so the
39
40
  * submit/reset click handler and `type` (submit/reset) have no effect in that mode. When the
@@ -350,10 +351,11 @@ formTarget?:string;
350
351
  loading:boolean;
351
352
  /** When set to a safe link URL, the button's root renders as a real `<a href=…>` instead of a
352
353
  * `<button>` — for a link styled as a button (e.g. a CTA). Unset (the default) renders a plain
353
- * `<button>`, byte-for-byte as before. Only `http:`/`https:`/`blob:`/`mailto:`/relative URLs are
354
- * honored (see `safeLinkHref`); an unsafe/unparseable value falls back to the native `<button>`.
355
- * Setting `download` narrows the allowlist to `safeDownloadHref`'s, which drops `mailto:` — a
356
- * mail handoff names no retrievable bytes, so it cannot be a download target.
354
+ * `<button>`, byte-for-byte as before. Only `http:`/`https:`/`blob:`/`mailto:`/`tel:`/`sms:`/relative
355
+ * URLs are honored (see `safeActionLinkHref`); an unsafe/unparseable value falls back to the
356
+ * native `<button>`. `tel:` and `sms:` hand off to the dialer or messaging app, like `mailto:`
357
+ * to the mail client. Setting `download` narrows the allowlist to `safeDownloadHref`'s, which
358
+ * drops all three — a handoff names no retrievable bytes, so it cannot be a download target.
357
359
  * `type` (submit/reset) has no effect while the anchor renders — an anchor has no submit/reset
358
360
  * concept, and native navigation is its own activation. While the button is disabled the anchor
359
361
  * renders with no `href` (see the class doc comment), so a disabled link button cannot navigate. */
@@ -1,4 +1,4 @@
1
- var _a;import{__decorate}from"tslib";import{FormControlController,reflectFormName}from"../../../internal/form-control-controller.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{FORM_CONTROL_LABEL_FACTORY,LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{installFormControlInternalsCapture}from"../../../internal/form-control-labels.js";import{chevronIcon,spinnerIcon}from"../../../internal/icons.js";import{hasIconOnlyDefaultContent,IconOnlyLabelObserver}from"../../../internal/icon-only-content.js";import{safeDownloadHref,safeLinkHref}from"../../../internal/safe-url.js";import{syncAriaControlsElements}from"../../../internal/aria-reflection.js";import{acquireNativeControlDescription}from"../../../internal/native-control-description.js";import{sizes}from"../../../internal/sizes.styles.js";import{variants}from"../../../internal/variants.styles.js";import{styles}from"./button.styles.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{getFormOwner,setFormOwner}from"../../../internal/direct-form-associated.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState}from"../../../internal/custom-states.js";import{literalSetConverter,omittedEmptyStringConverter}from"../../../internal/converters.js";import{resolveGuardedRel}from"../../../internal/link-rel.js";import{currentValidityValidator}from"../form-validator.js";import{findDefaultButton,isImplicitSubmission,submitFormImplicitly}from"../../../internal/submit-on-enter.js";import{createButtonExternalLabelController}from"./button-external-label.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings/shared.generated.js";installFormControlInternalsCapture();const BUTTON_TYPE=literalSetConverter(["button","submit","reset"],"button"),IMPLICIT_SUBMIT_INPUT=/^(text|search|url|tel|email|password|date|month|week|time|datetime-local|number)$/;class LyraButton extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired}}static get validators(){return[currentValidityValidator("required","disabled","loading","href","value")]}static{this.styles=[LyraElement.styles,sizes,variants,styles]}static{this.formAssociated=!0}static{this[_a]=createButtonExternalLabelController}static{this.properties={disabled:{type:Boolean,reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},customError:{attribute:"custom-error",reflect:!0,noAccessor:!0}}}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this.requestUpdate("disabled",old),this.updateValidity(),this.syncButtonStates()}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",reflectFormName(this,this._name),this.requestUpdate("name",old)}get effectiveDisabled(){return this._disabled||this._fieldsetDisabled}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}constructor(){super(),this._fieldsetDisabled=!1,this._disabled=!1,this._name="",this._value="",this._required=!1,this._variant="neutral",this._type="button",this.injectedHostTabIndex=!1,this.implicitForm=null,this.localDescriptionIds="",this.customValidityMessage="",this.reflectingCustomError=!1,this.accessibleLabel=null,this.triggerHasPopup=null,this.triggerKeyShortcuts=null,this.triggerExpanded=null,this.triggerPressed=null,this.pressed=null,this.triggerCurrent=null,this.triggerControls=null,this.triggerDescribedBy=null,this.appearance="accent",this.size="m",this.pill=!1,this.circle=!1,this.outline=!1,this.withCaret=!1,this.withStart=!1,this.withEnd=!1,this.wrap=!1,this.formNoValidate=!1,this.loading=!1,this.hasStartSlot=!1,this.hasEndSlot=!1,this.isIconButton=!1,this.iconOnlyObserver=new IconOnlyLabelObserver(this,()=>this.labelEl,()=>this.isIconButton,next=>{this.isIconButton=next,this.syncButtonStates()}),this.onFormKeyDown=event=>{const field=event.target,form=this.implicitForm;!form||!isImplicitSubmission(event)||!(field instanceof HTMLInputElement)||!IMPLICIT_SUBMIT_INPUT.test(field.type)||field.form!==form||this.baseEl?.localName==="a"||findDefaultButton(form)!==this||(event.preventDefault(),submitFormImplicitly(form))},this.onClick=event=>{if(this.type!=="submit"&&this.type!=="reset")return;const ownerWindow=this.ownerDocument.defaultView;let settled=!1;const finish=()=>{settled||(settled=!0,ownerWindow?.removeEventListener("click",finishAtWindow),!(event.defaultPrevented||this.effectiveDisabled||this.loading)&&this.runClickDefaultAction())},finishAtWindow=candidate=>{candidate===event&&finish()};ownerWindow?.addEventListener("click",finishAtWindow),queueMicrotask(finish)},this.onFocusChange=event=>{relayNativeEvent(this,event)},this.onAdornmentSlotChange=()=>{this.syncAdornmentSlots()},this.onDefaultSlotChange=()=>{this.isIconButton=hasIconOnlyDefaultContent(this),this.syncButtonStates()},this.validityController=new FormControlController(this,{invalid:init=>this.emit("lr-invalid",null,init),customError:()=>this.customValidityMessage}),this.internals=this.validityController.formInternals,this.updateValidity(),this.syncButtonStates()}get variant(){return this._variant}set variant(next){next==="primary"?this._variant="brand":next==="default"||next==="text"?this._variant="neutral":this._variant=next,next==="text"&&(this.appearance="plain")}get caret(){return this.withCaret}set caret(next){this.withCaret=!!next}get type(){return this._type}set type(next){const old=this._type;this._type=BUTTON_TYPE.normalize(typeof next=="string"?next.toLowerCase():next),this.requestUpdate("type",old)}get value(){return this._value}set value(next){this._value=next??"",this.updateValidity()}get required(){return this._required}set required(next){this._required=!!next,this.updateValidity()}get resolvedRel(){return resolveGuardedRel(this.rel,this.target)}click(){this.effectiveDisabled||this.loading||this.baseEl?.click()}focus(options){!this.effectiveDisabled&&!this.loading&&this.baseEl?.focus(options)}blur(){this.baseEl?.blur()}[(_a=FORM_CONTROL_LABEL_FACTORY,VALIDITY_ANCHOR)](){return this.baseEl??null}checkValidity(){return this.validityController.checkValidity()}reportValidity(){return this.validityController.syncConstraints(),this.internals.reportValidity()}setCustomValidity(message){const old=this.customValidityMessage||null,next=message??"";if(this.customValidityMessage=next,this.validityController.setCustomValidity(this.isValidationBarred?"":next),!this.reflectingCustomError){this.reflectingCustomError=!0;try{next?this.setAttribute("custom-error",next):this.removeAttribute("custom-error")}finally{this.reflectingCustomError=!1}}this.requestUpdate("customError",old)}resetValidity(){this.customValidityMessage="",this.validityController.setCustomValidity(""),this.updateValidity()}formStateRestoreCallback(state2,reason){this.value=typeof state2=="string"?state2:""}syncImplicitSubmission(form=this.getForm()){const next=this.type==="submit"&&this.isConnected?form:null;next!==this.implicitForm&&(this.implicitForm?.removeEventListener("keydown",this.onFormKeyDown),this.implicitForm=next,next?.addEventListener("keydown",this.onFormKeyDown))}formAssociatedCallback(form){this.syncImplicitSubmission(form)}runClickDefaultAction(){if(this.type==="submit"){const form=this.getForm();if(!form)return;this.hasSubmitterOverrides?this.submitAsNamedSubmitter(form):form.requestSubmit()}else this.type==="reset"&&this.getForm()?.reset()}get hasSubmitterOverrides(){return!!(this.name||this.value||this.formNoValidate)||this.formAction!==void 0||this.formEnctype!==void 0||this.formMethod!==void 0||this.formTarget!==void 0}submitAsNamedSubmitter(form){const submitter=this.ownerDocument.createElement("button");submitter.type="submit",submitter.hidden=!0,submitter.tabIndex=-1,this.name&&(submitter.name=this.name,submitter.value=this.value),this.formAction!==void 0&&submitter.setAttribute("formaction",this.formAction),this.formEnctype!==void 0&&submitter.setAttribute("formenctype",this.formEnctype),this.formMethod!==void 0&&submitter.setAttribute("formmethod",this.formMethod),this.formNoValidate&&(submitter.formNoValidate=!0),this.formTarget!==void 0&&submitter.setAttribute("formtarget",this.formTarget),this.parentElement&&this.closest("form")===form?this.insertAdjacentElement("afterend",submitter):form.append(submitter);try{form.requestSubmit(submitter)}finally{submitter.remove()}}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(this.updateValidity(),this.syncButtonStates(),this.requestUpdate())}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncDescribedByElements(),this.syncImplicitSubmission(),this.updateValidity(),this.syncButtonStates(),this.hasUpdated&&this.iconOnlyObserver.arm()}disconnectedCallback(){this.releaseExternalDescription(),this.syncImplicitSubmission(null),this.iconOnlyObserver.disarm(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.isConnected&&this.hasUpdated&&this.syncDescribedByElements()}willUpdate(changed){super.willUpdate(changed);const focusedControl=shadowFocusTarget(this);changed.has("loading")&&this.loading&&focusedControl!==null&&focusedControl===this.baseEl&&(this.hasAttribute("tabindex")||(this.tabIndex=-1,this.injectedHostTabIndex=!0),HTMLElement.prototype.focus.call(this,{preventScroll:!0})),this.hasUpdated||this.seedFirstRenderState(()=>{this.syncAdornmentSlots(),this.isIconButton=hasIconOnlyDefaultContent(this)})}syncAdornmentSlots(){const collection=this.children,children=collection?Array.from(collection):[];this.hasStartSlot=children.some(element=>{const slot=element.getAttribute("slot");return slot==="start"||slot==="prefix"}),this.hasEndSlot=children.some(element=>{const slot=element.getAttribute("slot");return slot==="end"||slot==="suffix"})}get labelGrows(){return this.withCaret||this.hasEndSlot||this.withEnd}updated(changed){if(super.updated(changed),changed.has("type")&&this.syncImplicitSubmission(),changed.has("loading")&&!this.loading&&this.injectedHostTabIndex){const parked=this.ownerDocument.activeElement===this&&!shadowFocusTarget(this);this.removeAttribute("tabindex"),this.injectedHostTabIndex=!1,parked&&this.baseEl?.focus({preventScroll:!0})}syncAriaControlsElements(this,this.baseEl,this.triggerControls),this.syncDescribedByElements(),this.iconOnlyObserver.arm(),this.updateValidity(),this.syncButtonStates()}updateValidity(){if(this.validityController){if(this.isValidationBarred){this.validityController.setCustomValidity(""),this.validityController.setValidity({});return}this.required&&!this.value?this.validityController.setValidity({valueMissing:!0},this.localize("fieldRequired")):this.validityController.setValidity({}),this.validityController.setCustomValidity(this.customValidityMessage)}}get isValidationBarred(){return this.effectiveDisabled||this.loading||this.baseEl?.localName==="a"}syncButtonStates(){this.internals&&(setCustomState(this.internals,"disabled",this.effectiveDisabled||this.loading),setCustomState(this.internals,"icon-button",this.isIconButton),setCustomState(this.internals,"link",this.baseEl?.localName==="a"),setCustomState(this.internals,"loading",this.loading))}syncDescribedByElements(){const target=this.isConnected?this.baseEl:void 0;if(!target){this.releaseExternalDescription();return}this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireNativeControlDescription(this,target,()=>this.localDescriptionIds)}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}render(){const pressed=this.pressed==="mixed"?"mixed":typeof this.pressed=="boolean"?String(this.pressed):["true","false","mixed"].includes(this.triggerPressed??"")?this.triggerPressed:nothing,current=["page","step","location","date","time","true","false"].includes(this.triggerCurrent??"")?this.triggerCurrent:nothing,content=html`
1
+ var _a;import{__decorate}from"tslib";import{FormControlController,reflectFormName}from"../../../internal/form-control-controller.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{FORM_CONTROL_LABEL_FACTORY,LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{installFormControlInternalsCapture}from"../../../internal/form-control-labels.js";import{chevronIcon,spinnerIcon}from"../../../internal/icons.js";import{hasIconOnlyDefaultContent,IconOnlyLabelObserver}from"../../../internal/icon-only-content.js";import{safeActionLinkHref,safeDownloadHref}from"../../../internal/safe-url.js";import{syncAriaControlsElements}from"../../../internal/aria-reflection.js";import{acquireNativeControlDescription}from"../../../internal/native-control-description.js";import{sizes}from"../../../internal/sizes.styles.js";import{variants}from"../../../internal/variants.styles.js";import{styles}from"./button.styles.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{getFormOwner,setFormOwner}from"../../../internal/direct-form-associated.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState}from"../../../internal/custom-states.js";import{literalSetConverter,omittedEmptyStringConverter}from"../../../internal/converters.js";import{resolveGuardedRel}from"../../../internal/link-rel.js";import{currentValidityValidator}from"../form-validator.js";import{findDefaultButton,isImplicitSubmission,submitFormImplicitly}from"../../../internal/submit-on-enter.js";import{createButtonExternalLabelController}from"./button-external-label.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings/shared.generated.js";installFormControlInternalsCapture();const BUTTON_TYPE=literalSetConverter(["button","submit","reset"],"button"),IMPLICIT_SUBMIT_INPUT=/^(text|search|url|tel|email|password|date|month|week|time|datetime-local|number)$/;class LyraButton extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired}}static get validators(){return[currentValidityValidator("required","disabled","loading","href","value")]}static{this.styles=[LyraElement.styles,sizes,variants,styles]}static{this.formAssociated=!0}static{this[_a]=createButtonExternalLabelController}static{this.properties={disabled:{type:Boolean,reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},customError:{attribute:"custom-error",reflect:!0,noAccessor:!0}}}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this.requestUpdate("disabled",old),this.updateValidity(),this.syncButtonStates()}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",reflectFormName(this,this._name),this.requestUpdate("name",old)}get effectiveDisabled(){return this._disabled||this._fieldsetDisabled}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}constructor(){super(),this._fieldsetDisabled=!1,this._disabled=!1,this._name="",this._value="",this._required=!1,this._variant="neutral",this._type="button",this.injectedHostTabIndex=!1,this.implicitForm=null,this.localDescriptionIds="",this.customValidityMessage="",this.reflectingCustomError=!1,this.accessibleLabel=null,this.triggerHasPopup=null,this.triggerKeyShortcuts=null,this.triggerExpanded=null,this.triggerPressed=null,this.pressed=null,this.triggerCurrent=null,this.triggerControls=null,this.triggerDescribedBy=null,this.appearance="accent",this.size="m",this.pill=!1,this.circle=!1,this.outline=!1,this.withCaret=!1,this.withStart=!1,this.withEnd=!1,this.wrap=!1,this.formNoValidate=!1,this.loading=!1,this.hasStartSlot=!1,this.hasEndSlot=!1,this.isIconButton=!1,this.iconOnlyObserver=new IconOnlyLabelObserver(this,()=>this.labelEl,()=>this.isIconButton,next=>{this.isIconButton=next,this.syncButtonStates()}),this.onFormKeyDown=event=>{const field=event.target,form=this.implicitForm;!form||!isImplicitSubmission(event)||!(field instanceof HTMLInputElement)||!IMPLICIT_SUBMIT_INPUT.test(field.type)||field.form!==form||this.baseEl?.localName==="a"||findDefaultButton(form)!==this||(event.preventDefault(),submitFormImplicitly(form))},this.onClick=event=>{if(this.type!=="submit"&&this.type!=="reset")return;const ownerWindow=this.ownerDocument.defaultView;let settled=!1;const finish=()=>{settled||(settled=!0,ownerWindow?.removeEventListener("click",finishAtWindow),!(event.defaultPrevented||this.effectiveDisabled||this.loading)&&this.runClickDefaultAction())},finishAtWindow=candidate=>{candidate===event&&finish()};ownerWindow?.addEventListener("click",finishAtWindow),queueMicrotask(finish)},this.onFocusChange=event=>{relayNativeEvent(this,event)},this.onAdornmentSlotChange=()=>{this.syncAdornmentSlots()},this.onDefaultSlotChange=()=>{this.isIconButton=hasIconOnlyDefaultContent(this),this.syncButtonStates()},this.validityController=new FormControlController(this,{invalid:init=>this.emit("lr-invalid",null,init),customError:()=>this.customValidityMessage}),this.internals=this.validityController.formInternals,this.updateValidity(),this.syncButtonStates()}get variant(){return this._variant}set variant(next){next==="primary"?this._variant="brand":next==="default"||next==="text"?this._variant="neutral":this._variant=next,next==="text"&&(this.appearance="plain")}get caret(){return this.withCaret}set caret(next){this.withCaret=!!next}get type(){return this._type}set type(next){const old=this._type;this._type=BUTTON_TYPE.normalize(typeof next=="string"?next.toLowerCase():next),this.requestUpdate("type",old)}get value(){return this._value}set value(next){this._value=next??"",this.updateValidity()}get required(){return this._required}set required(next){this._required=!!next,this.updateValidity()}get resolvedRel(){return resolveGuardedRel(this.rel,this.target)}click(){this.effectiveDisabled||this.loading||this.baseEl?.click()}focus(options){!this.effectiveDisabled&&!this.loading&&this.baseEl?.focus(options)}blur(){this.baseEl?.blur()}[(_a=FORM_CONTROL_LABEL_FACTORY,VALIDITY_ANCHOR)](){return this.baseEl??null}checkValidity(){return this.validityController.checkValidity()}reportValidity(){return this.validityController.syncConstraints(),this.internals.reportValidity()}setCustomValidity(message){const old=this.customValidityMessage||null,next=message??"";if(this.customValidityMessage=next,this.validityController.setCustomValidity(this.isValidationBarred?"":next),!this.reflectingCustomError){this.reflectingCustomError=!0;try{next?this.setAttribute("custom-error",next):this.removeAttribute("custom-error")}finally{this.reflectingCustomError=!1}}this.requestUpdate("customError",old)}resetValidity(){this.customValidityMessage="",this.validityController.setCustomValidity(""),this.updateValidity()}formStateRestoreCallback(state2,reason){this.value=typeof state2=="string"?state2:""}syncImplicitSubmission(form=this.getForm()){const next=this.type==="submit"&&this.isConnected?form:null;next!==this.implicitForm&&(this.implicitForm?.removeEventListener("keydown",this.onFormKeyDown),this.implicitForm=next,next?.addEventListener("keydown",this.onFormKeyDown))}formAssociatedCallback(form){this.syncImplicitSubmission(form)}runClickDefaultAction(){if(this.type==="submit"){const form=this.getForm();if(!form)return;this.hasSubmitterOverrides?this.submitAsNamedSubmitter(form):form.requestSubmit()}else this.type==="reset"&&this.getForm()?.reset()}get hasSubmitterOverrides(){return!!(this.name||this.value||this.formNoValidate)||this.formAction!==void 0||this.formEnctype!==void 0||this.formMethod!==void 0||this.formTarget!==void 0}submitAsNamedSubmitter(form){const submitter=this.ownerDocument.createElement("button");submitter.type="submit",submitter.hidden=!0,submitter.tabIndex=-1,this.name&&(submitter.name=this.name,submitter.value=this.value),this.formAction!==void 0&&submitter.setAttribute("formaction",this.formAction),this.formEnctype!==void 0&&submitter.setAttribute("formenctype",this.formEnctype),this.formMethod!==void 0&&submitter.setAttribute("formmethod",this.formMethod),this.formNoValidate&&(submitter.formNoValidate=!0),this.formTarget!==void 0&&submitter.setAttribute("formtarget",this.formTarget),this.parentElement&&this.closest("form")===form?this.insertAdjacentElement("afterend",submitter):form.append(submitter);try{form.requestSubmit(submitter)}finally{submitter.remove()}}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(this.updateValidity(),this.syncButtonStates(),this.requestUpdate())}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncDescribedByElements(),this.syncImplicitSubmission(),this.updateValidity(),this.syncButtonStates(),this.hasUpdated&&this.iconOnlyObserver.arm()}disconnectedCallback(){this.releaseExternalDescription(),this.syncImplicitSubmission(null),this.iconOnlyObserver.disarm(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.isConnected&&this.hasUpdated&&this.syncDescribedByElements()}willUpdate(changed){super.willUpdate(changed);const focusedControl=shadowFocusTarget(this);changed.has("loading")&&this.loading&&focusedControl!==null&&focusedControl===this.baseEl&&(this.hasAttribute("tabindex")||(this.tabIndex=-1,this.injectedHostTabIndex=!0),HTMLElement.prototype.focus.call(this,{preventScroll:!0})),this.hasUpdated||this.seedFirstRenderState(()=>{this.syncAdornmentSlots(),this.isIconButton=hasIconOnlyDefaultContent(this)})}syncAdornmentSlots(){const collection=this.children,children=collection?Array.from(collection):[];this.hasStartSlot=children.some(element=>{const slot=element.getAttribute("slot");return slot==="start"||slot==="prefix"}),this.hasEndSlot=children.some(element=>{const slot=element.getAttribute("slot");return slot==="end"||slot==="suffix"})}get labelGrows(){return this.withCaret||this.hasEndSlot||this.withEnd}updated(changed){if(super.updated(changed),changed.has("type")&&this.syncImplicitSubmission(),changed.has("loading")&&!this.loading&&this.injectedHostTabIndex){const parked=this.ownerDocument.activeElement===this&&!shadowFocusTarget(this);this.removeAttribute("tabindex"),this.injectedHostTabIndex=!1,parked&&this.baseEl?.focus({preventScroll:!0})}syncAriaControlsElements(this,this.baseEl,this.triggerControls),this.syncDescribedByElements(),this.iconOnlyObserver.arm(),this.updateValidity(),this.syncButtonStates()}updateValidity(){if(this.validityController){if(this.isValidationBarred){this.validityController.setCustomValidity(""),this.validityController.setValidity({});return}this.required&&!this.value?this.validityController.setValidity({valueMissing:!0},this.localize("fieldRequired")):this.validityController.setValidity({}),this.validityController.setCustomValidity(this.customValidityMessage)}}get isValidationBarred(){return this.effectiveDisabled||this.loading||this.baseEl?.localName==="a"}syncButtonStates(){this.internals&&(setCustomState(this.internals,"disabled",this.effectiveDisabled||this.loading),setCustomState(this.internals,"icon-button",this.isIconButton),setCustomState(this.internals,"link",this.baseEl?.localName==="a"),setCustomState(this.internals,"loading",this.loading))}syncDescribedByElements(){const target=this.isConnected?this.baseEl:void 0;if(!target){this.releaseExternalDescription();return}this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireNativeControlDescription(this,target,()=>this.localDescriptionIds)}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}render(){const pressed=this.pressed==="mixed"?"mixed":typeof this.pressed=="boolean"?String(this.pressed):["true","false","mixed"].includes(this.triggerPressed??"")?this.triggerPressed:nothing,current=["page","step","location","date","time","true","false"].includes(this.triggerCurrent??"")?this.triggerCurrent:nothing,content=html`
2
2
  <span
3
3
  part="start prefix"
4
4
  ?hidden=${!(this.hasStartSlot||this.withStart)}
@@ -15,7 +15,7 @@ var _a;import{__decorate}from"tslib";import{FormControlController,reflectFormNam
15
15
  </span>
16
16
  ${this.withCaret?html`<span part="caret" aria-hidden="true">${chevronIcon()}</span>`:nothing}
17
17
  ${this.loading?html`<span part="spinner" aria-hidden="true">${spinnerIcon()}</span>`:""}
18
- `,hasDownload=this.download!==void 0,href=hasDownload?safeDownloadHref(this.href):safeLinkHref(this.href);if(href){const disabled=this.effectiveDisabled||this.loading;return html`<a
18
+ `,hasDownload=this.download!==void 0,href=hasDownload?safeDownloadHref(this.href):safeActionLinkHref(this.href);if(href){const disabled=this.effectiveDisabled||this.loading;return html`<a
19
19
  part="base button"
20
20
  ?data-icon-button=${this.isIconButton}
21
21
  ?data-grow-label=${this.labelGrows}