@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,4 +1,4 @@
1
- import{__decorate}from"tslib";import{collectionSupport,publicCollectionTruncation}from"../../../internal/collection-snapshot.js";import{html,nothing,svg}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{firstByRetrievalIdentity,isNonBlankIdentity,isRecord}from"../retrieval-identity.js";import{readOwnDataValue}from"../../../internal/data-descriptors.js";import{srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink,AnnouncementSinkController}from"../../../internal/announcer.js";import{SourcePageController}from"../../../internal/source-page-controller.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{finiteCount,finiteInteger}from"../../../internal/numbers.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{closeIcon}from"../../../internal/icons.js";import{styles}from"./ingestion-queue.styles.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{LYRA_DEFAULT_ingestionAttemptCount,LYRA_DEFAULT_ingestionCancelWithContext,LYRA_DEFAULT_ingestionChunkCount,LYRA_DEFAULT_ingestionEmbeddedOfTotal,LYRA_DEFAULT_ingestionItemProgressLabel,LYRA_DEFAULT_ingestionQueueEmpty,LYRA_DEFAULT_ingestionQueueInputLimit,LYRA_DEFAULT_ingestionQueueLabel,LYRA_DEFAULT_ingestionRetryWithContext,LYRA_DEFAULT_ingestionStageCancelled,LYRA_DEFAULT_ingestionStageChunking,LYRA_DEFAULT_ingestionStageDone,LYRA_DEFAULT_ingestionStageEmbedding,LYRA_DEFAULT_ingestionStageExtracting,LYRA_DEFAULT_ingestionStageFailed,LYRA_DEFAULT_ingestionStageIndexing,LYRA_DEFAULT_ingestionStageQueued,LYRA_DEFAULT_ingestionStageUnknown,LYRA_DEFAULT_ingestionStageUploading,LYRA_DEFAULT_untitledSource}from"../../../internal/default-strings/retrieval.generated.js";import{LYRA_DEFAULT_cancel,LYRA_DEFAULT_loading,LYRA_DEFAULT_retry,LYRA_DEFAULT_tableLoadFailed}from"../../../internal/default-strings/shared.generated.js";const INGESTION_STAGES=new Set(["queued","uploading","extracting","chunking","embedding","indexing","done","failed","cancelled"]);function normalizedStage(stage){return INGESTION_STAGES.has(stage)?stage:"unknown"}const ACTIVE_STAGES=["uploading","extracting","chunking","embedding","indexing"],CANCELABLE_STAGES=["queued",...ACTIVE_STAGES];function badgeVariantForStage(stage){switch(stage){case"done":return"success";case"failed":return"danger";case"queued":case"cancelled":case"unknown":return"neutral";default:return"brand"}}const SOURCE_QUERY=Object.freeze({}),ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function retryIcon(){return svg`
1
+ import{__decorate}from"tslib";import{collectionSupport,publicCollectionTruncation}from"../../../internal/collection-snapshot.js";import{html,nothing,svg}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{deepActiveElementIn}from"../../../internal/active-element.js";import{captureComposedFocusRepair,applyComposedFocusRepair}from"../../../internal/focus-navigation.js";import{tag}from"../../../internal/prefix.js";import{devWarnOnce}from"../../../internal/dev-warning.js";import{projectIngestionPresentation,ingestionActionKey}from"./ingestion-queue-presentation.js";import{LyraElement}from"../../../internal/lyra-element.js";import{firstByRetrievalIdentity,isNonBlankIdentity,isRecord}from"../retrieval-identity.js";import{readOwnDataValue}from"../../../internal/data-descriptors.js";import{srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink,AnnouncementSinkController}from"../../../internal/announcer.js";import{SourcePageController}from"../../../internal/source-page-controller.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{finiteCount,finiteInteger}from"../../../internal/numbers.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{closeIcon}from"../../../internal/icons.js";import{styles}from"./ingestion-queue.styles.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{LYRA_DEFAULT_ingestionActionWithContext,LYRA_DEFAULT_ingestionAttemptCount,LYRA_DEFAULT_ingestionCancelWithContext,LYRA_DEFAULT_ingestionChunkCount,LYRA_DEFAULT_ingestionEmbeddedOfTotal,LYRA_DEFAULT_ingestionItemProgressLabel,LYRA_DEFAULT_ingestionQueueActionLimit,LYRA_DEFAULT_ingestionQueueEmpty,LYRA_DEFAULT_ingestionQueueInputLimit,LYRA_DEFAULT_ingestionQueueLabel,LYRA_DEFAULT_ingestionRetryWithContext,LYRA_DEFAULT_ingestionStageCancelled,LYRA_DEFAULT_ingestionStageChunking,LYRA_DEFAULT_ingestionStageDone,LYRA_DEFAULT_ingestionStageEmbedding,LYRA_DEFAULT_ingestionStageExtracting,LYRA_DEFAULT_ingestionStageFailed,LYRA_DEFAULT_ingestionStageIndexing,LYRA_DEFAULT_ingestionStageQueued,LYRA_DEFAULT_ingestionStageUnknown,LYRA_DEFAULT_ingestionStageUploading,LYRA_DEFAULT_untitledSource}from"../../../internal/default-strings/retrieval.generated.js";import{LYRA_DEFAULT_cancel,LYRA_DEFAULT_loading,LYRA_DEFAULT_retry,LYRA_DEFAULT_tableLoadFailed}from"../../../internal/default-strings/shared.generated.js";const INGESTION_STAGES=new Set(["queued","uploading","extracting","chunking","embedding","indexing","done","failed","cancelled","custom"]);function normalizedStage(stage){return INGESTION_STAGES.has(stage)?stage:"unknown"}const ACTIVE_STAGES=["uploading","extracting","chunking","embedding","indexing"],CANCELABLE_STAGES=["queued",...ACTIVE_STAGES],DEFAULT_RETRY_ACTIONS=Object.freeze([Object.freeze({type:"retry"})]),DEFAULT_CANCEL_ACTIONS=Object.freeze([Object.freeze({type:"cancel"})]),NO_ACTIONS=Object.freeze([]);function badgeVariantForStage(stage){switch(stage){case"done":return"success";case"failed":return"danger";case"queued":case"cancelled":case"unknown":case"custom":return"neutral";default:return"brand"}}const SOURCE_QUERY=Object.freeze({}),ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function retryIcon(){return svg`
2
2
  <svg
3
3
  width="1em"
4
4
  height="1em"
@@ -11,7 +11,7 @@ import{__decorate}from"tslib";import{collectionSupport,publicCollectionTruncatio
11
11
  aria-hidden="true"
12
12
  focusable="false"
13
13
  ><polyline points="1 4 1 10 7 10"></polyline><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"></path></svg>
14
- `}const DEFAULT_VIRTUALIZE_AT=100;class LyraIngestionQueue extends LyraElement{constructor(){super(...arguments),this.items=[],this.sourceEpoch=0,this.sourceSyncing=!1,this.sourceRows=[],this.sourceItemIdentities=new WeakSet,this.sourceStateVersion=0,this.sourcePages=new SourcePageController(this,{normalizeRecord:(record,isCurrent)=>this.projectSourceItem(record,isCurrent),validateMetadata:()=>{},onChange:()=>{this.sourceStateVersion++}}),this.sourcePage=0,this.sourcePageSize=100,this.onSourcePage=event=>{event.stopPropagation(),this.sourceBlocked||(this.sourcePage=event.detail.page-1)},this.virtualizeAt=DEFAULT_VIRTUALIZE_AT,this.announce=!1,this.failureLiveText="",this.isMounting=!0,this.initialFailuresAnnounced=!1,this.limitAnnouncements=new AnnouncementSinkController(this,{eager:["polite"]}),this.limitInitialized=!1,this.previouslyInputTruncated=!1,this.sourceStatusInitialized=!1,this.previousSourceStatus="",this.fallbackFailureItems=new WeakSet,this.ingestionItemKey=item=>item.id,this.stopOwnedEvent=event=>{event.stopPropagation()},this.itemTemplate=(item,ownRole)=>{const stage=normalizedStage(item.stage),stageLabel=this.stageLabel(stage),name=item.document.name.trim()?item.document.name:this.localize("untitledSource"),showProgress=stage!=="unknown"&&ACTIVE_STAGES.includes(stage),canRetry=stage==="failed",canCancel=stage!=="unknown"&&CANCELABLE_STAGES.includes(stage),attempts=this.normalizedAttempts(item),hasMeta=item.chunkCount!==void 0||item.embeddedChunkCount!==void 0||attempts>0,indeterminate=item.progress===void 0||!Number.isFinite(item.progress);return html`
14
+ `}const DEFAULT_VIRTUALIZE_AT=100;class LyraIngestionQueue extends LyraElement{constructor(){super(...arguments),this.items=[],this.sourceEpoch=0,this.sourceSyncing=!1,this.sourceRows=[],this.presentations=new WeakMap,this.focusRepairGeneration=0,this.sourceStateVersion=0,this.sourcePages=new SourcePageController(this,{normalizeRecord:(record,isCurrent)=>this.projectSourceItem(record,isCurrent),validateMetadata:()=>{},onChange:()=>{this.sourceStateVersion++}}),this.sourcePage=0,this.sourcePageSize=100,this.onSourcePage=event=>{event.stopPropagation(),this.sourceBlocked||(this.sourcePage=event.detail.page-1)},this.virtualizeAt=DEFAULT_VIRTUALIZE_AT,this.announce=!1,this.failureLiveText="",this.isMounting=!0,this.initialFailuresAnnounced=!1,this.limitAnnouncements=new AnnouncementSinkController(this,{eager:["polite"]}),this.limitInitialized=!1,this.previouslyInputTruncated=!1,this.sourceStatusInitialized=!1,this.previousSourceStatus="",this.fallbackFailureItems=new WeakSet,this.ingestionItemKey=item=>item.id,this.stopOwnedEvent=event=>{event.stopPropagation()},this.itemTemplate=(item,ownRole)=>{const stage=this.itemStage(item),stageLabel=stage==="custom"?item.customStage.label:this.stageLabel(stage),name=item.document.name.trim()?item.document.name:this.localize("untitledSource"),showProgress=stage==="custom"?item.customStage.showProgress===!0:ACTIVE_STAGES.includes(stage),actions=this.rowActions(item),attempts=this.normalizedAttempts(item),hasMeta=item.chunkCount!==void 0||item.embeddedChunkCount!==void 0||attempts>0,indeterminate=item.progress===void 0||!Number.isFinite(item.progress);return html`
15
15
  <div
16
16
  part="item"
17
17
  role=${ownRole?"listitem":nothing}
@@ -19,7 +19,7 @@ import{__decorate}from"tslib";import{collectionSupport,publicCollectionTruncatio
19
19
  >
20
20
  <div part="item-header">
21
21
  <span part="item-name" title=${name}>${name}</span>
22
- <lr-badge part="item-stage" variant=${badgeVariantForStage(stage)}
22
+ <lr-badge part="item-stage" variant=${stage==="custom"?item.customStage.variant??"neutral":badgeVariantForStage(stage)}
23
23
  >${stageLabel}</lr-badge
24
24
  >
25
25
  </div>
@@ -41,39 +41,26 @@ import{__decorate}from"tslib";import{collectionSupport,publicCollectionTruncatio
41
41
  >`:nothing}
42
42
  </div>`:nothing}
43
43
  ${stage==="failed"&&item.error?html`<p part="item-error">${this.fallbackFailureItems.has(item)?this.localize("ingestionStageFailed"):item.error}</p>`:nothing}
44
- ${canRetry||canCancel?html`<div part="item-actions">
45
- ${canRetry?html`<button
46
- part="retry-button"
47
- type="button"
48
- aria-label=${this.localize("ingestionRetryWithContext",void 0,{label:name})}
49
- @click=${()=>this.onRetryClick(item)}
50
- >
51
- ${retryIcon()}<span>${this.localize("retry")}</span>
52
- </button>`:nothing}
53
- ${canCancel?html`<button
54
- part="cancel-button"
55
- type="button"
56
- aria-label=${this.localize("ingestionCancelWithContext",void 0,{label:name})}
57
- @click=${()=>this.onCancelClick(item)}
58
- >
59
- ${closeIcon()}<span>${this.localize("cancel")}</span>
60
- </button>`:nothing}
61
- </div>`:nothing}
44
+ ${actions.length?html`<div part="item-actions">${repeat(actions,ingestionActionKey,action=>this.renderRowAction(item,action,name))}</div>`:nothing}
45
+ ${this.renderActionLimit(item,name)}
62
46
  </div>
63
- `}}static{this.defaultStrings={...super.defaultStrings,cancel:LYRA_DEFAULT_cancel,ingestionAttemptCount:LYRA_DEFAULT_ingestionAttemptCount,ingestionCancelWithContext:LYRA_DEFAULT_ingestionCancelWithContext,ingestionChunkCount:LYRA_DEFAULT_ingestionChunkCount,ingestionEmbeddedOfTotal:LYRA_DEFAULT_ingestionEmbeddedOfTotal,ingestionItemProgressLabel:LYRA_DEFAULT_ingestionItemProgressLabel,ingestionQueueEmpty:LYRA_DEFAULT_ingestionQueueEmpty,ingestionQueueInputLimit:LYRA_DEFAULT_ingestionQueueInputLimit,ingestionQueueLabel:LYRA_DEFAULT_ingestionQueueLabel,ingestionRetryWithContext:LYRA_DEFAULT_ingestionRetryWithContext,ingestionStageCancelled:LYRA_DEFAULT_ingestionStageCancelled,ingestionStageChunking:LYRA_DEFAULT_ingestionStageChunking,ingestionStageDone:LYRA_DEFAULT_ingestionStageDone,ingestionStageEmbedding:LYRA_DEFAULT_ingestionStageEmbedding,ingestionStageExtracting:LYRA_DEFAULT_ingestionStageExtracting,ingestionStageFailed:LYRA_DEFAULT_ingestionStageFailed,ingestionStageIndexing:LYRA_DEFAULT_ingestionStageIndexing,ingestionStageQueued:LYRA_DEFAULT_ingestionStageQueued,ingestionStageUnknown:LYRA_DEFAULT_ingestionStageUnknown,ingestionStageUploading:LYRA_DEFAULT_ingestionStageUploading,loading:LYRA_DEFAULT_loading,retry:LYRA_DEFAULT_retry,tableLoadFailed:LYRA_DEFAULT_tableLoadFailed,untitledSource:LYRA_DEFAULT_untitledSource}}static{this.collectionSupport=collectionSupport}static{this.identityCollectionProperties=Object.freeze(["items"])}static{this.ownedCollectionProperties=Object.freeze(["items"])}static{this.styles=[LyraElement.styles,styles,srOnly]}get dataSource(){return this._dataSource}set dataSource(value){const previous=this._dataSource;this._dataSource=value,this.sourceEpoch++,this.requestUpdate("dataSource",previous)}get sourceTotal(){return this.sourceMode?this.sourcePages.state.result?.total??null:null}get sourceMode(){return this.dataSource!==void 0}get sourceFailed(){return this.sourceMode&&!this.sourcePages.state.pending&&!this.sourcePages.state.result}get sourceBlocked(){return this.sourceMode&&(!this.isConnected||this.sourcePages.state.pending||this.sourceFailed)}projectSourceItem(record,isCurrent){const assertCurrent=()=>{if(!isCurrent())throw new TypeError("Obsolete source record")},descriptorOf=(target,key)=>{assertCurrent();const descriptor=getOwnDataDescriptor(target,key);return assertCurrent(),descriptor};assertCurrent();const field=(value2,key)=>{if(!isRecord(value2))throw new TypeError("Invalid source item");const descriptor=descriptorOf(value2,key);if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)throw new TypeError("Invalid source field");return descriptor===MISSING_OWN_DATA_DESCRIPTOR?void 0:descriptor.value};let units=0;const text=(value2,required=!1)=>{if(!(value2===void 0&&!required)){if(typeof value2!="string"||value2.length>65536||(units+=value2.length)>65536)throw new TypeError("Invalid source text");return value2}},raw=record.value,id=text(field(raw,"id"),!0),rawDocument=field(raw,"document"),documentId=text(field(rawDocument,"id"),!0);if(id!==record.key||!isNonBlankIdentity(documentId))throw new TypeError("Invalid source identity");const document=Object.freeze({id:documentId,name:text(field(rawDocument,"name"),!0),mimeType:text(field(rawDocument,"mimeType")),uri:text(field(rawDocument,"uri")),version:text(field(rawDocument,"version"))}),stage=text(field(raw,"stage")),errorValue=field(raw,"error"),error=errorValue==null?void 0:text(typeof errorValue=="string"?errorValue:this.localize("ingestionStageFailed")),numbers={};for(const key of["progress","chunkCount","embeddedChunkCount","attempts"]){const value2=field(raw,key);if(value2!==void 0){if(typeof value2!="number")throw new TypeError("Invalid source number");numbers[key]=value2}}const value=Object.freeze({id,document,stage,error,...numbers});return assertCurrent(),this.sourceItemIdentities.add(value),errorValue!=null&&typeof errorValue!="string"&&this.fallbackFailureItems.add(value),assertCurrent(),{key:record.key,order:record.order,value}}syncSource(){if(!(!this.sourcePages||this.sourceSyncing)){this.sourceSyncing=!0;try{if(!this.sourceMode){this.sourceInputs&&this.sourcePages.bind(void 0),this.sourceInputs=void 0,this.sourceSize=void 0,this.sourceResult=void 0,this.sourceRows=[];return}const source=this.dataSource,size=finiteInteger(this.sourcePageSize,100,1,500);let page=finiteInteger(this.sourcePage,0,0,Math.floor(Number.MAX_SAFE_INTEGER/size));this.sourceSize!==void 0&&this.sourceSize!==size&&(page=0,this.sourcePage=0),this.sourceSize=size;const revision=source.revision,inputs=[source,revision,this.sourceEpoch,this.effectiveLocale,size,page];if(this.sourceInputs&&inputs.every((value,index)=>value===this.sourceInputs[index]))return;this.sourceInputs=inputs,this.sourceRows=[],this.sourceResult=void 0,this.sourcePages.bind({source,revision,epoch:this.sourceEpoch,locale:this.effectiveLocale}),this.sourcePages.request(SOURCE_QUERY,page,size)}catch{this.sourcePages.bind(void 0),this.sourceRows=[],this.sourceResult=void 0}finally{this.sourceSyncing=!1}}}acceptSourcePage(){const result=this.sourcePages.state.result;!result||result===this.sourceResult||(this.sourceResult=result,this.sourceRows=result.rows.map(record=>record.value),this.sourcePage!==this.sourcePages.state.page&&(this.sourceSyncing=!0,this.sourcePage=this.sourcePages.state.page,this.sourceSyncing=!1,this.sourceInputs=this.sourceInputs?[...this.sourceInputs.slice(0,-1),this.sourcePages.state.page]:void 0))}requestUpdate(...args){args[0]===void 0&&(this.sourceEpoch=(this.sourceEpoch??0)+1),(args[0]===void 0||["dataSource","sourcePage","sourcePageSize"].includes(String(args[0])))&&this.syncSource(),super.requestUpdate(...args)}onSourceRetry(source,state2){!this.isConnected||!this.sourceMode||!this.sourceFailed||this.dataSource!==source||this.sourcePages.state!==state2||(this.sourceInputs=void 0,this.syncSource(),this.sourceStateVersion++)}adoptedCallback(){super.adoptedCallback(),this.limitAnnouncements.adopted(),this.sourcePages.adopted(),this.sourceStatusInitialized=!1}inputLimitText(){const truncation=publicCollectionTruncation(this,"items"),number=getNumberFormat(this.effectiveLocale);return truncation?this.localize("ingestionQueueInputLimit",void 0,{count:number.format(truncation.retained),total:number.format(truncation.source)}):""}updated(changed){if(super.updated(changed),this.sourceMode){const status=this.sourceFailed?this.localize("tableLoadFailed"):this.sourcePages.state.pending?this.localize("loading"):"";this.sourceStatusInitialized&&status&&status!==this.previousSourceStatus&&this.limitAnnouncements.announcePolite(status),this.sourceStatusInitialized=!0,this.previousSourceStatus=status;return}this.sourceStatusInitialized=!1,this.previousSourceStatus="";const inputTruncated=publicCollectionTruncation(this,"items")!==void 0;this.limitInitialized&&inputTruncated&&!this.previouslyInputTruncated&&this.limitAnnouncements.announcePolite(this.inputLimitText()),this.limitInitialized=!0,this.previouslyInputTruncated=inputTruncated}renderInputLimit(){const text=this.inputLimitText();return text?html`<p part="limit" role="note">${text}</p>`:nothing}get effectiveVirtualizeAt(){return finiteCount(this.virtualizeAt,DEFAULT_VIRTUALIZE_AT)}normalizeItems(value){const rows=[];for(const valueItem of Array.isArray(value)?value:[])try{if(!isRecord(valueItem))continue;const id=readOwnDataValue(valueItem,"id"),source=readOwnDataValue(valueItem,"document");if(!isNonBlankIdentity(id)||!isRecord(source))continue;const documentId=readOwnDataValue(source,"id"),name=readOwnDataValue(source,"name");if(!isNonBlankIdentity(documentId)||typeof name!="string")continue;const document=Object.freeze(Object.fromEntries(["id","name","mimeType","uri","version"].map(key=>[key,readOwnDataValue(source,key)]).filter(([,field])=>field!==void 0))),fields=Object.fromEntries(["stage","progress","chunkCount","embeddedChunkCount","attempts"].map(key=>[key,readOwnDataValue(valueItem,key)]).filter(([,field])=>field!==void 0)),error=readOwnDataValue(valueItem,"error"),row=Object.freeze({...fields,id,document,...error===void 0?{}:{error:error===null||typeof error=="string"?error:this.localize("ingestionStageFailed")}});error!=null&&typeof error!="string"&&this.fallbackFailureItems.add(row),rows.push(row)}catch{continue}return firstByRetrievalIdentity(rows,item=>item.id)}get normalizedItems(){const cached=this.normalizedItemsCache;if(cached&&cached.source===this.items&&cached.locale===this.effectiveLocale&&cached.failureText===this.localize("ingestionStageFailed"))return cached.result;const result=this.normalizeItems(this.items);return this.normalizedItemsCache={source:this.items,locale:this.effectiveLocale,failureText:this.localize("ingestionStageFailed"),result},result}connectedCallback(){super.connectedCallback(),this.sink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}disconnectedCallback(){super.disconnectedCallback(),this.failureLiveText="",this.sourceStatusInitialized=!1,this.previousSourceStatus="",this.isMounting=!0,this.sink?.release(),this.sink=void 0}willUpdate(changed){if(super.willUpdate(changed),this.syncSource(),this.sourceMode){this.acceptSourcePage(),this.failureLiveText="",this.isMounting=!0;return}const wasMounting=this.isMounting;if(this.isMounting=!1,wasMounting){this.announce&&!this.initialFailuresAnnounced&&(this.initialFailuresAnnounced=!0,this.announceFailures(this.normalizedItems.flatMap(item=>item.stage==="failed"&&item.error?[item.error]:[])));return}if(!changed.has("items"))return;const previousItems=this.normalizedItemsCache?.result??[],previousById=new Map(previousItems.map(item=>[item.id,item]));this.announceFailures(this.normalizedItems.flatMap(item=>{if(item.stage!=="failed"||!item.error)return[];const previous=previousById.get(item.id),previousError=previous&&this.fallbackFailureItems.has(previous)?this.localize("ingestionStageFailed"):previous?.error;return!previous||previous.stage!=="failed"||previousError!==item.error?[item.error]:[]}))}announceFailures(freshErrors){this.failureLiveText=freshErrors.length?getListFormat(this.effectiveLocale,{type:"conjunction"}).format(freshErrors):"",this.failureLiveText!==""&&this.sink?.announce(this.failureLiveText)}stageLabel(stage){switch(stage){case"queued":return this.localize("ingestionStageQueued");case"uploading":return this.localize("ingestionStageUploading");case"extracting":return this.localize("ingestionStageExtracting");case"chunking":return this.localize("ingestionStageChunking");case"embedding":return this.localize("ingestionStageEmbedding");case"indexing":return this.localize("ingestionStageIndexing");case"done":return this.localize("ingestionStageDone");case"failed":return this.localize("ingestionStageFailed");case"cancelled":return this.localize("ingestionStageCancelled");case"unknown":return this.localize("ingestionStageUnknown")}}chunkCountText(count){const safeCount=finiteCount(count);return this.localize("ingestionChunkCount",void 0,{count:getNumberFormat(this.effectiveLocale).format(safeCount),pluralCount:safeCount})}normalizedAttempts(item){return finiteCount(item.attempts??0,0,Number.MAX_SAFE_INTEGER-1)}onRetryClick(item){(this.sourceMode||this.sourceItemIdentities.has(item))&&(!this.sourceMode||this.sourceBlocked||!this.sourceRows.includes(item))||this.emit("lr-retry",{itemId:item.id,attempt:this.normalizedAttempts(item)+1})}onCancelClick(item){(this.sourceMode||this.sourceItemIdentities.has(item))&&(!this.sourceMode||this.sourceBlocked||!this.sourceRows.includes(item))||this.emit("lr-cancel",{itemId:item.id})}renderRows(items){return items.length>this.effectiveVirtualizeAt?html`<lr-virtual-list
47
+ `}}static{this.defaultStrings={...super.defaultStrings,cancel:LYRA_DEFAULT_cancel,ingestionActionWithContext:LYRA_DEFAULT_ingestionActionWithContext,ingestionAttemptCount:LYRA_DEFAULT_ingestionAttemptCount,ingestionCancelWithContext:LYRA_DEFAULT_ingestionCancelWithContext,ingestionChunkCount:LYRA_DEFAULT_ingestionChunkCount,ingestionEmbeddedOfTotal:LYRA_DEFAULT_ingestionEmbeddedOfTotal,ingestionItemProgressLabel:LYRA_DEFAULT_ingestionItemProgressLabel,ingestionQueueActionLimit:LYRA_DEFAULT_ingestionQueueActionLimit,ingestionQueueEmpty:LYRA_DEFAULT_ingestionQueueEmpty,ingestionQueueInputLimit:LYRA_DEFAULT_ingestionQueueInputLimit,ingestionQueueLabel:LYRA_DEFAULT_ingestionQueueLabel,ingestionRetryWithContext:LYRA_DEFAULT_ingestionRetryWithContext,ingestionStageCancelled:LYRA_DEFAULT_ingestionStageCancelled,ingestionStageChunking:LYRA_DEFAULT_ingestionStageChunking,ingestionStageDone:LYRA_DEFAULT_ingestionStageDone,ingestionStageEmbedding:LYRA_DEFAULT_ingestionStageEmbedding,ingestionStageExtracting:LYRA_DEFAULT_ingestionStageExtracting,ingestionStageFailed:LYRA_DEFAULT_ingestionStageFailed,ingestionStageIndexing:LYRA_DEFAULT_ingestionStageIndexing,ingestionStageQueued:LYRA_DEFAULT_ingestionStageQueued,ingestionStageUnknown:LYRA_DEFAULT_ingestionStageUnknown,ingestionStageUploading:LYRA_DEFAULT_ingestionStageUploading,loading:LYRA_DEFAULT_loading,retry:LYRA_DEFAULT_retry,tableLoadFailed:LYRA_DEFAULT_tableLoadFailed,untitledSource:LYRA_DEFAULT_untitledSource}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-item-action"])}static{this.identityCollectionProperties=Object.freeze(["items"])}static{this.ownedCollectionProperties=Object.freeze(["items"])}static{this.styles=[LyraElement.styles,styles,srOnly]}get dataSource(){return this._dataSource}set dataSource(value){const previous=this._dataSource;this._dataSource=value,this.sourceEpoch++,this.requestUpdate("dataSource",previous)}get sourceTotal(){return this.sourceMode?this.sourcePages.state.result?.total??null:null}get sourceMode(){return this.dataSource!==void 0}get sourceFailed(){return this.sourceMode&&!this.sourcePages.state.pending&&!this.sourcePages.state.result}get sourceBlocked(){return this.sourceMode&&(!this.isConnected||this.sourcePages.state.pending||this.sourceFailed)}projectSourceItem(record,isCurrent){const assertCurrent=()=>{if(!isCurrent())throw new TypeError("Obsolete source record")},descriptorOf=(target,key)=>{assertCurrent();const descriptor=getOwnDataDescriptor(target,key);return assertCurrent(),descriptor};assertCurrent();const field=(value2,key)=>{if(!isRecord(value2))throw new TypeError("Invalid source item");const descriptor=descriptorOf(value2,key);if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)throw new TypeError("Invalid source field");return descriptor===MISSING_OWN_DATA_DESCRIPTOR?void 0:descriptor.value};let units=0;const text=(value2,required=!1)=>{if(!(value2===void 0&&!required)){if(typeof value2!="string"||value2.length>65536||(units+=value2.length)>65536)throw new TypeError("Invalid source text");return value2}},raw=record.value,id=text(field(raw,"id"),!0),rawDocument=field(raw,"document"),documentId=text(field(rawDocument,"id"),!0);if(id!==record.key||!isNonBlankIdentity(documentId))throw new TypeError("Invalid source identity");const document=Object.freeze({id:documentId,name:text(field(rawDocument,"name"),!0),mimeType:text(field(rawDocument,"mimeType")),uri:text(field(rawDocument,"uri")),version:text(field(rawDocument,"version"))}),stage=text(field(raw,"stage")),errorValue=field(raw,"error"),error=errorValue==null?void 0:text(typeof errorValue=="string"?errorValue:this.localize("ingestionStageFailed")),numbers={};for(const key of["progress","chunkCount","embeddedChunkCount","attempts"]){const value2=field(raw,key);if(value2!==void 0){if(typeof value2!="number")throw new TypeError("Invalid source number");numbers[key]=value2}}const presentation=projectIngestionPresentation(raw,stage,isCurrent,65536-units),value=Object.freeze({id,document,stage,error,...numbers,...presentation.customStage?{customStage:presentation.customStage}:{},...presentation.actions===void 0?{}:{actions:presentation.actions}});return this.presentations.set(value,presentation),assertCurrent(),errorValue!=null&&typeof errorValue!="string"&&this.fallbackFailureItems.add(value),assertCurrent(),{key:record.key,order:record.order,value}}syncSource(){if(!(!this.sourcePages||this.sourceSyncing)){this.sourceSyncing=!0;try{if(!this.sourceMode){this.sourceInputs&&this.sourcePages.bind(void 0),this.sourceInputs=void 0,this.sourceSize=void 0,this.sourceResult=void 0,this.sourceRows=[];return}const source=this.dataSource,size=finiteInteger(this.sourcePageSize,100,1,500);let page=finiteInteger(this.sourcePage,0,0,Math.floor(Number.MAX_SAFE_INTEGER/size));this.sourceSize!==void 0&&this.sourceSize!==size&&(page=0,this.sourcePage=0),this.sourceSize=size;const revision=source.revision,inputs=[source,revision,this.sourceEpoch,this.effectiveLocale,size,page];if(this.sourceInputs&&inputs.every((value,index)=>value===this.sourceInputs[index]))return;this.sourceInputs=inputs,this.sourceRows=[],this.sourceResult=void 0,this.sourcePages.bind({source,revision,epoch:this.sourceEpoch,locale:this.effectiveLocale}),this.sourcePages.request(SOURCE_QUERY,page,size)}catch{this.sourcePages.bind(void 0),this.sourceRows=[],this.sourceResult=void 0}finally{this.sourceSyncing=!1}}}acceptSourcePage(){const result=this.sourcePages.state.result;!result||result===this.sourceResult||(this.sourceResult=result,this.sourceRows=result.rows.map(record=>record.value),this.sourcePage!==this.sourcePages.state.page&&(this.sourceSyncing=!0,this.sourcePage=this.sourcePages.state.page,this.sourceSyncing=!1,this.sourceInputs=this.sourceInputs?[...this.sourceInputs.slice(0,-1),this.sourcePages.state.page]:void 0))}requestUpdate(...args){args[0]===void 0&&(this.sourceEpoch=(this.sourceEpoch??0)+1),(args[0]===void 0||["dataSource","sourcePage","sourcePageSize"].includes(String(args[0])))&&this.syncSource(),super.requestUpdate(...args)}onSourceRetry(source,state2){!this.isConnected||!this.sourceMode||!this.sourceFailed||this.dataSource!==source||this.sourcePages.state!==state2||(this.sourceInputs=void 0,this.syncSource(),this.sourceStateVersion++)}adoptedCallback(){this.focusRepairGeneration++,this.actionFocusRepair=void 0,super.adoptedCallback(),this.limitAnnouncements.adopted(),this.sourcePages.adopted(),this.sourceStatusInitialized=!1}inputLimitText(){const truncation=publicCollectionTruncation(this,"items"),number=getNumberFormat(this.effectiveLocale);return truncation?this.localize("ingestionQueueInputLimit",void 0,{count:number.format(truncation.retained),total:number.format(truncation.source)}):""}updated(changed){if(super.updated(changed),this.restoreActionFocus(),this.sourceMode){const status=this.sourceFailed?this.localize("tableLoadFailed"):this.sourcePages.state.pending?this.localize("loading"):"";this.sourceStatusInitialized&&status&&status!==this.previousSourceStatus&&this.limitAnnouncements.announcePolite(status),this.sourceStatusInitialized=!0,this.previousSourceStatus=status;return}this.sourceStatusInitialized=!1,this.previousSourceStatus="";const inputTruncated=publicCollectionTruncation(this,"items")!==void 0;this.limitInitialized&&inputTruncated&&!this.previouslyInputTruncated&&this.limitAnnouncements.announcePolite(this.inputLimitText()),this.limitInitialized=!0,this.previouslyInputTruncated=inputTruncated}renderInputLimit(){const text=this.inputLimitText();return text?html`<p part="limit" role="note">${text}</p>`:nothing}get effectiveVirtualizeAt(){return finiteCount(this.virtualizeAt,DEFAULT_VIRTUALIZE_AT)}normalizeItems(value){const rows=[];for(const valueItem of Array.isArray(value)?value:[])try{if(!isRecord(valueItem))continue;const id=readOwnDataValue(valueItem,"id"),source=readOwnDataValue(valueItem,"document");if(!isNonBlankIdentity(id)||!isRecord(source))continue;const documentId=readOwnDataValue(source,"id"),name=readOwnDataValue(source,"name");if(!isNonBlankIdentity(documentId)||typeof name!="string")continue;const document=Object.freeze(Object.fromEntries(["id","name","mimeType","uri","version"].map(key=>[key,readOwnDataValue(source,key)]).filter(([,field])=>field!==void 0))),fields=Object.fromEntries(["stage","progress","chunkCount","embeddedChunkCount","attempts"].map(key=>[key,readOwnDataValue(valueItem,key)]).filter(([,field])=>field!==void 0)),error=readOwnDataValue(valueItem,"error"),presentation=projectIngestionPresentation(valueItem,fields.stage,()=>this.items===value&&!this.sourceMode),row=Object.freeze({...fields,id,document,...error===void 0?{}:{error:error===null||typeof error=="string"?error:this.localize("ingestionStageFailed")},...presentation.customStage?{customStage:presentation.customStage}:{},...presentation.actions===void 0?{}:{actions:presentation.actions}});this.presentations.set(row,presentation),error!=null&&typeof error!="string"&&this.fallbackFailureItems.add(row),rows.push(row)}catch{continue}return firstByRetrievalIdentity(rows,item=>item.id)}get normalizedItems(){const cached=this.normalizedItemsCache;if(cached&&cached.source===this.items&&cached.locale===this.effectiveLocale&&cached.failureText===this.localize("ingestionStageFailed"))return cached.result;const result=this.normalizeItems(this.items);return this.normalizedItemsCache={source:this.items,locale:this.effectiveLocale,failureText:this.localize("ingestionStageFailed"),result},result}connectedCallback(){super.connectedCallback(),this.sink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.focusRepairGeneration++,this.actionFocusRepair=void 0,super.disconnectedCallback(),this.failureLiveText="",this.sourceStatusInitialized=!1,this.previousSourceStatus="",this.isMounting=!0,this.sink?.release(),this.sink=void 0}willUpdate(changed){if(super.willUpdate(changed),this.syncSource(),this.sourceMode){this.acceptSourcePage(),this.captureActionFocus(),this.failureLiveText="",this.isMounting=!0;return}this.captureActionFocus();const wasMounting=this.isMounting;if(this.isMounting=!1,wasMounting){this.announce&&!this.initialFailuresAnnounced&&(this.initialFailuresAnnounced=!0,this.announceFailures(this.normalizedItems.flatMap(item=>item.stage==="failed"&&item.error?[item.error]:[])));return}if(!changed.has("items"))return;const previousItems=this.normalizedItemsCache?.result??[],previousById=new Map(previousItems.map(item=>[item.id,item]));this.announceFailures(this.normalizedItems.flatMap(item=>{if(item.stage!=="failed"||!item.error)return[];const previous=previousById.get(item.id),previousError=previous&&this.fallbackFailureItems.has(previous)?this.localize("ingestionStageFailed"):previous?.error;return!previous||previous.stage!=="failed"||previousError!==item.error?[item.error]:[]}))}announceFailures(freshErrors){this.failureLiveText=freshErrors.length?getListFormat(this.effectiveLocale,{type:"conjunction"}).format(freshErrors):"",this.failureLiveText!==""&&this.sink?.announce(this.failureLiveText)}stageLabel(stage){switch(stage){case"queued":return this.localize("ingestionStageQueued");case"uploading":return this.localize("ingestionStageUploading");case"extracting":return this.localize("ingestionStageExtracting");case"chunking":return this.localize("ingestionStageChunking");case"embedding":return this.localize("ingestionStageEmbedding");case"indexing":return this.localize("ingestionStageIndexing");case"done":return this.localize("ingestionStageDone");case"failed":return this.localize("ingestionStageFailed");case"cancelled":return this.localize("ingestionStageCancelled");case"unknown":case"custom":return this.localize("ingestionStageUnknown")}}chunkCountText(count){const safeCount=finiteCount(count);return this.localize("ingestionChunkCount",void 0,{count:getNumberFormat(this.effectiveLocale).format(safeCount),pluralCount:safeCount})}normalizedAttempts(item){return finiteCount(item.attempts??0,0,Number.MAX_SAFE_INTEGER-1)}itemStage(item){const stage=normalizedStage(item.stage);return stage==="custom"&&!item.customStage?"unknown":stage}rowActions(item){const stage=this.itemStage(item);return stage==="unknown"?NO_ACTIONS:(item.actions??(stage==="failed"?DEFAULT_RETRY_ACTIONS:CANCELABLE_STAGES.includes(stage)?DEFAULT_CANCEL_ACTIONS:NO_ACTIONS)).filter(action=>action.type==="custom"||(action.type==="retry"?stage==="failed":CANCELABLE_STAGES.includes(stage)))}currentRows(){return this.sourceMode?this.sourceRows:this.normalizedItems}activateRowAction(item,action){!this.isConnected||this.sourceMode&&this.sourceBlocked||!this.currentRows().includes(item)||!this.rowActions(item).includes(action)||action.disabled||(action.type==="retry"?this.emit("lr-retry",{itemId:item.id,attempt:this.normalizedAttempts(item)+1}):action.type==="cancel"?this.emit("lr-cancel",{itemId:item.id}):action.type==="custom"&&this.emit("lr-item-action",Object.freeze({itemId:item.id,actionId:action.id})))}renderedActionButtons(){const virtual=this.renderRoot.querySelector(tag("virtual-list"));return[...this.renderRoot.querySelectorAll("button[data-ingestion-action]"),...virtual?.shadowRoot?.querySelectorAll("button[data-ingestion-action]")??[]]}captureActionFocus(){const active=deepActiveElementIn(this.ownerDocument);if(!active||!this.renderedActionButtons().includes(active))return;const itemId=active.getAttribute("data-ingestion-item"),key=active.getAttribute("data-ingestion-action"),current=this.currentRows().find(row=>row.id===itemId);if(current&&this.rowActions(current).some(action=>ingestionActionKey(action)===key&&!action.disabled))return;const snapshot=captureComposedFocusRepair(this,active);if(!snapshot)return;const siblings=this.renderedActionButtons().filter(button=>button.getAttribute("data-ingestion-item")===itemId),renderedIds=[...new Set(this.renderedActionButtons().map(button=>button.getAttribute("data-ingestion-item")))];this.focusRepairGeneration++,this.actionFocusRepair={snapshot,itemId,actionIndex:Math.max(0,siblings.indexOf(active)),rowIndex:Math.max(0,renderedIds.indexOf(itemId))}}restoreActionFocus(){const pending=this.actionFocusRepair;if(this.actionFocusRepair=void 0,!pending)return;const generation=this.focusRepairGeneration;this.updateComplete.then(async()=>{const virtual=this.renderRoot.querySelector(tag("virtual-list"));if(virtual&&await virtual.updateComplete,!this.isConnected||generation!==this.focusRepairGeneration)return;const available=this.renderedActionButtons().filter(button=>!button.disabled),sameRow=available.filter(button=>button.getAttribute("data-ingestion-item")===pending.itemId),target=sameRow[Math.min(pending.actionIndex,sameRow.length-1)],ids=[...new Set(available.map(button=>button.getAttribute("data-ingestion-item")))],nearId=ids[Math.min(pending.rowIndex,ids.length-1)],nearby=available.filter(button=>button.getAttribute("data-ingestion-item")===nearId),list=this.renderRoot.querySelector('[part="list"]'),virtualBase=virtual?.shadowRoot?.querySelector('[part="base"]');applyComposedFocusRepair(pending.snapshot,[target,...sameRow,...nearby,virtualBase,list])})}renderRowAction(item,action,name){const custom=action.type==="custom",part=custom?"item-action-button":action.type==="retry"?"retry-button":"cancel-button",label=custom?action.label:this.localize(action.type==="retry"?"retry":"cancel"),accessibleName=custom?this.localize("ingestionActionWithContext",void 0,{action:label,label:name}):this.localize(action.type==="retry"?"ingestionRetryWithContext":"ingestionCancelWithContext",void 0,{label:name});return html`<button part=${part} type="button" ?disabled=${action.disabled===!0}
48
+ data-ingestion-item=${item.id} data-ingestion-action=${ingestionActionKey(action)}
49
+ aria-label=${accessibleName} @click=${()=>this.activateRowAction(item,action)}
50
+ >${custom?nothing:action.type==="retry"?retryIcon():closeIcon()}<span>${label}</span></button>`}renderActionLimit(item,name){const limit=this.presentations.get(item)?.actionLimit;if(!limit)return nothing;devWarnOnce(`lyra-ingestion-action-limit:${this.localName}`,`<${this.localName}>: a row retained ${limit.retained} of ${limit.source} actions; only the first 32 action positions are inspected.`);const number=getNumberFormat(this.effectiveLocale);return html`<p part="item-action-limit" role="note">${this.localize("ingestionQueueActionLimit",void 0,{count:number.format(limit.retained),total:number.format(limit.source),label:name})}</p>`}renderRows(items){return items.length>this.effectiveVirtualizeAt?html`<lr-virtual-list
64
51
  part="list"
65
- exportparts="item:item, item-header:item-header, item-name:item-name, item-stage:item-stage, item-progress:item-progress, item-meta:item-meta, item-chunk-count:item-chunk-count, item-embedding-status:item-embedding-status, item-attempts:item-attempts, item-error:item-error, item-actions:item-actions, retry-button:retry-button, cancel-button:cancel-button"
52
+ exportparts="item:item, item-header:item-header, item-name:item-name, item-stage:item-stage, item-progress:item-progress, item-meta:item-meta, item-chunk-count:item-chunk-count, item-embedding-status:item-embedding-status, item-attempts:item-attempts, item-error:item-error, item-actions:item-actions, retry-button:retry-button, cancel-button:cancel-button, item-action-button:item-action-button, item-action-limit:item-action-limit"
66
53
  .items=${items}
67
54
  .renderItem=${item=>this.itemTemplate(item,!1)}
68
55
  .keyFunction=${this.ingestionItemKey}
69
56
  @lr-virtual-scroll=${this.stopOwnedEvent}
70
57
  @lr-visible-range-change=${this.stopOwnedEvent}
71
- ></lr-virtual-list>`:html`<div part="list" role="list">
58
+ ></lr-virtual-list>`:html`<div part="list" role="list" tabindex="-1">
72
59
  ${repeat(items,item=>item.id,item=>this.itemTemplate(item,!0))}
73
60
  </div>`}renderSource(){const failed=this.sourceFailed,retrySource=this.dataSource,retryState=this.sourcePages.state,pending=this.sourcePages.state.pending,label=retrievalSemanticLabel(this,this.label==null?this.localize("ingestionQueueLabel"):this.label);return html`<div part="base" role=${retrievalSemanticRole(this,"region")??nothing} aria-label=${label??nothing} aria-busy=${pending?"true":"false"}>
74
61
  ${failed||pending?html`<p part="source-status">${this.localize(failed?"tableLoadFailed":"loading")}</p>`:nothing}
75
62
  ${failed?html`<button type="button" part="source-retry" @click=${()=>this.onSourceRetry(retrySource,retryState)}>${this.localize("retry")}</button>`:nothing}
76
- ${failed||pending?nothing:this.sourceRows.length?this.renderRows(this.sourceRows):html`<div part="list"><lr-empty part="empty" heading=${this.localize("ingestionQueueEmpty")}></lr-empty></div>`}
63
+ ${failed||pending?nothing:this.sourceRows.length?this.renderRows(this.sourceRows):html`<div part="list" tabindex="-1"><lr-empty part="empty" heading=${this.localize("ingestionQueueEmpty")}></lr-empty></div>`}
77
64
  <lr-pagination part="source-pagination" format="compact" .page=${finiteInteger(this.sourcePage,0,0,Number.MAX_SAFE_INTEGER-1)+1}
78
65
  .pageSize=${finiteInteger(this.sourcePageSize,100,1,500)} .total=${this.sourceTotal??-1} .disabled=${this.sourceBlocked||this.sourceTotal===null}
79
66
  .strings=${this.strings} @lr-page-change=${this.onSourcePage} @lr-before-page-change=${this.stopOwnedEvent} @lr-activate=${this.stopOwnedEvent}
@@ -87,7 +74,7 @@ import{__decorate}from"tslib";import{collectionSupport,publicCollectionTruncatio
87
74
  <div part="failure-live" class="sr-only" aria-hidden="true">
88
75
  ${this.failureLiveText}
89
76
  </div>
90
- <div part="list">
77
+ <div part="list" tabindex="-1">
91
78
  <lr-empty
92
79
  part="empty"
93
80
  heading=${this.localize("ingestionQueueEmpty")}
@@ -1 +1 @@
1
- import{iconHitTarget,focusRing}from"../../../internal/interactive-control.styles.js";import{css}from"lit";const styles=css` :host { display: block; --_lr-ingestion-queue-max-height: none; } [part="base"] { display: block; box-sizing: border-box; min-inline-size: 0; } [part="list"] { display: flex; flex-direction: column; box-sizing: border-box; max-block-size: var( --lr-ingestion-queue-max-height, var(--_lr-ingestion-queue-max-height) ); overflow-y: auto; overflow-x: clip; } lr-virtual-list { display: block; --lr-virtual-list-height: var(--lr-size-24rem); } [part="item"], lr-virtual-list::part(item) { display: flex; flex-direction: column; gap: var(--lr-space-xs); box-sizing: border-box; padding: var(--lr-space-s) var(--lr-space-m); border-block-end: var(--lr-border-width-thin) solid var(--lr-color-border-subtle); } [part="item-header"], lr-virtual-list::part(item-header) { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: var(--lr-space-s); } [part="item-name"], lr-virtual-list::part(item-name) { min-inline-size: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: var(--lr-font-weight-medium); color: var(--lr-color-text); } [part="item-progress"], lr-virtual-list::part(item-progress) { display: block; } [part="item-meta"], lr-virtual-list::part(item-meta) { display: flex; flex-wrap: wrap; gap: var(--lr-space-s); font-size: var(--lr-font-size-xs); color: var(--lr-color-text-quiet); } [part="item-chunk-count"], lr-virtual-list::part(item-chunk-count), [part="item-embedding-status"], lr-virtual-list::part(item-embedding-status), [part="item-attempts"], lr-virtual-list::part(item-attempts) { unicode-bidi: plaintext; } [part="item-error"], lr-virtual-list::part(item-error) { margin: 0; color: var(--lr-color-danger); font-size: var(--lr-font-size-sm); overflow-wrap: anywhere; } [part="item-actions"], lr-virtual-list::part(item-actions) { display: flex; flex-wrap: wrap; gap: var(--lr-space-s); } [part="source-retry"], [part="retry-button"], lr-virtual-list::part(retry-button), [part="cancel-button"], lr-virtual-list::part(cancel-button) { display: inline-flex; align-items: center; gap: var(--lr-size-0-35em); box-sizing: border-box; ${iconHitTarget} padding: var(--lr-size-0-25rem) var(--lr-space-s); border: var(--lr-border-width-thin) solid var(--lr-color-border); border-radius: var(--lr-radius-pill); background: var(--lr-color-surface); color: var(--lr-color-text); font: inherit; font-size: var(--lr-font-size-xs); cursor: pointer; transition: background-color var(--lr-transition-fast), border-color var(--lr-transition-fast), color var(--lr-transition-fast); } [part="source-retry"]:hover, [part="retry-button"]:hover, lr-virtual-list::part(retry-button):hover { border-color: var(--lr-color-brand); color: var(--lr-color-brand); } [part="source-retry"]:active, [part="retry-button"]:active, lr-virtual-list::part(retry-button):active { border-color: var(--lr-color-brand); color: var(--lr-color-brand); background: color-mix( in oklab, var(--lr-color-surface), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part="cancel-button"]:hover, lr-virtual-list::part(cancel-button):hover { border-color: var(--lr-color-danger); color: var(--lr-color-danger); } [part="cancel-button"]:active, lr-virtual-list::part(cancel-button):active { border-color: var(--lr-color-danger); color: var(--lr-color-danger); background: color-mix( in oklab, var(--lr-color-surface), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part="source-retry"]:focus-visible, [part="retry-button"]:focus-visible, lr-virtual-list::part(retry-button):focus-visible, [part="cancel-button"]:focus-visible, lr-virtual-list::part(cancel-button):focus-visible { ${focusRing} } @media (prefers-reduced-motion: reduce) { [part="source-retry"], [part="retry-button"], lr-virtual-list::part(retry-button), [part="cancel-button"], lr-virtual-list::part(cancel-button) { transition: none !important; } } [part='source-pagination'] { display: block; margin-block-start: var(--lr-space-s); } [part='source-status'], [part='limit'] { margin: 0; padding: var(--lr-space-s); color: var(--lr-color-text-quiet); font-size: var(--lr-font-size-sm); overflow-wrap: anywhere; } `;export{styles};
1
+ import{iconHitTarget,focusRing}from"../../../internal/interactive-control.styles.js";import{css}from"lit";const styles=css` :host { display: block; --_lr-ingestion-queue-max-height: none; } [part="base"] { display: block; box-sizing: border-box; min-inline-size: 0; } [part="list"] { display: flex; flex-direction: column; box-sizing: border-box; max-block-size: var( --lr-ingestion-queue-max-height, var(--_lr-ingestion-queue-max-height) ); overflow-y: auto; overflow-x: clip; } lr-virtual-list { display: block; --lr-virtual-list-height: var(--lr-size-24rem); } [part="item"], lr-virtual-list::part(item) { display: flex; flex-direction: column; gap: var(--lr-space-xs); box-sizing: border-box; padding: var(--lr-space-s) var(--lr-space-m); border-block-end: var(--lr-border-width-thin) solid var(--lr-color-border-subtle); } [part="item-header"], lr-virtual-list::part(item-header) { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: var(--lr-space-s); } [part="item-name"], lr-virtual-list::part(item-name) { min-inline-size: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: var(--lr-font-weight-medium); color: var(--lr-color-text); } [part="item-progress"], lr-virtual-list::part(item-progress) { display: block; } [part='item-stage'], lr-virtual-list::part(item-stage) { min-inline-size: 0; max-inline-size: 100%; } [part="item-meta"], lr-virtual-list::part(item-meta) { display: flex; flex-wrap: wrap; gap: var(--lr-space-s); font-size: var(--lr-font-size-xs); color: var(--lr-color-text-quiet); } [part="item-chunk-count"], lr-virtual-list::part(item-chunk-count), [part="item-embedding-status"], lr-virtual-list::part(item-embedding-status), [part="item-attempts"], lr-virtual-list::part(item-attempts) { unicode-bidi: plaintext; } [part="item-error"], lr-virtual-list::part(item-error) { margin: 0; color: var(--lr-color-danger); font-size: var(--lr-font-size-sm); overflow-wrap: anywhere; } [part="item-actions"], lr-virtual-list::part(item-actions) { display: flex; flex-wrap: wrap; gap: var(--lr-space-s); } [part="source-retry"], [part="retry-button"], lr-virtual-list::part(retry-button), [part="cancel-button"], lr-virtual-list::part(cancel-button), [part='item-action-button'], lr-virtual-list::part(item-action-button) { display: inline-flex; align-items: center; gap: var(--lr-size-0-35em); box-sizing: border-box; ${iconHitTarget} padding: var(--lr-size-0-25rem) var(--lr-space-s); border: var(--lr-border-width-thin) solid var(--lr-color-border); border-radius: var(--lr-radius-pill); background: var(--lr-color-surface); color: var(--lr-color-text); font: inherit; font-size: var(--lr-font-size-xs); cursor: pointer; max-inline-size: 100%; overflow-wrap: anywhere; transition: var(--lr-transition-interactive); } [part="source-retry"]:hover:where(:not(:disabled)), [part="retry-button"]:hover:where(:not(:disabled)), lr-virtual-list::part(retry-button):hover:not(:disabled), [part='item-action-button']:hover:where(:not(:disabled)), lr-virtual-list::part(item-action-button):hover:not(:disabled) { border-color: var(--lr-color-brand); color: var(--lr-color-brand); } [part="source-retry"]:active:where(:not(:disabled)), [part="retry-button"]:active:where(:not(:disabled)), lr-virtual-list::part(retry-button):active:not(:disabled), [part='item-action-button']:active:where(:not(:disabled)), lr-virtual-list::part(item-action-button):active:not(:disabled) { border-color: var(--lr-color-brand); color: var(--lr-color-brand); background: color-mix( in oklab, var(--lr-color-surface), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part="cancel-button"]:hover:where(:not(:disabled)), lr-virtual-list::part(cancel-button):hover:not(:disabled) { border-color: var(--lr-color-danger); color: var(--lr-color-danger); } [part="cancel-button"]:active:where(:not(:disabled)), lr-virtual-list::part(cancel-button):active:not(:disabled) { border-color: var(--lr-color-danger); color: var(--lr-color-danger); background: color-mix( in oklab, var(--lr-color-surface), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part="source-retry"]:focus-visible, [part="retry-button"]:focus-visible, lr-virtual-list::part(retry-button):focus-visible, [part="cancel-button"]:focus-visible, lr-virtual-list::part(cancel-button):focus-visible, [part='item-action-button']:focus-visible, lr-virtual-list::part(item-action-button):focus-visible { ${focusRing} } [part='retry-button']:disabled, [part='cancel-button']:disabled, [part='item-action-button']:disabled, lr-virtual-list::part(retry-button):disabled, lr-virtual-list::part(cancel-button):disabled, lr-virtual-list::part(item-action-button):disabled { opacity: var(--lr-opacity-disabled); cursor: not-allowed; } @media (prefers-reduced-motion: reduce) { [part="source-retry"], [part="retry-button"], lr-virtual-list::part(retry-button), [part="cancel-button"], lr-virtual-list::part(cancel-button), [part='item-action-button'], lr-virtual-list::part(item-action-button) { transition: none !important; } } [part='source-pagination'] { display: block; margin-block-start: var(--lr-space-s); } [part='source-status'], [part='limit'], [part='item-action-limit'], lr-virtual-list::part(item-action-limit) { margin: 0; padding: var(--lr-space-s); color: var(--lr-color-text-quiet); font-size: var(--lr-font-size-sm); overflow-wrap: anywhere; } `;export{styles};
@@ -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{snapshotMindMapTopics}from"./mind-map-model.js";import{html,nothing,svg}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{isRtl}from"../../../internal/rtl.js";import{finiteCount}from"../../../internal/numbers.js";import{resolveCssTokenLength}from"../../../internal/css-token-length.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{decimateMindMapLayout,createMindMapLayout}from"./mind-map-layout.js";import{styles}from"./mind-map.styles.js";import{LYRA_DEFAULT_mindMapCollapsed,LYRA_DEFAULT_mindMapExpanded,LYRA_DEFAULT_mindMapInputLimit,LYRA_DEFAULT_mindMapLabel,LYRA_DEFAULT_mindMapLeafStatus,LYRA_DEFAULT_mindMapNodeLimit,LYRA_DEFAULT_mindMapTopicStatus}from"../../../internal/default-strings/retrieval.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_expand,LYRA_DEFAULT_loading,LYRA_DEFAULT_noData,LYRA_DEFAULT_retry,LYRA_DEFAULT_treeSourceError,LYRA_DEFAULT_treeSourceSummary}from"../../../internal/default-strings/shared.generated.js";const DEFAULT_RING_GAP_PX=96,MAX_RENDERED_MIND_MAP_NODES=500,NAV_KEYS=new Set(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End","Enter"," "]);class LyraMindMap extends LyraElement{constructor(){super(...arguments),this.sourceVersion=0,this.sourceViewAuthority=new WeakMap,this.sourcePaint=0,this.sourceDiagramScheduled=!1,this.sourceDiagramRows=new Map,this.sourceDiagramCurrent=()=>!1,this.sourceControl=new HierarchySourceController(this,{normalize:(value,key)=>{const current=this.sourceAuthority(),field=name=>{if(!current())throw new Error("Topic source changed");const result=hierarchyField(value,name);if(!current())throw new Error("Topic source changed");return result},id=hierarchyKey(field("id"));if(id!==key)throw new TypeError("Topic key mismatch");return Object.freeze({id,label:hierarchyText(field("label"))})},payload:{maxUnits:2e6,maxRowUnits:65536,unitsOf:topic=>topic.id.length+topic.label.length},onChange:()=>{this._treeSource!==void 0&&this.clearSourceDiagram();const old=this.sourcePaint++;this.requestUpdate("sourcePaint",old)},accepted:(action,row,_state,current)=>{!current()||this.treeSource===void 0||(action.type==="toggle"?this.emit("lr-topic-toggle",{topicId:action.key,expanded:action.expanded}):action.type==="select"&&row?.childCount===0&&this.emit("lr-topic-select",{topicId:action.key}))}}),this._topics=Object.freeze([]),this.topicsSource=this._topics,this.inputTruncated=!1,this.expandDepth=1,this.expandedOverrides=new Map,this.focusedId=null,this.liveText="",this.cachedLayout={placed:[],links:[],width:0,height:0,centerX:0,centerY:0},this.totalTopicCount=0,this.topicsTruncated=!1,this.ownerRealmGeneration=0,this.observedSize="",this.layoutInvalidated=!0,this.layoutContext="",this.onKeyDown=e=>{if(this.treeSource!==void 0){if(!this.sourceDiagramCurrent())return;const row=this.sourceDiagramRows.get(this.focusedId??"")??this.sourceDiagramRows.values().next().value;if(!row)return;const index=this.sourceControl.window.source.indexOfKey?.(row.key);typeof index=="number"&&index>=0&&this.sourceControl.keydown(e,row,index,isRtl(this),selected=>this.selectSourceRow(selected));return}const placed=this.cachedLayout.placed;if(placed.length===0||!NAV_KEYS.has(e.key))return;if(e.preventDefault(),this.focusedId===null){this.focusNodeById(placed[0].id);return}const current=placed.find(p=>p.id===this.focusedId);if(!current)return;if(e.key==="Enter"||e.key===" "){e.repeat||this.activate(current);return}if(e.key==="ArrowUp"){current.parentId&&this.focusNodeById(current.parentId);return}if(e.key==="ArrowDown"){if(!current.hasChildren)return;this.isExpanded(current.id,current.depth)||(this.toggle(current,!1),this.relayout());const child=this.childrenOf(current.id)[0];child&&this.focusNodeById(child.id);return}const rtl=isRtl(this),forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";if(e.key===forwardKey||e.key===backwardKey||e.key==="Home"||e.key==="End"){const siblings=this.siblingsOf(current),index=siblings.findIndex(s=>s.id===current.id);let next=index;e.key===forwardKey?next=Math.min(siblings.length-1,index+1):e.key===backwardKey?next=Math.max(0,index-1):e.key==="Home"?next=0:next=siblings.length-1;const target=siblings[next];target&&this.focusNodeById(target.id)}},this.onFocusIn=()=>{if(this.focusedId!==null)return;const first=this.cachedLayout.placed[0];first&&(this.focusedId=first.id)}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,expand:LYRA_DEFAULT_expand,loading:LYRA_DEFAULT_loading,mindMapCollapsed:LYRA_DEFAULT_mindMapCollapsed,mindMapExpanded:LYRA_DEFAULT_mindMapExpanded,mindMapInputLimit:LYRA_DEFAULT_mindMapInputLimit,mindMapLabel:LYRA_DEFAULT_mindMapLabel,mindMapLeafStatus:LYRA_DEFAULT_mindMapLeafStatus,mindMapNodeLimit:LYRA_DEFAULT_mindMapNodeLimit,mindMapTopicStatus:LYRA_DEFAULT_mindMapTopicStatus,noData:LYRA_DEFAULT_noData,retry:LYRA_DEFAULT_retry,treeSourceError:LYRA_DEFAULT_treeSourceError,treeSourceSummary:LYRA_DEFAULT_treeSourceSummary}}static{this.styles=[LyraElement.styles,hierarchySourceStyles,styles,srOnly]}static get observedAttributes(){return[...new Set([...super.observedAttributes,"dir","lang"])]}get treeSource(){return this._treeSource}set treeSource(value){const old=this._treeSource;this._treeSource=value,this.sourceVersion++,this.sourceWrapper=value===void 0?void 0:this.wrapSource(value),this.clearSourceDiagram(),this.sourceControl?.update(this.sourceWrapper,this.effectiveLocale,!0),this.layoutInvalidated=!0,this.requestUpdate("treeSource",old)}revealSourceKey(key){return this.treeSource===void 0?Promise.resolve(!1):this.sourceControl.reveal(key)}sourceAuthority(){const source=this.treeSource,version=this.sourceVersion,owner=this.ownerDocument,epoch=this.sourceControl.epoch,projection=this.sourceControl.projection,accepted=projection?this.sourceViewAuthority.get(projection.rows):void 0,owned=()=>this.isConnected&&this.ownerDocument===owner&&this.treeSource===source&&this.sourceVersion===version&&this.sourceControl.epoch===epoch&&this.sourceControl.projection===projection&&(source===void 0||!this.sourceControl.loading);return()=>owned()&&(source===void 0||!!accepted?.())&&owned()}wrapSource(source){const host=this,wrapper={get revision(){return source.revision},async project(request){const version=host.sourceVersion,owner=host.ownerDocument,owned=()=>host.isConnected&&host.ownerDocument===owner&&host.treeSource===source&&host.sourceWrapper===wrapper&&host.sourceVersion===version&&!request.signal.aborted,current=()=>{if(!owned())return!1;try{const revision=source.revision;return owned()&&revision===request.revision}catch{return!1}},check=()=>{if(!current())throw new Error("Topic source changed")};check();const project=source.project;check();const result=await project.call(source,request);check();const rows=result.rows;if(check(),rows===null||typeof rows!="object")throw new TypeError("Invalid topic source rows");return host.sourceViewAuthority.set(rows,current),result}};return wrapper}clearSourceDiagram(){this.sourceDiagramRows=new Map,this.sourceDiagramCurrent=()=>!1,this.cachedLayout={placed:[],links:[],width:0,height:0,centerX:0,centerY:0}}requestUpdate(name,oldValue){this._treeSource!==void 0&&name===void 0&&(this.sourceVersion++,this.sourceWrapper=this.wrapSource(this._treeSource),this.clearSourceDiagram(),this.sourceControl?.update(this.sourceWrapper,this.effectiveLocale,!0)),super.requestUpdate(name,oldValue)}selectSourceRow(row){if(row.disabled||this.sourceControl.loading||this.sourceControl.error)return;const current=this.sourceAuthority(),index=this.sourceControl.adapter.indexOfKey?.(row.key);if(!current()||typeof index!="number"||index<0)return;const slot=this.sourceControl.slot(index);!current()||slot.state!=="ready"||slot.value!==row||this.sourceControl.project(row.childCount?{type:"toggle",key:row.key,expanded:!row.expanded}:{type:"select",key:row.key,selected:!0,scope:"item"},!0,row)}scheduleSourceDiagram(){this.sourceDiagramScheduled||(this.sourceDiagramScheduled=!0,queueMicrotask(()=>{if(this.sourceDiagramScheduled=!1,this.treeSource===void 0||!this.isConnected)return;const current=this.sourceAuthority(),control=this.sourceControl,rows=new Map;if(!control.loading&&!control.error)for(const element of control.list?.projectedRows??[]){if(rows.size===301)break;const key=element.querySelector("[data-source-key]")?.dataset.sourceKey;if(!key)continue;const slot=control.slot(Number(element.dataset.rowIndex));if(!current())return;slot.state==="ready"&&slot.value.key===key&&rows.set(key,slot.value)}const previous=this.sourceDiagramRows,root=[...rows.values()].find(row=>row.parentKey===null||!rows.has(row.parentKey)),connected=new Map,topics=new Map;if(root)for(const row of rows.values()){if(row!==root&&(!row.parentKey||!connected.has(row.parentKey)))continue;const topic={id:row.key,label:row.value.label,children:[]};connected.set(row.key,row),topics.set(row.key,topic),row!==root&&topics.get(row.parentKey).children.push(topic)}if(!this.layoutInvalidated&&connected.size===previous.size&&[...connected].every(([key,row])=>previous.get(key)===row)&&this.sourceDiagramCurrent())return;const layout=createMindMapLayout(root?[topics.get(root.key)]:[])(this.label??this.localize("mindMapLabel"),{ringGap:this.ringGapPx(),rtl:isRtl(this),isExpanded:id=>connected.get(id)?.expanded??!1});current()&&(this.sourceDiagramRows=connected,this.sourceDiagramCurrent=current,this.cachedLayout={...layout,placed:layout.placed.map(node=>({...node,hasChildren:!!connected.get(node.id)?.childCount,expanded:connected.get(node.id)?.expanded??!1}))},this.layoutInvalidated=!1,this.requestUpdate("sourceDiagram",!1))}))}get topics(){return this._topics}set topics(value){if(Object.is(value,this.topicsSource)||Object.is(value,this._topics))return;const previous=this._topics,snapshot=snapshotMindMapTopics(value);this.topicsSource=value,this._topics=snapshot.topics,this.inputTruncated=snapshot.truncated,this.requestUpdate("topics",previous)}connectedCallback(){super.connectedCallback(),this.announcementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.layoutInvalidated=!0,this.armResizeObserver()}armResizeObserver(){const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!this.isConnected||!ownerWindow?.ResizeObserver||this.resizeObserver&&this.resizeObserverDocument===ownerDocument)return;this.resetResizeWork();const generation=this.ownerRealmGeneration,observer=new ownerWindow.ResizeObserver(entries=>{if(this.resizeObserver!==observer||this.resizeObserverDocument!==ownerDocument||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument)return;const rect=entries[0]?.contentRect,size=rect?`${rect.width}:${rect.height}`:"";if(size&&size===this.observedSize)return;this.observedSize=size,this.resizeRafId!=null&&this.resizeRafOwner?.cancelAnimationFrame(this.resizeRafId);const handle=ownerWindow.requestAnimationFrame(()=>{this.resizeRafId!==handle||this.resizeRafOwner!==ownerWindow||this.resizeRafDocument!==ownerDocument||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.resizeRafId=void 0,this.resizeRafOwner=void 0,this.resizeRafDocument=void 0,this.layoutInvalidated=!0,this.requestUpdate("layout",!1))});this.resizeRafId=handle,this.resizeRafOwner=ownerWindow,this.resizeRafDocument=ownerDocument});this.resizeObserver=observer,this.resizeObserverDocument=ownerDocument,observer.observe(this)}disconnectedCallback(){this.sourceVersion++,this.clearSourceDiagram(),this.resetResizeWork(),this.announcementSink?.release(),this.announcementSink=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.sourceControl.adopted(),this.sourceVersion++,this.clearSourceDiagram(),this.resetResizeWork(),this.announcementSink?.release(),this.announcementSink=void 0}resetResizeWork(){this.ownerRealmGeneration+=1,this.resizeRafId!=null&&this.resizeRafOwner?.cancelAnimationFrame(this.resizeRafId),this.resizeRafId=void 0,this.resizeRafOwner=void 0,this.resizeRafDocument=void 0,this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeObserverDocument=void 0,this.observedSize=""}attributeChangedCallback(name,oldValue,value){super.attributeChangedCallback(name,oldValue,value),(name==="dir"||name==="lang")&&oldValue!==value&&(this.layoutInvalidated=!0,this.requestUpdate("layout",!1))}get effectiveExpandDepth(){return finiteCount(this.expandDepth,1)}isExpanded(id,depth){return this.expandedOverrides.get(id)??depth<this.effectiveExpandDepth}ringGapPx(){const hostStyle=this.ownerDocument.defaultView?.getComputedStyle(this)??this.style,raw=hostStyle.getPropertyValue("--lr-mind-map-ring-gap").trim()||hostStyle.getPropertyValue("--_lr-mind-map-ring-gap").trim();return resolveCssTokenLength(raw,{host:this})??DEFAULT_RING_GAP_PX}layoutInputs(){return[this.topics,this.expandDepth,this.expandedOverrides,this.label,this.strings,this.effectiveLocale]}relayout(){this.topicLayout?.source!==this.topics&&(this.topicLayout={source:this.topics,compute:createMindMapLayout(this.topics)});const hubLabel=this.label==null?this.localize("mindMapLabel"):this.label,fullLayout=this.topicLayout.compute(hubLabel,{ringGap:this.ringGapPx(),rtl:isRtl(this),isExpanded:(id,depth)=>this.isExpanded(id,depth)});this.laidOutInputs=this.layoutInputs();const decimated=decimateMindMapLayout(fullLayout.placed,fullLayout.links,MAX_RENDERED_MIND_MAP_NODES);this.totalTopicCount=decimated.totalCount,this.topicsTruncated=decimated.truncated,this.cachedLayout={...fullLayout,placed:[...decimated.placed],links:[...decimated.links]}}willUpdate(changed){if(super.willUpdate(changed),this.sourceControl.update(this.sourceWrapper,this.effectiveLocale),this.treeSource!==void 0){(changed.has("label")||changed.has("strings")||changed.has("locale"))&&(this.layoutInvalidated=!0),this.scheduleSourceDiagram();return}this.hasUpdated&&changed.has("topics")&&this.inputTruncated&&this.announcementSink?.announce(this.localize("mindMapInputLimit"));const context=`${this.label==null?this.localize("mindMapLabel"):this.label}\0${isRtl(this)?"rtl":"ltr"}`,structuralChange=changed.has("topics")||changed.has("expandDepth")||changed.has("expandedOverrides")||changed.has("label")||changed.has("strings")||changed.has("locale");(this.layoutInvalidated||structuralChange&&(!this.laidOutInputs||this.layoutInputs().some((value,index)=>value!==this.laidOutInputs[index]))||context!==this.layoutContext)&&(this.relayout(),this.layoutContext=context,this.layoutInvalidated=!1,this.focusedId&&!this.cachedLayout.placed.some(topic=>topic.id===this.focusedId)&&(this.focusedId=this.cachedLayout.placed[0]?.id??null))}setAnnouncement(text){this.liveText=text,this.announcementSink?.announce(text)}toggle(node,announce=!0){if(this.treeSource!==void 0){const row=this.sourceDiagramRows.get(node.id);row&&this.sourceDiagramCurrent()&&this.selectSourceRow(row);return}const expanded=!this.isExpanded(node.id,node.depth),next=new Map(this.expandedOverrides);next.set(node.id,expanded),this.expandedOverrides=next,this.emit("lr-topic-toggle",{topicId:node.id,expanded}),announce&&this.setAnnouncement(this.localize(expanded?"mindMapExpanded":"mindMapCollapsed",void 0,{label:node.label}))}activate(node){if(this.treeSource!==void 0){const row=this.sourceDiagramRows.get(node.id);row&&this.sourceDiagramCurrent()&&this.selectSourceRow(row);return}node.hasChildren?this.toggle(node):this.emit("lr-topic-select",{topicId:node.id})}siblingsOf(node){return this.cachedLayout.placed.filter(p=>p.parentId===node.parentId)}childrenOf(id){return this.cachedLayout.placed.filter(p=>p.parentId===id)}announce(node){const numberFormat=getNumberFormat(this.effectiveLocale);this.setAnnouncement(node.hasChildren?this.localize("mindMapTopicStatus",void 0,{label:node.label,level:numberFormat.format(node.depth+1),count:numberFormat.format(this.childrenOf(node.id).length)}):this.localize("mindMapLeafStatus",void 0,{label:node.label,level:numberFormat.format(node.depth+1)}))}focusNodeById(id){this.focusedId=id;const node=this.cachedLayout.placed.find(p=>p.id===id);node&&this.announce(node)}onNodeClick(node){if(this.treeSource!==void 0){this.activate(node);return}this.focusedId=node.id,this.svgEl?.focus(),node.hasChildren||this.announce(node),this.activate(node)}connectorControlPoint(from,to){const layout=this.cachedLayout,parentR=Math.hypot(from.x-layout.centerX,from.y-layout.centerY),dir=isRtl(this)?-1:1;return{x:layout.centerX+dir*parentR*Math.sin(to.angle),y:layout.centerY-parentR*Math.cos(to.angle)}}renderSemanticNode(node,childrenByParent){const children=childrenByParent.get(node.id)??[];return 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{snapshotMindMapTopics}from"./mind-map-model.js";import{html,nothing,svg}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{isRtl}from"../../../internal/rtl.js";import{finiteCount}from"../../../internal/numbers.js";import{resolveCssTokenLength}from"../../../internal/css-token-length.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{decimateMindMapLayout,createMindMapLayout}from"./mind-map-layout.js";import{styles}from"./mind-map.styles.js";import{LYRA_DEFAULT_mindMapCollapsed,LYRA_DEFAULT_mindMapExpanded,LYRA_DEFAULT_mindMapInputLimit,LYRA_DEFAULT_mindMapLabel,LYRA_DEFAULT_mindMapLeafStatus,LYRA_DEFAULT_mindMapNodeLimit,LYRA_DEFAULT_mindMapTopicStatus}from"../../../internal/default-strings/retrieval.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_expand,LYRA_DEFAULT_loading,LYRA_DEFAULT_noData,LYRA_DEFAULT_retry,LYRA_DEFAULT_treeSourceError,LYRA_DEFAULT_treeSourceSummary}from"../../../internal/default-strings/shared.generated.js";const DEFAULT_RING_GAP_PX=96,MAX_RENDERED_MIND_MAP_NODES=500,NAV_KEYS=new Set(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End","Enter"," "]);class LyraMindMap extends LyraElement{constructor(){super(...arguments),this.sourceVersion=0,this.sourceViewAuthority=new WeakMap,this.sourcePaint=0,this.sourceDiagramScheduled=!1,this.sourceDiagramRows=new Map,this.sourceDiagramCurrent=()=>!1,this.sourceControl=new HierarchySourceController(this,{normalize:(value,key)=>{const current=this.sourceAuthority(),field=name=>{if(!current())throw new Error("Topic source changed");const result=hierarchyField(value,name);if(!current())throw new Error("Topic source changed");return result},id=hierarchyKey(field("id"));if(id!==key)throw new TypeError("Topic key mismatch");return Object.freeze({id,label:hierarchyText(field("label"))})},payload:{maxUnits:2e6,maxRowUnits:65536,unitsOf:topic=>topic.id.length+topic.label.length},onChange:()=>{this._treeSource!==void 0&&this.clearSourceDiagram();const old=this.sourcePaint++;this.requestUpdate("sourcePaint",old)},accepted:(action,row,_state,current)=>{!current()||this.treeSource===void 0||(action.type==="toggle"?this.emit("lr-topic-toggle",{topicId:action.key,expanded:action.expanded}):action.type==="select"&&row?.childCount===0&&this.emit("lr-topic-select",{topicId:action.key}))}}),this._topics=Object.freeze([]),this.topicsSource=this._topics,this.inputTruncated=!1,this.expandDepth=1,this.expandedOverrides=new Map,this.focusedId=null,this.liveText="",this.cachedLayout={placed:[],links:[],width:0,height:0,centerX:0,centerY:0},this.totalTopicCount=0,this.topicsTruncated=!1,this.ownerRealmGeneration=0,this.observedSize="",this.layoutInvalidated=!0,this.layoutContext="",this.onKeyDown=e=>{if(this.treeSource!==void 0){if(!this.sourceDiagramCurrent())return;const row=this.sourceDiagramRows.get(this.focusedId??"")??this.sourceDiagramRows.values().next().value;if(!row)return;const index=this.sourceControl.window.source.indexOfKey?.(row.key);typeof index=="number"&&index>=0&&this.sourceControl.keydown(e,row,index,isRtl(this),selected=>this.selectSourceRow(selected));return}const placed=this.cachedLayout.placed;if(placed.length===0||!NAV_KEYS.has(e.key))return;if(e.preventDefault(),this.focusedId===null){this.focusNodeById(placed[0].id);return}const current=placed.find(p=>p.id===this.focusedId);if(!current)return;if(e.key==="Enter"||e.key===" "){e.repeat||this.activate(current);return}if(e.key==="ArrowUp"){current.parentId&&this.focusNodeById(current.parentId);return}if(e.key==="ArrowDown"){if(!current.hasChildren)return;this.isExpanded(current.id,current.depth)||(this.toggle(current,!1),this.relayout());const child=this.childrenOf(current.id)[0];child&&this.focusNodeById(child.id);return}const rtl=isRtl(this),forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";if(e.key===forwardKey||e.key===backwardKey||e.key==="Home"||e.key==="End"){const siblings=this.siblingsOf(current),index=siblings.findIndex(s=>s.id===current.id);let next=index;e.key===forwardKey?next=Math.min(siblings.length-1,index+1):e.key===backwardKey?next=Math.max(0,index-1):e.key==="Home"?next=0:next=siblings.length-1;const target=siblings[next];target&&this.focusNodeById(target.id)}},this.onFocusIn=()=>{if(this.focusedId!==null)return;const first=this.cachedLayout.placed[0];first&&(this.focusedId=first.id)}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,expand:LYRA_DEFAULT_expand,loading:LYRA_DEFAULT_loading,mindMapCollapsed:LYRA_DEFAULT_mindMapCollapsed,mindMapExpanded:LYRA_DEFAULT_mindMapExpanded,mindMapInputLimit:LYRA_DEFAULT_mindMapInputLimit,mindMapLabel:LYRA_DEFAULT_mindMapLabel,mindMapLeafStatus:LYRA_DEFAULT_mindMapLeafStatus,mindMapNodeLimit:LYRA_DEFAULT_mindMapNodeLimit,mindMapTopicStatus:LYRA_DEFAULT_mindMapTopicStatus,noData:LYRA_DEFAULT_noData,retry:LYRA_DEFAULT_retry,treeSourceError:LYRA_DEFAULT_treeSourceError,treeSourceSummary:LYRA_DEFAULT_treeSourceSummary}}static{this.styles=[LyraElement.styles,hierarchySourceStyles,styles,srOnly]}static get observedAttributes(){return[...new Set([...super.observedAttributes,"dir","lang"])]}get treeSource(){return this._treeSource}set treeSource(value){const old=this._treeSource;this._treeSource=value,this.sourceVersion++,this.sourceWrapper=value===void 0?void 0:this.wrapSource(value),this.clearSourceDiagram(),this.sourceControl?.update(this.sourceWrapper,this.effectiveLocale,!0),this.layoutInvalidated=!0,this.requestUpdate("treeSource",old)}revealSourceKey(key){return this.treeSource===void 0?Promise.resolve(!1):this.sourceControl.reveal(key)}sourceAuthority(){const source=this.treeSource,version=this.sourceVersion,owner=this.ownerDocument,epoch=this.sourceControl.epoch,projection=this.sourceControl.projection,accepted=projection?this.sourceViewAuthority.get(projection.rows):void 0,owned=()=>this.isConnected&&this.ownerDocument===owner&&this.treeSource===source&&this.sourceVersion===version&&this.sourceControl.epoch===epoch&&this.sourceControl.projection===projection&&(source===void 0||!this.sourceControl.loading);return()=>owned()&&(source===void 0||!!accepted?.())&&owned()}wrapSource(source){const host=this,wrapper={get revision(){return source.revision},async project(request){const version=host.sourceVersion,owner=host.ownerDocument,owned=()=>host.isConnected&&host.ownerDocument===owner&&host.treeSource===source&&host.sourceWrapper===wrapper&&host.sourceVersion===version&&!request.signal.aborted,current=()=>{if(!owned())return!1;try{const revision=source.revision;return owned()&&revision===request.revision}catch{return!1}},check=()=>{if(!current())throw new Error("Topic source changed")};check();const project=source.project;check();const result=await project.call(source,request);check();const rows=result.rows;if(check(),rows===null||typeof rows!="object")throw new TypeError("Invalid topic source rows");return host.sourceViewAuthority.set(rows,current),result}};return wrapper}clearSourceDiagram(){this.sourceDiagramRows=new Map,this.sourceDiagramCurrent=()=>!1,this.cachedLayout={placed:[],links:[],width:0,height:0,centerX:0,centerY:0}}requestUpdate(name,oldValue){this._treeSource!==void 0&&name===void 0&&(this.sourceVersion++,this.sourceWrapper=this.wrapSource(this._treeSource),this.clearSourceDiagram(),this.sourceControl?.update(this.sourceWrapper,this.effectiveLocale,!0)),super.requestUpdate(name,oldValue)}selectSourceRow(row){if(row.disabled||this.sourceControl.loading||this.sourceControl.error)return;const current=this.sourceAuthority(),index=this.sourceControl.adapter.indexOfKey?.(row.key);if(!current()||typeof index!="number"||index<0)return;const slot=this.sourceControl.slot(index);!current()||slot.state!=="ready"||slot.value!==row||this.sourceControl.project(row.childCount?{type:"toggle",key:row.key,expanded:!row.expanded}:{type:"select",key:row.key,selected:!0,scope:"item"},!0,row)}scheduleSourceDiagram(){this.sourceDiagramScheduled||(this.sourceDiagramScheduled=!0,queueMicrotask(()=>{if(this.sourceDiagramScheduled=!1,this.treeSource===void 0||!this.isConnected)return;const current=this.sourceAuthority(),control=this.sourceControl,rows=new Map;if(!control.loading&&!control.error)for(const element of control.list?.projectedRows??[]){if(rows.size===301)break;const key=element.querySelector("[data-source-key]")?.dataset.sourceKey;if(!key)continue;const slot=control.slot(Number(element.dataset.rowIndex));if(!current())return;slot.state==="ready"&&slot.value.key===key&&rows.set(key,slot.value)}const previous=this.sourceDiagramRows,root=[...rows.values()].find(row=>row.parentKey===null||!rows.has(row.parentKey)),connected=new Map,topics=new Map;if(root)for(const row of rows.values()){if(row!==root&&(!row.parentKey||!connected.has(row.parentKey)))continue;const topic={id:row.key,label:row.value.label,children:[]};connected.set(row.key,row),topics.set(row.key,topic),row!==root&&topics.get(row.parentKey).children.push(topic)}if(!this.layoutInvalidated&&connected.size===previous.size&&[...connected].every(([key,row])=>previous.get(key)===row)&&this.sourceDiagramCurrent())return;const layout=createMindMapLayout(root?[topics.get(root.key)]:[])(this.label??this.localize("mindMapLabel"),{ringGap:this.ringGapPx(),rtl:isRtl(this),isExpanded:id=>connected.get(id)?.expanded??!1});current()&&(this.sourceDiagramRows=connected,this.sourceDiagramCurrent=current,this.cachedLayout={...layout,placed:layout.placed.map(node=>({...node,hasChildren:!!connected.get(node.id)?.childCount,expanded:connected.get(node.id)?.expanded??!1}))},this.layoutInvalidated=!1,this.requestUpdate("sourceDiagram",!1))}))}get topics(){return this._topics}set topics(value){if(Object.is(value,this.topicsSource)||Object.is(value,this._topics))return;const previous=this._topics,snapshot=snapshotMindMapTopics(value);this.topicsSource=value,this._topics=snapshot.topics,this.inputTruncated=snapshot.truncated,this.requestUpdate("topics",previous)}connectedCallback(){super.connectedCallback(),this.announcementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.layoutInvalidated=!0,this.armResizeObserver()}armResizeObserver(){const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!this.isConnected||!ownerWindow?.ResizeObserver||this.resizeObserver&&this.resizeObserverDocument===ownerDocument)return;this.resetResizeWork();const generation=this.ownerRealmGeneration,observer=new ownerWindow.ResizeObserver(entries=>{if(this.resizeObserver!==observer||this.resizeObserverDocument!==ownerDocument||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument)return;const rect=entries[0]?.contentRect,size=rect?`${rect.width}:${rect.height}`:"";if(size&&size===this.observedSize)return;this.observedSize=size,this.resizeRafId!=null&&this.resizeRafOwner?.cancelAnimationFrame(this.resizeRafId);const handle=ownerWindow.requestAnimationFrame(()=>{this.resizeRafId!==handle||this.resizeRafOwner!==ownerWindow||this.resizeRafDocument!==ownerDocument||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.resizeRafId=void 0,this.resizeRafOwner=void 0,this.resizeRafDocument=void 0,this.layoutInvalidated=!0,this.requestUpdate("layout",!1))});this.resizeRafId=handle,this.resizeRafOwner=ownerWindow,this.resizeRafDocument=ownerDocument});this.resizeObserver=observer,this.resizeObserverDocument=ownerDocument,observer.observe(this)}disconnectedCallback(){this.sourceVersion++,this.clearSourceDiagram(),this.resetResizeWork(),this.announcementSink?.release(),this.announcementSink=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.sourceControl.adopted(),this.sourceVersion++,this.clearSourceDiagram(),this.resetResizeWork(),this.announcementSink?.release(),this.announcementSink=void 0}resetResizeWork(){this.ownerRealmGeneration+=1,this.resizeRafId!=null&&this.resizeRafOwner?.cancelAnimationFrame(this.resizeRafId),this.resizeRafId=void 0,this.resizeRafOwner=void 0,this.resizeRafDocument=void 0,this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeObserverDocument=void 0,this.observedSize=""}attributeChangedCallback(name,oldValue,value){super.attributeChangedCallback(name,oldValue,value),(name==="dir"||name==="lang")&&oldValue!==value&&(this.layoutInvalidated=!0,this.requestUpdate("layout",!1))}get effectiveExpandDepth(){return finiteCount(this.expandDepth,1)}isExpanded(id,depth){return this.expandedOverrides.get(id)??depth<this.effectiveExpandDepth}ringGapPx(){const hostStyle=this.ownerDocument.defaultView?.getComputedStyle(this)??this.style,raw=hostStyle.getPropertyValue("--lr-mind-map-ring-gap").trim()||hostStyle.getPropertyValue("--_lr-mind-map-ring-gap").trim();return resolveCssTokenLength(raw,{host:this})??DEFAULT_RING_GAP_PX}layoutInputs(){return[this.topics,this.expandDepth,this.expandedOverrides,this.label,this.strings,this.effectiveLocale]}relayout(){this.topicLayout?.source!==this.topics&&(this.topicLayout={source:this.topics,compute:createMindMapLayout(this.topics)});const hubLabel=this.label==null?this.localize("mindMapLabel"):this.label,fullLayout=this.topicLayout.compute(hubLabel,{ringGap:this.ringGapPx(),rtl:isRtl(this),isExpanded:(id,depth)=>this.isExpanded(id,depth)});this.laidOutInputs=this.layoutInputs();const decimated=decimateMindMapLayout(fullLayout.placed,fullLayout.links,MAX_RENDERED_MIND_MAP_NODES);this.totalTopicCount=decimated.totalCount,this.topicsTruncated=decimated.truncated,this.cachedLayout={...fullLayout,placed:[...decimated.placed],links:[...decimated.links]}}willUpdate(changed){if(super.willUpdate(changed),this.sourceControl.update(this.sourceWrapper,this.effectiveLocale),this.treeSource!==void 0){(changed.has("label")||changed.has("strings")||changed.has("locale"))&&(this.layoutInvalidated=!0),this.scheduleSourceDiagram();return}this.hasUpdated&&changed.has("topics")&&this.inputTruncated&&this.announcementSink?.announce(this.localize("mindMapInputLimit"));const context=`${this.label==null?this.localize("mindMapLabel"):this.label}\0${isRtl(this)?"rtl":"ltr"}`,structuralChange=changed.has("topics")||changed.has("expandDepth")||changed.has("expandedOverrides")||changed.has("label")||changed.has("strings")||changed.has("locale");(this.layoutInvalidated||structuralChange&&(!this.laidOutInputs||this.layoutInputs().some((value,index)=>value!==this.laidOutInputs[index]))||context!==this.layoutContext)&&(this.relayout(),this.layoutContext=context,this.layoutInvalidated=!1,this.focusedId&&!this.cachedLayout.placed.some(topic=>topic.id===this.focusedId)&&(this.focusedId=this.cachedLayout.placed[0]?.id??null))}setAnnouncement(text){this.liveText=text,this.announcementSink?.announce(text)}toggle(node,announce=!0){const expanded=!this.isExpanded(node.id,node.depth),next=new Map(this.expandedOverrides);next.set(node.id,expanded),this.expandedOverrides=next,this.emit("lr-topic-toggle",{topicId:node.id,expanded}),announce&&this.setAnnouncement(this.localize(expanded?"mindMapExpanded":"mindMapCollapsed",void 0,{label:node.label}))}activate(node){if(this.treeSource!==void 0){const row=this.sourceDiagramRows.get(node.id);row&&this.sourceDiagramCurrent()&&this.selectSourceRow(row);return}node.hasChildren?this.toggle(node):this.emit("lr-topic-select",{topicId:node.id})}siblingsOf(node){return this.cachedLayout.placed.filter(p=>p.parentId===node.parentId)}childrenOf(id){return this.cachedLayout.placed.filter(p=>p.parentId===id)}announce(node){const numberFormat=getNumberFormat(this.effectiveLocale);this.setAnnouncement(node.hasChildren?this.localize("mindMapTopicStatus",void 0,{label:node.label,level:numberFormat.format(node.depth+1),count:numberFormat.format(this.childrenOf(node.id).length)}):this.localize("mindMapLeafStatus",void 0,{label:node.label,level:numberFormat.format(node.depth+1)}))}focusNodeById(id){this.focusedId=id;const node=this.cachedLayout.placed.find(p=>p.id===id);node&&this.announce(node)}onNodeClick(node){if(this.treeSource!==void 0){this.activate(node);return}this.focusedId=node.id,this.svgEl?.focus(),node.hasChildren||this.announce(node),this.activate(node)}connectorControlPoint(from,to){const layout=this.cachedLayout,parentR=Math.hypot(from.x-layout.centerX,from.y-layout.centerY),dir=isRtl(this)?-1:1;return{x:layout.centerX+dir*parentR*Math.sin(to.angle),y:layout.centerY-parentR*Math.cos(to.angle)}}renderSemanticNode(node,childrenByParent){const children=childrenByParent.get(node.id)??[];return html`
2
2
  <div
3
3
  role="treeitem"
4
4
  aria-level=${node.depth+1}
@@ -72,4 +72,4 @@ sourcePageSize:number;
72
72
  /** Exact matching neighborhood count, or null before a current successful query.*/
73
73
  get sourceTotal():number|null;private sourceEpoch;private sourceNavigation;private sourcePaint;private sourceBinding?;private sourcePageBinding?;private sourceError;private sourceFailedEpoch?;private sourceSyncing;private sourcePromise;private readonly sourcePages;private sourceCurrent;private syncSource;
74
74
  /** Reveals and focuses a global neighborhood node without selecting or expanding it.*/
75
- revealSourceKey(key:string):Promise<boolean>;connectedCallback():void;disconnectedCallback():void;private get effectiveVirtualizeAt();private readonly announcements;private sortedRowsCache;private groupsCache;private hasComputedRows;private processedSignature;private explicitRefresh;private groupDeps?;private presentationDeps?;requestUpdate(...args:Parameters<LyraElement['requestUpdate']>):void;protected willUpdate(changed:PropertyValues<this>):void;private sortedRows;private computeSortedRows;private groups;private computeGroups;private directionGlyph;private directionText;private renderRow;private readonly virtualListKeyFunction;private renderNeighborRow;adoptedCallback():void;private renderSource;protected updated(changed:PropertyValues<this>):void;private inputLimitMessage;private renderInputLimit;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-neighbor-list':LyraNeighborList;}}
75
+ revealSourceKey(key:string):Promise<boolean>;connectedCallback():void;disconnectedCallback():void;private get effectiveVirtualizeAt();private readonly announcements;private sortedRowsCache;private groupsCache;private hasComputedRows;private processedSignature;private explicitRefresh;private groupDeps?;private presentationDeps?;requestUpdate(...args:Parameters<LyraElement['requestUpdate']>):void;protected willUpdate(changed:PropertyValues<this>):void;private sortedRows;private computeSortedRows;private computeGroups;private directionGlyph;private directionText;private renderRow;private readonly virtualListKeyFunction;private renderNeighborRow;adoptedCallback():void;private renderSource;protected updated(changed:PropertyValues<this>):void;private inputLimitMessage;private renderInputLimit;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-neighbor-list':LyraNeighborList;}}
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{SourcePageController}from"../../../internal/source-page-controller.js";import{sourceCount,sourceRevision}from"../../../internal/source-request-controller.js";import"../../data/pagination/pagination.class.js";function sourceField(value,key){if(!value||typeof value!="object")throw new TypeError("Invalid neighborhood value");const descriptor=Object.getOwnPropertyDescriptor(value,key);if(descriptor&&!("value"in descriptor))throw new TypeError("Accessor neighborhood field");return descriptor?.value}function sourceRows(raw,limit){if(!Array.isArray(raw))throw new TypeError("Invalid neighborhood page");const length=sourceCount(sourceField(raw,"length"));if(length>limit)throw new RangeError("Neighborhood page limit");let units=0;const text=(value,required=!1)=>{if(!(value===void 0&&!required)){if(typeof value!="string"||required&&!value.trim()||value.length>65536||(units+=value.length)>2e6)throw new TypeError("Invalid neighborhood text");return value}};return Object.freeze(Array.from({length},(_,index)=>{const entry=sourceField(raw,index),record=sourceField(entry,"value");if(sourceField(record,"kind")!=="node")throw new TypeError("Expected neighborhood node");const node=sourceField(record,"value"),key=text(sourceField(entry,"key"),!0),id=text(sourceField(node,"id"),!0);if(key!==`node:${id}`)throw new TypeError("Invalid neighborhood identity");const label=text(sourceField(node,"label")),accessibleLabel=text(sourceField(node,"accessibleLabel")),type=text(sourceField(node,"type"));return Object.freeze({key,order:sourceCount(sourceField(entry,"order")),value:Object.freeze({id,...label===void 0?{}:{label},...accessibleLabel===void 0?{}:{accessibleLabel},...type===void 0?{}:{type}})})}))}function sourceSummary(raw){return Object.freeze({nodes:sourceCount(sourceField(raw,"nodes")),edges:sourceCount(sourceField(raw,"edges"))})}import{AnnouncementSinkController}from"../../../internal/announcer.js";import{lyraLocaleCatalogVersion}from"../../../internal/localization-runtime.js";import{collectionSupport,publicCollectionTruncation}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{guard}from"lit/directives/guard.js";import{LyraElement}from"../../../internal/lyra-element.js";import{firstByRetrievalIdentity}from"../retrieval-identity.js";import{expandIcon}from"../../../internal/icons.js";import{finiteInteger,finiteCount}from"../../../internal/numbers.js";import{getCollator,getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import"../../overlays/empty/empty.class.js";import{styles}from"./neighbor-list.styles.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{LYRA_DEFAULT_graphDataListLimit,LYRA_DEFAULT_neighborExpand,LYRA_DEFAULT_neighborGroupHeader,LYRA_DEFAULT_neighborListEmpty,LYRA_DEFAULT_neighborListLabel,LYRA_DEFAULT_neighborRowLabel,LYRA_DEFAULT_neighborSourceChoose,LYRA_DEFAULT_neighborSourceError,LYRA_DEFAULT_neighborSourceSummary}from"../../../internal/default-strings/retrieval.generated.js";import{LYRA_DEFAULT_loading,LYRA_DEFAULT_neighborDirectionBoth,LYRA_DEFAULT_neighborDirectionIn,LYRA_DEFAULT_neighborDirectionOut,LYRA_DEFAULT_retry}from"../../../internal/default-strings/shared.generated.js";let virtualListRegistration;class LyraNeighborList extends LyraElement{constructor(){super(...arguments),this.rows=[],this.types=[],this.groupByRelation=!1,this.expandable=!1,this.virtualizeAt=100,this.centerKey=null,this.sourceDirection="both",this._sourceNodeTypes=Object.freeze([]),this.sourceTypesError=!1,this.sourceTypesVersion=0,this.sourcePage=0,this.sourcePageSize=100,this.sourceEpoch=0,this.sourceNavigation=0,this.sourcePaint=0,this.sourceError=!1,this.sourceSyncing=!1,this.sourcePromise=Promise.resolve(!1),this.sourcePages=new SourcePageController(this,{normalizeRecord:row=>row,normalizeSummary:sourceSummary,validateMetadata:result=>{if(result.total>result.summary.nodes)throw new RangeError("Invalid neighborhood total")},onChange:()=>{const old=this.sourcePaint++;this.requestUpdate("sourcePaint",old)}}),this.announcements=new AnnouncementSinkController(this,{eager:["polite"]}),this.sortedRowsCache=[],this.hasComputedRows=!1,this.processedSignature="",this.explicitRefresh=0,this.renderRow=item=>this.renderNeighborRow(item),this.virtualListKeyFunction=item=>item.node.id}static{this.defaultStrings={...super.defaultStrings,graphDataListLimit:LYRA_DEFAULT_graphDataListLimit,loading:LYRA_DEFAULT_loading,neighborDirectionBoth:LYRA_DEFAULT_neighborDirectionBoth,neighborDirectionIn:LYRA_DEFAULT_neighborDirectionIn,neighborDirectionOut:LYRA_DEFAULT_neighborDirectionOut,neighborExpand:LYRA_DEFAULT_neighborExpand,neighborGroupHeader:LYRA_DEFAULT_neighborGroupHeader,neighborListEmpty:LYRA_DEFAULT_neighborListEmpty,neighborListLabel:LYRA_DEFAULT_neighborListLabel,neighborRowLabel:LYRA_DEFAULT_neighborRowLabel,neighborSourceChoose:LYRA_DEFAULT_neighborSourceChoose,neighborSourceError:LYRA_DEFAULT_neighborSourceError,neighborSourceSummary:LYRA_DEFAULT_neighborSourceSummary,retry:LYRA_DEFAULT_retry}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["rows","types"])}static{this.styles=[LyraElement.styles,styles]}get graphSource(){return this._graphSource}set graphSource(value){const previous=this._graphSource;this._graphSource=value,this.requestUpdate("graphSource",previous),previous===value&&super.requestUpdate()}get sourceNodeTypes(){return this._sourceNodeTypes}set sourceNodeTypes(value){const previous=this._sourceNodeTypes,transaction=++this.sourceTypesVersion;try{if(!Array.isArray(value))throw new TypeError("Invalid neighborhood types");const length=sourceCount(sourceField(value,"length"));if(length>500)throw new RangeError("Neighborhood type limit");const types=new Set;let units=0;for(let i=0;i<length;i++){const item=sourceField(value,i);if(typeof item!="string"||!item.trim()||item.length>65536)throw new TypeError("Invalid neighborhood type");if(!types.has(item)){if(units+=item.length,units>2e6)throw new RangeError("Neighborhood type budget");types.add(item)}}if(transaction!==this.sourceTypesVersion)return;this._sourceNodeTypes=Object.freeze([...types].sort()),this.sourceTypesError=!1}catch{if(transaction!==this.sourceTypesVersion)return;this._sourceNodeTypes=Object.freeze([]),this.sourceTypesError=!0}this.requestUpdate("sourceNodeTypes",previous)}get sourceTotal(){return this.graphSource!==void 0&&this.centerKey!==null&&!this.sourceError&&this.sourceBinding?.[3]===this.sourceEpoch?this.sourcePages.state.result?.total??null:null}sourceCurrent(){const source=this.graphSource,epoch=this.sourceEpoch,owner=this.ownerDocument;let revision;try{revision=source?.revision}catch{return()=>!1}return()=>{try{return source?.revision===revision&&this.isConnected&&this.ownerDocument===owner&&this.graphSource===source&&this.sourceEpoch===epoch}catch{return!1}}}syncSource(){if(!this.sourcePages||this.sourceSyncing)return;this.sourceSyncing=!0;const epoch=this.sourceEpoch;try{if(this.sourceError&&this.sourceFailedEpoch===epoch)return;const source=this.graphSource;if(source===void 0||this.centerKey===null||!this.isConnected){(this.sourceBinding||this.sourcePageBinding)&&this.sourcePages.bind(void 0),this.sourceBinding=void 0,this.sourcePageBinding=void 0,this.sourceError=!1;return}if(this.sourceTypesError||typeof this.centerKey!="string"||!this.centerKey.startsWith("node:")||!this.centerKey.slice(5).trim()||this.centerKey.length>65536||!["in","out","both"].includes(this.sourceDirection))throw new TypeError("Invalid neighborhood scope");const revision=sourceRevision(source.revision),records=source.records,locale=this.effectiveLocale,queryRead=records.query,lookupRead=records.lookup,locateRead=records.locate;if(sourceRevision(records.revision)!==revision||typeof queryRead!="function"||typeof lookupRead!="function"||typeof locateRead!="function")throw new TypeError("Invalid neighborhood provider");if(epoch!==this.sourceEpoch||source!==this.graphSource)return;const binding=[source,records,revision,epoch,locale];if(!this.sourceBinding||binding.some((value,index)=>value!==this.sourceBinding[index])){this.sourceBinding=binding,this.sourcePageBinding=void 0,this.sourceError=!1;const current=()=>source.revision===revision&&source.records===records&&records.revision===revision&&this.isConnected&&epoch===this.sourceEpoch&&source===this.graphSource,check=()=>{if(!current())throw new Error("Obsolete neighborhood")};if(this.sourcePages.bind({revision,epoch,locale,source:{revision,query:async request=>{check();const raw=await queryRead.call(records,request);if(check(),sourceField(raw,"groups")!==void 0||sourceField(raw,"tags")!==void 0)throw new TypeError("Unexpected neighborhood metadata");const result={rows:sourceRows(sourceField(raw,"rows"),request.pageSize),total:sourceCount(sourceField(raw,"total")),summary:sourceSummary(sourceField(raw,"summary"))};return check(),result},lookup:async(keys,context)=>{check();const raw=await lookupRead.call(records,keys,context);check();const rows=sourceRows(raw,keys.length);return check(),rows},locate:async(key,query,context)=>{check();const result=await locateRead.call(records,key,query,context);return check(),result}}}),epoch!==this.sourceEpoch||source!==this.graphSource)return}const size=finiteInteger(this.sourcePageSize,100,1,500),page=finiteInteger(this.sourcePage,0,0,Math.floor(Number.MAX_SAFE_INTEGER/size)),signature=[page,size,this.centerKey,this.sourceDirection,this.sourceNodeTypes];(!this.sourcePageBinding||signature.some((value,index)=>value!==this.sourcePageBinding[index]))&&(this.sourcePageBinding=signature,this.sourcePromise=this.sourcePages.request(Object.freeze({kind:"nodes",search:"",centerKey:this.centerKey,direction:this.sourceDirection,nodeTypes:this.sourceNodeTypes}),page,size))}catch{epoch===this.sourceEpoch&&(this.sourceError=!0,this.sourceFailedEpoch=epoch,this.sourcePages.bind(void 0),this.sourceBinding=void 0,this.sourcePageBinding=void 0)}finally{this.sourceSyncing=!1,epoch!==this.sourceEpoch&&queueMicrotask(()=>{const old=this.sourcePaint++;this.requestUpdate("sourcePaint",old)})}}async revealSourceKey(key){const navigation=++this.sourceNavigation;if(this.graphSource===void 0||this.centerKey===null||typeof key!="string"||!key.startsWith("node:")||!key.slice(5).trim()||key.length>65536)return!1;this.syncSource();const sourceCurrent=this.sourceCurrent(),current=()=>sourceCurrent()&&this.sourceNavigation===navigation;if(await this.sourcePromise,!current()||this.sourceError)return!1;const index=await this.sourcePages.locate(key);if(!current()||index===null||(this.sourceSyncing=!0,this.sourcePage=Math.floor(index/finiteInteger(this.sourcePageSize,100,1,500)),this.sourceSyncing=!1,this.syncSource(),await this.sourcePromise,await this.updateComplete,!current()))return!1;const target=[...this.renderRoot.querySelectorAll("[data-source-key]")].find(node=>node.dataset.sourceKey===key);return!target||!current()||(target.scrollIntoView({block:"nearest"}),!current())?!1:(target.focus(),current()&&this.renderRoot.querySelector("[data-source-key]:focus")===target)}connectedCallback(){super.connectedCallback(),this.sourceEpoch++,this.syncSource()}disconnectedCallback(){this.sourceEpoch++,this.sourceNavigation++,this.sourcePages.bind(void 0),this.sourceBinding=void 0,this.sourcePageBinding=void 0,super.disconnectedCallback()}get effectiveVirtualizeAt(){return finiteCount(this.virtualizeAt,100)}requestUpdate(...args){if(this.sourcePages&&(!this.sourceSyncing||args[0]!=="sourcePage"))if(args[0]===void 0||["graphSource","centerKey","sourceDirection","sourceNodeTypes","sourcePageSize"].includes(String(args[0]))){if(this.sourceEpoch++,this.sourceNavigation++,["centerKey","sourceDirection","sourceNodeTypes","sourcePageSize"].includes(String(args[0]))){const syncing=this.sourceSyncing;this.sourceSyncing=!0,this.sourcePage=0,this.sourceSyncing=syncing}}else args[0]==="sourcePage"&&this.sourceNavigation++;args[0]===void 0&&(this.explicitRefresh=(this.explicitRefresh??0)+1),super.requestUpdate(...args)}willUpdate(changed){if(super.willUpdate(changed),this.syncSource(),this.graphSource!==void 0){const state=this.sourcePages.state;state.result&&this.sourcePage!==state.page&&(this.sourceSyncing=!0,this.sourcePage=state.page,this.sourceSyncing=!1,this.sourcePageBinding&&(this.sourcePageBinding=[state.page,...this.sourcePageBinding.slice(1)])),(changed.has("rows")||changed.has("groupByRelation"))&&(this.hasComputedRows=!1);return}if(this.hasUpdated&&changed.has("rows")){const message=this.inputLimitMessage();message&&this.announcements.announcePolite(message)}const signature=`${this.effectiveLocale} ${this.groupByRelation}`;(!this.hasComputedRows||changed.has("rows")||changed.has("groupByRelation")||signature!==this.processedSignature)&&(this.hasComputedRows=!0,this.processedSignature=signature,this.sortedRowsCache=this.computeSortedRows());const groupDeps=[this.sortedRowsCache,this.effectiveLocale,this.strings,lyraLocaleCatalogVersion(this.effectiveLocale),this.explicitRefresh];(!this.groupDeps||groupDeps.some((value,index)=>value!==this.groupDeps[index]))&&(this.groupDeps=groupDeps,this.groupsCache=this.computeGroups(this.sortedRowsCache));const presentationDeps=[...groupDeps,this.types,this.expandable];(!this.presentationDeps||presentationDeps.some((value,index)=>value!==this.presentationDeps[index]))&&(this.presentationDeps=presentationDeps,this.renderRow=item=>this.renderNeighborRow(item)),this.sortedRowsCache.length>this.effectiveVirtualizeAt&&(virtualListRegistration??=import("../../layout/virtual-list/virtual-list.js").catch(()=>virtualListRegistration=void 0))}sortedRows(){return this.sortedRowsCache}computeSortedRows(){const rows=firstByRetrievalIdentity(this.rows,row=>row?.node?.id);if(!this.groupByRelation)return rows;const compare=getCollator(this.effectiveLocale).compare;return rows.sort((a,b)=>compare(a.relation,b.relation))}groups(sorted){return sorted===this.sortedRowsCache?this.groupsCache:this.computeGroups(sorted)}computeGroups(sorted){if(!this.groupByRelation)return;const groups=[],counts=new Map;for(const row of sorted)counts.set(row.relation,(counts.get(row.relation)??0)+1);const numberFormat=getNumberFormat(this.effectiveLocale);let lastRelation;return sorted.forEach((row,i)=>{if(row.relation!==lastRelation){const count=numberFormat.format(counts.get(row.relation)??0);groups.push({key:row.relation,label:this.localize("neighborGroupHeader",void 0,{relation:row.relation,count}),startIndex:i}),lastRelation=row.relation}}),groups}directionGlyph(direction){return direction==="both"?"↔":direction==="out"?"→":"←"}directionText(direction){return this.localize(direction==="in"?"neighborDirectionIn":direction==="out"?"neighborDirectionOut":"neighborDirectionBoth")}renderNeighborRow(row){const nodeLabel=row.node.label||row.node.id,directionText=this.directionText(row.direction),accessibleName=this.localize("neighborRowLabel",void 0,{label:nodeLabel,relation:row.relation,direction:directionText}),nodeType=typeof row.node.type=="string"&&row.node.type.trim()!==""?row.node.type:void 0;this.typeLabels?.[0]!==this.types&&(this.typeLabels=[this.types,new Map(firstByRetrievalIdentity(this.types,type=>type?.id).map(type=>[type.id,type.label]))]);const meta=[nodeType&&(this.typeLabels[1].get(nodeType)??nodeType),row.node.degree!=null?getNumberFormat(this.effectiveLocale).format(finiteCount(row.node.degree)):void 0].filter(v=>typeof v=="string"&&v!==""),metaText=getListFormat(this.effectiveLocale,{style:"short",type:"unit"}).format(meta);return html`
1
+ import{__decorate}from"tslib";import{SourcePageController}from"../../../internal/source-page-controller.js";import{sourceCount,sourceRevision}from"../../../internal/source-request-controller.js";import"../../data/pagination/pagination.class.js";function sourceField(value,key){if(!value||typeof value!="object")throw new TypeError("Invalid neighborhood value");const descriptor=Object.getOwnPropertyDescriptor(value,key);if(descriptor&&!("value"in descriptor))throw new TypeError("Accessor neighborhood field");return descriptor?.value}function sourceRows(raw,limit){if(!Array.isArray(raw))throw new TypeError("Invalid neighborhood page");const length=sourceCount(sourceField(raw,"length"));if(length>limit)throw new RangeError("Neighborhood page limit");let units=0;const text=(value,required=!1)=>{if(!(value===void 0&&!required)){if(typeof value!="string"||required&&!value.trim()||value.length>65536||(units+=value.length)>2e6)throw new TypeError("Invalid neighborhood text");return value}};return Object.freeze(Array.from({length},(_,index)=>{const entry=sourceField(raw,index),record=sourceField(entry,"value");if(sourceField(record,"kind")!=="node")throw new TypeError("Expected neighborhood node");const node=sourceField(record,"value"),key=text(sourceField(entry,"key"),!0),id=text(sourceField(node,"id"),!0);if(key!==`node:${id}`)throw new TypeError("Invalid neighborhood identity");const label=text(sourceField(node,"label")),accessibleLabel=text(sourceField(node,"accessibleLabel")),type=text(sourceField(node,"type"));return Object.freeze({key,order:sourceCount(sourceField(entry,"order")),value:Object.freeze({id,...label===void 0?{}:{label},...accessibleLabel===void 0?{}:{accessibleLabel},...type===void 0?{}:{type}})})}))}function sourceSummary(raw){return Object.freeze({nodes:sourceCount(sourceField(raw,"nodes")),edges:sourceCount(sourceField(raw,"edges"))})}import{AnnouncementSinkController}from"../../../internal/announcer.js";import{lyraLocaleCatalogVersion}from"../../../internal/localization-runtime.js";import{collectionSupport,publicCollectionTruncation}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{guard}from"lit/directives/guard.js";import{LyraElement}from"../../../internal/lyra-element.js";import{firstByRetrievalIdentity}from"../retrieval-identity.js";import{expandIcon}from"../../../internal/icons.js";import{finiteInteger,finiteCount}from"../../../internal/numbers.js";import{getCollator,getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import"../../overlays/empty/empty.class.js";import{styles}from"./neighbor-list.styles.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{LYRA_DEFAULT_graphDataListLimit,LYRA_DEFAULT_neighborExpand,LYRA_DEFAULT_neighborGroupHeader,LYRA_DEFAULT_neighborListEmpty,LYRA_DEFAULT_neighborListLabel,LYRA_DEFAULT_neighborRowLabel,LYRA_DEFAULT_neighborSourceChoose,LYRA_DEFAULT_neighborSourceError,LYRA_DEFAULT_neighborSourceSummary}from"../../../internal/default-strings/retrieval.generated.js";import{LYRA_DEFAULT_loading,LYRA_DEFAULT_neighborDirectionBoth,LYRA_DEFAULT_neighborDirectionIn,LYRA_DEFAULT_neighborDirectionOut,LYRA_DEFAULT_retry}from"../../../internal/default-strings/shared.generated.js";let virtualListRegistration;class LyraNeighborList extends LyraElement{constructor(){super(...arguments),this.rows=[],this.types=[],this.groupByRelation=!1,this.expandable=!1,this.virtualizeAt=100,this.centerKey=null,this.sourceDirection="both",this._sourceNodeTypes=Object.freeze([]),this.sourceTypesError=!1,this.sourceTypesVersion=0,this.sourcePage=0,this.sourcePageSize=100,this.sourceEpoch=0,this.sourceNavigation=0,this.sourcePaint=0,this.sourceError=!1,this.sourceSyncing=!1,this.sourcePromise=Promise.resolve(!1),this.sourcePages=new SourcePageController(this,{normalizeRecord:row=>row,normalizeSummary:sourceSummary,validateMetadata:result=>{if(result.total>result.summary.nodes)throw new RangeError("Invalid neighborhood total")},onChange:()=>{const old=this.sourcePaint++;this.requestUpdate("sourcePaint",old)}}),this.announcements=new AnnouncementSinkController(this,{eager:["polite"]}),this.sortedRowsCache=[],this.hasComputedRows=!1,this.processedSignature="",this.explicitRefresh=0,this.virtualListKeyFunction=item=>item.node.id}static{this.defaultStrings={...super.defaultStrings,graphDataListLimit:LYRA_DEFAULT_graphDataListLimit,loading:LYRA_DEFAULT_loading,neighborDirectionBoth:LYRA_DEFAULT_neighborDirectionBoth,neighborDirectionIn:LYRA_DEFAULT_neighborDirectionIn,neighborDirectionOut:LYRA_DEFAULT_neighborDirectionOut,neighborExpand:LYRA_DEFAULT_neighborExpand,neighborGroupHeader:LYRA_DEFAULT_neighborGroupHeader,neighborListEmpty:LYRA_DEFAULT_neighborListEmpty,neighborListLabel:LYRA_DEFAULT_neighborListLabel,neighborRowLabel:LYRA_DEFAULT_neighborRowLabel,neighborSourceChoose:LYRA_DEFAULT_neighborSourceChoose,neighborSourceError:LYRA_DEFAULT_neighborSourceError,neighborSourceSummary:LYRA_DEFAULT_neighborSourceSummary,retry:LYRA_DEFAULT_retry}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["rows","types"])}static{this.styles=[LyraElement.styles,styles]}get graphSource(){return this._graphSource}set graphSource(value){const previous=this._graphSource;this._graphSource=value,this.requestUpdate("graphSource",previous),previous===value&&super.requestUpdate()}get sourceNodeTypes(){return this._sourceNodeTypes}set sourceNodeTypes(value){const previous=this._sourceNodeTypes,transaction=++this.sourceTypesVersion;try{if(!Array.isArray(value))throw new TypeError("Invalid neighborhood types");const length=sourceCount(sourceField(value,"length"));if(length>500)throw new RangeError("Neighborhood type limit");const types=new Set;let units=0;for(let i=0;i<length;i++){const item=sourceField(value,i);if(typeof item!="string"||!item.trim()||item.length>65536)throw new TypeError("Invalid neighborhood type");if(!types.has(item)){if(units+=item.length,units>2e6)throw new RangeError("Neighborhood type budget");types.add(item)}}if(transaction!==this.sourceTypesVersion)return;this._sourceNodeTypes=Object.freeze([...types].sort()),this.sourceTypesError=!1}catch{if(transaction!==this.sourceTypesVersion)return;this._sourceNodeTypes=Object.freeze([]),this.sourceTypesError=!0}this.requestUpdate("sourceNodeTypes",previous)}get sourceTotal(){return this.graphSource!==void 0&&this.centerKey!==null&&!this.sourceError&&this.sourceBinding?.[3]===this.sourceEpoch?this.sourcePages.state.result?.total??null:null}sourceCurrent(){const source=this.graphSource,epoch=this.sourceEpoch,owner=this.ownerDocument;let revision;try{revision=source?.revision}catch{return()=>!1}return()=>{try{return source?.revision===revision&&this.isConnected&&this.ownerDocument===owner&&this.graphSource===source&&this.sourceEpoch===epoch}catch{return!1}}}syncSource(){if(!this.sourcePages||this.sourceSyncing)return;this.sourceSyncing=!0;const epoch=this.sourceEpoch;try{if(this.sourceError&&this.sourceFailedEpoch===epoch)return;const source=this.graphSource;if(source===void 0||this.centerKey===null||!this.isConnected){(this.sourceBinding||this.sourcePageBinding)&&this.sourcePages.bind(void 0),this.sourceBinding=void 0,this.sourcePageBinding=void 0,this.sourceError=!1;return}if(this.sourceTypesError||typeof this.centerKey!="string"||!this.centerKey.startsWith("node:")||!this.centerKey.slice(5).trim()||this.centerKey.length>65536||!["in","out","both"].includes(this.sourceDirection))throw new TypeError("Invalid neighborhood scope");const revision=sourceRevision(source.revision),records=source.records,locale=this.effectiveLocale,queryRead=records.query,lookupRead=records.lookup,locateRead=records.locate;if(sourceRevision(records.revision)!==revision||typeof queryRead!="function"||typeof lookupRead!="function"||typeof locateRead!="function")throw new TypeError("Invalid neighborhood provider");if(epoch!==this.sourceEpoch||source!==this.graphSource)return;const binding=[source,records,revision,epoch,locale];if(!this.sourceBinding||binding.some((value,index)=>value!==this.sourceBinding[index])){this.sourceBinding=binding,this.sourcePageBinding=void 0,this.sourceError=!1;const current=()=>source.revision===revision&&source.records===records&&records.revision===revision&&this.isConnected&&epoch===this.sourceEpoch&&source===this.graphSource,check=()=>{if(!current())throw new Error("Obsolete neighborhood")};if(this.sourcePages.bind({revision,epoch,locale,source:{revision,query:async request=>{check();const raw=await queryRead.call(records,request);if(check(),sourceField(raw,"groups")!==void 0||sourceField(raw,"tags")!==void 0)throw new TypeError("Unexpected neighborhood metadata");const result={rows:sourceRows(sourceField(raw,"rows"),request.pageSize),total:sourceCount(sourceField(raw,"total")),summary:sourceSummary(sourceField(raw,"summary"))};return check(),result},lookup:async(keys,context)=>{check();const raw=await lookupRead.call(records,keys,context);check();const rows=sourceRows(raw,keys.length);return check(),rows},locate:async(key,query,context)=>{check();const result=await locateRead.call(records,key,query,context);return check(),result}}}),epoch!==this.sourceEpoch||source!==this.graphSource)return}const size=finiteInteger(this.sourcePageSize,100,1,500),page=finiteInteger(this.sourcePage,0,0,Math.floor(Number.MAX_SAFE_INTEGER/size)),signature=[page,size,this.centerKey,this.sourceDirection,this.sourceNodeTypes];(!this.sourcePageBinding||signature.some((value,index)=>value!==this.sourcePageBinding[index]))&&(this.sourcePageBinding=signature,this.sourcePromise=this.sourcePages.request(Object.freeze({kind:"nodes",search:"",centerKey:this.centerKey,direction:this.sourceDirection,nodeTypes:this.sourceNodeTypes}),page,size))}catch{epoch===this.sourceEpoch&&(this.sourceError=!0,this.sourceFailedEpoch=epoch,this.sourcePages.bind(void 0),this.sourceBinding=void 0,this.sourcePageBinding=void 0)}finally{this.sourceSyncing=!1,epoch!==this.sourceEpoch&&queueMicrotask(()=>{const old=this.sourcePaint++;this.requestUpdate("sourcePaint",old)})}}async revealSourceKey(key){const navigation=++this.sourceNavigation;if(this.graphSource===void 0||this.centerKey===null||typeof key!="string"||!key.startsWith("node:")||!key.slice(5).trim()||key.length>65536)return!1;this.syncSource();const sourceCurrent=this.sourceCurrent(),current=()=>sourceCurrent()&&this.sourceNavigation===navigation;if(await this.sourcePromise,!current()||this.sourceError)return!1;const index=await this.sourcePages.locate(key);if(!current()||index===null||(this.sourceSyncing=!0,this.sourcePage=Math.floor(index/finiteInteger(this.sourcePageSize,100,1,500)),this.sourceSyncing=!1,this.syncSource(),await this.sourcePromise,await this.updateComplete,!current()))return!1;const target=[...this.renderRoot.querySelectorAll("[data-source-key]")].find(node=>node.dataset.sourceKey===key);return!target||!current()||(target.scrollIntoView({block:"nearest"}),!current())?!1:(target.focus(),current()&&this.renderRoot.querySelector("[data-source-key]:focus")===target)}connectedCallback(){super.connectedCallback(),this.sourceEpoch++,this.syncSource()}disconnectedCallback(){this.sourceEpoch++,this.sourceNavigation++,this.sourcePages.bind(void 0),this.sourceBinding=void 0,this.sourcePageBinding=void 0,super.disconnectedCallback()}get effectiveVirtualizeAt(){return finiteCount(this.virtualizeAt,100)}requestUpdate(...args){if(this.sourcePages&&(!this.sourceSyncing||args[0]!=="sourcePage"))if(args[0]===void 0||["graphSource","centerKey","sourceDirection","sourceNodeTypes","sourcePageSize"].includes(String(args[0]))){if(this.sourceEpoch++,this.sourceNavigation++,["centerKey","sourceDirection","sourceNodeTypes","sourcePageSize"].includes(String(args[0]))){const syncing=this.sourceSyncing;this.sourceSyncing=!0,this.sourcePage=0,this.sourceSyncing=syncing}}else args[0]==="sourcePage"&&this.sourceNavigation++;args[0]===void 0&&(this.explicitRefresh=(this.explicitRefresh??0)+1),super.requestUpdate(...args)}willUpdate(changed){if(super.willUpdate(changed),this.syncSource(),this.graphSource!==void 0){const state=this.sourcePages.state;state.result&&this.sourcePage!==state.page&&(this.sourceSyncing=!0,this.sourcePage=state.page,this.sourceSyncing=!1,this.sourcePageBinding&&(this.sourcePageBinding=[state.page,...this.sourcePageBinding.slice(1)])),(changed.has("rows")||changed.has("groupByRelation"))&&(this.hasComputedRows=!1);return}if(this.hasUpdated&&changed.has("rows")){const message=this.inputLimitMessage();message&&this.announcements.announcePolite(message)}const signature=`${this.effectiveLocale} ${this.groupByRelation}`;(!this.hasComputedRows||changed.has("rows")||changed.has("groupByRelation")||signature!==this.processedSignature)&&(this.hasComputedRows=!0,this.processedSignature=signature,this.sortedRowsCache=this.computeSortedRows());const groupDeps=[this.sortedRowsCache,this.effectiveLocale,this.strings,lyraLocaleCatalogVersion(this.effectiveLocale),this.explicitRefresh];(!this.groupDeps||groupDeps.some((value,index)=>value!==this.groupDeps[index]))&&(this.groupDeps=groupDeps,this.groupsCache=this.computeGroups(this.sortedRowsCache));const presentationDeps=[...groupDeps,this.types,this.expandable];(!this.presentationDeps||presentationDeps.some((value,index)=>value!==this.presentationDeps[index]))&&(this.presentationDeps=presentationDeps,this.renderRow=item=>this.renderNeighborRow(item)),this.sortedRowsCache.length>this.effectiveVirtualizeAt&&(virtualListRegistration??=import("../../layout/virtual-list/virtual-list.js").catch(()=>virtualListRegistration=void 0))}sortedRows(){return this.sortedRowsCache}computeSortedRows(){const rows=firstByRetrievalIdentity(this.rows,row=>row?.node?.id);if(!this.groupByRelation)return rows;const compare=getCollator(this.effectiveLocale).compare;return rows.sort((a,b)=>compare(a.relation,b.relation))}computeGroups(sorted){if(!this.groupByRelation)return;const groups=[],counts=new Map;for(const row of sorted)counts.set(row.relation,(counts.get(row.relation)??0)+1);const numberFormat=getNumberFormat(this.effectiveLocale);let lastRelation;return sorted.forEach((row,i)=>{if(row.relation!==lastRelation){const count=numberFormat.format(counts.get(row.relation)??0);groups.push({key:row.relation,label:this.localize("neighborGroupHeader",void 0,{relation:row.relation,count}),startIndex:i}),lastRelation=row.relation}}),groups}directionGlyph(direction){return direction==="both"?"↔":direction==="out"?"→":"←"}directionText(direction){return this.localize(direction==="in"?"neighborDirectionIn":direction==="out"?"neighborDirectionOut":"neighborDirectionBoth")}renderNeighborRow(row){const nodeLabel=row.node.label||row.node.id,directionText=this.directionText(row.direction),accessibleName=this.localize("neighborRowLabel",void 0,{label:nodeLabel,relation:row.relation,direction:directionText}),nodeType=typeof row.node.type=="string"&&row.node.type.trim()!==""?row.node.type:void 0;this.typeLabels?.[0]!==this.types&&(this.typeLabels=[this.types,new Map(firstByRetrievalIdentity(this.types,type=>type?.id).map(type=>[type.id,type.label]))]);const meta=[nodeType&&(this.typeLabels[1].get(nodeType)??nodeType),row.node.degree!=null?getNumberFormat(this.effectiveLocale).format(finiteCount(row.node.degree)):void 0].filter(v=>typeof v=="string"&&v!==""),metaText=getListFormat(this.effectiveLocale,{style:"short",type:"unit"}).format(meta);return html`
2
2
  <button
3
3
  part="node-label"
4
4
  type="button"
@@ -51,10 +51,10 @@ import{__decorate}from"tslib";import{SourcePageController}from"../../../internal
51
51
  .items=${guard([sorted],()=>sorted)}
52
52
  .renderItem=${this.renderRow}
53
53
  .keyFunction=${this.virtualListKeyFunction}
54
- .groups=${this.groups(sorted)}
54
+ .groups=${this.groupsCache}
55
55
  ></lr-virtual-list>
56
56
  </div>
57
- `;const groups=this.groups(sorted),groupsByStartIndex=new Map(groups?.map(g=>[g.startIndex,g])??[]);return html`
57
+ `;const groups=this.groupsCache,groupsByStartIndex=new Map(groups?.map(g=>[g.startIndex,g])??[]);return html`
58
58
  <div part="base" role=${role??nothing} aria-label=${label??nothing}>
59
59
  ${this.renderInputLimit()}
60
60
  <div role="list">
@@ -31,7 +31,7 @@ import{__decorate}from"tslib";import{SourcePageController}from"../../../internal
31
31
  ></lr-chunk-inspector>
32
32
  ${this.presentation==="expanded"?this.renderMetadata(chunk.metadata):nothing}
33
33
  </div>
34
- `}}static{this.defaultStrings={...super.defaultStrings,chunkInspectorEmpty:LYRA_DEFAULT_chunkInspectorEmpty,chunkInspectorLabel:LYRA_DEFAULT_chunkInspectorLabel,loadMore:LYRA_DEFAULT_loadMore,loading:LYRA_DEFAULT_loading,retrievalResultsInputLimit:LYRA_DEFAULT_retrievalResultsInputLimit,retrievalResultsSelectRowOrdinal:LYRA_DEFAULT_retrievalResultsSelectRowOrdinal,retry:LYRA_DEFAULT_retry,sourceSelectionFailed:LYRA_DEFAULT_sourceSelectionFailed,sourceSelectionLoading:LYRA_DEFAULT_sourceSelectionLoading,tableLoadFailed:LYRA_DEFAULT_tableLoadFailed,untitledSource:LYRA_DEFAULT_untitledSource,valueInvalid:LYRA_DEFAULT_valueInvalid,valueTruncated:LYRA_DEFAULT_valueTruncated}}static{this.collectionSupport=collectionSupport}static{this.identityCollectionProperties=Object.freeze(["chunks"])}static{this.ownedCollectionProperties=Object.freeze(["chunks","selectedChunkIds","groupOrder"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-selection-change","lr-chunk-open"])}static{this.identityEventDetailCollectionItems=Object.freeze({"lr-selection-change":Object.freeze(["chunks"])})}get dataSource(){return this._dataSource}set dataSource(value){const old=this._dataSource;this._dataSource=value,this.sourceEpoch++,this.requestUpdate("dataSource",old)}get sourceTotal(){return this.sourceMode?this.sourcePages.state.result?.total??null:null}get sourceMode(){return this.dataSource!==void 0}get sourceBlocked(){return this.sourceMode&&(!this.isConnected||!!this.errorText||this.sourcePages.state.pending||!this.sourcePages.state.result)}get sourceSelectionBlocked(){return this.sourceBlocked||this.sourceMode&&(this.sourcePages.state.selectionPending||this.sourceSelectionFailed)}projectSourceChunk(record,isCurrent){let units=0;const read=(input,key)=>{if(!isCurrent())throw new Error("Obsolete source chunk");const value2=readOwnDataValue(input,key);if(!isCurrent())throw new Error("Obsolete source chunk");return value2},fields=(input,keys)=>{if(!input||typeof input!="object"||Array.isArray(input))throw new TypeError("Invalid source chunk");const copy={};for(const key of keys){const value2=read(input,key);if(typeof value2=="string"&&(units+=value2.length,value2.length>65536||units>65536))throw new RangeError("Source chunk text too large");value2!==void 0&&(copy[key]=value2)}return copy},raw=fields(record.value,["id","text","score","metadata","rank","queryId","stage","traceId","scores"]);raw.source=fields(read(record.value,"source"),["id","name","mimeType","uri","version"]);const locator=read(record.value,"locator");if(locator!==void 0){const projected=fields(locator,["kind","page","quote","prefix","suffix","id","start","end","sheet","range","cfi"]);for(const key of["kind","quote","prefix","suffix","id","sheet","range","cfi"])if(projected[key]!==void 0&&typeof projected[key]!="string")throw new TypeError("Invalid source locator text");for(const key of["page","start","end"])if(projected[key]!==void 0&&(typeof projected[key]!="number"||!Number.isFinite(projected[key])))throw new TypeError("Invalid source locator number");const rect=read(locator,"rect");if(rect!==void 0){const coordinates=fields(rect,["x","y","width","height"]);for(const key of["x","y","width","height"])if(typeof coordinates[key]!="number"||!Number.isFinite(coordinates[key]))throw new TypeError("Invalid source locator rectangle");projected.rect=coordinates}const path=read(locator,"path");if(path!==void 0){if(!Array.isArray(path))throw new TypeError("Invalid source locator path");const length=read(path,"length");if(typeof length!="number"||!Number.isSafeInteger(length)||length<0||length>500)throw new RangeError("Source locator path too large");projected.path=Array.from({length},(_,index)=>{const value2=read(path,String(index));if(typeof value2!="string"&&typeof value2!="number")throw new TypeError("Invalid source locator path");if(typeof value2=="string"&&(units+=value2.length,units>65536))throw new RangeError("Source chunk text too large");return value2})}raw.locator=projected}const scores=raw.scores;scores&&typeof scores=="object"&&!Array.isArray(scores)&&(raw.scores=fields(scores,["dense","sparse","rerank","final"]));const value=projectRetrievalChunk(raw);if(!isCurrent())throw new Error("Obsolete source chunk");if(!value)throw new TypeError("Invalid source chunk");return this.sourceRowKeys.set(value,record.key),{key:record.key,order:record.order,value}}validateSourcePage(result,query){if(!query.withoutDedupe&&result.rows.some(record=>record.key!==record.value.id))throw new TypeError("Invalid canonical source identity");if(query.grouping==="none"){if(result.groups?.length)throw new TypeError("Unexpected source groups");return}if(!result.groups)throw new TypeError("Missing source groups");if(!result.rows.length)return;const size=this.sourcePages.state.pageSize,start=Math.min(this.sourcePages.state.page,Math.floor((result.total-1)/size))*size,end=start+result.rows.length;let covered=start,previousEnd=-1;for(const group of result.groups){if(group.startIndex<previousEnd||Math.max(start,group.startIndex)!==covered)throw new TypeError("Invalid source group coverage");previousEnd=group.startIndex+group.itemCount,covered=Math.min(end,previousEnd)}if(covered!==end)throw new TypeError("Incomplete source groups")}canonicalSourceAdapter(source){if(this.sourceAdapter?.original===source)return this.sourceAdapter.adapter;if(!source||typeof source.query!="function"||typeof source.lookup!="function"||typeof source.locate!="function")throw new TypeError("Invalid source");const adapter={revision:source.revision,query:request=>source.query(request),locate:(key,query,context)=>source.locate(key,query,context),lookup:async(keys,context)=>{const records=await source.lookup(keys,context);if(!Array.isArray(records)||records.length>500)throw new TypeError("Invalid canonical lookup");for(let index=0;index<records.length;index++){const record=readOwnDataValue(records,String(index)),key=readOwnDataValue(record,"key"),value=readOwnDataValue(record,"value");if(key!==readOwnDataValue(value,"id"))throw new TypeError("Invalid canonical lookup identity")}return records}};return this.sourceAdapter={original:source,adapter},adapter}syncSource(force=!1){if(!(!this.sourcePages||this.sourceSyncing)){this.sourceSyncing=!0;try{if(!this.sourceMode){this.sourceInputs&&(this.sourceVersion++,this.focusRestoreGeneration++,this.sourcePages.bind(void 0),this.processedChunksCache=void 0),this.sourceInputs=void 0,this.sourceQueryInputs=void 0,this.sourceResult=void 0,this.sourceRows=[],this.sourceGroups=[],this.sourceSelectionInputs=void 0,this.sourceSelectionEvent=void 0,this.sourceActiveInputs=void 0,this.sourceReveal=void 0;return}const source=this.dataSource,size=finiteInteger(this.sourcePageSize,100,1,500);let page=finiteInteger(this.sourcePage,0,0,Math.floor(Number.MAX_SAFE_INTEGER/size));const queryInputs=[this.sort,this.withoutDedupe,this.grouping,this.groupBy,this.groupLabel,this.groupOrder,size];this.hasUpdated&&this.sourceQueryInputs&&queryInputs.some((value,index)=>value!==this.sourceQueryInputs[index])&&(page=0,this.sourcePage=0),this.sourceQueryInputs=queryInputs;const inputs=[source,source.revision,this.sourceEpoch,this.effectiveLocale,...queryInputs,page];if(!force&&this.sourceInputs&&inputs.every((value,index)=>value===this.sourceInputs[index]))return;(!this.sourceInputs||inputs.slice(0,3).some((value,index)=>value!==this.sourceInputs[index]))&&(this.sourceSelectionInputs=void 0,this.sourceSelectionEvent=void 0),this.sourceInputs=inputs,this.sourceVersion++,this.focusRestoreGeneration++,this.sourceRows=[],this.sourceGroups=[],this.sourceResult=void 0,this.sourceReveal=void 0,this.expandedChunkIds=[],this.sourcePages.bind({source:this.canonicalSourceAdapter(source),revision:source.revision,epoch:this.sourceEpoch,locale:this.effectiveLocale});const query=Object.freeze({sort:this.sort,withoutDedupe:this.withoutDedupe,grouping:this.grouping,groupBy:this.groupBy,groupLabel:this.groupLabel,groupOrder:this.groupOrder});this.sourcePages.request(query,page,size)}catch{this.sourcePages.bind(void 0),this.sourceRows=[],this.sourceGroups=[],this.sourceResult=void 0}finally{this.sourceSyncing=!1}}}syncSourceSelection(){if(!this.sourceMode||!this.isConnected||!this.sourceAdapter||!this.sourceInputs)return;const ids=this.selectedChunkIds,source=this.dataSource,epoch=this.sourceEpoch,revision=source.revision,inputs=[source,revision,epoch,ids];if(this.sourceSelectionInputs&&inputs.every((value,index)=>value===this.sourceSelectionInputs[index]))return;this.sourceSelectionInputs=inputs,this.sourceSelectionFailed=!1;const owner=this.ownerDocument,lifecycle=this.sourceLifecycle,canonicalIds=canonicalIdentityList(ids);this.sourcePages.resolveSelection(canonicalIds).then(records=>{if(source.revision!==revision||lifecycle!==this.sourceLifecycle||!this.isConnected||this.ownerDocument!==owner||this.dataSource!==source||this.sourceEpoch!==epoch||this.selectedChunkIds!==ids)return;if(!records){this.sourceSelectionFailed=!0,this.sourceStateVersion++;return}const retained=new Set(records.map(record=>record.key)),accepted=canonicalIds.filter(id=>retained.has(id)),report=this.sourceSelectionEvent===ids;this.sourceSelectionEvent=void 0,accepted.length!==ids.length&&(this.selectedChunkIds=accepted);const committed=this.selectedChunkIds;if(report){const chunks=records.map(record=>record.value);this.emit("lr-selection-change",{selectedChunkIds:[...committed],chunks})}this.sourceStateVersion++})}acceptSourcePage(){const result=this.sourcePages.state.result;if(!result||result===this.sourceResult)return;this.sourceResult=result,this.sourceRows=result.rows.map(record=>record.value);const start=this.sourcePages.state.page*this.sourcePages.state.pageSize;this.sourceGroups=(result.groups??[]).map(group=>({key:group.key,label:group.label,startIndex:Math.max(0,group.startIndex-start)})),this.sourcePage!==this.sourcePages.state.page&&(this.sourceSyncing=!0,this.sourcePage=this.sourcePages.state.page,this.sourceSyncing=!1,this.sourceInputs=this.sourceInputs?[...this.sourceInputs.slice(0,-1),this.sourcePages.state.page]:void 0);const reveal=this.sourceReveal;this.sourceReveal=void 0,reveal?.version===this.sourceVersion&&this.revealSourceActive(reveal.id,reveal.version)}syncSourceActive(){if(!this.activeChunkId){this.sourceActiveInputs=void 0;return}if(this.sourceBlocked)return;const source=this.dataSource,id=this.activeChunkId,inputs=[source,source.revision,this.sourceEpoch,this.effectiveLocale,...this.sourceQueryInputs??[],id];if(this.sourceActiveInputs&&inputs.every((value,index)=>value===this.sourceActiveInputs[index]))return;this.sourceActiveInputs=inputs;const version=this.sourceVersion,owner=this.ownerDocument;this.sourcePages.locate(id).then(index=>{if(index===null||!this.isConnected||this.ownerDocument!==owner||!this.sourceMode||this.dataSource!==source||this.sourceVersion!==version||this.activeChunkId!==id)return;const page=Math.floor(index/finiteInteger(this.sourcePageSize,100,1,500));if(page===this.sourcePage){this.revealSourceActive(id,version);return}this.sourcePage=page,this.sourceReveal={id,version:this.sourceVersion}})}revealSourceActive(id,version){const owner=this.ownerDocument;this.updateComplete.then(async()=>{const list=this.renderRoot.querySelector(tag("virtual-list"));if(!list||(await list.updateComplete,!this.isConnected||this.ownerDocument!==owner||!this.sourceMode||this.sourceBlocked||this.sourceVersion!==version||this.activeChunkId!==id||list!==this.renderRoot.querySelector(tag("virtual-list"))))return;const index=this.sourceRows.findIndex(chunk=>chunk.id===id);index>=0&&list.scrollToIndex(index,{align:"auto",behavior:"auto"})})}currentSourceRow(chunk){return!(this.sourceMode||this.sourceRowKeys.has(chunk))||this.sourceMode&&!this.sourceBlocked&&this.sourceRows.includes(chunk)}invalidateSourceLifecycle(){this.sourceLifecycle++,this.sourceVersion++,this.focusRestoreGeneration++,this.sourceSelectionInputs=void 0,this.sourceSelectionEvent=void 0,this.sourceActiveInputs=void 0,this.sourceReveal=void 0,this.sourceStatusInitialized=!1,this.sourceStatus=""}adoptedCallback(){this.invalidateSourceLifecycle(),this.sourcePages.adopted(),super.adoptedCallback()}requestUpdate(...args){args[0]===void 0&&(this.explicitRefresh=!0,this.sourceEpoch=(this.sourceEpoch??0)+1),args[0]==="selectedChunkIds"&&(this.sourceSelectionEvent=void 0),(args[0]===void 0||["dataSource","sourcePage","sourcePageSize","sort","withoutDedupe","grouping","groupBy","groupLabel","groupOrder"].includes(String(args[0])))&&this.syncSource(),super.requestUpdate(...args)}inputLimitText(){if(this.sourceMode)return"";const truncation=publicCollectionTruncation(this,"chunks"),number=getNumberFormat(this.effectiveLocale);return truncation?this.localize("retrievalResultsInputLimit",void 0,{count:number.format(truncation.retained),total:number.format(truncation.source)}):""}renderInputLimit(){const text=this.inputLimitText();return text?html`<p part="limit" role="note">${text}</p>`:nothing}connectedCallback(){super.connectedCallback(),this.errorAnnouncementSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}),this.emptyAnnouncementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this});const generation=++this.connectionGeneration;announceAfterFirstPaint(this,()=>generation===this.connectionGeneration,()=>{!this.announce||this.initialStateAnnounced||(this.initialStateAnnounced=!0,this.announcePresentedState())})}disconnectedCallback(){this.invalidateSourceLifecycle(),this.isMounting=!0,this.connectionGeneration+=1,this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0,this.emptyAnnouncementSink?.release(),this.emptyAnnouncementSink=void 0,this.wasEmptyPresented=!1,super.disconnectedCallback()}deepActiveElement(){return deepActiveElementIn(this.isConnected?this.shadowRoot:null)}chunkAnchor(start){let current=start;for(;current&&current!==this;){if(current.hasAttribute("data-chunk-id"))return current;if(current.parentElement){current=current.parentElement;continue}const root=current.getRootNode();current=root.nodeType===11&&"host"in root?root.host:null}return null}renderedChunkIds(){const roots=[this.renderRoot],virtualList=this.renderRoot.querySelector(tag("virtual-list"));return virtualList?.shadowRoot&&roots.push(virtualList.shadowRoot),roots.flatMap(root=>[...root.querySelectorAll(`${tag("chunk-inspector")}[data-chunk-id]`)].map(element=>element.getAttribute("data-chunk-id")).filter(id=>id!==null))}willUpdate(changed){if(super.willUpdate(changed),this.syncSource(),this.sourceMode){this.acceptSourcePage(),this.syncSourceSelection(),this.syncSourceActive();return}const refresh=this.explicitRefresh;this.explicitRefresh=!1;const groupingLocaleSignature=this.grouping==="source"?`${this.effectiveLocale}\0${this.localize("untitledSource")}`:"";if((this.processedChunksCache===void 0||refresh||changed.has("chunks")||changed.has("withoutDedupe")||changed.has("sort")||changed.has("grouping")||changed.has("groupBy")||changed.has("groupLabel")||changed.has("groupOrder")||groupingLocaleSignature!==this.processedGroupingLocaleSignature)&&(this.processedGroupingLocaleSignature=groupingLocaleSignature,this.processedChunksCache=this.computeProcessedChunks()),changed.has("chunks")){const present=new Set(this.processedChunks.chunks.map(chunk=>chunk.id)),kept=this.expandedChunkIds.filter(id=>present.has(id));kept.length!==this.expandedChunkIds.length&&(this.expandedChunkIds=kept)}if(changed.has("chunks")||changed.has("selectedChunkIds")){const normalized=this.normalizedSelectedChunkIds();if(normalized.length!==this.selectedChunkIds.length||normalized.some((id,index)=>id!==this.selectedChunkIds[index])){const shouldAnnounce=this.hasUpdated&&changed.has("chunks");writeNormalizedOwnedCollection(this,"selectedChunkIds",()=>{this.selectedChunkIds=normalized}),shouldAnnounce&&this.reportSelection(normalized)}}if(!changed.has("chunks")&&!changed.has("withoutDedupe")&&!changed.has("sort")&&!changed.has("grouping")&&!changed.has("groupBy")&&!changed.has("groupLabel")&&!changed.has("groupOrder")&&!changed.has("presentation")&&!changed.has("withoutSelection")&&!changed.has("virtualizeAt")&&!changed.has("loading")&&!changed.has("errorText"))return;const focusedId=this.chunkAnchor(this.deepActiveElement())?.getAttribute("data-chunk-id");if(!focusedId)return;const previousIds=this.previousProcessedChunkIds.length?this.previousProcessedChunkIds:this.renderedChunkIds(),focusedIndex=Math.max(0,previousIds.indexOf(focusedId)),nextChunks=this.errorText?[]:this.processedChunks.chunks;if(nextChunks.length===0){this.pendingFocusTarget="base";return}const survivingIndex=nextChunks.findIndex(chunk=>chunk.id===focusedId),nextIndex=survivingIndex>=0?survivingIndex:Math.min(focusedIndex,nextChunks.length-1);this.pendingFocusTarget=nextChunks[nextIndex].id}updated(changed){if(super.updated(changed),this.sourceMode){const status=this.sourcePages.state.pending?this.localize("loading"):this.sourcePages.state.result?this.sourcePages.state.selectionPending?this.localize("sourceSelectionLoading"):this.sourceSelectionFailed?this.localize("sourceSelectionFailed"):"":this.localize("tableLoadFailed");this.sourceStatusInitialized&&status&&status!==this.sourceStatus&&this.emptyAnnouncementSink?.announce(status),this.sourceStatusInitialized=!0,this.sourceStatus=status;return}const inputTruncated=publicCollectionTruncation(this,"chunks")!==void 0;this.limitInitialized&&inputTruncated&&!this.previouslyInputTruncated&&this.emptyAnnouncementSink?.announce(this.inputLimitText()),this.limitInitialized=!0,this.previouslyInputTruncated=inputTruncated;const wasMounting=this.isMounting;this.isMounting=!1,!wasMounting&&changed.has("errorText")&&this.errorText!==""&&this.isConnected&&(this.initialStateAnnounced=!0,this.errorAnnouncementSink?.announce(this.errorText));const emptyPresented=!this.loading&&this.errorText===""&&this.processedChunks.chunks.length===0;!wasMounting&&!this.wasEmptyPresented&&emptyPresented&&this.isConnected&&(this.initialStateAnnounced=!0,this.emptyAnnouncementSink?.announce(this.localize("chunkInspectorEmpty"))),this.wasEmptyPresented=emptyPresented,this.previousProcessedChunkIds=this.errorText?[]:this.processedChunks.chunks.map(chunk=>chunk.id);const generation=++this.focusRestoreGeneration,target=this.pendingFocusTarget;target!==void 0&&(this.pendingFocusTarget=void 0,this.restoreControlledFocus(target,generation))}announcePresentedState(){if(!this.sourceMode){if(this.errorText!==""){this.errorAnnouncementSink?.announce(this.errorText);return}!this.loading&&this.processedChunks.chunks.length===0&&this.emptyAnnouncementSink?.announce(this.localize("chunkInspectorEmpty"))}}async restoreControlledFocus(target,generation){if(await this.updateComplete,generation!==this.focusRestoreGeneration||!this.isConnected)return;if(target==="base"){this.renderRoot.querySelector('[part="base"]')?.focus();return}const virtualList=this.renderRoot.querySelector(tag("virtual-list"));if(await virtualList?.updateComplete,generation!==this.focusRestoreGeneration||!this.isConnected)return;const roots=[this.renderRoot];virtualList?.shadowRoot&&roots.push(virtualList.shadowRoot);const candidates=roots.flatMap(root=>[...root.querySelectorAll("[data-chunk-id]")]),checkbox=candidates.find(element=>element.localName===tag("checkbox")&&element.getAttribute("data-chunk-id")===target);if(checkbox){checkbox.focus();return}const inspector=candidates.find(element=>element.localName===tag("chunk-inspector")&&element.getAttribute("data-chunk-id")===target);await inspector?.updateComplete,!(generation!==this.focusRestoreGeneration||!this.isConnected)&&inspector?.shadowRoot?.querySelector('[part="open-button"]')?.focus()}get effectiveVirtualizeAt(){return finiteCount(this.virtualizeAt,50)}canonicalChunks(){return this.canonicalSource!==this.chunks&&(this.canonicalSource=this.chunks,this.canonicalCache=firstByRetrievalIdentity(this.chunks.flatMap(value=>projectRetrievalChunk(value)??[]),chunk=>chunk.id),this.canonicalById=new Map(this.canonicalCache.map(chunk=>[chunk.id,chunk])),this.canonicalOrder=new Map(this.canonicalCache.map((chunk,index)=>[chunk.id,index]))),this.canonicalCache}normalizedSelectedChunkIds(){return this.canonicalSource!==this.chunks&&this.canonicalChunks(),canonicalIdentityList(this.selectedChunkIds).filter(id=>this.canonicalById.has(id))}get processedChunks(){return this.sourceMode?{chunks:this.sourceRows,groups:this.sourceGroups}:this.processedChunksCache??=this.computeProcessedChunks()}computeProcessedChunks(){const canonical=this.canonicalChunks(),sorted=this.sort==="score"?[...canonical].sort((a,b)=>safeScore(b.score)-safeScore(a.score)):canonical;if(this.grouping==="source")return this.bucketed(sorted,chunk=>chunk.source.id,(_id,groupChunks)=>groupChunks[0].source.name||this.localize("untitledSource"));if(this.grouping==="custom"&&this.groupBy){const groupBy=this.groupBy;return this.bucketed(sorted,groupBy,(id,groupChunks)=>this.groupLabel?.(id,groupChunks)??id)}return{chunks:sorted,groups:[]}}orderedGroupKeys(grouped){const firstSeen=[...grouped.keys()];if(this.grouping!=="custom"||!this.groupOrder)return firstSeen;if(typeof this.groupOrder=="function")return firstSeen.sort(this.groupOrder);const ordered=[...new Set(this.groupOrder)].filter(id=>grouped.has(id)),listed=new Set(ordered);return[...ordered,...firstSeen.filter(id=>!listed.has(id))]}bucketed(sorted,keyOf,labelOf){const grouped=new Map;for(const chunk of sorted){const key=keyOf(chunk),existing=grouped.get(key);existing?existing.push(chunk):grouped.set(key,[chunk])}const rows=[],groups=[];for(const key of this.orderedGroupKeys(grouped)){const groupChunks=grouped.get(key);!groupChunks||groupChunks.length===0||(groups.push({key,label:labelOf(key,groupChunks),startIndex:rows.length}),rows.push(...groupChunks))}return{chunks:rows,groups}}reportSelection(chunkIds){this.canonicalSource!==this.chunks&&this.canonicalChunks();const chunks=[...new Set(chunkIds)].flatMap(id=>this.canonicalById.get(id)??[]).sort((a,b)=>this.canonicalOrder.get(a.id)-this.canonicalOrder.get(b.id));this.emit("lr-selection-change",snapshotEventDetail({selectedChunkIds:chunkIds,chunks},this.ownerDocument.defaultView))}toggleSelect(chunk){if(!this.currentSourceRow(chunk)||this.sourceSelectionBlocked)return;if(this.sourceMode){const next2=new Set(this.selectedChunkIds);next2.has(chunk.id)?next2.delete(chunk.id):next2.size<1e4&&next2.add(chunk.id),this.selectedChunkIds=[...next2],this.sourceSelectionEvent=this.selectedChunkIds;return}const next=new Set(this.normalizedSelectedChunkIds());next.has(chunk.id)?next.delete(chunk.id):next.add(chunk.id),this.selectedChunkIds=[...next],this.reportSelection(this.selectedChunkIds)}rowChunksFor(chunk){let row=this.rowChunks.get(chunk);return row||this.rowChunks.set(chunk,row=[toLyraChunk(chunk)]),row}renderMetadata(metadata){return renderRetrievalMetadata(metadata,this.effectiveLocale,this.localize("valueInvalid"),this.localize("valueTruncated"))}isChunkSelected(id){const source=this.selectedChunkIds;return source.length===0||this.processedChunks.chunks.length<=1?(this.selectedMembership=void 0,source.includes(id)):(this.selectedMembership?.source!==source&&(this.selectedMembership={source,ids:new Set(source)}),this.selectedMembership.ids.has(id))}legacyLoadMoreHandler(){const chunks=this.chunks,version=this.sourceVersion;return event=>{event.stopPropagation(),!(!this.isConnected||this.sourceMode||this.sourceVersion!==version||this.chunks!==chunks||!this.hasMore||this.loading||this.errorText||event.currentTarget?.getRootNode()!==this.renderRoot)&&this.emit("lr-load-more")}}renderLoadMoreFooter(){return this.hasMore?html`
34
+ `}}static{this.defaultStrings={...super.defaultStrings,chunkInspectorEmpty:LYRA_DEFAULT_chunkInspectorEmpty,chunkInspectorLabel:LYRA_DEFAULT_chunkInspectorLabel,loadMore:LYRA_DEFAULT_loadMore,loading:LYRA_DEFAULT_loading,retrievalResultsInputLimit:LYRA_DEFAULT_retrievalResultsInputLimit,retrievalResultsSelectRowOrdinal:LYRA_DEFAULT_retrievalResultsSelectRowOrdinal,retry:LYRA_DEFAULT_retry,sourceSelectionFailed:LYRA_DEFAULT_sourceSelectionFailed,sourceSelectionLoading:LYRA_DEFAULT_sourceSelectionLoading,tableLoadFailed:LYRA_DEFAULT_tableLoadFailed,untitledSource:LYRA_DEFAULT_untitledSource,valueInvalid:LYRA_DEFAULT_valueInvalid,valueTruncated:LYRA_DEFAULT_valueTruncated}}static{this.collectionSupport=collectionSupport}static{this.identityCollectionProperties=Object.freeze(["chunks"])}static{this.ownedCollectionProperties=Object.freeze(["chunks","selectedChunkIds","groupOrder"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-selection-change","lr-chunk-open"])}static{this.identityEventDetailCollectionItems=Object.freeze({"lr-selection-change":Object.freeze(["chunks"])})}get dataSource(){return this._dataSource}set dataSource(value){const old=this._dataSource;this._dataSource=value,this.sourceEpoch++,this.requestUpdate("dataSource",old)}get sourceTotal(){return this.sourceMode?this.sourcePages.state.result?.total??null:null}get sourceMode(){return this.dataSource!==void 0}get sourceBlocked(){return this.sourceMode&&(!this.isConnected||!!this.errorText||this.sourcePages.state.pending||!this.sourcePages.state.result)}get sourceSelectionBlocked(){return this.sourceBlocked||this.sourceMode&&(this.sourcePages.state.selectionPending||this.sourceSelectionFailed)}projectSourceChunk(record,isCurrent){let units=0;const read=(input,key)=>{if(!isCurrent())throw new Error("Obsolete source chunk");const value2=readOwnDataValue(input,key);if(!isCurrent())throw new Error("Obsolete source chunk");return value2},fields=(input,keys)=>{if(!input||typeof input!="object"||Array.isArray(input))throw new TypeError("Invalid source chunk");const copy={};for(const key of keys){const value2=read(input,key);if(typeof value2=="string"&&(units+=value2.length,value2.length>65536||units>65536))throw new RangeError("Source chunk text too large");value2!==void 0&&(copy[key]=value2)}return copy},raw=fields(record.value,["id","text","score","metadata","rank","queryId","stage","traceId","scores"]);raw.source=fields(read(record.value,"source"),["id","name","mimeType","uri","version"]);const locator=read(record.value,"locator");if(locator!==void 0){const projected=fields(locator,["kind","page","quote","prefix","suffix","id","start","end","sheet","range","cfi"]);for(const key of["kind","quote","prefix","suffix","id","sheet","range","cfi"])if(projected[key]!==void 0&&typeof projected[key]!="string")throw new TypeError("Invalid source locator text");for(const key of["page","start","end"])if(projected[key]!==void 0&&(typeof projected[key]!="number"||!Number.isFinite(projected[key])))throw new TypeError("Invalid source locator number");const rect=read(locator,"rect");if(rect!==void 0){const coordinates=fields(rect,["x","y","width","height"]);for(const key of["x","y","width","height"])if(typeof coordinates[key]!="number"||!Number.isFinite(coordinates[key]))throw new TypeError("Invalid source locator rectangle");projected.rect=coordinates}const path=read(locator,"path");if(path!==void 0){if(!Array.isArray(path))throw new TypeError("Invalid source locator path");const length=read(path,"length");if(typeof length!="number"||!Number.isSafeInteger(length)||length<0||length>500)throw new RangeError("Source locator path too large");projected.path=Array.from({length},(_,index)=>{const value2=read(path,String(index));if(typeof value2!="string"&&typeof value2!="number")throw new TypeError("Invalid source locator path");if(typeof value2=="string"&&(units+=value2.length,units>65536))throw new RangeError("Source chunk text too large");return value2})}raw.locator=projected}const scores=raw.scores;scores&&typeof scores=="object"&&!Array.isArray(scores)&&(raw.scores=fields(scores,["dense","sparse","rerank","final"]));const value=projectRetrievalChunk(raw);if(!isCurrent())throw new Error("Obsolete source chunk");if(!value)throw new TypeError("Invalid source chunk");return this.sourceRowKeys.set(value,record.key),{key:record.key,order:record.order,value}}validateSourcePage(result,query){if(!query.withoutDedupe&&result.rows.some(record=>record.key!==record.value.id))throw new TypeError("Invalid canonical source identity");if(query.grouping==="none"){if(result.groups?.length)throw new TypeError("Unexpected source groups");return}if(!result.groups)throw new TypeError("Missing source groups");if(!result.rows.length)return;const size=this.sourcePages.state.pageSize,start=Math.min(this.sourcePages.state.page,Math.floor((result.total-1)/size))*size,end=start+result.rows.length;let covered=start,previousEnd=-1;for(const group of result.groups){if(group.startIndex<previousEnd||Math.max(start,group.startIndex)!==covered)throw new TypeError("Invalid source group coverage");previousEnd=group.startIndex+group.itemCount,covered=Math.min(end,previousEnd)}if(covered!==end)throw new TypeError("Incomplete source groups")}canonicalSourceAdapter(source){if(this.sourceAdapter?.original===source)return this.sourceAdapter.adapter;if(!source||typeof source.query!="function"||typeof source.lookup!="function"||typeof source.locate!="function")throw new TypeError("Invalid source");const adapter={revision:source.revision,query:request=>source.query(request),locate:(key,query,context)=>source.locate(key,query,context),lookup:async(keys,context)=>{const records=await source.lookup(keys,context);if(!Array.isArray(records)||records.length>500)throw new TypeError("Invalid canonical lookup");for(let index=0;index<records.length;index++){const record=readOwnDataValue(records,String(index)),key=readOwnDataValue(record,"key"),value=readOwnDataValue(record,"value");if(key!==readOwnDataValue(value,"id"))throw new TypeError("Invalid canonical lookup identity")}return records}};return this.sourceAdapter={original:source,adapter},adapter}syncSource(force=!1){if(!(!this.sourcePages||this.sourceSyncing)){this.sourceSyncing=!0;try{if(!this.sourceMode){this.sourceInputs&&(this.sourceVersion++,this.focusRestoreGeneration++,this.sourcePages.bind(void 0),this.processedChunksCache=void 0),this.sourceInputs=void 0,this.sourceQueryInputs=void 0,this.sourceResult=void 0,this.sourceRows=[],this.sourceGroups=[],this.sourceSelectionInputs=void 0,this.sourceSelectionEvent=void 0,this.sourceActiveInputs=void 0,this.sourceReveal=void 0;return}const source=this.dataSource,size=finiteInteger(this.sourcePageSize,100,1,500);let page=finiteInteger(this.sourcePage,0,0,Math.floor(Number.MAX_SAFE_INTEGER/size));const queryInputs=[this.sort,this.withoutDedupe,this.grouping,this.groupBy,this.groupLabel,this.groupOrder,size];this.hasUpdated&&this.sourceQueryInputs&&queryInputs.some((value,index)=>value!==this.sourceQueryInputs[index])&&(page=0,this.sourcePage=0),this.sourceQueryInputs=queryInputs;const inputs=[source,source.revision,this.sourceEpoch,this.effectiveLocale,...queryInputs,page];if(!force&&this.sourceInputs&&inputs.every((value,index)=>value===this.sourceInputs[index]))return;(!this.sourceInputs||inputs.slice(0,3).some((value,index)=>value!==this.sourceInputs[index]))&&(this.sourceSelectionInputs=void 0,this.sourceSelectionEvent=void 0),this.sourceInputs=inputs,this.sourceVersion++,this.focusRestoreGeneration++,this.sourceRows=[],this.sourceGroups=[],this.sourceResult=void 0,this.sourceReveal=void 0,this.expandedChunkIds=[],this.sourcePages.bind({source:this.canonicalSourceAdapter(source),revision:source.revision,epoch:this.sourceEpoch,locale:this.effectiveLocale});const query=Object.freeze({sort:this.sort,withoutDedupe:this.withoutDedupe,grouping:this.grouping,groupBy:this.groupBy,groupLabel:this.groupLabel,groupOrder:this.groupOrder});this.sourcePages.request(query,page,size)}catch{this.sourcePages.bind(void 0),this.sourceRows=[],this.sourceGroups=[],this.sourceResult=void 0}finally{this.sourceSyncing=!1}}}syncSourceSelection(){if(!this.sourceMode||!this.isConnected||!this.sourceAdapter||!this.sourceInputs)return;const ids=this.selectedChunkIds,source=this.dataSource,epoch=this.sourceEpoch,revision=source.revision,inputs=[source,revision,epoch,ids];if(this.sourceSelectionInputs&&inputs.every((value,index)=>value===this.sourceSelectionInputs[index]))return;this.sourceSelectionInputs=inputs,this.sourceSelectionFailed=!1;const owner=this.ownerDocument,lifecycle=this.sourceLifecycle,canonicalIds=canonicalIdentityList(ids);this.sourcePages.resolveSelection(canonicalIds).then(records=>{if(source.revision!==revision||lifecycle!==this.sourceLifecycle||!this.isConnected||this.ownerDocument!==owner||this.dataSource!==source||this.sourceEpoch!==epoch||this.selectedChunkIds!==ids)return;if(!records){this.sourceSelectionFailed=!0,this.sourceStateVersion++;return}const retained=new Set(records.map(record=>record.key)),accepted=canonicalIds.filter(id=>retained.has(id)),report=this.sourceSelectionEvent===ids;this.sourceSelectionEvent=void 0,accepted.length!==ids.length&&(this.selectedChunkIds=accepted);const committed=this.selectedChunkIds;if(report){const chunks=records.map(record=>record.value);this.emit("lr-selection-change",{selectedChunkIds:[...committed],chunks})}this.sourceStateVersion++})}acceptSourcePage(){const result=this.sourcePages.state.result;if(!result||result===this.sourceResult)return;this.sourceResult=result,this.sourceRows=result.rows.map(record=>record.value);const start=this.sourcePages.state.page*this.sourcePages.state.pageSize;this.sourceGroups=(result.groups??[]).map(group=>({key:group.key,label:group.label,startIndex:Math.max(0,group.startIndex-start)})),this.sourcePage!==this.sourcePages.state.page&&(this.sourceSyncing=!0,this.sourcePage=this.sourcePages.state.page,this.sourceSyncing=!1,this.sourceInputs=this.sourceInputs?[...this.sourceInputs.slice(0,-1),this.sourcePages.state.page]:void 0);const reveal=this.sourceReveal;this.sourceReveal=void 0,reveal?.version===this.sourceVersion&&this.revealSourceActive(reveal.id,reveal.version)}syncSourceActive(){if(!this.activeChunkId){this.sourceActiveInputs=void 0;return}if(this.sourceBlocked)return;const source=this.dataSource,id=this.activeChunkId,inputs=[source,source.revision,this.sourceEpoch,this.effectiveLocale,...this.sourceQueryInputs??[],id];if(this.sourceActiveInputs&&inputs.every((value,index)=>value===this.sourceActiveInputs[index]))return;this.sourceActiveInputs=inputs;const version=this.sourceVersion,owner=this.ownerDocument;this.sourcePages.locate(id).then(index=>{if(index===null||!this.isConnected||this.ownerDocument!==owner||!this.sourceMode||this.dataSource!==source||this.sourceVersion!==version||this.activeChunkId!==id)return;const page=Math.floor(index/finiteInteger(this.sourcePageSize,100,1,500));if(page===this.sourcePage){this.revealSourceActive(id,version);return}this.sourcePage=page,this.sourceReveal={id,version:this.sourceVersion}})}revealSourceActive(id,version){const owner=this.ownerDocument;this.updateComplete.then(async()=>{const list=this.renderRoot.querySelector(tag("virtual-list"));if(!list||(await list.updateComplete,!this.isConnected||this.ownerDocument!==owner||!this.sourceMode||this.sourceBlocked||this.sourceVersion!==version||this.activeChunkId!==id||list!==this.renderRoot.querySelector(tag("virtual-list"))))return;const index=this.sourceRows.findIndex(chunk=>chunk.id===id);index>=0&&list.scrollToIndex(index,{align:"auto",behavior:"auto"})})}currentSourceRow(chunk){return!(this.sourceMode||this.sourceRowKeys.has(chunk))||this.sourceMode&&!this.sourceBlocked&&this.sourceRows.includes(chunk)}invalidateSourceLifecycle(){this.sourceLifecycle++,this.sourceVersion++,this.focusRestoreGeneration++,this.sourceSelectionInputs=void 0,this.sourceSelectionEvent=void 0,this.sourceActiveInputs=void 0,this.sourceReveal=void 0,this.sourceStatusInitialized=!1,this.sourceStatus=""}adoptedCallback(){this.invalidateSourceLifecycle(),this.sourcePages.adopted(),super.adoptedCallback()}requestUpdate(...args){args[0]===void 0&&(this.explicitRefresh=!0,this.sourceEpoch=(this.sourceEpoch??0)+1),args[0]==="selectedChunkIds"&&(this.sourceSelectionEvent=void 0),(args[0]===void 0||["dataSource","sourcePage","sourcePageSize","sort","withoutDedupe","grouping","groupBy","groupLabel","groupOrder"].includes(String(args[0])))&&this.syncSource(),super.requestUpdate(...args)}inputLimitText(){const truncation=publicCollectionTruncation(this,"chunks"),number=getNumberFormat(this.effectiveLocale);return truncation?this.localize("retrievalResultsInputLimit",void 0,{count:number.format(truncation.retained),total:number.format(truncation.source)}):""}renderInputLimit(){const text=this.inputLimitText();return text?html`<p part="limit" role="note">${text}</p>`:nothing}connectedCallback(){super.connectedCallback(),this.errorAnnouncementSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}),this.emptyAnnouncementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this});const generation=++this.connectionGeneration;announceAfterFirstPaint(this,()=>generation===this.connectionGeneration,()=>{!this.announce||this.initialStateAnnounced||(this.initialStateAnnounced=!0,this.announcePresentedState())})}disconnectedCallback(){this.invalidateSourceLifecycle(),this.isMounting=!0,this.connectionGeneration+=1,this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0,this.emptyAnnouncementSink?.release(),this.emptyAnnouncementSink=void 0,this.wasEmptyPresented=!1,super.disconnectedCallback()}deepActiveElement(){return deepActiveElementIn(this.isConnected?this.shadowRoot:null)}chunkAnchor(start){let current=start;for(;current&&current!==this;){if(current.hasAttribute("data-chunk-id"))return current;if(current.parentElement){current=current.parentElement;continue}const root=current.getRootNode();current=root.nodeType===11&&"host"in root?root.host:null}return null}renderedChunkIds(){const roots=[this.renderRoot],virtualList=this.renderRoot.querySelector(tag("virtual-list"));return virtualList?.shadowRoot&&roots.push(virtualList.shadowRoot),roots.flatMap(root=>[...root.querySelectorAll(`${tag("chunk-inspector")}[data-chunk-id]`)].map(element=>element.getAttribute("data-chunk-id")).filter(id=>id!==null))}willUpdate(changed){if(super.willUpdate(changed),this.syncSource(),this.sourceMode){this.acceptSourcePage(),this.syncSourceSelection(),this.syncSourceActive();return}const refresh=this.explicitRefresh;this.explicitRefresh=!1;const groupingLocaleSignature=this.grouping==="source"?`${this.effectiveLocale}\0${this.localize("untitledSource")}`:"";if((this.processedChunksCache===void 0||refresh||changed.has("chunks")||changed.has("withoutDedupe")||changed.has("sort")||changed.has("grouping")||changed.has("groupBy")||changed.has("groupLabel")||changed.has("groupOrder")||groupingLocaleSignature!==this.processedGroupingLocaleSignature)&&(this.processedGroupingLocaleSignature=groupingLocaleSignature,this.processedChunksCache=this.computeProcessedChunks()),changed.has("chunks")){const present=new Set(this.processedChunks.chunks.map(chunk=>chunk.id)),kept=this.expandedChunkIds.filter(id=>present.has(id));kept.length!==this.expandedChunkIds.length&&(this.expandedChunkIds=kept)}if(changed.has("chunks")||changed.has("selectedChunkIds")){const normalized=this.normalizedSelectedChunkIds();if(normalized.length!==this.selectedChunkIds.length||normalized.some((id,index)=>id!==this.selectedChunkIds[index])){const shouldAnnounce=this.hasUpdated&&changed.has("chunks");writeNormalizedOwnedCollection(this,"selectedChunkIds",()=>{this.selectedChunkIds=normalized}),shouldAnnounce&&this.reportSelection(normalized)}}if(!changed.has("chunks")&&!changed.has("withoutDedupe")&&!changed.has("sort")&&!changed.has("grouping")&&!changed.has("groupBy")&&!changed.has("groupLabel")&&!changed.has("groupOrder")&&!changed.has("presentation")&&!changed.has("withoutSelection")&&!changed.has("virtualizeAt")&&!changed.has("loading")&&!changed.has("errorText"))return;const focusedId=this.chunkAnchor(this.deepActiveElement())?.getAttribute("data-chunk-id");if(!focusedId)return;const previousIds=this.previousProcessedChunkIds.length?this.previousProcessedChunkIds:this.renderedChunkIds(),focusedIndex=Math.max(0,previousIds.indexOf(focusedId)),nextChunks=this.errorText?[]:this.processedChunks.chunks;if(nextChunks.length===0){this.pendingFocusTarget="base";return}const survivingIndex=nextChunks.findIndex(chunk=>chunk.id===focusedId),nextIndex=survivingIndex>=0?survivingIndex:Math.min(focusedIndex,nextChunks.length-1);this.pendingFocusTarget=nextChunks[nextIndex].id}updated(changed){if(super.updated(changed),this.sourceMode){const status=this.sourcePages.state.pending?this.localize("loading"):this.sourcePages.state.result?this.sourcePages.state.selectionPending?this.localize("sourceSelectionLoading"):this.sourceSelectionFailed?this.localize("sourceSelectionFailed"):"":this.localize("tableLoadFailed");this.sourceStatusInitialized&&status&&status!==this.sourceStatus&&this.emptyAnnouncementSink?.announce(status),this.sourceStatusInitialized=!0,this.sourceStatus=status;return}const inputTruncated=publicCollectionTruncation(this,"chunks")!==void 0;this.limitInitialized&&inputTruncated&&!this.previouslyInputTruncated&&this.emptyAnnouncementSink?.announce(this.inputLimitText()),this.limitInitialized=!0,this.previouslyInputTruncated=inputTruncated;const wasMounting=this.isMounting;this.isMounting=!1,!wasMounting&&changed.has("errorText")&&this.errorText!==""&&this.isConnected&&(this.initialStateAnnounced=!0,this.errorAnnouncementSink?.announce(this.errorText));const emptyPresented=!this.loading&&this.errorText===""&&this.processedChunks.chunks.length===0;!wasMounting&&!this.wasEmptyPresented&&emptyPresented&&this.isConnected&&(this.initialStateAnnounced=!0,this.emptyAnnouncementSink?.announce(this.localize("chunkInspectorEmpty"))),this.wasEmptyPresented=emptyPresented,this.previousProcessedChunkIds=this.errorText?[]:this.processedChunks.chunks.map(chunk=>chunk.id);const generation=++this.focusRestoreGeneration,target=this.pendingFocusTarget;target!==void 0&&(this.pendingFocusTarget=void 0,this.restoreControlledFocus(target,generation))}announcePresentedState(){if(!this.sourceMode){if(this.errorText!==""){this.errorAnnouncementSink?.announce(this.errorText);return}!this.loading&&this.processedChunks.chunks.length===0&&this.emptyAnnouncementSink?.announce(this.localize("chunkInspectorEmpty"))}}async restoreControlledFocus(target,generation){if(await this.updateComplete,generation!==this.focusRestoreGeneration||!this.isConnected)return;if(target==="base"){this.renderRoot.querySelector('[part="base"]')?.focus();return}const virtualList=this.renderRoot.querySelector(tag("virtual-list"));if(await virtualList?.updateComplete,generation!==this.focusRestoreGeneration||!this.isConnected)return;const roots=[this.renderRoot];virtualList?.shadowRoot&&roots.push(virtualList.shadowRoot);const candidates=roots.flatMap(root=>[...root.querySelectorAll("[data-chunk-id]")]),checkbox=candidates.find(element=>element.localName===tag("checkbox")&&element.getAttribute("data-chunk-id")===target);if(checkbox){checkbox.focus();return}const inspector=candidates.find(element=>element.localName===tag("chunk-inspector")&&element.getAttribute("data-chunk-id")===target);await inspector?.updateComplete,!(generation!==this.focusRestoreGeneration||!this.isConnected)&&inspector?.shadowRoot?.querySelector('[part="open-button"]')?.focus()}get effectiveVirtualizeAt(){return finiteCount(this.virtualizeAt,50)}canonicalChunks(){return this.canonicalSource!==this.chunks&&(this.canonicalSource=this.chunks,this.canonicalCache=firstByRetrievalIdentity(this.chunks.flatMap(value=>projectRetrievalChunk(value)??[]),chunk=>chunk.id),this.canonicalById=new Map(this.canonicalCache.map(chunk=>[chunk.id,chunk])),this.canonicalOrder=new Map(this.canonicalCache.map((chunk,index)=>[chunk.id,index]))),this.canonicalCache}normalizedSelectedChunkIds(){return this.canonicalSource!==this.chunks&&this.canonicalChunks(),canonicalIdentityList(this.selectedChunkIds).filter(id=>this.canonicalById.has(id))}get processedChunks(){return this.sourceMode?{chunks:this.sourceRows,groups:this.sourceGroups}:this.processedChunksCache??=this.computeProcessedChunks()}computeProcessedChunks(){const canonical=this.canonicalChunks(),sorted=this.sort==="score"?[...canonical].sort((a,b)=>safeScore(b.score)-safeScore(a.score)):canonical;if(this.grouping==="source")return this.bucketed(sorted,chunk=>chunk.source.id,(_id,groupChunks)=>groupChunks[0].source.name||this.localize("untitledSource"));if(this.grouping==="custom"&&this.groupBy){const groupBy=this.groupBy;return this.bucketed(sorted,groupBy,(id,groupChunks)=>this.groupLabel?.(id,groupChunks)??id)}return{chunks:sorted,groups:[]}}orderedGroupKeys(grouped){const firstSeen=[...grouped.keys()];if(this.grouping!=="custom"||!this.groupOrder)return firstSeen;if(typeof this.groupOrder=="function")return firstSeen.sort(this.groupOrder);const ordered=[...new Set(this.groupOrder)].filter(id=>grouped.has(id)),listed=new Set(ordered);return[...ordered,...firstSeen.filter(id=>!listed.has(id))]}bucketed(sorted,keyOf,labelOf){const grouped=new Map;for(const chunk of sorted){const key=keyOf(chunk),existing=grouped.get(key);existing?existing.push(chunk):grouped.set(key,[chunk])}const rows=[],groups=[];for(const key of this.orderedGroupKeys(grouped)){const groupChunks=grouped.get(key);!groupChunks||groupChunks.length===0||(groups.push({key,label:labelOf(key,groupChunks),startIndex:rows.length}),rows.push(...groupChunks))}return{chunks:rows,groups}}reportSelection(chunkIds){this.canonicalSource!==this.chunks&&this.canonicalChunks();const chunks=[...new Set(chunkIds)].flatMap(id=>this.canonicalById.get(id)??[]).sort((a,b)=>this.canonicalOrder.get(a.id)-this.canonicalOrder.get(b.id));this.emit("lr-selection-change",snapshotEventDetail({selectedChunkIds:chunkIds,chunks},this.ownerDocument.defaultView))}toggleSelect(chunk){if(!this.currentSourceRow(chunk)||this.sourceSelectionBlocked)return;if(this.sourceMode){const next2=new Set(this.selectedChunkIds);next2.has(chunk.id)?next2.delete(chunk.id):next2.size<1e4&&next2.add(chunk.id),this.selectedChunkIds=[...next2],this.sourceSelectionEvent=this.selectedChunkIds;return}const next=new Set(this.normalizedSelectedChunkIds());next.has(chunk.id)?next.delete(chunk.id):next.add(chunk.id),this.selectedChunkIds=[...next],this.reportSelection(this.selectedChunkIds)}rowChunksFor(chunk){let row=this.rowChunks.get(chunk);return row||this.rowChunks.set(chunk,row=[toLyraChunk(chunk)]),row}renderMetadata(metadata){return renderRetrievalMetadata(metadata,this.effectiveLocale,this.localize("valueInvalid"),this.localize("valueTruncated"))}isChunkSelected(id){const source=this.selectedChunkIds;return source.length===0||this.processedChunks.chunks.length<=1?(this.selectedMembership=void 0,source.includes(id)):(this.selectedMembership?.source!==source&&(this.selectedMembership={source,ids:new Set(source)}),this.selectedMembership.ids.has(id))}legacyLoadMoreHandler(){const chunks=this.chunks,version=this.sourceVersion;return event=>{event.stopPropagation(),!(!this.isConnected||this.sourceMode||this.sourceVersion!==version||this.chunks!==chunks||!this.hasMore||this.loading||this.errorText||event.currentTarget?.getRootNode()!==this.renderRoot)&&this.emit("lr-load-more")}}renderLoadMoreFooter(){return this.hasMore?html`
35
35
  <div part="load-more-row">
36
36
  ${this.loading?html`<lr-spinner part="spinner"></lr-spinner>`:html`<button
37
37
  type="button"
@@ -123,7 +123,7 @@ maxLines:number;
123
123
  /** Anchor kinds this component resolves via `scrollToAnchor()`. Feature-detectable capability
124
124
  * mirror -- the same pattern every other `DocumentAnchorTarget`-adopting viewer uses for this
125
125
  * field. */
126
- readonly anchorKinds:readonly LyraAnchorKind[];private copyStatus;private diffTooLarge;private copyAnnouncementSink?;private searchMatches;private searchMatchCountExact;private searchActiveIndex;private searchQuery;private lastSearchLocale;private pendingSearchResetEvent;private forcedVisibleOps;private readonly searchAnnouncements;private readonly searchAnnouncer;private highlightedOldLines;private highlightedNewLines;private highlightToken;private loadHighlighterCore;private copyTimer?;private copyGeneration;private oldTextSnapshot;private newTextSnapshot;private languageSnapshot;private languagesSnapshot?;private diffOps;private opIndexMap;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private hasSearchState;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;private cancelCopyTimer;private resetCopyFeedback;private get highlightLimited();private syncHighlight;private tokenizeLines;private computeFolds;private foldMarker;private revealOp;private lineElementForOpIndex;private scrollOpIndexIntoView;
126
+ readonly anchorKinds:readonly LyraAnchorKind[];private copyStatus;private diffTooLarge;private copyAnnouncementSink?;private searchMatches;private searchMatchCountExact;private searchActiveIndex;private searchQuery;private lastSearchLocale;private pendingSearchResetEvent;private forcedVisibleOps;private readonly searchAnnouncements;private readonly searchAnnouncer;private highlightedOldLines;private highlightedNewLines;private highlightToken;private loadHighlighterCore;private copyTimer?;private copyGeneration;private scrollGeneration;private searchGeneration;private oldTextSnapshot;private newTextSnapshot;private languageSnapshot;private languagesSnapshot?;private diffOps;private opIndexMap;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private hasSearchState;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;private cancelCopyTimer;private resetCopyFeedback;private get highlightLimited();private syncHighlight;private tokenizeLines;private computeFolds;private foldMarker;private revealOp;private lineElementForOpIndex;private scrollAuthority;private scrollOpIndexIntoView;
127
127
  /** Resolves a `line-range` anchor by scrolling the line at its 0-based `start` op index into
128
128
  * view, first expanding any `contextLines` fold currently hiding it. `end` is not consulted
129
129
  * here -- it only widens what a covering `highlights` entry paints; the scroll target is
@@ -133,14 +133,14 @@ protected applyAnchor(anchor:LyraAnchor):Promise<boolean>;private resolvedHighli
133
133
  * contains a locale-aware case-insensitive substring of `query`, ordered by that line's
134
134
  * `line-range` op index; an empty/whitespace query behaves like `clearSearch()` and resolves
135
135
  * `0`. Inspect `lr-search-change.matchCountExact` to distinguish an exact total from a lower
136
- * bound once a resource ceiling is reached. */
136
+ * bound once a resource ceiling is reached. A superseded search resolves `0`. */
137
137
  search(query:string):Promise<number>;
138
138
  /** Advances to the next match, wrapping to the first after the last. Resolves `true` once the
139
- * active match moved, `false` when there are no matches -- the shape the shared
140
- * `LyraTextViewerTarget` search contract declares. */
139
+ * active match moved, `false` when there are no matches or navigation is superseded -- the
140
+ * shape the shared `LyraTextViewerTarget` search contract declares. */
141
141
  searchNext():Promise<boolean>;
142
142
  /** Moves to the previous match, wrapping to the last before the first. Resolves `true` once the
143
- * active match moved, `false` when there are no matches. */
143
+ * active match moved, `false` when there are no matches or navigation is superseded. */
144
144
  searchPrevious():Promise<boolean>;
145
145
  /** Clears the query, matches, and active index, and resets `lr-search-change` to a
146
146
  * 0-match/no-active-index state. */