@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
@@ -339,7 +339,7 @@ selectedEdgeIds:readonly string[];
339
339
  dimmedNodeIds:readonly string[];
340
340
  /** Same contract as `dimmedNodeIds`, for edges. An edge's dimming key is the same `linkKey()`
341
341
  * value (`LyraGraphEdge.id`, else `` `${source}->${target}` ``) `selectedEdgeIds` already uses. */
342
- dimmedEdgeIds:readonly string[];private readonly arrowMarkerId;private loading;private loadFailed;private loadLibrary;private loadGeneration;private containerSize;private simNodes;private simLinks;private simNodeById;private danglingLinks;private lastPositionById;private lastHiddenNodeCount;private activeGraphItem;private graphLiveText;private readonly announcements;private graphAnnouncementsReady;private pendingGraphItemFocus;private isMounting;private authorRole;private syncingGraphHostRole;private simulation?;private chargeForce?;private linkForce?;private d3?;private detachedGraphChanges;private zoomedEl?;private gEl?;private zoomBehavior?;private boundNodeEls;private nodeEls;private nodeHitEls;private nodeLabelEls;private expandIndicatorEls;private lastKeyActivateIndex;private lastKeyActivateTime;private lastActivation?;private lastAppliedFocusNodeId;private focusHaloEl?;private communityHullEls;private communityHullHitEls;private communityLabelEls;private canvasEl?;private canvasCtx?;private pickCanvas?;private pickCtx?;private hostResizeObserver?;private hostResizeObserverDocument?;private canvasDprQuery?;private canvasDrawRafId?;private canvasDrawRafOwner?;private visible;private intersectionObserver?;private canvasDrawPending;private pickDirty;private canvasCamera;private canvasTooltipEl?;private pickItems;private canvasDragNode?;private canvasPointerId?;private canvasDragFrame?;private canvasDragFrameOwner?;private canvasDragGeneration;private pendingCanvasDrag?;private canvasPointerDownAt?;private canvasPointerDownId?;private pendingHover?;private canvasHover?;private hoverRafId?;private hoverRafOwner?;private svgHoverNodeId?;private canvasScene?;private canvasSceneHasEdgeLabels;private cameraTweenId?;private cameraTweenFrameOwner?;private cameraTweenResolve?;private isCameraTweening;private viewportChangeRafId?;private viewportChangeRafOwner?;private linkEls;private linkHitEls;private linkLabelEls;private linkLabelHiddenByLength;private edgeLabelWidthCache;private danglingLinkEls;private edgeLabelMeasureCanvas?;private edgeLabelMeasureCtx?;private linkPaintProbe?;private readonly linkPaintVisibilityCache;private readonly resolvedCssColorCache;private reducedMotion;private spatial?;private spatialLoad?;private spatialGeneration;private layeredEngine?;private layeredLoad?;private layeredGeneration;private optionalLoadFailure?;private d3LoadFailed;private loadSpatialController;private loadLayeredLayout;private ensureSpatial;private ensureLayered;protected getUpdateComplete():Promise<boolean>;private createSpatial;private spatialMessages;constructor();attributeChangedCallback(name:string,oldValue:string|null,value:string|null):void;private hostOwnsGraphSemantics;private syncGraphHostRole;private get ownerWindow();private computedStyle;connectedCallback():void;private setGraphVisibility;private connect2d;disconnectedCallback():void;adoptedCallback():void;private scheduleViewportChange;private nodeRadius;private safeLinkWidth;private isInteractiveLink;private navigableLinksCache?;private navigableLinks;private lengthInPixels;private get requestedWidth();private get requestedHeight();private get safeWidth();private get safeHeight();private recordContainerSize;private measureHostBox;private syncRequestedHeightVar;private get safeMinZoom();private get safeMaxZoom();private get effectiveZoomBounds();private get safeEdgeLabelMinZoom();private get resolvedNodeLabelsMode();private canvasNodeLabelsVisible;private get safeSeed();private get safeChargeStrength();private get safeLinkDistance();private nodeTypeIndex?;private nodeTypeEntry;private resolveNodeType;private nodeShape;private labeledNodeTypes;private nodeFill;private visibleNodes;private resolveLinksAgainst;private visibleCommunitiesCache?;private visibleCommunities;private communityHull;private onCommunityClick;private cameraTransitionMs;private cancelCameraTween;private isApplyingZoomTransform;private applyZoomTransform;private tweenCamera;
342
+ dimmedEdgeIds:readonly string[];private readonly arrowMarkerId;private loading;private loadFailed;private loadLibrary;private libraryLoad?;private loadGeneration;private containerSize;private simNodes;private simLinks;private simNodeById;private danglingLinks;private lastPositionById;private lastHiddenNodeCount;private activeGraphItem;private graphLiveText;private readonly announcements;private graphAnnouncementsReady;private pendingGraphItemFocus;private isMounting;private authorRole;private syncingGraphHostRole;private simulation?;private chargeForce?;private linkForce?;private d3?;private detachedGraphChanges;private zoomedEl?;private gEl?;private zoomBehavior?;private boundNodeEls;private nodeEls;private nodeHitEls;private nodeLabelEls;private expandIndicatorEls;private lastKeyActivateIndex;private lastKeyActivateTime;private lastActivation?;private lastAppliedFocusNodeId;private focusHaloEl?;private communityHullEls;private communityHullHitEls;private communityLabelEls;private canvasEl?;private canvasCtx?;private pickCanvas?;private pickCtx?;private hostResizeObserver?;private hostResizeObserverDocument?;private canvasDprQuery?;private canvasDrawRafId?;private canvasDrawRafOwner?;private visible;private intersectionObserver?;private canvasDrawPending;private pickDirty;private canvasCamera;private canvasTooltipEl?;private pickItems;private canvasDragNode?;private canvasPointerId?;private canvasDragFrame?;private canvasDragFrameOwner?;private canvasDragGeneration;private pendingCanvasDrag?;private canvasPointerDownAt?;private canvasPointerDownId?;private pendingHover?;private canvasHover?;private hoverRafId?;private hoverRafOwner?;private svgHoverNodeId?;private canvasScene?;private canvasSceneHasEdgeLabels;private cameraTweenId?;private cameraTweenFrameOwner?;private cameraTweenResolve?;private isCameraTweening;private viewportChangeRafId?;private viewportChangeRafOwner?;private linkEls;private linkHitEls;private linkLabelEls;private linkLabelHiddenByLength;private edgeLabelWidthCache;private danglingLinkEls;private edgeLabelMeasureCanvas?;private edgeLabelMeasureCtx?;private linkPaintProbe?;private readonly linkPaintVisibilityCache;private readonly resolvedCssColorCache;private reducedMotion;private spatial?;private spatialLoad?;private spatialGeneration;private layeredEngine?;private layeredLoad?;private layeredGeneration;private optionalLoadFailure?;private d3LoadFailed;private loadSpatialController;private loadLayeredLayout;private ensureSpatial;private ensureLayered;protected getUpdateComplete():Promise<boolean>;private createSpatial;private spatialMessages;constructor();attributeChangedCallback(name:string,oldValue:string|null,value:string|null):void;private hostOwnsGraphSemantics;private syncGraphHostRole;private get ownerWindow();private computedStyle;connectedCallback():void;private setGraphVisibility;private connect2d;disconnectedCallback():void;adoptedCallback():void;private scheduleViewportChange;private nodeRadius;private safeLinkWidth;private isInteractiveLink;private navigableLinksCache?;private navigableLinks;private lengthInPixels;private get requestedWidth();private get requestedHeight();private get safeWidth();private get safeHeight();private recordContainerSize;private measureHostBox;private syncRequestedHeightVar;private get safeMinZoom();private get safeMaxZoom();private get effectiveZoomBounds();private get safeEdgeLabelMinZoom();private get resolvedNodeLabelsMode();private canvasNodeLabelsVisible;private get safeSeed();private get safeChargeStrength();private get safeLinkDistance();private nodeTypeIndex?;private nodeTypeEntry;private resolveNodeType;private nodeShape;private labeledNodeTypes;private nodeFill;private visibleNodes;private resolveLinksAgainst;private visibleCommunitiesCache?;private visibleCommunities;private communityHull;private onCommunityClick;private cameraTransitionMs;private cancelCameraTween;private isApplyingZoomTransform;private applyZoomTransform;private tweenCamera;
343
343
  /** Animates the camera so `id` centers in the viewport (the `width` x `height` viewBox), at
344
344
  * `options.zoom` (clamped to `[minZoom, maxZoom]`) or the current scale when omitted. Resolves
345
345
  * `true` on arrival; `false` for an id with no matching entry in `simNodes` -- there's nothing
@@ -21,7 +21,7 @@ import{__decorate}from"tslib";import{ENGINE_3D_PREFERENCE,ENGINE_3D_REASON_MESSA
21
21
  .pageSize=${finiteInteger(this.sourcePageSize,100,1,500)} .total=${this.sourceTotal??-1} .disabled=${failed||state2.pending||this.sourceTotal===null}
22
22
  .strings=${this.strings} @lr-page-change=${event=>{event.stopPropagation(),this.sourcePage=event.detail.page-1}}
23
23
  @lr-before-page-change=${stop} @lr-activate=${stop} @focus=${stop} @blur=${stop}></lr-pagination>
24
- </section>`}get graphModel(){if(this.sourceMode){if(!this.sourceModel){const scene=this.sourceBindingError?void 0:this.sourceScene.state.scene,nodes=Object.freeze(scene?.nodes.map(entry=>entry.value)??[]),ids=new Set(nodes.map(node=>node.id));this.sourceModel=Object.freeze({nodes,links:Object.freeze(scene?.edges.map(entry=>entry.value)??[]),nodeTypes:this.nodeTypes,communities:Object.freeze(this.communities.map(community=>Object.freeze({...community,memberIds:Object.freeze(community.memberIds.filter(id=>ids.has(id)))})))})}return this.sourceModel}const sources=this.normalizedGraphSources;return(!sources||sources[0]!==this.nodes||sources[1]!==this.edges||sources[2]!==this.nodeTypes||sources[3]!==this.communities)&&(this.normalizedGraphSources=[this.nodes,this.edges,this.nodeTypes,this.communities],this.normalizedGraphModel=normalizeGraphModel(this.nodes,this.edges,this.nodeTypes,this.communities)),this.normalizedGraphModel}get engine(){return this._engine}set engine(value){const old=this._engine;this._engine=ENGINE_3D_PREFERENCE.normalize(value),old===this._engine&&this.isConnected?(this.spatial?.retryEngine(),this.requestUpdate()):this.requestUpdate("engine",old)}get graphColumns(){return this._graphColumns}set graphColumns(value){const old=this._graphColumns;if(old!==value){if(this._graphColumns=value,this.engineColumns=void 0,this.engineColumnsInvalid=!1,value!==void 0){const result=admitGraphEngineColumns(value);result.ok?this.engineColumns=result.value:this.engineColumnsInvalid=!0}this.requestUpdate("graphColumns",old),this.engineColumnsInvalid&&this.scheduleAfterUpdate(()=>{this.isConnected&&this.graphColumns===value&&this.engineColumnsInvalid&&!this.sourceMode&&this.announcements.announceAssertive(this.localize("largeDataInvalid"))},"graph-columns-error")}}get view(){return this._view}set view(value){const next=GRAPH_VIEW.normalize(value),old=this._view;next!==old&&(this._view=next,this.requestUpdate("view",old))}get camera(){return this.engine==="webgl"?this._camera:this.builtinCamera}set camera(value){const old=this._camera;this._camera=value==null?void 0:graphWebglCamera(value,{yaw:0,pitch:0,distance:500,target:{x:0,y:0,z:0}}),this.builtinCamera=value==null?void 0:normalizeGraphCamera(value,{yaw:0,pitch:0,distance:500,target:{x:0,y:0,z:0}}),this.requestUpdate("camera",old)}get layout(){return this._layout}set layout(next){const normalized=GRAPH_LAYOUT.normalize(next),old=this._layout;old!==normalized&&(this._layout=normalized,this.requestUpdate("layout",old))}loadSpatialController(){return import("./graph-spatial-controller.js")}loadLayeredLayout(){return import("../../../internal/layered-layout.js")}ensureSpatial(){if(this.spatial||!this.isConnected||this.view==="2d"||this.sourceList)return Promise.resolve();if(this.spatialLoad)return this.spatialLoad;const generation=++this.spatialGeneration,pending=this.loadSpatialController().then(({GraphSpatialController})=>{generation!==this.spatialGeneration||!this.isConnected||this.view==="2d"||this.sourceList||(this.spatial=this.createSpatial(GraphSpatialController),this.optionalLoadFailure=void 0,this.loadFailed=!1,this.paintGraph())},()=>{generation===this.spatialGeneration&&this.isConnected&&this.view!=="2d"&&(this.optionalLoadFailure="spatial",this.loadFailed=!0,this.announcements.announceAssertive(this.localize("graphSpatialUnavailable")),this.paintGraph())}).finally(()=>{this.spatialLoad===pending&&(this.spatialLoad=void 0)});return this.spatialLoad=pending,pending}ensureLayered(){if(this.layeredEngine||!this.isConnected||this.view!=="2d"||this.layout!=="layered")return Promise.resolve();if(this.layeredLoad)return this.layeredLoad;const generation=++this.layeredGeneration;this.loading=!0;const pending=this.loadLayeredLayout().then(({layeredLayout})=>{generation!==this.layeredGeneration||!this.isConnected||this.view!=="2d"||this.layout!=="layered"||(this.layeredEngine=layeredLayout,this.optionalLoadFailure=void 0,this.loading=!this.d3,this.loadFailed=!1,this.d3&&this.rebuildSimulation(),this.paintGraph())},()=>{generation===this.layeredGeneration&&this.isConnected&&this.layout==="layered"&&(this.optionalLoadFailure="layered",this.loading=!1,this.loadFailed=!0)}).finally(()=>{this.layeredLoad===pending&&(this.layeredLoad=void 0)});return this.layeredLoad=pending,pending}async getUpdateComplete(){const complete=await super.getUpdateComplete(),pending=this.view!=="2d"?this.spatialLoad:this.layout==="layered"?this.layeredLoad:void 0;return pending&&(await pending,this.isUpdatePending)?super.getUpdateComplete():complete}createSpatial(Controller){return new Controller(this,{repaint:()=>this.paintGraph(),model:()=>this.graphModel,columns:()=>this.sourceMode?void 0:this.engineColumns,sourceMode:()=>this.sourceMode,engineFallback:detail=>{this.emit("lr-engine-fallback",detail),this.announcements.announceAssertive(`${this.localize(ENGINE_3D_REASON_MESSAGE[detail.reason])} ${this.localize(ENGINE_3D_SHOWING_MESSAGE[detail.to])}`)},engineMessage:key=>this.localize(key),nodeRenderError:detail=>{this.emit("lr-node-render-error",detail),this.announcements.announceAssertive(this.localize("graphCustomNodesError"))},effectNotice:key=>this.announcements.announceAssertive(this.localize(key==="graphGlowUnavailable"?"graphGlowUnavailable":"graphCustomNodesUnavailable")),categoryColors:()=>this.withCanvasColorResolver(resolve=>Array.from({length:8},(_,index)=>resolve(categoricalPaletteColor(index)))),locale:()=>this.effectiveLocale,direction:()=>this.effectiveDirection,pageText:values=>this.localize("graphSpatialPage",void 0,values),viewport:()=>({width:this.safeWidth,height:this.safeHeight}),messages:()=>this.spatialMessages(),communityText:values=>this.localize("graphCommunity",void 0,values),nodeText:node=>this.nodeAccessibleText(node),edgeText:edge=>this.linkAccessibleText(edge),nodeTooltip:node=>this.nodeTooltipText(node),edgeTooltip:edge=>this.linkTooltipText(edge),nodeShape:node=>this.nodeShape(node),paint:(nodes,edges)=>this.withCanvasColorResolver(resolve=>{const css=this.computedStyle(),nodeDefault=css.getPropertyValue("--lr-graph-node-fill").trim()||css.getPropertyValue("--lr-color-brand").trim(),edgeDefault=css.getPropertyValue("--lr-graph-edge-color").trim()||css.getPropertyValue("--lr-color-border").trim();return{nodes:new Map(nodes.map(({node})=>[node.id,resolve(this.nodeFill(node)??nodeDefault)])),edges:new Map(edges.map(edge=>[graphLinkIdentity(edge),resolve(sanitizeNodeColor(edge.color)??edgeDefault)])),visibleEdges:new Set(edges.filter(edge=>this.isInteractiveLink(edge,resolve,edgeDefault)).map(graphLinkIdentity)),text:resolve(css.getPropertyValue("--lr-color-text").trim()),selected:resolve(css.getPropertyValue("--lr-graph-selected-color").trim()||css.getPropertyValue("--lr-color-success").trim()),font:css.getPropertyValue("--lr-font").trim()||css.fontFamily,fontSize:this.edgeLabelFontPx(),dimmedOpacity:finiteRange(Number(css.getPropertyValue("--lr-graph-dimmed-opacity").trim()||.35),.35,0,1)}}),activate:(hit,event)=>{if(!this.sourceDiagramBlocked)if(hit.kind==="node"){const position=this.spatial?.position(hit.id);if(!position)return;const current=this.selectionActionAuthority();this.emit("lr-node-activate",{nodeId:hit.id,...position}),current()&&this.emitSelectionIntent("node",hit.id,event.ctrlKey||event.metaKey)}else this.onLinkClick(hit.edge,event)},expand:nodeId=>this.emit("lr-node-expand",{nodeId}),hover:(previous,next)=>{previous?.kind==="node"?this.emit("lr-node-leave",{nodeId:previous.id}):previous?.kind==="link"&&this.emitEdgeHover("leave",this.linkHoverDetail(previous.edge)),next?.kind==="node"?this.emit("lr-node-enter",{nodeId:next.id}):next?.kind==="link"&&this.emitEdgeHover("enter",this.linkHoverDetail(next.edge))},community:community=>this.onCommunityClick(community),cameraChanged:camera=>this.emit("lr-camera-change",{camera}),viewChanged:()=>this.emit("lr-view-change",{view:this.view}),unavailable:()=>this.announcements.announceAssertive(this.localize("graphSpatialUnavailable")),clearSelection:()=>this.clearSelection(),afterUpdate:(callback,key)=>this.scheduleAfterUpdate(callback,key)})}spatialMessages(){return{customError:this.localize("graphCustomNodesError"),customUnavailable:this.localize("graphCustomNodesUnavailable"),glowUnavailable:this.localize("graphGlowUnavailable"),controls:this.localize("graphSpatialControls"),view3d:this.localize("graphView3d"),viewList:this.localize("graphViewList"),fit:this.localize("graphFit"),left:this.localize("graphOrbitLeft"),right:this.localize("graphOrbitRight"),up:this.localize("graphOrbitUp"),down:this.localize("graphOrbitDown"),instructions:this.localize("graphSpatialInstructions"),unavailable:this.localize("graphSpatialUnavailable"),zoomIn:this.localize("zoomIn"),zoomOut:this.localize("zoomOut"),previous:this.localize("previous"),next:this.localize("next"),dataList:this.localize("graphDataList"),noData:this.localize("noData")}}constructor(){super(),this.sourceEpoch=0,this.sourceNavigation=0,this.sourceSyncing=!1,this.sourceQuery=EMPTY_SOURCE_QUERY,this.sourceCenter=null,this.sourceKeys=[],this.sourceMissing=!1,this.sourceRestoreFocus=!1,this.sourceRestorePager=!1,this.sourcePagePromise=Promise.resolve(!1),this.sourceState=0,this.sourceModelVersion=0,this.sourcePaint=0,this.sourceScene=new GraphSourceController(this,{onChange:()=>{this.sourceState++}}),this.sourcePages=new SourcePageController(this,{normalizeRecord:record=>record,normalizeSummary:value=>graphSourceSummary(value),validateMetadata:(result,query2)=>{const count=result.summary[query2.kind];if(result.total>count||!query2.search&&query2.centerKey===null&&!query2.nodeTypes.length&&result.total!==count||result.rows.some(row=>row.value.kind!==(query2.kind==="nodes"?"node":"edge")))throw new TypeError("Invalid global graph count or kind");this.assertSourceTotals(result.summary)},onChange:()=>{this.sourceState++}}),this.sourceComposition=new GraphSourceCompositionController(this,()=>{const profile=this.sourceComposition.profile;profile&&this.setSourceQuery({...EMPTY_SOURCE_QUERY,search:profile.search,nodeTypes:profile.nodeTypes}),this.sourceState++},async keys=>{if(!this.sourceMode||this.sourceComposition.profile?.empty)return;const profile=this.sourceComposition.profile,currentSource=this.sourceAuthority(),current=()=>currentSource()&&this.sourceComposition.profile===profile,records=await this.sourcePages.resolveSelection(keys);return records&&current()?Object.freeze({records,current}):void 0},async key=>{if(!this.sourceMode||this.sourceComposition.profile?.empty)return;const source=this.graphSource,epoch=this.sourceEpoch,profile=this.sourceComposition.profile;this.sourceNavigation++;const current=this.sourceAuthority();if((this.sourceScene.state.pending||!this.sourceScene.state.scene?.nodes.some(node=>node.key===key))&&(!await this.ensureSourceScene(key,current)||!current()))return;if(this.sourceList){if(![...this.renderRoot.querySelectorAll("[data-source-key]")].some(row=>row.dataset.sourceKey===key)&&!await this.revealSourceRecord(key,!1))return}else if(!await this.focusSceneNode(key.slice(5),void 0,current))return;const finalCurrent=this.sourceAuthority(),accepted=()=>finalCurrent()&&this.graphSource===source&&this.sourceEpoch===epoch&&this.sourceComposition.profile===profile;return accepted()?accepted:void 0}),this.sourcePage=0,this.sourcePageSize=100,this.nodes=[],this.edges=[],this.nodeTypes=[],this.hiddenTypes=[],this.communities=[],this.nodeRenderer=void 0,this.glow=!1,this._engine="builtin",this.engineColumnsInvalid=!1,this._view="2d",this._layout="force",this.renderer="svg",this.fitTo="none",this.width=800,this.height=600,this.chargeStrength=-300,this.edgeDistance=100,this.minZoom=.1,this.maxZoom=8,this.label=null,this.accessibleLabel=null,this.withEdgeLabels=!1,this.edgeLabelMinZoom=.6,this.focusNodeId=null,this.selectionMode="none",this.selectedNodeIds=[],this.selectedEdgeIds=[],this.dimmedNodeIds=[],this.dimmedEdgeIds=[],this.arrowMarkerId=nextId("graph-arrow"),this.loading=!0,this.loadFailed=!1,this.loadLibrary=loadD3,this.loadGeneration=0,this.containerSize=null,this.simNodes=[],this.simLinks=[],this.simNodeById=new Map,this.danglingLinks=[],this.lastPositionById=new Map,this.lastHiddenNodeCount=0,this.activeGraphItem=0,this.graphLiveText="",this.announcements=new AnnouncementSinkController(this,{eager:["polite","assertive"]}),this.graphAnnouncementsReady=!1,this.isMounting=!0,this.authorRole=null,this.syncingGraphHostRole=!1,this.detachedGraphChanges=new Map,this.boundNodeEls=new WeakSet,this.nodeEls=[],this.nodeHitEls=[],this.nodeLabelEls=[],this.expandIndicatorEls=[],this.lastKeyActivateIndex=null,this.lastKeyActivateTime=0,this.lastAppliedFocusNodeId=null,this.communityHullEls=[],this.communityHullHitEls=[],this.communityLabelEls=[],this.visible=!0,this.canvasDrawPending=!1,this.pickDirty=!0,this.canvasCamera={k:1,x:0,y:0},this.pickItems=[],this.canvasDragGeneration=0,this.canvasSceneHasEdgeLabels=!1,this.isCameraTweening=!1,this.linkEls=[],this.linkHitEls=[],this.linkLabelEls=[],this.linkLabelHiddenByLength=[],this.edgeLabelWidthCache=new Map,this.danglingLinkEls=[],this.linkPaintVisibilityCache=new Map,this.resolvedCssColorCache=new Map,this.reducedMotion=!1,this.spatialGeneration=0,this.layeredGeneration=0,this.d3LoadFailed=!1,this.isApplyingZoomTransform=!1,this.onCanvasDprChange=()=>{this.watchCanvasDpr(),this.markCanvasDirty()},this.canvasNodesById=new Map,this.canvasLinksById=new Map,this.canvasLabelNodes=[],this.canvasExpandableNodes=[],this.onCanvasPointerDown=e=>{if(e.button!==0||(this.canvasPointerDownAt={x:e.clientX,y:e.clientY},this.canvasPointerDownId=e.pointerId,this.layout==="layered"))return;const hit=this.hitTest(e.clientX,e.clientY);if(hit?.kind==="node"){this.canvasDragNode=hit.node,this.canvasPointerId=e.pointerId;try{this.canvasEl.setPointerCapture(e.pointerId)}catch{}hit.node.fx=hit.node.x,hit.node.fy=hit.node.y,this.simulation?.alphaTarget(.3).restart()}},this.onCanvasPointerMove=e=>{if(this.canvasDragNode&&this.canvasPointerId===e.pointerId){if(this.pendingCanvasDrag={x:e.clientX,y:e.clientY},this.canvasDragFrame===void 0){const owner=this.ownerWindow;if(owner){const generation=this.canvasDragGeneration;this.canvasDragFrameOwner=owner,this.canvasDragFrame=owner.requestAnimationFrame(()=>{generation===this.canvasDragGeneration&&this.flushCanvasDrag()})}}return}if(this.pendingHover={x:e.clientX,y:e.clientY},this.hoverRafId!=null)return;const frameOwner=this.ownerWindow;frameOwner&&(this.hoverRafOwner=frameOwner,this.hoverRafId=frameOwner.requestAnimationFrame(()=>{if(this.hoverRafId=void 0,this.hoverRafOwner=void 0,!this.isConnected||this.ownerWindow!==frameOwner)return;const pending=this.pendingHover;if(this.pendingHover=void 0,!pending||this.canvasHoverSuppressed()||this.pickDirty&&this.simulationIsTicking())return;const hit=this.hitTest(pending.x,pending.y);this.updateCanvasTooltip(hit,pending.x,pending.y),this.updateCanvasHover(hit)}))},this.onCanvasPointerUp=e=>{this.finishCanvasNodeDrag(e.pointerId);const down=this.takeCanvasPointerDown(e.pointerId);if(!down||Math.hypot(e.clientX-down.x,e.clientY-down.y)>5)return;const hit=this.hitTest(e.clientX,e.clientY);if(!hit){this.clearSelection();return}hit.kind==="node"?this.onNodeClick(hit.node,e):hit.kind==="link"?this.onLinkClick(hit.link,e):this.onCommunityClick(hit.entry.community)},this.onCanvasPointerCancel=e=>{this.finishCanvasNodeDrag(e.pointerId),this.takeCanvasPointerDown(e.pointerId)},this.onCanvasLostPointerCapture=e=>{this.finishCanvasNodeDrag(e.pointerId,!1),this.takeCanvasPointerDown(e.pointerId)},this.onCanvasPointerLeave=()=>{this.pendingHover=void 0,this.hoverRafId!=null&&(this.hoverRafOwner?.cancelAnimationFrame(this.hoverRafId),this.hoverRafId=void 0,this.hoverRafOwner=void 0),this.updateCanvasTooltip(void 0,0,0),this.canvasHoverSuppressed()?this.canvasHover=void 0:this.updateCanvasHover(void 0)},this.onCanvasDblClick=e=>{const hit=this.hitTest(e.clientX,e.clientY),node=hit?.kind==="node"?hit.node:this.nodeAtCanvasPoint(e.clientX,e.clientY);node&&(e.stopImmediatePropagation(),this.emit("lr-node-expand",{nodeId:node.id}))},this.explicitRefresh=!1,this.cursorUpdate=!1,this.paintUpdate=!0,this.svgCursorItems=[],this.isDragging=!1,this.isPanning=!1,new ThemeWatcher(this,()=>{const reduced=prefersReducedMotion(this);reduced!==this.reducedMotion&&(this.reducedMotion=reduced,reduced?this.simulation?.stop():this.visible&&this.view==="2d"&&this.safeSeed==null&&this.simulation?.restart()),this.linkPaintVisibilityCache.clear(),this.resolvedCssColorCache.clear(),this.view!=="2d"?this.spatial?.invalidate():this.renderer==="canvas"&&this.markCanvasDirty()},["(prefers-reduced-motion: reduce)"])}attributeChangedCallback(name,oldValue,value){super.attributeChangedCallback(name,oldValue,value),name==="role"&&oldValue!==value&&!this.syncingGraphHostRole&&(this.authorRole=value)}hostOwnsGraphSemantics(){return this.hasAttribute("aria-label")}syncGraphHostRole(){if(this.authorRole===null){this.syncingGraphHostRole=!0;try{this.hostOwnsGraphSemantics()?this.setAttribute("role","group"):this.removeAttribute("role")}finally{this.syncingGraphHostRole=!1}}}get ownerWindow(){return this.ownerDocument.defaultView??void 0}computedStyle(){const view=this.ownerWindow;return view?view.getComputedStyle(this):this.style}connectedCallback(){if(super.connectedCallback(),this.sourceInputs=void 0,this.syncGraphSource(),this.detachedGraphChanges.size){for(const[key,previous]of this.detachedGraphChanges)this.requestUpdate(key,previous);this.detachedGraphChanges.clear(),this.paintGraph()}this.reducedMotion=prefersReducedMotion(this);const IntersectionObserverCtor=this.ownerWindow?.IntersectionObserver;this.view==="2d"&&IntersectionObserverCtor&&(this.intersectionObserver=new IntersectionObserverCtor(entries=>{this.setGraphVisibility(entries[0]?.isIntersecting??!0)}),this.intersectionObserver.observe(this)),this.fitTo==="container"&&(this.syncHostResizeObserver(),this.measureHostBox()),this.view==="2d"?this.connect2d():(this.loading=!1,this.ensureSpatial(),this.paintGraph())}setGraphVisibility(visible){const wasVisible=this.visible;this.visible=visible,visible?wasVisible||(!this.reducedMotion&&this.safeSeed==null&&this.view==="2d"&&this.simulation&&this.simulation.alpha()>this.simulation.alphaMin()&&this.simulation.restart(),this.canvasDrawPending&&(this.canvasDrawPending=!1,this.scheduleCanvasDraw())):this.simulation?.stop()}connect2d(){const Observer=this.ownerWindow?.IntersectionObserver;if(!this.intersectionObserver&&Observer&&(this.intersectionObserver=new Observer(entries=>{this.setGraphVisibility(entries[0]?.isIntersecting??!0)}),this.intersectionObserver.observe(this)),this.d3){this.visible&&!this.reducedMotion&&this.safeSeed==null&&this.simulation?.restart(),this.renderer==="canvas"&&this.canvasEl&&this.canvasEl===this.zoomedEl&&(this.ensureCanvasOwnerRealm(),this.syncHostResizeObserver(),this.watchCanvasDpr(),this.markCanvasDirty());return}const generation=++this.loadGeneration;this.loadLibrary().then(async mods=>{try{await super.getUpdateComplete()}catch{return}if(await new Promise(resolve=>this.updateBrowserDerivedState(resolve)),!(generation!==this.loadGeneration||!this.isConnected)){if(this.loading=!1,!mods){this.d3LoadFailed=!0,this.loadFailed=!0;return}this.d3LoadFailed=!1,this.loadFailed=!1,this.d3=mods,this.rebuildSimulation()}})}disconnectedCallback(){this.sourceNavigation++,this.sourceEpoch++,this.sourceInputs=void 0,this.sourcePageInputs=void 0,super.disconnectedCallback(),this.spatialGeneration++,this.layeredGeneration++,this.spatialLoad=void 0,this.layeredLoad=void 0,this.spatial?.disconnect(),this.loadGeneration+=1,this.simulation?.stop(),this.finishCanvasNodeDrag(void 0,!0,!1),this.takeCanvasPointerDown(),this.cancelCameraTween(),this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0,this.hostResizeObserver?.disconnect(),this.hostResizeObserver=void 0,this.hostResizeObserverDocument=void 0,this.canvasDprQuery?.removeEventListener("change",this.onCanvasDprChange),this.canvasDprQuery=void 0,this.canvasDrawRafId!=null&&(this.canvasDrawRafOwner?.cancelAnimationFrame(this.canvasDrawRafId),this.canvasDrawRafId=void 0,this.canvasDrawRafOwner=void 0),this.hoverRafId!=null&&(this.hoverRafOwner?.cancelAnimationFrame(this.hoverRafId),this.hoverRafId=void 0,this.hoverRafOwner=void 0),this.pendingHover=void 0,this.canvasHover=void 0,this.canvasTooltipEl?.setAttribute("hidden",""),this.pendingGraphItemFocus=void 0,this.viewportChangeRafId!=null&&(this.viewportChangeRafOwner?.cancelAnimationFrame(this.viewportChangeRafId),this.viewportChangeRafId=void 0,this.viewportChangeRafOwner=void 0)}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted(),this.sourceEpoch++,this.sourceNavigation++,this.sourceInputs=void 0,this.sourceScene.adopted(),this.sourcePages.adopted(),this.sourceState++,this.ensureCanvasOwnerRealm()}scheduleViewportChange(){if(this.view!=="2d"||this.viewportChangeRafId!=null)return;const frameOwner=this.ownerWindow;frameOwner&&(this.viewportChangeRafOwner=frameOwner,this.viewportChangeRafId=frameOwner.requestAnimationFrame(()=>{if(this.viewportChangeRafId=void 0,this.viewportChangeRafOwner=void 0,!this.isConnected||this.ownerWindow!==frameOwner)return;const transform=this.renderer==="canvas"||!this.d3||!this.zoomedEl?this.canvasCamera:this.d3.zoomTransform(this.zoomedEl);this.emit("lr-viewport-change",{zoom:transform.k,x:transform.x,y:transform.y,k:transform.k})}))}nodeRadius(n){const r=n.radius??(MIN_RADIUS+MAX_RADIUS)/2;return Number.isFinite(r)?Math.min(MAX_RADIUS,Math.max(MIN_RADIUS,r)):(MIN_RADIUS+MAX_RADIUS)/2}safeLinkWidth(link){return finiteRange(link.width??1.5,1.5,0)}isInteractiveLink(link,resolveColor,defaultPaint){if(this.safeLinkWidth(link)<=0)return!1;const effectivePaint=sanitizeNodeColor(link.color)??defaultPaint,color=effectivePaint?resolveColor(effectivePaint).trim().toLowerCase():void 0;if(!color)return!0;if(color==="transparent"||/^#[\da-f]{4}$/.test(color)&&color.endsWith("0")||/^#[\da-f]{8}$/.test(color)&&color.endsWith("00")||/\/\s*0(?:\.0+)?%?\s*\)$/.test(color)||/^(?:rgba|hsla)\(/.test(color)&&/,\s*0(?:\.0+)?\s*\)$/.test(color))return!1;const cached=this.linkPaintVisibilityCache.get(color);if(cached!==void 0)return cached;this.linkPaintProbe??=this.ownerDocument.createElement("canvas"),this.linkPaintProbe.width=1,this.linkPaintProbe.height=1;const context=this.linkPaintProbe.getContext("2d",{willReadFrequently:!0});if(!context)return!0;let visible=!0;try{context.clearRect(0,0,1,1),context.fillStyle="rgb(1 2 3)",context.fillStyle=color,context.fillRect(0,0,1,1),visible=context.getImageData(0,0,1,1).data[3]!==0}catch{visible=!0}return this.linkPaintVisibilityCache.set(color,visible),visible}navigableLinks(){return this.navigableLinksCache||(this.navigableLinksCache=this.simLinks.length?this.withCanvasColorResolver(resolveColor=>{const computed=this.computedStyle(),defaultPaint=computed.getPropertyValue("--lr-graph-edge-color").trim()||computed.getPropertyValue("--lr-color-border").trim();return this.simLinks.filter(link=>this.isInteractiveLink(link,resolveColor,defaultPaint))}):[]),this.navigableLinksCache}lengthInPixels(value){return typeof value=="string"?resolveCssTokenLength(value,{host:this})??Number.NaN:value}get requestedWidth(){return finiteRange(this.lengthInPixels(this.width),800,1)}get requestedHeight(){return finiteRange(this.lengthInPixels(this.height),600,1)}get safeWidth(){const requested=this.requestedWidth,measured=this.fitTo==="container"&&this.containerSize;return measured?finiteRange(measured.width,requested,1):requested}get safeHeight(){const requested=this.requestedHeight,measured=this.fitTo==="container"&&this.containerSize;return measured?finiteRange(measured.height,requested,1):requested}recordContainerSize(width,height){const w=Math.round(finiteRange(width,0,0)),h=Math.round(finiteRange(height,0,0));return w<=0||h<=0||this.containerSize?.width===w&&this.containerSize?.height===h?!1:(this.containerSize={width:w,height:h},!0)}measureHostBox(){return this.isConnected?(this.syncRequestedHeightVar(),this.recordContainerSize(this.clientWidth,this.clientHeight)):!1}syncRequestedHeightVar(){this.style.setProperty("--_lr-graph-requested-height",`${this.requestedHeight}px`)}get safeMinZoom(){return finiteRange(this.minZoom,.1,.001,1e3)}get safeMaxZoom(){return finiteRange(this.maxZoom,8,.001,1e3)}get effectiveZoomBounds(){const min=this.safeMinZoom,max=this.safeMaxZoom;return Object.freeze({min:Math.min(min,max),max:Math.max(min,max)})}get safeEdgeLabelMinZoom(){return finiteRange(this.edgeLabelMinZoom,.6,.001,1e3)}get resolvedNodeLabelsMode(){return this.nodeLabels??(this.renderer==="canvas"?"zoom":"always")}canvasNodeLabelsVisible(){const mode=this.resolvedNodeLabelsMode;return mode==="none"?!1:mode==="zoom"?this.canvasCamera.k>=NODE_LABEL_MIN_ZOOM:!0}get safeSeed(){return this.seed==null?void 0:finiteInteger(this.seed,0)}get safeChargeStrength(){return finiteNumber(this.chargeStrength,-300)}get safeLinkDistance(){return finiteRange(this.edgeDistance,100,0)}nodeTypeEntry(node){const types=this.graphModel.nodeTypes;if(this.nodeTypeIndex?.[0]!==types){const labeled=this.labeledNodeTypes();this.nodeTypeIndex=[types,new Map(types.map((type,index)=>{const slot=labeled.indexOf(type);return[type.id,[type,slot<0?index:slot]]}))]}return node.type==null?void 0:this.nodeTypeIndex[1].get(node.type)}resolveNodeType(node){return this.nodeTypeEntry(node)?.[0]}nodeShape(node){return this.resolveNodeType(node)?.shape??"circle"}labeledNodeTypes(){return this.graphModel.nodeTypes.filter(candidate=>typeof candidate?.label=="string"&&candidate.label.trim().length>0)}nodeFill(node){const ownColor=sanitizeNodeColor(node.color);if(ownColor)return ownColor;const entry=this.nodeTypeEntry(node);if(entry)return sanitizeNodeColor(entry[0].color)||categoricalPaletteColor(entry[1])}visibleNodes(){const hiddenTypes=canonicalIdentityList(this.hiddenTypes);if(!hiddenTypes.length)return this.graphModel.nodes;const hidden=new Set(hiddenTypes);return this.graphModel.nodes.filter(n=>n.type==null||!hidden.has(n.type))}resolveLinksAgainst(byId){const nodeExists=new Set(this.graphModel.nodes.map(n=>n.id)),resolved=[],dangling=[];for(const l of this.graphModel.links){const source=byId.get(l.source);if(!source)continue;const target=byId.get(l.target);target?resolved.push(copyGraphLinkIdentity(l,{...l,source,target})):nodeExists.has(l.target)||dangling.push(copyGraphLinkIdentity(l,{...l,source,target:{id:l.target,x:source.x,y:source.y},dangling:!0}))}return{resolved,dangling}}visibleCommunities(){if(!this.visibleCommunitiesCache){const byCommunity=new Map,positions=new Map;this.simNodes.forEach((node,index)=>{if(positions.set(node.id,index),node.communityId!=null){const members=byCommunity.get(node.communityId);members?members.push(node):byCommunity.set(node.communityId,[node])}}),this.visibleCommunitiesCache=this.graphModel.communities.flatMap(community=>{const members=new Map;for(const node of byCommunity.get(community.id)??[])members.set(node.id,node);for(const id of community.memberIds??[]){const node=this.simNodeById.get(id);node&&members.set(id,node)}const ordered=[...members.values()].sort((a,b)=>positions.get(a.id)-positions.get(b.id));return ordered.length?[{community,members:ordered}]:[]})}return this.visibleCommunitiesCache}communityHull(members){return convexHull(members.map(n=>({x:n.x??0,y:n.y??0})))}onCommunityClick(community){this.emit("lr-community-activate",{communityId:community.id})}cameraTransitionMs(){const parsed=parseFloat(this.computedStyle().getPropertyValue("--lr-transition-base"));return Number.isFinite(parsed)?parsed:180}cancelCameraTween(){this.cameraTweenId!=null&&(this.cameraTweenFrameOwner?.cancelAnimationFrame(this.cameraTweenId),this.cameraTweenId=void 0,this.cameraTweenFrameOwner=void 0),this.isCameraTweening=!1;const resolve=this.cameraTweenResolve;resolve&&(this.cameraTweenResolve=void 0,resolve(!1))}applyZoomTransform(transform){if(!(!this.d3||!this.zoomedEl||!this.zoomBehavior)){this.isApplyingZoomTransform=!0;try{this.zoomBehavior.transform(this.d3.select(this.zoomedEl),transform)}finally{this.isApplyingZoomTransform=!1}}}tweenCamera(computeTarget){return new Promise(resolve=>{if(!this.d3||!this.zoomedEl||!this.zoomBehavior){resolve(!1);return}this.cancelCameraTween(),this.cameraTweenResolve=resolve,this.isCameraTweening=!0;const frameOwner=this.ownerWindow;if(!frameOwner){this.isCameraTweening=!1,this.cameraTweenResolve=void 0,resolve(!1);return}if(prefersReducedMotion(this)){this.applyZoomTransform(computeTarget()),this.isCameraTweening=!1,this.cameraTweenResolve=void 0,resolve(!0);return}const current=this.d3.zoomTransform(this.zoomedEl),duration=this.cameraTransitionMs(),start=frameOwner.performance.now(),startK=current.k,startX=current.x,startY=current.y,step=now=>{if(this.cameraTweenResolve!==resolve)return;if(!this.isConnected||this.ownerWindow!==frameOwner){this.cameraTweenId=void 0,this.cameraTweenFrameOwner=void 0,this.isCameraTweening=!1,this.cameraTweenResolve=void 0,resolve(!1);return}const t=!prefersReducedMotion(this)&&duration>0?Math.min(1,(now-start)/duration):1,target=computeTarget(),targetK=target.k,targetX=target.x,targetY=target.y;this.applyZoomTransform(this.d3.zoomIdentity.translate(startX+(targetX-startX)*t,startY+(targetY-startY)*t).scale(startK+(targetK-startK)*t)),t<1?(this.cameraTweenFrameOwner=frameOwner,this.cameraTweenId=frameOwner.requestAnimationFrame(step)):(this.cameraTweenId=void 0,this.cameraTweenFrameOwner=void 0,this.isCameraTweening=!1,this.cameraTweenResolve=void 0,resolve(!0))};this.cameraTweenFrameOwner=frameOwner,this.cameraTweenId=frameOwner.requestAnimationFrame(step)})}async focusNode(id,options){if(this.sourceMode){if(typeof id!="string"||!id.length||id.length+5>65536)return!1;if(this.sourceList)return this.revealSourceRecord(`node:${id}`,!1);this.sourceNavigation++;const current=this.sourceAuthority();return!await this.ensureSourceScene(`node:${id}`,current)||!current()?!1:this.focusSceneNode(id,options,current)}return!this.sourceMode&&this.graphColumns!==void 0&&(this.engineColumnsInvalid||this.view==="2d")?!1:this.focusSceneNode(id,options)}async focusSceneNode(id,options,currentSource=()=>!0){if(this.view!=="2d"){if(!this.isConnected||(await this.ensureSpatial(),!this.isConnected||this._view==="2d"||!currentSource()))return!1;const focused=this.spatial?.focusNode(id,options?.zoom);if(focused){const columnRow=this.sourceMode?void 0:this.engineColumns?.row(id),node2=columnRow===void 0?this.graphModel.nodes.find(candidate=>candidate.id===id):{id,label:this.engineColumns?.columns.labels?.[columnRow]};node2&&this.announcements.announcePolite(this.localize("graphNodeFocused",void 0,{label:this.nodeAccessibleText(node2)}))}return focused??!1}const node=this.simNodes.find(n=>n.id===id);if(!node||!this.d3||!this.zoomedEl||!this.zoomBehavior)return!1;const current=this.d3.zoomTransform(this.zoomedEl),bounds=this.effectiveZoomBounds,k=finiteRange(options?.zoom??current.k,current.k,bounds.min,bounds.max),arrived=await this.tweenCamera(()=>this.d3.zoomIdentity.translate(this.safeWidth/2-k*(node.x??0),this.safeHeight/2-k*(node.y??0)).scale(k));return arrived&&currentSource()&&(this.graphLiveText=this.localize("graphNodeFocused",void 0,{label:this.nodeAccessibleText(node)})),arrived&&currentSource()}fit(options){if(!this.sourceMode&&this.graphColumns!==void 0&&(this.engineColumnsInvalid||this.view==="2d"))return;if(this.view!=="2d"){this.spatial?this.spatial.fit(options?.padding):this.isConnected&&this.ensureSpatial().then(()=>this.updateComplete).then(()=>{this.isConnected&&this.view!=="2d"&&this.spatial?.fit(options?.padding)});return}if(!this.d3||!this.zoomedEl||!this.zoomBehavior||!this.simNodes.length)return;const padding=finiteRange(options?.padding??24,24,0);this.tweenCamera(()=>{const fitPoints=[];for(const n of this.simNodes){const r=this.nodeRadius(n);fitPoints.push({x:(n.x??0)-r,y:(n.y??0)-r}),fitPoints.push({x:(n.x??0)+r,y:(n.y??0)+r})}for(const entry of this.visibleCommunities())for(const p of this.communityHull(entry.members))fitPoints.push({x:p.x-HULL_PADDING,y:p.y-HULL_PADDING}),fitPoints.push({x:p.x+HULL_PADDING,y:p.y+HULL_PADDING});const{minX,maxX,minY,maxY}=extent(fitPoints,point=>point.x,point=>point.y),bounds=this.effectiveZoomBounds,transform=fitTransform({minX,minY,maxX,maxY},{width:this.safeWidth,height:this.safeHeight},padding,bounds);return this.d3.zoomIdentity.translate(transform.x,transform.y).scale(transform.zoom)})}updateFocusHalo(){if(!this.focusHaloEl)return;const node=this.focusNodeId!=null?this.simNodeById.get(this.focusNodeId):void 0;node?(this.focusHaloEl.setAttribute("cx",String(node.x??0)),this.focusHaloEl.setAttribute("cy",String(node.y??0)),this.focusHaloEl.setAttribute("r",String(this.nodeRadius(node)+FOCUS_HALO_PADDING)),this.focusHaloEl.removeAttribute("hidden")):this.focusHaloEl.setAttribute("hidden","")}setUpCanvasSurface(){this.canvasCtx=this.canvasEl.getContext("2d")??void 0,this.ensureCanvasOwnerRealm(),this.syncHostResizeObserver(),this.watchCanvasDpr(),this.canvasTooltipEl=this.renderRoot.querySelector('[part="tooltip"]')??void 0,this.bindCanvasPointer(),this.bindCanvasZoom()}ensureCanvasOwnerRealm(){const ownerDocument=this.ownerDocument;this.edgeLabelMeasureCanvas?.ownerDocument!==ownerDocument&&(this.edgeLabelMeasureCanvas=void 0,this.edgeLabelMeasureCtx=void 0,this.edgeLabelWidthCache.clear()),!(!this.pickCanvas&&this.renderer!=="canvas")&&this.pickCanvas?.ownerDocument!==ownerDocument&&(this.pickCanvas=ownerDocument.createElement("canvas"),this.pickCtx=this.pickCanvas.getContext("2d",{willReadFrequently:!0}),this.pickDirty=!0)}syncHostResizeObserver(){if(this.view!=="2d"||this.renderer!=="canvas"&&this.fitTo!=="container"){this.hostResizeObserver?.disconnect(),this.hostResizeObserver=void 0,this.hostResizeObserverDocument=void 0;return}this.hostResizeObserver&&this.hostResizeObserverDocument===this.ownerDocument||this.watchHostResize()}watchHostResize(){this.hostResizeObserver?.disconnect();const ResizeObserverCtor=this.ownerWindow?.ResizeObserver;if(!ResizeObserverCtor){this.hostResizeObserver=void 0,this.hostResizeObserverDocument=void 0;return}this.hostResizeObserver=new ResizeObserverCtor(entries=>{const box=entries[entries.length-1]?.contentRect;this.fitTo==="container"&&box&&this.recordContainerSize(box.width,box.height),this.renderer==="canvas"&&this.canvasEl&&this.markCanvasDirty()}),this.hostResizeObserverDocument=this.ownerDocument,this.hostResizeObserver.observe(this)}watchCanvasDpr(){this.canvasDprQuery?.removeEventListener("change",this.onCanvasDprChange);const view=this.ownerWindow;if(!view?.matchMedia){this.canvasDprQuery=void 0;return}this.canvasDprQuery=view.matchMedia(`(resolution: ${view.devicePixelRatio}dppx)`),this.canvasDprQuery.addEventListener("change",this.onCanvasDprChange)}markCanvasDirty(){this.canvasScene=void 0,this.pickDirty=!0,this.scheduleCanvasDraw()}markCanvasCameraDirty(){this.pickDirty=!0,this.scheduleCanvasDraw()}scheduleCanvasDraw(){if(this.view!=="2d")return;if(!this.visible){this.canvasDrawPending=!0;return}if(this.canvasDrawRafId!=null)return;const frameOwner=this.ownerWindow;frameOwner&&(this.canvasDrawRafOwner=frameOwner,this.canvasDrawRafId=frameOwner.requestAnimationFrame(()=>{this.canvasDrawRafId=void 0,this.canvasDrawRafOwner=void 0,!(!this.isConnected||this.ownerWindow!==frameOwner)&&this.drawCanvas()}))}resolveCssColorWithProbe(value,probe){const cached=this.resolvedCssColorCache.get(value);if(cached!==void 0)return cached;probe.style.color="",probe.style.color=value;const result=getComputedStyle(probe).color.trim()||getComputedStyle(this).color||"transparent";return this.resolvedCssColorCache.set(value,result),result}createCanvasColorProbe(){const probe=this.ownerDocument.createElement("span");return probe.setAttribute("aria-hidden","true"),probe.style.position="absolute",probe.style.inlineSize="0",probe.style.blockSize="0",probe.style.overflow="hidden",probe.style.visibility="hidden",probe.style.pointerEvents="none",this.renderRoot.append(probe),probe}withCanvasColorResolver(callback){let probe;try{return callback(value=>{const cached=this.resolvedCssColorCache.get(value);return cached!==void 0?cached:(probe??=this.createCanvasColorProbe(),this.resolveCssColorWithProbe(value,probe))})}finally{probe?.remove()}}refreshCanvasGeometry(scene){for(let i=0;i<this.simNodes.length;i++){const node=this.simNodes[i];scene.nodes[i].x=node.x??0,scene.nodes[i].y=node.y??0}for(let i=0;i<this.simLinks.length;i++)Object.assign(scene.links[i],this.linkCoordinates(this.simLinks[i]));for(let i=0;i<this.canvasLabelNodes.length;i++){const node=this.canvasLabelNodes[i];scene.nodeLabels[i].x=(node.x??0)+this.nodeRadius(node)+2,scene.nodeLabels[i].y=node.y??0}for(let i=0;i<this.canvasExpandableNodes.length;i++){const node=this.canvasExpandableNodes[i],indicator=scene.expandIndicators[i];indicator.x=node.x??0,indicator.y=node.y??0}const communities=this.visibleCommunities();for(let i=0;i<communities.length;i++)scene.hulls[i].d=hullPathD(this.communityHull(communities[i].members));const focus=this.focusNodeId==null?void 0:this.simNodeById.get(this.focusNodeId);if(focus&&scene.focusHalo&&(scene.focusHalo.x=focus.x??0,scene.focusHalo.y=focus.y??0),scene.edgeLabels.length=0,this.withEdgeLabels&&this.canvasCamera.k>=this.safeEdgeLabelMinZoom)for(const link of this.simLinks){const label=ownGraphText(link,"label");if(!label)continue;const coordinates=this.linkCoordinates(link);this.edgeLabelWidth(label)>Math.hypot(coordinates.x2-coordinates.x1,coordinates.y2-coordinates.y1)*EDGE_LABEL_LENGTH_GATE_RATIO||scene.edgeLabels.push({...this.edgeLabelPosition(link),text:label})}}buildCanvasScene(cs){return this.canvasLabelNodes=this.simNodes.filter(node=>!!ownGraphText(node,"label")),this.canvasExpandableNodes=this.simNodes.filter(node=>node.expandable),this.withCanvasColorResolver(resolveColor=>{const hullFillDefault=cs.getPropertyValue("--lr-graph-hull-fill").trim()||cs.getPropertyValue("--lr-color-brand").trim(),hulls=this.visibleCommunities().map(entry=>({d:hullPathD(this.communityHull(entry.members)),fill:resolveColor(sanitizeNodeColor(entry.community.color)??hullFillDefault)})),linkColorDefault=cs.getPropertyValue("--lr-graph-edge-color").trim()||cs.getPropertyValue("--lr-color-border").trim(),links=this.simLinks.map(l=>{const coords=this.linkCoordinates(l),own=sanitizeNodeColor(l.color);return{x1:coords.x1,y1:coords.y1,x2:coords.x2,y2:coords.y2,color:resolveColor(own??linkColorDefault),width:this.safeLinkWidth(l),dash:l.dash,directed:l.directed,selected:this.isSelected("link",this.linkKey(l)),dimmed:this.isDimmed("link",this.linkKey(l))}}),edgeLabels=this.withEdgeLabels&&this.canvasCamera.k>=this.safeEdgeLabelMinZoom?this.simLinks.flatMap(l=>{const label=ownGraphText(l,"label");if(!label)return[];const pos=this.edgeLabelPosition(l),coords=this.linkCoordinates(l),edgeLength=Math.hypot(coords.x2-coords.x1,coords.y2-coords.y1);return this.edgeLabelWidth(label)>edgeLength*EDGE_LABEL_LENGTH_GATE_RATIO?[]:[{x:pos.x,y:pos.y,text:label}]}):[],nodeFillDefault=cs.getPropertyValue("--lr-graph-node-fill").trim()||cs.getPropertyValue("--lr-color-brand").trim(),nodes=this.simNodes.map(n=>{const fill=this.nodeFill(n);return{x:n.x??0,y:n.y??0,r:this.nodeRadius(n),shape:this.nodeShape(n),fill:resolveColor(fill??nodeFillDefault),selected:this.isSelected("node",n.id),dimmed:this.isDimmed("node",n.id)}}),nodeLabels=this.simNodes.flatMap(n=>{const label=ownGraphText(n,"label");return label?[{x:(n.x??0)+this.nodeRadius(n)+2,y:n.y??0,text:label}]:[]}),expandIndicators=this.simNodes.filter(n=>n.expandable).map(n=>({x:n.x??0,y:n.y??0,r:this.nodeRadius(n)})),focusNode=this.focusNodeId!=null?this.simNodeById.get(this.focusNodeId):void 0,scene={hulls,links,edgeLabels,nodes,nodeLabels,expandIndicators,focusHalo:focusNode?{x:focusNode.x??0,y:focusNode.y??0,r:this.nodeRadius(focusNode)+FOCUS_HALO_PADDING}:void 0,showNodeLabels:this.canvasNodeLabelsVisible(),haloColor:resolveColor(this.ownerWindow?.matchMedia?.("(forced-colors: active)").matches?"CanvasText":cs.getPropertyValue("--lr-graph-focus-halo-color").trim()||cs.getPropertyValue("--lr-color-brand").trim()),selectedColor:resolveColor(cs.getPropertyValue("--lr-graph-selected-color").trim()||cs.getPropertyValue("--lr-color-success").trim()),dimmedOpacity:(()=>{const value=Number(cs.getPropertyValue("--lr-graph-dimmed-opacity").trim());return Number.isFinite(value)?Math.min(1,Math.max(0,value)):.35})(),hullOpacity:(()=>{const value=Number(cs.getPropertyValue("--lr-graph-hull-opacity").trim());return Number.isFinite(value)?Math.min(1,Math.max(0,value)):.12})(),labelColor:resolveColor(cs.getPropertyValue("--lr-color-text").trim()),labelHaloColor:resolveColor(cs.getPropertyValue("--lr-graph-edge-label-halo").trim()||cs.getPropertyValue("--lr-color-surface").trim()),expandBadgeFill:resolveColor(cs.getPropertyValue("--lr-color-surface").trim()),expandBadgeStroke:resolveColor(cs.getPropertyValue("--lr-color-border-strong").trim()),font:`${this.edgeLabelFontPx()}px ${cs.getPropertyValue("--lr-font").trim()||"sans-serif"}`,borderWidths:["thin","medium","thick"].map((size,index)=>resolveCssTokenLength(cs.getPropertyValue(`--lr-border-width-${size}`).trim(),{host:this})??index+1)};return this.canvasNodesById=new Map(this.simNodes.map((node,index)=>[node.id,scene.nodes[index]])),this.canvasLinksById=new Map(this.simLinks.map((link,index)=>[this.linkKey(link),scene.links[index]])),this.updateCanvasFocus(scene),scene})}updateCanvasFocus(scene){const index=shadowFocusTarget(this)?.getAttribute("part")==="cursor-item"?this.normalizedGraphItem():-1,node=index>=0&&index<this.linkIndexBase()?this.simNodes[index]:void 0,link=index>=this.linkIndexBase()&&index<this.communityIndexBase()?this.navigableLinks()[index-this.linkIndexBase()]:void 0,community=index>=this.communityIndexBase()?this.visibleCommunities()[index-this.communityIndexBase()]:void 0;scene.keyboardFocusRing=node?{x:node.x??0,y:node.y??0,r:this.nodeRadius(node)+4}:void 0,scene.keyboardFocusLink=link?{...this.linkCoordinates(link),width:this.safeLinkWidth(link)}:void 0,scene.keyboardFocusHull=community?{d:hullPathD(this.communityHull(community.members))}:void 0}drawCanvas(){if(!this.canvasEl||!this.canvasCtx)return;const dpr=this.ownerWindow?.devicePixelRatio||1,w=this.canvasEl.clientWidth||this.safeWidth,h=this.canvasEl.clientHeight||this.safeHeight,backingW=Math.round(w*dpr),backingH=Math.round(h*dpr);(this.canvasEl.width!==backingW||this.canvasEl.height!==backingH)&&(this.canvasEl.width=backingW,this.canvasEl.height=backingH);const ctx=this.canvasCtx;ctx.setTransform(dpr,0,0,dpr,0,0),ctx.clearRect(0,0,w,h);const edgeLabelsVisible=this.withEdgeLabels&&this.canvasCamera.k>=this.safeEdgeLabelMinZoom,nodeLabelsVisible=this.canvasNodeLabelsVisible();(!this.canvasScene||this.canvasScene.showNodeLabels!==nodeLabelsVisible||this.canvasSceneHasEdgeLabels!==edgeLabelsVisible)&&(this.canvasScene=this.buildCanvasScene(this.computedStyle()),this.canvasSceneHasEdgeLabels=edgeLabelsVisible),this.updateCanvasFocus(this.canvasScene),drawGraphScene(ctx,this.canvasCamera,this.canvasScene,{width:w,height:h})}rebuildPickItems(){this.pickItems=[...this.visibleCommunities().map(entry=>({kind:"hull",entry})),...this.navigableLinks().map(link=>({kind:"link",link})),...this.simNodes.map(node=>({kind:"node",node}))]}redrawPickCanvas(){if(!this.pickCtx||!this.canvasEl||!this.pickCanvas)return;(this.pickCanvas.width!==this.canvasEl.width||this.pickCanvas.height!==this.canvasEl.height)&&(this.pickCanvas.width=this.canvasEl.width,this.pickCanvas.height=this.canvasEl.height),this.rebuildPickItems();const dpr=this.ownerWindow?.devicePixelRatio||1;this.pickCtx.setTransform(dpr,0,0,dpr,0,0),drawPickingScene(this.pickCtx,this.canvasCamera,{hulls:this.pickItems.filter(i=>i.kind==="hull").map(i=>({d:hullPathD(this.communityHull(i.entry.members))})),links:this.pickItems.filter(i=>i.kind==="link").map(i=>{const c=this.linkCoordinates(i.link);return{x1:c.x1,y1:c.y1,x2:c.x2,y2:c.y2,width:this.safeLinkWidth(i.link)}}),nodes:this.pickItems.filter(i=>i.kind==="node").map(i=>({x:i.node.x??0,y:i.node.y??0,r:this.nodeRadius(i.node)+2,shape:this.nodeShape(i.node)}))}),this.pickDirty=!1}hitTest(clientX,clientY){if(!this.canvasEl||!this.pickCtx)return;this.pickDirty&&this.redrawPickCanvas();const rect=this.canvasEl.getBoundingClientRect(),dpr=this.ownerWindow?.devicePixelRatio||1,px=Math.round((clientX-rect.left)*dpr),py=Math.round((clientY-rect.top)*dpr);if(px<0||py<0||px>=this.pickCtx.canvas.width||py>=this.pickCtx.canvas.height)return;const data=this.pickCtx.getImageData(px,py,1,1).data,index=pickColorToIndex(data[0],data[1],data[2]);return index>=0?this.pickItems[index]:void 0}bindCanvasZoom(){if(!this.d3||!this.canvasEl)return;const bounds=this.effectiveZoomBounds,zoomBehavior=this.d3.zoom().scaleExtent([bounds.min,bounds.max]).on("start",()=>{this.isApplyingZoomTransform||(this.isPanning=!0,this.cancelCameraTween())}).on("zoom",event=>{this.canvasCamera={k:event.transform.k,x:event.transform.x,y:event.transform.y},this.markCanvasCameraDirty(),this.scheduleViewportChange()}).on("end",()=>{this.isPanning=!1});this.zoomBehavior=zoomBehavior,this.d3.select(this.canvasEl).call(zoomBehavior)}bindCanvasPointer(){const canvas=this.canvasEl;canvas.addEventListener("pointerdown",this.onCanvasPointerDown),canvas.addEventListener("pointermove",this.onCanvasPointerMove),canvas.addEventListener("pointerup",this.onCanvasPointerUp),canvas.addEventListener("pointercancel",this.onCanvasPointerCancel),canvas.addEventListener("lostpointercapture",this.onCanvasLostPointerCapture),canvas.addEventListener("pointerleave",this.onCanvasPointerLeave),canvas.addEventListener("dblclick",this.onCanvasDblClick)}simulationIsTicking(){return this.simulation!=null&&this.simulation.alpha()>this.simulation.alphaMin()}flushCanvasDrag(redraw=!0){this.canvasDragGeneration++,this.canvasDragFrame!==void 0&&this.canvasDragFrameOwner?.cancelAnimationFrame(this.canvasDragFrame),this.canvasDragFrame=void 0,this.canvasDragFrameOwner=void 0;const pending=this.pendingCanvasDrag;if(this.pendingCanvasDrag=void 0,!pending||!redraw||!this.isConnected||!this.canvasEl)return;const node=this.canvasDragNode&&this.simNodeById.get(this.canvasDragNode.id);if(!node)return;const rect=this.canvasEl.getBoundingClientRect();node.fx=(pending.x-rect.left-this.canvasCamera.x)/this.canvasCamera.k,node.fy=(pending.y-rect.top-this.canvasCamera.y)/this.canvasCamera.k,this.markCanvasCameraDirty()}finishCanvasNodeDrag(pointerId,releaseCapture=!0,redraw=!0){const activePointerId=this.canvasPointerId;if(activePointerId==null||pointerId!=null&&pointerId!==activePointerId)return;this.flushCanvasDrag(redraw);const node=this.canvasDragNode&&this.simNodeById.get(this.canvasDragNode.id);if(this.canvasDragNode=void 0,this.canvasPointerId=void 0,this.simulation?.alphaTarget(0),node){if(redraw&&this.isConnected&&node.fx!=null&&node.fy!=null){node.x=node.fx,node.y=node.fy,node.vx=0,node.vy=0;const position=this.lastPositionById.get(node.id);position&&(position.x=node.x,position.y=node.y)}node.fx=null,node.fy=null}if(releaseCapture&&this.canvasEl)try{this.canvasEl.releasePointerCapture(activePointerId)}catch{}redraw?this.markCanvasDirty():(this.canvasScene=void 0,this.pickDirty=!0)}takeCanvasPointerDown(pointerId){if(pointerId!=null&&this.canvasPointerDownId!==pointerId)return;const down=this.canvasPointerDownAt;return this.canvasPointerDownAt=void 0,this.canvasPointerDownId=void 0,down}canvasHoverSuppressed(){return!!this.canvasDragNode||this.isDragging||this.isPanning||this.isCameraTweening}updateCanvasHover(hit){const next=hit?.kind==="node"?{kind:"node",id:hit.node.id}:hit?.kind==="link"?{kind:"link",id:this.linkKey(hit.link),detail:this.linkHoverDetail(hit.link)}:void 0,previous=this.canvasHover;previous?.kind===next?.kind&&previous?.id===next?.id||(this.canvasHover=next,previous?.kind==="node"?this.emit("lr-node-leave",{nodeId:previous.id}):previous?.kind==="link"&&this.emitEdgeHover("leave",previous.detail),!(!this.isConnected||this.renderer!=="canvas"||this.canvasHover!==next)&&(next?.kind==="node"?this.emit("lr-node-enter",{nodeId:next.id}):next?.kind==="link"&&this.emitEdgeHover("enter",next.detail)))}nodeAtCanvasPoint(clientX,clientY){if(!this.canvasEl)return;const rect=this.canvasEl.getBoundingClientRect(),worldX=(clientX-rect.left-this.canvasCamera.x)/this.canvasCamera.k,worldY=(clientY-rect.top-this.canvasCamera.y)/this.canvasCamera.k;let closest,closestDistance=1/0;for(const node of this.simNodes){const distance=Math.hypot((node.x??0)-worldX,(node.y??0)-worldY);distance<=this.nodeRadius(node)+2/this.canvasCamera.k&&distance<closestDistance&&(closest=node,closestDistance=distance)}return closest}updateCanvasTooltip(hit,clientX,clientY){if(!this.canvasTooltipEl)return;if(!hit||hit.kind==="hull"){this.canvasTooltipEl.setAttribute("hidden","");return}const rect=this.canvasEl.getBoundingClientRect();this.canvasTooltipEl.textContent=hit.kind==="node"?this.nodeTooltipText(hit.node):this.linkTooltipText(hit.link);let left=clientX-rect.left,top=clientY-rect.top;this.canvasTooltipEl.style.left=`${left}px`,this.canvasTooltipEl.style.top=`${top}px`,this.canvasTooltipEl.removeAttribute("hidden");const tooltipRect=this.canvasTooltipEl.getBoundingClientRect(),view=this.ownerWindow;if(!view)return;const minLeft=Math.max(0,rect.left),maxRight=Math.min(view.innerWidth,rect.right),minTop=Math.max(0,rect.top),maxBottom=Math.min(view.innerHeight,rect.bottom);tooltipRect.right>maxRight&&(left-=tooltipRect.right-maxRight),tooltipRect.left<minLeft&&(left+=minLeft-tooltipRect.left),tooltipRect.bottom>maxBottom&&(top-=tooltipRect.bottom-maxBottom),tooltipRect.top<minTop&&(top+=minTop-tooltipRect.top),this.canvasTooltipEl.style.left=`${left}px`,this.canvasTooltipEl.style.top=`${top}px`}isSelected(kind,id){return identitySet(kind==="node"?this.selectedNodeIds:this.selectedEdgeIds).has(id)}paintedCurrent(kind,id){return this.selectionMode==="none"&&this.isSelected(kind,id)?"true":nothing}isDimmed(kind,id){return identitySet(kind==="node"?this.dimmedNodeIds:this.dimmedEdgeIds).has(id)}linkKey(link){return graphLinkIdentity(link)}emitSelectionIntent(kind,id,toggle){if(this.selectionMode==="none")return;const selected=this.isSelected(kind,id),time=this.ownerWindow?.performance.now()??0,repeat=this.lastActivation?.id===id&&time-this.lastActivation.time<=EXPAND_KEY_INTERVAL_MS;if(this.lastActivation={id,time},this.selectionMode==="single"||!toggle){if(this.selectionMode==="single"&&selected){repeat||this.emit("lr-selection-change",{selectedNodeIds:[],selectedEdgeIds:[]});return}this.emit("lr-selection-change",kind==="node"?{selectedNodeIds:[id],selectedEdgeIds:[]}:{selectedNodeIds:[],selectedEdgeIds:[id]});return}const selectedNodeIds=canonicalIdentityList(this.selectedNodeIds),selectedLinkIds=canonicalIdentityList(this.selectedEdgeIds),nodeIds=kind==="node"?selected?selectedNodeIds.filter(x=>x!==id):[...selectedNodeIds,id]:selectedNodeIds,linkIds=kind==="link"?selected?selectedLinkIds.filter(x=>x!==id):[...selectedLinkIds,id]:selectedLinkIds;this.emit("lr-selection-change",{selectedNodeIds:nodeIds,selectedEdgeIds:linkIds})}clearSelection(){this.selectionMode!=="none"&&(!canonicalIdentityList(this.selectedNodeIds).length&&!canonicalIdentityList(this.selectedEdgeIds).length||this.emit("lr-selection-change",{selectedNodeIds:[],selectedEdgeIds:[]}))}requestUpdate(...args){if(args[0]===void 0&&(this.explicitRefresh=!0,this.sourceEpoch=(this.sourceEpoch??0)+1,this.sourceNavigation=(this.sourceNavigation??0)+1),!this.sourceSyncing&&["sourcePage","sourcePageSize"].includes(String(args[0]))){this.sourceNavigation=(this.sourceNavigation??0)+1;const active=this.shadowRoot?.activeElement;this.sourceRestoreFocus=!!active&&!!this.shadowRoot?.querySelector('[part="source-navigator"]')?.contains(active),this.sourceRestorePager=active===this.shadowRoot?.querySelector(tag("pagination"))}(args[0]===void 0||["graphSource","sourcePage","sourcePageSize"].includes(String(args[0])))&&this.syncGraphSource(),super.requestUpdate(...args)}willUpdate(changed){this.syncGraphSource();const acceptedScene=this.sourceScene.state.scene,sourceSceneChanged=this.sourceMode&&(this.sourceModelScene!==acceptedScene||changed.has("graphSource")||changed.has("nodeTypes")||changed.has("communities"));if(sourceSceneChanged&&(this.sourceModelScene=acceptedScene,this.sourceModel=void 0,this.sourceModelVersion++),this.sourceMode&&this.sourcePages.state.result){try{this.assertSourceTotals(this.sourcePages.state.result.summary)}catch(error){this.sourceBindingError=error,this.sourceModel=void 0}this.sourcePage!==this.sourcePages.state.page&&(this.sourceSyncing=!0,this.sourcePage=this.sourcePages.state.page,this.sourceSyncing=!1,this.sourcePageInputs&&(this.sourcePageInputs=[this.sourcePage,...this.sourcePageInputs.slice(1)]))}if(this.sourceMode){const records=this.sourcePages.state,recordStatus=this.sourceBindingError||records.error||records.selectionError?"error":records.pending?"loading":"ready";this.announcements.transition("source-records",recordStatus,recordStatus==="error"?this.localize("graphSourceRecordsError"):recordStatus==="loading"?this.localize("loading"):"");const scene=this.sourceScene.state,sceneStatus=this.sourceBindingError||scene.error?"error":scene.pending?"loading":"ready";this.announcements.transition("source-scene",sceneStatus,sceneStatus==="error"?this.localize("graphSourceSceneError"):sceneStatus==="loading"?this.localize("loading"):"")}this.sourceMode&&!this.sourceComposition.profile?.empty&&changed.has("view")&&this.view!=="list"&&!this.sourceScene.state.scene&&!this.sourceScene.state.pending&&!this.sourceBindingError&&this.sourceScene.request({mode:"neighborhood",centerKey:this.sourceCenter,bounds:null,includeKeys:this.sourceKeys}),changed.has("view")&&(this.spatialGeneration++,this.spatialLoad=void 0,this.view!=="2d"&&(this.layeredGeneration++,this.layeredLoad=void 0)),(this.optionalLoadFailure==="spatial"&&this.view==="2d"||this.optionalLoadFailure==="layered"&&(this.view!=="2d"||this.layout!=="layered"))&&(this.optionalLoadFailure=void 0),this.loadFailed=this.view!=="2d"?this.optionalLoadFailure==="spatial":this.d3LoadFailed||this.layout==="layered"&&this.optionalLoadFailure==="layered",changed.has("layout")&&this.layout!=="layered"&&(this.layeredGeneration++,this.layeredLoad=void 0,this.view==="2d"&&(this.loading=!this.d3&&!this.loadFailed)),this.view!=="2d"&&!this.loadFailed&&!this.sourceList&&this.ensureSpatial(),this.view==="2d"&&this.layout==="layered"&&!this.loadFailed&&this.ensureLayered(),super.willUpdate(changed),changed.has("view")&&this.isConnected&&(this.view!=="2d"?(this.loadGeneration+=1,this.simulation?.stop(),this.cancelCameraTween(),this.finishCanvasNodeDrag(void 0,!0,!1),this.takeCanvasPointerDown(),this.canvasDrawRafId!=null&&this.canvasDrawRafOwner?.cancelAnimationFrame(this.canvasDrawRafId),this.canvasDrawRafId=void 0,this.canvasDrawRafOwner=void 0,this.hoverRafId!=null&&this.hoverRafOwner?.cancelAnimationFrame(this.hoverRafId),this.hoverRafId=void 0,this.hoverRafOwner=void 0,this.pendingHover=void 0,this.viewportChangeRafId!=null&&this.viewportChangeRafOwner?.cancelAnimationFrame(this.viewportChangeRafId),this.viewportChangeRafId=void 0,this.viewportChangeRafOwner=void 0,this.canvasDprQuery?.removeEventListener("change",this.onCanvasDprChange),this.canvasDprQuery=void 0,this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0,this.zoomedEl=void 0,this.gEl=void 0,this.boundNodeEls=new WeakSet,this.syncHostResizeObserver()):changed.get("view")!==void 0&&(this.spatial?.disconnect(),this.connect2d(),this.d3&&this.rebuildSimulation())),this.loading=this.view==="2d"&&!this.loadFailed&&(!this.d3||this.layout==="layered"&&!this.layeredEngine),changed.has("height")&&this.syncRequestedHeightVar(),changed.has("fitTo")&&this.fitTo!=="container"&&(this.containerSize=null),this.fitTo==="container"&&!this.containerSize&&this.measureHostBox();const cursorOnly=!this.explicitRefresh&&changed.size>0&&[...changed.keys()].every(key=>key==="activeGraphItem"||key==="graphLiveText");if(this.paintUpdate=this.explicitRefresh||![...changed.keys()].every(key=>["activeGraphItem","graphLiveText","selectedNodeIds","selectedEdgeIds","dimmedNodeIds","dimmedEdgeIds","minZoom","maxZoom","camera","focusNodeId","selectionMode"].includes(String(key))),this.cursorUpdate=cursorOnly,this.paintUpdate)if(!this.explicitRefresh&&[...changed.keys()].every(key=>["width","height","containerSize","fitTo"].includes(String(key))))for(const value of this.resolvedCssColorCache.keys())/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\([\d\s.,%+/-]+\))$/i.test(value)||this.resolvedCssColorCache.delete(value);else this.resolvedCssColorCache.clear();if(this.explicitRefresh=!1,this.paintUpdate&&(this.navigableLinksCache=void 0),this.syncGraphHostRole(),!this.isMounting&&this.view==="2d"&&(changed.has("nodeRenderer")||changed.has("view"))&&this.nodeRenderer!=null&&this.scheduleAfterUpdate(()=>{this.isConnected&&this.view==="2d"&&this.nodeRenderer!=null&&this.announcements.announceAssertive(this.localize("graphCustomNodesUnavailable"))},"graph-custom-nodes-unavailable"),!this.isMounting&&this.view==="2d"&&(changed.has("glow")||changed.has("view"))&&this.glow===!0&&this.scheduleAfterUpdate(()=>{this.isConnected&&this.view==="2d"&&this.glow===!0&&this.announcements.announceAssertive(this.localize("graphGlowUnavailable"))},"graph-glow-unavailable"),this.view!=="2d"){this.spatial?.prepare(),this.focusNodeId==null?this.lastAppliedFocusNodeId=null:!this.sourceMode&&this.focusNodeId!==this.lastAppliedFocusNodeId&&this.spatial?.focusNode(this.focusNodeId)&&(this.lastAppliedFocusNodeId=this.focusNodeId),this.isMounting=!1;return}const wasMounting=this.isMounting;this.isMounting=!1;const hiddenTypesChanged=changed.has("hiddenTypes")&&!sameIds(canonicalIdentityList(changed.get("hiddenTypes")??[]),canonicalIdentityList(this.hiddenTypes)),structureChanged=this.d3&&(sourceSceneChanged||changed.has("sourceModelVersion")||!this.sourceMode&&(changed.has("nodes")||changed.has("edges"))||hiddenTypesChanged||changed.has("layout")||this.layout==="layered"&&changed.has("edgeDistance")),graphItemsChanged=!!(structureChanged||changed.has("simNodes")||changed.has("communities")),activePart=shadowFocusTarget(this)?.getAttribute("part")??"",hadGraphItemFocus=graphItemsChanged&&["node","link","hull","cursor-item"].includes(activePart),previousIndex=this.normalizedGraphItem(),previousIdentity=graphItemsChanged?this.graphItemIdentity(previousIndex):void 0;if(structureChanged&&this.isConnected){this.rebuildSimulation(),this.renderer==="svg"&&this.simNodes.length+this.simLinks.length>1e3&&devWarnOnce("lr-graph-svg-scale",'<lr-graph>: renderer="svg" draws every node and link as DOM; use renderer="canvas" above about 1,000 of them.');const hovered=this.svgHoverNodeId;hovered!=null&&!this.simNodeById.has(hovered)&&(this.svgHoverNodeId=void 0,this.emit("lr-node-leave",{nodeId:hovered})),this.canvasHover?.kind==="node"&&!this.simNodeById.has(this.canvasHover.id)&&this.updateCanvasHover(void 0),this.navigableLinksCache=void 0}if(graphItemsChanged){this.visibleCommunitiesCache=void 0;const retainedIndex=previousIdentity?this.graphItemIndex(previousIdentity):-1,nextIndex=retainedIndex>=0?retainedIndex:this.normalizedGraphItem(previousIndex);this.activeGraphItem=nextIndex>=0?nextIndex:0,hadGraphItemFocus&&(this.pendingGraphItemFocus=nextIndex>=0?nextIndex:"base",nextIndex>=0&&(this.graphLiveText=this.graphItemAnnouncement(nextIndex)))}const selectedNodeIdsChanged=changed.has("selectedNodeIds")&&!sameIds(changed.get("selectedNodeIds"),this.selectedNodeIds),selectedLinkIdsChanged=changed.has("selectedEdgeIds")&&!sameIds(changed.get("selectedEdgeIds"),this.selectedEdgeIds);(selectedNodeIdsChanged||selectedLinkIdsChanged)&&!wasMounting&&(this.graphLiveText=this.localize("graphSelectionCount",void 0,{count:getNumberFormat(this.effectiveLocale).format(canonicalIdentityList(this.selectedNodeIds).length+canonicalIdentityList(this.selectedEdgeIds).length)}))}updated(changed){if(super.updated(changed),this.publishSourceComposition(),this.sourceMode&&!this.sourcePages.state.pending&&this.sourceRestoreFocus){this.sourceRestoreFocus=!1;const target=this.sourceRestorePager?this.renderRoot.querySelector(tag("pagination")):void 0;if(this.sourceRestorePager=!1,target){const current=this.sourceAuthority();target.updateComplete.then(()=>{current()&&target.focus()})}else(this.renderRoot.querySelector("[data-source-key]")??this.renderRoot.querySelector('[part="source-navigator"]'))?.focus()}if(this.sourceMode&&this.focusNodeId&&this.focusNodeId!==this.lastAppliedFocusNodeId&&(!this.loading||this.view!=="2d")&&this.scheduleAfterUpdate(()=>{const id=this.focusNodeId;this.sourceMode&&id&&id!==this.lastAppliedFocusNodeId&&(!this.loading||this.view!=="2d")&&(this.lastAppliedFocusNodeId=id,this.focusNode(id))},"graph-source-focus"),!this.isConnected){for(const[key,previous]of changed)this.detachedGraphChanges.has(key)||this.detachedGraphChanges.set(key,previous);return}if(this.view!=="2d"){this.setAttribute("aria-busy","false"),this.spatial?.update(this.paintUpdate);return}this.setAttribute("aria-busy",String(this.loading));const announceGraphText=this.graphAnnouncementsReady&&changed.has("graphLiveText")&&this.graphLiveText!=="";if(!this.loading&&!this.loadFailed&&(this.graphAnnouncementsReady=!0),announceGraphText&&this.announcements.announcePolite(this.graphLiveText),changed.has("loadFailed")&&changed.get("loadFailed")!==void 0&&this.loadFailed&&this.announcements.announceAssertive(this.localize("graphMissingLibrary")),(changed.has("fitTo")||changed.has("renderer"))&&this.syncHostResizeObserver(),!this.d3)return;!changed.has("nodes")&&!changed.has("edges")&&!changed.has("hiddenTypes")&&((changed.has("width")||changed.has("height")||changed.has("containerSize")||changed.has("fitTo"))&&(this.simulation?.force("center",this.d3.forceCenter(this.safeWidth/2,this.safeHeight/2)),this.simulation?.alpha(.1).restart()),(changed.has("chargeStrength")||changed.has("edgeDistance"))&&(changed.has("chargeStrength")&&this.chargeForce?.strength(this.safeChargeStrength),changed.has("edgeDistance")&&this.linkForce?.distance(this.safeLinkDistance),this.simulation?.alpha(.3).restart())),this.applyInteractions(changed);const cursorOnly=this.cursorUpdate;if(this.renderer==="svg"){cursorOnly||(this.svgCursorItems=[...this.renderRoot.querySelectorAll('[part="node"]'),...this.renderRoot.querySelectorAll('[part="link"][tabindex]'),...this.renderRoot.querySelectorAll('[part="hull"]')]);const next=this.svgCursorItems[this.normalizedGraphItem()];this.svgCursorElement!==next&&this.svgCursorElement?.setAttribute("tabindex","-1"),next?.setAttribute("tabindex","0"),this.svgCursorElement=next}this.renderer==="canvas"&&cursorOnly?this.scheduleCanvasDraw():this.applyCanvasInteractions(changed),this.focusNodeId==null?this.lastAppliedFocusNodeId=null:!this.sourceMode&&this.focusNodeId!==this.lastAppliedFocusNodeId&&this.simNodeById.has(this.focusNodeId)&&(this.lastAppliedFocusNodeId=this.focusNodeId,this.focusNode(this.focusNodeId)),this.visible||this.simulation?.stop(),this.updateFocusHalo();const pendingFocus=this.pendingGraphItemFocus;pendingFocus!==void 0&&(this.pendingGraphItemFocus=void 0,pendingFocus==="base"?this.renderRoot.querySelector('[part="canvas"], [part="svg"]')?.focus():this.focusGraphItemElement(pendingFocus))}applyInteractions(changed){if(!this.d3||this.renderer!=="svg")return;const svgEl=this.renderRoot.querySelector("svg"),reboundSurface=svgEl&&svgEl!==this.zoomedEl;if(svgEl&&reboundSurface){this.syncHostResizeObserver(),this.canvasHover=void 0,this.zoomedEl=svgEl,this.gEl=this.renderRoot.querySelector("g"),this.focusHaloEl=this.renderRoot.querySelector('[part="focus-halo"]');const bounds=this.effectiveZoomBounds,zoomBehavior=this.d3.zoom().scaleExtent([bounds.min,bounds.max]).on("start",()=>{this.isApplyingZoomTransform||(this.isPanning=!0,this.cancelCameraTween())}).on("zoom",event=>{this.gEl?.setAttribute("transform",event.transform.toString()),this.updateHitAreaZoomScale(event.transform.k),this.updateEdgeLabelZoomGate(event.transform.k),this.updateNodeLabelZoomGate(event.transform.k),this.scheduleViewportChange()}).on("end",()=>{this.isPanning=!1});this.zoomBehavior=zoomBehavior,this.d3.select(svgEl).call(zoomBehavior),this.updateHitAreaZoomScale(1),this.updateEdgeLabelZoomGate(1),this.updateNodeLabelZoomGate(1)}else if(this.zoomBehavior&&(changed.has("minZoom")||changed.has("maxZoom"))){const bounds=this.effectiveZoomBounds;this.zoomBehavior.scaleExtent([bounds.min,bounds.max])}if(changed.has("nodeLabels")&&this.zoomedEl&&this.updateNodeLabelZoomGate(this.d3.zoomTransform(this.zoomedEl).k),!(reboundSurface||changed.has("simNodes")||changed.has("simLinks")||changed.has("nodeTypes")||changed.has("withEdgeLabels")||changed.has("nodeLabels")||changed.has("communities")))return;const nodeEls=Array.from(this.renderRoot.querySelectorAll('[part="node"]'));this.nodeEls=nodeEls,this.nodeHitEls=Array.from(this.renderRoot.querySelectorAll('[data-hit-area="node"]')),this.nodeLabelEls=nodeEls.map(el=>el.parentElement?.querySelector('[part="label"]')??null),this.expandIndicatorEls=nodeEls.map(el=>el.parentElement?.querySelector('[part="expand-indicator"]')??null),this.linkEls=Array.from(this.renderRoot.querySelectorAll('[part="link"]:not([data-dangling])')),this.linkHitEls=Array.from(this.renderRoot.querySelectorAll('[data-hit-area="link"]')),this.linkLabelEls=this.linkEls.map(el=>el.parentElement?.querySelector('[part="link-label"]')??null),this.linkLabelHiddenByLength=[],this.danglingLinkEls=Array.from(this.renderRoot.querySelectorAll('[part="link"][data-dangling]')),this.communityHullEls=Array.from(this.renderRoot.querySelectorAll('[part="hull"]')),this.communityHullHitEls=Array.from(this.renderRoot.querySelectorAll('[data-hit-area="hull"]')),this.communityLabelEls=Array.from(this.renderRoot.querySelectorAll('[part="community-label"]')),this.layout!=="layered"&&nodeEls.forEach((el,i)=>{const id=this.simNodes[i]?.id;if(id!=null)for(const dragTarget of[el,this.nodeHitEls[i]])!dragTarget||this.boundNodeEls.has(dragTarget)||(this.boundNodeEls.add(dragTarget),this.d3.select(dragTarget).call(this.d3.drag().on("start",event=>{this.isDragging=!0,event.sourceEvent?.stopPropagation(),event.active||this.simulation?.alphaTarget(.3).restart();const n=this.simNodeById.get(id);n&&(n.fx=n.x,n.fy=n.y)}).on("drag",event=>{const n=this.simNodeById.get(id);n&&(n.fx=event.x,n.fy=event.y)}).on("end",event=>{this.isDragging=!1,event.active||this.simulation?.alphaTarget(0);const n=this.simNodeById.get(id);n&&(n.fx=null,n.fy=null)})))})}updateHitAreaZoomScale(zoom){const safeZoom=finiteRange(zoom,1,Number.EPSILON);this.gEl?.style.setProperty("--_lr-graph-hit-area-scale",String(1/safeZoom))}applyCanvasInteractions(changed){if(this.renderer!=="canvas"||!this.canvasEl)return;this.canvasEl!==this.zoomedEl&&(this.zoomedEl=this.canvasEl,this.setUpCanvasSurface());const bounds=this.effectiveZoomBounds;if(this.zoomBehavior?.scaleExtent([bounds.min,bounds.max]),!this.paintUpdate&&this.canvasScene){for(const[property2,map,flag]of[["selectedNodeIds",this.canvasNodesById,"selected"],["selectedEdgeIds",this.canvasLinksById,"selected"],["dimmedNodeIds",this.canvasNodesById,"dimmed"],["dimmedEdgeIds",this.canvasLinksById,"dimmed"]]){if(!changed.has(property2))continue;const before=identitySet(changed.get(property2)??[]),after=identitySet(this[property2]);for(const id of before){const item=map.get(id);item&&(item[flag]=after.has(id))}for(const id of after){const item=map.get(id);item&&(item[flag]=!0)}}if(changed.has("focusNodeId")){const node=this.focusNodeId==null?void 0:this.simNodeById.get(this.focusNodeId);this.canvasScene.focusHalo=node?{x:node.x??0,y:node.y??0,r:this.nodeRadius(node)+FOCUS_HALO_PADDING}:void 0}this.scheduleCanvasDraw()}else this.markCanvasDirty()}onTick(){for(const l of this.danglingLinks){const source=l.source,target=l.target;target.x=(source.x??0)+STUB_OFFSET_PX,target.y=(source.y??0)+STUB_OFFSET_PX}for(const n of this.simNodes)if(n.x!=null&&n.y!=null){const position=this.lastPositionById.get(n.id)??{x:n.x,y:n.y};position.x=n.x,position.y=n.y,this.lastPositionById.set(n.id,position)}if(this.renderer==="canvas"){this.canvasScene&&this.refreshCanvasGeometry(this.canvasScene),this.markCanvasCameraDirty(),this.scheduleViewportChange();return}this.simNodes.forEach((n,i)=>{const el=this.nodeEls[i];el&&(el.tagName==="circle"?(el.setAttribute("cx",String(n.x??0)),el.setAttribute("cy",String(n.y??0))):el.setAttribute("transform",`translate(${n.x??0},${n.y??0})`));const hit=this.nodeHitEls[i];hit&&(hit.setAttribute("x1",String((n.x??0)-NODE_HIT_SEGMENT_HALF)),hit.setAttribute("y1",String(n.y??0)),hit.setAttribute("x2",String((n.x??0)+NODE_HIT_SEGMENT_HALF)),hit.setAttribute("y2",String(n.y??0)));const label=this.nodeLabelEls[i];label&&(label.setAttribute("x",String((n.x??0)+this.nodeRadius(n)+2)),label.setAttribute("y",String(n.y??0)))}),this.simLinks.forEach((l,i)=>{const line=this.linkEls[i],coordinates=this.linkCoordinates(l);for(const target of[line,this.linkHitEls[i]])target&&(target.setAttribute("x1",String(coordinates.x1)),target.setAttribute("y1",String(coordinates.y1)),target.setAttribute("x2",String(coordinates.x2)),target.setAttribute("y2",String(coordinates.y2)))}),this.withEdgeLabels&&this.simLinks.forEach((l,i)=>{const labelEl=this.linkLabelEls[i];if(!labelEl)return;const label=ownGraphText(l,"label"),pos=this.edgeLabelPosition(l);labelEl.setAttribute("x",String(pos.x)),labelEl.setAttribute("y",String(pos.y));const{x1,y1,x2,y2}=this.linkCoordinates(l),edgeLength=Math.hypot(x2-x1,y2-y1),tooLong=this.edgeLabelWidth(label??"")>edgeLength*EDGE_LABEL_LENGTH_GATE_RATIO;this.linkLabelHiddenByLength[i]!==tooLong&&(this.linkLabelHiddenByLength[i]=tooLong,labelEl.setAttribute("visibility",tooLong?"hidden":"visible"))}),this.simNodes.forEach((n,i)=>{const indicator=this.expandIndicatorEls[i];indicator&&indicator.setAttribute("transform",`translate(${n.x??0},${n.y??0})`)}),this.danglingLinks.forEach((l,i)=>{const line=this.danglingLinkEls[i];if(!line)return;const coordinates=this.linkCoordinates(l);line.setAttribute("x1",String(coordinates.x1)),line.setAttribute("y1",String(coordinates.y1)),line.setAttribute("x2",String(coordinates.x2)),line.setAttribute("y2",String(coordinates.y2))}),this.updateFocusHalo(),this.visibleCommunities().forEach((entry,i)=>{const hullEl=this.communityHullEls[i],hullHitEl=this.communityHullHitEls[i],labelEl=this.communityLabelEls[i];if(!hullEl&&!hullHitEl&&!labelEl)return;const hull=this.communityHull(entry.members);hullEl&&hullEl.setAttribute("d",hullPathD(hull)),hullHitEl&&hullHitEl.setAttribute("d",hullPathD(hull)),labelEl&&(labelEl.setAttribute("x",String(hullCentroidX(hull))),labelEl.setAttribute("y",String(hullTopY(hull)-HULL_PADDING)))}),this.scheduleViewportChange()}rebuildSimulation(){if(this.view!=="2d"||!this.d3)return;this.simulation?.stop(),this.boundNodeEls=new WeakSet;const liveIds=new Set(this.graphModel.nodes.map(n=>n.id));for(const id of this.lastPositionById.keys())liveIds.has(id)||this.lastPositionById.delete(id);const visible=this.visibleNodes();if(this.layout==="layered"){if(!this.layeredEngine){this.ensureLayered();return}this.rebuildLayeredLayout(visible);return}const prevById=new Map(this.simNodes.map(n=>[n.id,n])),nodes=visible.map(n=>{const prev=prevById.get(n.id);if(prev)return{...prev,...n};const remembered=this.lastPositionById.get(n.id);return remembered?{...n,x:remembered.x,y:remembered.y}:{...n}}),byId=new Map(nodes.map(n=>[n.id,n])),{resolved:resolvedLinks,dangling:danglingLinks}=this.resolveLinksAgainst(byId),links=resolvedLinks;this.danglingLinks=danglingLinks;const seedForSpawn=this.safeSeed,incidentLinks=new Map;if(nodes.some(n=>n.x!=null))for(const l of resolvedLinks)for(const id of new Set([l.source.id,l.target.id])){const incident=incidentLinks.get(id);incident?incident.push(l):incidentLinks.set(id,[l])}for(const n of nodes){if(n.x!=null&&n.y!=null)continue;const neighborLink=incidentLinks.get(n.id)?.find(l=>{const source2=l.source,target2=l.target;return source2.id===n.id&&target2.x!=null||target2.id===n.id&&source2.x!=null});if(!neighborLink)continue;const source=neighborLink.source,target=neighborLink.target,neighbor=source.id===n.id?target:source,jitterRadius=this.safeLinkDistance/2,angle=seedForSpawn!=null?hashNodeSeed(seedForSpawn,n.id)/4294967296*Math.PI*2:Math.random()*Math.PI*2;n.x=(neighbor.x??0)+Math.cos(angle)*jitterRadius,n.y=(neighbor.y??0)+Math.sin(angle)*jitterRadius}if(seedForSpawn!=null)for(const n of nodes){if(n.x!=null&&n.y!=null)continue;const rng=mulberry32(hashNodeSeed(seedForSpawn,n.id));n.x=rng()*this.safeWidth,n.y=rng()*this.safeHeight}this.linkForce=this.d3.forceLink(links).distance(this.safeLinkDistance),this.chargeForce=this.d3.forceManyBody().strength(this.safeChargeStrength);const simulation=this.d3.forceSimulation(nodes).force("link",this.linkForce).force("charge",this.chargeForce).force("center",this.d3.forceCenter(this.safeWidth/2,this.safeHeight/2)).force("collide",this.d3.forceCollide().radius(n=>this.nodeRadius(n)+10)).on("tick",()=>this.onTick());if(this.simulation=simulation,this.visible||simulation.stop(),prefersReducedMotion(this)||this.safeSeed!=null){const pinnedForSettle=new Set;for(const n of nodes)(prevById.has(n.id)||this.lastPositionById.has(n.id))&&n.x!=null&&n.y!=null&&n.fx==null&&n.fy==null&&(n.fx=n.x,n.fy=n.y,pinnedForSettle.add(n.id));for(simulation.stop();simulation.alpha()>simulation.alphaMin();)simulation.tick();for(const n of nodes)pinnedForSettle.has(n.id)&&(n.fx=null,n.fy=null)}this.simNodes=nodes,this.simNodeById=byId,this.simLinks=links;for(const n of nodes)n.x!=null&&n.y!=null&&this.lastPositionById.set(n.id,{x:n.x,y:n.y});this.announceHiddenNodeCount(nodes.length)}announceHiddenNodeCount(visibleNodeCount){const totalNodeCount=this.graphModel.nodes.length,hiddenNodeCount=totalNodeCount-visibleNodeCount;totalNodeCount>0&&(hiddenNodeCount>0||this.lastHiddenNodeCount>0)&&(this.graphLiveText=this.localize("graphNodesHidden",void 0,{hidden:getNumberFormat(this.effectiveLocale).format(hiddenNodeCount),total:getNumberFormat(this.effectiveLocale).format(totalNodeCount)})),this.lastHiddenNodeCount=hiddenNodeCount}rebuildLayeredLayout(visible){const boxes=visible.map(n=>{const r=this.nodeRadius(n);return{id:n.id,width:r*2,height:r*2}}),visibleIds=new Set(visible.map(n=>n.id)),edges=this.graphModel.links.filter(l=>visibleIds.has(l.source)&&visibleIds.has(l.target)).map(l=>({source:l.source,target:l.target})),{positions:raw}=this.layeredEngine({nodes:boxes,edges,options:{gapX:12,gapY:this.safeLinkDistance}}),bounds=extent(raw.values(),point=>point.x,point=>point.y),offsetX=raw.size?this.safeWidth/2-(bounds.minX+(bounds.maxX-bounds.minX)/2):this.safeWidth/2,offsetY=raw.size?this.safeHeight/2-(bounds.minY+(bounds.maxY-bounds.minY)/2):this.safeHeight/2,nodes=visible.map(n=>{const p=raw.get(n.id);return{...n,x:p.x+offsetX,y:p.y+offsetY}}),byId=new Map(nodes.map(n=>[n.id,n])),{resolved,dangling}=this.resolveLinksAgainst(byId);this.danglingLinks=dangling,this.simulation=void 0,this.simNodes=nodes,this.simNodeById=byId,this.simLinks=resolved;for(const n of nodes)n.x!=null&&n.y!=null&&this.lastPositionById.set(n.id,{x:n.x,y:n.y});this.announceHiddenNodeCount(nodes.length)}selectionActionAuthority(){if(!this.sourceMode){const columns=this.graphColumns;return columns===void 0?()=>!0:()=>!this.sourceMode&&this.graphColumns===columns&&!this.engineColumnsInvalid}const current=this.sourceAuthority(),nodes=this.selectedNodeIds,edges=this.selectedEdgeIds;return()=>current()&&nodes===this.selectedNodeIds&&edges===this.selectedEdgeIds}onNodeClick(node,e){if(this.sourceDiagramBlocked)return;const current=this.selectionActionAuthority(),detail={nodeId:node.id,x:node.x??0,y:node.y??0};this.emit("lr-node-activate",{...detail}),current()&&this.emitSelectionIntent("node",node.id,!!(e?.ctrlKey||e?.metaKey))}getNodePosition(id){if(!this.sourceMode&&this.graphColumns!==void 0&&(this.engineColumnsInvalid||this.view==="2d"))return;if(this.view!=="2d"){const position=this.getNodePosition3d(id);return position?{x:position.x,y:position.y}:void 0}const node=this.simNodes.find(candidate=>candidate.id===id);if(!(!node||!Number.isFinite(node.x)||!Number.isFinite(node.y)))return{x:node.x,y:node.y}}getNodePosition3d(id){if(!this.sourceMode&&this.graphColumns!==void 0&&this.engineColumnsInvalid||this.view==="2d")return;if(this.spatial)return this.spatial.position(id);if(!this.sourceMode&&this.engineColumns){const row=this.engineColumns.row(id),positions=this.engineColumns.data.positions;return row===void 0?void 0:positions?Object.freeze({x:positions[row*3],y:positions[row*3+1],z:positions[row*3+2]}):spatialNodePosition({id})}const node=this.visibleNodes().find(candidate=>candidate.id===id);return node?spatialNodePosition(node):void 0}getNodeScreenPosition(id){if(!this.sourceMode&&this.graphColumns!==void 0&&(this.engineColumnsInvalid||this.view==="2d"))return;if(this.view!=="2d")return this.spatial?.screenPosition(id);const position=this.getNodePosition(id);if(!position||!this.zoomedEl||!this.d3)return;const hostRect=this.getBoundingClientRect(),rect=this.zoomedEl.getBoundingClientRect(),camera=this.d3.zoomTransform(this.zoomedEl),x=position.x*camera.k+camera.x,y=position.y*camera.k+camera.y;if("getScreenCTM"in this.zoomedEl){const matrix=this.zoomedEl.getScreenCTM();return matrix?{x:matrix.a*x+matrix.c*y+matrix.e-hostRect.left,y:matrix.b*x+matrix.d*y+matrix.f-hostRect.top}:void 0}return{x:rect.left-hostRect.left+x,y:rect.top-hostRect.top+y}}onLinkClick(link,e){if(this.sourceDiagramBlocked)return;const source=typeof link.source=="object"?link.source.id:String(link.source),target=typeof link.target=="object"?link.target.id:String(link.target),current=this.selectionActionAuthority();this.emit("lr-edge-activate",{sourceNodeId:source,targetNodeId:target,...link.id?{edgeId:link.id}:{}}),current()&&this.emitSelectionIntent("link",this.linkKey(link),!!(e?.ctrlKey||e?.metaKey))}onNodeEnter(node,e){this.isDragging||this.isPanning||this.isCameraTweening||(e.currentTarget.setAttribute("data-hovered",""),this.svgHoverNodeId=node.id,this.emit("lr-node-enter",{nodeId:node.id}))}onNodeLeave(node,e){this.isDragging||this.isPanning||this.isCameraTweening||(e.currentTarget.removeAttribute("data-hovered"),this.svgHoverNodeId=void 0,this.emit("lr-node-leave",{nodeId:node.id}))}onNodeDblClick(node,e){e.stopPropagation(),this.emit("lr-node-expand",{nodeId:node.id})}onLinkEnter(link,e){this.isDragging||this.isPanning||this.isCameraTweening||(e.currentTarget.setAttribute("data-hovered",""),this.emitEdgeHover("enter",this.linkHoverDetail(link)))}linkHoverDetail(link){const source=typeof link.source=="object"?link.source.id:String(link.source),target=typeof link.target=="object"?link.target.id:String(link.target);return{sourceNodeId:source,targetNodeId:target,...link.id?{edgeId:link.id}:{}}}onLinkLeave(link,e){this.isDragging||this.isPanning||this.isCameraTweening||(e.currentTarget.removeAttribute("data-hovered"),this.emitEdgeHover("leave",this.linkHoverDetail(link)))}emitEdgeHover(phase,detail){this.emit(phase==="enter"?"lr-edge-enter":"lr-edge-leave",{...detail})}nodeAccessibleText(node){let text=ownGraphText(node,"accessibleLabel")||ownGraphText(node,"label")||node.id;const type=this.resolveNodeType(node),typeLabel=type?ownGraphText(type,"label"):void 0;return typeLabel!==void 0&&(text=this.localize("graphTypedNode",void 0,{label:text,type:typeLabel})),node.expandable&&(text=this.localize("graphExpandableItem",void 0,{item:text})),text}boundedGraphText(value){if(typeof value!="string")return"";const normalized=value.replace(/\s+/g," ").trim();return normalized.length>512?`${normalized.slice(0,512)}…`:normalized}nodeTooltipText(node){return this.boundedGraphText(ownGraphText(node,"description")||ownGraphText(node,"label")||ownGraphText(node,"accessibleLabel")||node.id)}linkAccessibleText(link){const accessibleLabel=ownGraphText(link,"accessibleLabel");if(accessibleLabel)return accessibleLabel;const endpointText=endpoint=>typeof endpoint=="object"?this.nodeAccessibleText(endpoint):String(endpoint),source=endpointText(link.source),target=endpointText(link.target);return ownGraphText(link,"label")||this.localize("graphLink",void 0,{source,target})}linkTooltipText(link){return this.boundedGraphText(ownGraphText(link,"description")||ownGraphText(link,"label")||ownGraphText(link,"accessibleLabel")||this.linkAccessibleText(link))}linkCoordinates(link){const source=link.source,target=link.target,x1=source.x??0,y1=source.y??0,targetX=target.x??0,targetY=target.y??0;if(!link.directed||link.dangling)return{x1,y1,x2:targetX,y2:targetY};const dx=targetX-x1,dy=targetY-y1,distance=Math.hypot(dx,dy);if(distance===0)return{x1,y1,x2:targetX,y2:targetY};const inset=Math.min(this.nodeRadius(target),distance);return{x1,y1,x2:targetX-dx/distance*inset,y2:targetY-dy/distance*inset}}edgeLabelPosition(link){const{x1,y1,x2,y2}=this.linkCoordinates(link),dx=x2-x1,dy=y2-y1,len=Math.hypot(dx,dy),mx=(x1+x2)/2,my=(y1+y2)/2;return len===0?{x:mx,y:my}:{x:mx+-dy/len*EDGE_LABEL_OFFSET_PX,y:my+dx/len*EDGE_LABEL_OFFSET_PX}}edgeLabelFontPx(){const raw=this.computedStyle().getPropertyValue("--lr-font-size-2xs").trim();return resolveCssTokenLength(raw,{host:this})??DEFAULT_EDGE_LABEL_FONT_PX}edgeLabelContext(){return this.edgeLabelMeasureCanvas?.ownerDocument!==this.ownerDocument&&(this.edgeLabelMeasureCanvas=this.ownerDocument.createElement("canvas"),this.edgeLabelMeasureCtx=this.edgeLabelMeasureCanvas.getContext("2d")),this.edgeLabelMeasureCtx??null}edgeLabelWidth(text){const cached=this.edgeLabelWidthCache.get(text);if(cached!=null)return cached;const ctx=this.edgeLabelContext();let width;if(ctx){const fontFamily=this.computedStyle().getPropertyValue("--lr-font").trim()||"sans-serif";ctx.font=`${this.edgeLabelFontPx()}px ${fontFamily}`,width=ctx.measureText(text).width}else width=text.length*this.edgeLabelFontPx()*.6;if(this.edgeLabelWidthCache.size>=EDGE_LABEL_WIDTH_CACHE_MAX){const oldest=this.edgeLabelWidthCache.keys().next().value;oldest!==void 0&&this.edgeLabelWidthCache.delete(oldest)}return this.edgeLabelWidthCache.set(text,width),width}updateEdgeLabelZoomGate(k){this.gEl&&(k<this.safeEdgeLabelMinZoom?this.gEl.setAttribute("data-edge-labels-hidden",""):this.gEl.removeAttribute("data-edge-labels-hidden"))}updateNodeLabelZoomGate(k){this.gEl&&(this.resolvedNodeLabelsMode==="zoom"&&k<NODE_LABEL_MIN_ZOOM?this.gEl.setAttribute("data-node-labels-hidden",""):this.gEl.removeAttribute("data-node-labels-hidden"))}linkIndexBase(){return this.simNodes.length}communityIndexBase(){return this.linkIndexBase()+this.navigableLinks().length}graphItemCount(){return this.communityIndexBase()+this.visibleCommunities().length}normalizedGraphItem(index=this.activeGraphItem){const count=this.graphItemCount();return count?Math.min(Math.max(index,0),count-1):-1}graphItemIdentity(index){if(index<0)return;if(index<this.linkIndexBase()){const node=this.simNodes[index];return node?{kind:"node",id:node.id}:void 0}if(index<this.communityIndexBase()){const link=this.navigableLinks()[index-this.linkIndexBase()];return link?{kind:"link",id:this.linkKey(link)}:void 0}const community=this.visibleCommunities()[index-this.communityIndexBase()]?.community;return community?{kind:"community",id:community.id}:void 0}graphItemIndex(identity){if(identity.kind==="node")return this.simNodes.findIndex(node=>node.id===identity.id);if(identity.kind==="link"){const index2=this.navigableLinks().findIndex(link=>this.linkKey(link)===identity.id);return index2<0?-1:this.linkIndexBase()+index2}const index=this.visibleCommunities().findIndex(entry=>entry.community.id===identity.id);return index<0?-1:this.communityIndexBase()+index}communityText(community){return ownGraphText(community,"label")??community.id}graphItemText(index){if(index<this.linkIndexBase()){const node=this.simNodes[index];return node?this.localize("graphNode",void 0,{label:this.nodeTooltipText(node)}):""}if(index<this.communityIndexBase()){const link=this.navigableLinks()[index-this.linkIndexBase()];return link?this.linkTooltipText(link):""}const entry=this.visibleCommunities()[index-this.communityIndexBase()];return entry?this.localize("graphCommunity",void 0,{label:this.communityText(entry.community),count:getNumberFormat(this.effectiveLocale).format(entry.members.length)}):""}graphItemAnnouncement(index){return this.localize("graphItemAnnouncement",void 0,{item:this.graphItemText(index),index:getNumberFormat(this.effectiveLocale).format(index+1),total:getNumberFormat(this.effectiveLocale).format(this.graphItemCount())})}onGraphItemFocus(index){this.normalizedGraphItem(index)<0||(this.activeGraphItem=index,this.graphLiveText=this.graphItemAnnouncement(index))}focusGraphItem(index){const normalized=this.normalizedGraphItem(index);normalized<0||(this.activeGraphItem=normalized,this.graphLiveText=this.graphItemAnnouncement(normalized),this.updateComplete.then(()=>this.focusGraphItemElement(normalized)))}focusGraphItemElement(index){if(this.renderer==="canvas"){this.renderRoot.querySelector('[part="cursor-item"]')?.focus(),this.scheduleCanvasDraw();return}this.svgCursorItems[index]?.focus()}onGraphKeyDown(e,index,activate){if(e.key==="Enter"||e.key===" "){if(e.preventDefault(),e.repeat)return;if(this.onGraphItemFocus(index),activate(e),index<this.simNodes.length){const now=this.ownerWindow?.performance.now()??0;if(this.lastKeyActivateIndex===index&&now-this.lastKeyActivateTime<=EXPAND_KEY_INTERVAL_MS){const node=this.simNodes[index];node&&this.emit("lr-node-expand",{nodeId:node.id}),this.lastKeyActivateIndex=null}else this.lastKeyActivateIndex=index,this.lastKeyActivateTime=now}return}const count=this.graphItemCount();if(!count)return;const rtl=isRtl(this),forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";let next=index;if(e.key===forwardKey||e.key==="ArrowDown")next=Math.min(count-1,index+1);else if(e.key===backwardKey||e.key==="ArrowUp")next=Math.max(0,index-1);else if(e.key==="Home")next=0;else if(e.key==="End")next=count-1;else return;e.preventDefault(),this.focusGraphItem(next)}render(){if(this.sourceList||this.sourceMode&&this.sourceComposition.profile?.empty)return html`<div class="source-layout source-list">${this.renderSourceNavigator()}</div>`;const svg2=this.view==="2d"&&this.renderer==="svg",result=svg2&&this.cursorUpdate&&this.svgTemplate?this.svgTemplate:this.renderGraph();this.svgTemplate=svg2?result:void 0;const sceneState=this.sourceScene.state,bindingError=this.sourceBindingError,current=this.sourceAuthority(),retryScene=()=>{current()&&this.sourceScene.state===sceneState&&this.sourceBindingError===bindingError&&!sceneState.pending&&(sceneState.error||bindingError)&&this.requestUpdate()},diagram=this.sourceMode&&(this.sourceScene.state.pending||this.sourceScene.state.error||this.sourceBindingError)?html`<div part="source-status" aria-busy=${this.sourceScene.state.pending?"true":"false"}>${this.localize(this.sourceScene.state.pending?"loading":"graphSourceSceneError")}
24
+ </section>`}get graphModel(){if(this.sourceMode){if(!this.sourceModel){const scene=this.sourceBindingError?void 0:this.sourceScene.state.scene,nodes=Object.freeze(scene?.nodes.map(entry=>entry.value)??[]),ids=new Set(nodes.map(node=>node.id));this.sourceModel=Object.freeze({nodes,links:Object.freeze(scene?.edges.map(entry=>entry.value)??[]),nodeTypes:this.nodeTypes,communities:Object.freeze(this.communities.map(community=>Object.freeze({...community,memberIds:Object.freeze(community.memberIds.filter(id=>ids.has(id)))})))})}return this.sourceModel}const sources=this.normalizedGraphSources;return(!sources||sources[0]!==this.nodes||sources[1]!==this.edges||sources[2]!==this.nodeTypes||sources[3]!==this.communities)&&(this.normalizedGraphSources=[this.nodes,this.edges,this.nodeTypes,this.communities],this.normalizedGraphModel=normalizeGraphModel(this.nodes,this.edges,this.nodeTypes,this.communities)),this.normalizedGraphModel}get engine(){return this._engine}set engine(value){const old=this._engine;this._engine=ENGINE_3D_PREFERENCE.normalize(value),old===this._engine&&this.isConnected?(this.spatial?.retryEngine(),this.requestUpdate()):this.requestUpdate("engine",old)}get graphColumns(){return this._graphColumns}set graphColumns(value){const old=this._graphColumns;if(old!==value){if(this._graphColumns=value,this.engineColumns=void 0,this.engineColumnsInvalid=!1,value!==void 0){const result=admitGraphEngineColumns(value);result.ok?this.engineColumns=result.value:this.engineColumnsInvalid=!0}this.requestUpdate("graphColumns",old),this.engineColumnsInvalid&&this.scheduleAfterUpdate(()=>{this.isConnected&&this.graphColumns===value&&this.engineColumnsInvalid&&!this.sourceMode&&this.announcements.announceAssertive(this.localize("largeDataInvalid"))},"graph-columns-error")}}get view(){return this._view}set view(value){const next=GRAPH_VIEW.normalize(value),old=this._view;next!==old&&(this._view=next,this.requestUpdate("view",old))}get camera(){return this.engine==="webgl"?this._camera:this.builtinCamera}set camera(value){const old=this._camera;this._camera=value==null?void 0:graphWebglCamera(value,{yaw:0,pitch:0,distance:500,target:{x:0,y:0,z:0}}),this.builtinCamera=value==null?void 0:normalizeGraphCamera(value,{yaw:0,pitch:0,distance:500,target:{x:0,y:0,z:0}}),this.requestUpdate("camera",old)}get layout(){return this._layout}set layout(next){const normalized=GRAPH_LAYOUT.normalize(next),old=this._layout;old!==normalized&&(this._layout=normalized,this.requestUpdate("layout",old))}loadSpatialController(){return import("./graph-spatial-controller.js")}loadLayeredLayout(){return import("../../../internal/layered-layout.js")}ensureSpatial(){if(this.spatial||!this.isConnected||this.view==="2d"||this.sourceList)return Promise.resolve();if(this.spatialLoad)return this.spatialLoad;const generation=++this.spatialGeneration,pending=this.loadSpatialController().then(({GraphSpatialController})=>{generation!==this.spatialGeneration||!this.isConnected||this.view==="2d"||this.sourceList||(this.spatial=this.createSpatial(GraphSpatialController),this.optionalLoadFailure=void 0,this.loadFailed=!1,this.paintGraph())},()=>{generation===this.spatialGeneration&&this.isConnected&&this.view!=="2d"&&(this.optionalLoadFailure="spatial",this.loadFailed=!0,this.announcements.announceAssertive(this.localize("graphSpatialUnavailable")),this.paintGraph())}).finally(()=>{this.spatialLoad===pending&&(this.spatialLoad=void 0)});return this.spatialLoad=pending,pending}ensureLayered(){if(this.layeredEngine||!this.isConnected||this.view!=="2d"||this.layout!=="layered")return Promise.resolve();if(this.layeredLoad)return this.layeredLoad;const generation=++this.layeredGeneration;this.loading=!0;const pending=this.loadLayeredLayout().then(({layeredLayout})=>{generation!==this.layeredGeneration||!this.isConnected||this.view!=="2d"||this.layout!=="layered"||(this.layeredEngine=layeredLayout,this.optionalLoadFailure=void 0,this.loading=!this.d3,this.loadFailed=!1,this.d3&&this.rebuildSimulation(),this.paintGraph())},()=>{generation===this.layeredGeneration&&this.isConnected&&this.layout==="layered"&&(this.optionalLoadFailure="layered",this.loading=!1,this.loadFailed=!0)}).finally(()=>{this.layeredLoad===pending&&(this.layeredLoad=void 0)});return this.layeredLoad=pending,pending}async getUpdateComplete(){const complete=await super.getUpdateComplete(),pending=this.view!=="2d"?this.spatialLoad:this.layout==="layered"?this.layeredLoad:void 0;return pending&&(await pending,this.isUpdatePending)?super.getUpdateComplete():complete}createSpatial(Controller){return new Controller(this,{repaint:()=>this.paintGraph(),model:()=>this.graphModel,columns:()=>this.sourceMode?void 0:this.engineColumns,sourceMode:()=>this.sourceMode,engineFallback:detail=>{this.emit("lr-engine-fallback",detail),this.announcements.announceAssertive(`${this.localize(ENGINE_3D_REASON_MESSAGE[detail.reason])} ${this.localize(ENGINE_3D_SHOWING_MESSAGE[detail.to])}`)},engineMessage:key=>this.localize(key),nodeRenderError:detail=>{this.emit("lr-node-render-error",detail),this.announcements.announceAssertive(this.localize("graphCustomNodesError"))},effectNotice:key=>this.announcements.announceAssertive(this.localize(key==="graphGlowUnavailable"?"graphGlowUnavailable":"graphCustomNodesUnavailable")),categoryColors:()=>this.withCanvasColorResolver(resolve=>Array.from({length:8},(_,index)=>resolve(categoricalPaletteColor(index)))),locale:()=>this.effectiveLocale,direction:()=>this.effectiveDirection,pageText:values=>this.localize("graphSpatialPage",void 0,values),viewport:()=>({width:this.safeWidth,height:this.safeHeight}),messages:()=>this.spatialMessages(),communityText:values=>this.localize("graphCommunity",void 0,values),nodeText:node=>this.nodeAccessibleText(node),edgeText:edge=>this.linkAccessibleText(edge),nodeTooltip:node=>this.nodeTooltipText(node),edgeTooltip:edge=>this.linkTooltipText(edge),nodeShape:node=>this.nodeShape(node),paint:(nodes,edges)=>this.withCanvasColorResolver(resolve=>{const css=this.computedStyle(),nodeDefault=css.getPropertyValue("--lr-graph-node-fill").trim()||css.getPropertyValue("--lr-color-brand").trim(),edgeDefault=css.getPropertyValue("--lr-graph-edge-color").trim()||css.getPropertyValue("--lr-color-border").trim();return{nodes:new Map(nodes.map(({node})=>[node.id,resolve(this.nodeFill(node)??nodeDefault)])),edges:new Map(edges.map(edge=>[graphLinkIdentity(edge),resolve(sanitizeNodeColor(edge.color)??edgeDefault)])),visibleEdges:new Set(edges.filter(edge=>this.isInteractiveLink(edge,resolve,edgeDefault)).map(graphLinkIdentity)),text:resolve(css.getPropertyValue("--lr-color-text").trim()),selected:resolve(css.getPropertyValue("--lr-graph-selected-color").trim()||css.getPropertyValue("--lr-color-success").trim()),font:css.getPropertyValue("--lr-font").trim()||css.fontFamily,fontSize:this.edgeLabelFontPx(),dimmedOpacity:finiteRange(Number(css.getPropertyValue("--lr-graph-dimmed-opacity").trim()||.35),.35,0,1)}}),activate:(hit,event)=>{if(!this.sourceDiagramBlocked)if(hit.kind==="node"){const position=this.spatial?.position(hit.id);if(!position)return;const current=this.selectionActionAuthority();this.emit("lr-node-activate",{nodeId:hit.id,...position}),current()&&this.emitSelectionIntent("node",hit.id,event.ctrlKey||event.metaKey)}else this.onLinkClick(hit.edge,event)},expand:nodeId=>this.emit("lr-node-expand",{nodeId}),hover:(previous,next)=>{previous?.kind==="node"?this.emit("lr-node-leave",{nodeId:previous.id}):previous?.kind==="link"&&this.emitEdgeHover("leave",this.linkHoverDetail(previous.edge)),next?.kind==="node"?this.emit("lr-node-enter",{nodeId:next.id}):next?.kind==="link"&&this.emitEdgeHover("enter",this.linkHoverDetail(next.edge))},community:community=>this.onCommunityClick(community),cameraChanged:camera=>this.emit("lr-camera-change",{camera}),viewChanged:()=>this.emit("lr-view-change",{view:this.view}),unavailable:()=>this.announcements.announceAssertive(this.localize("graphSpatialUnavailable")),clearSelection:()=>this.clearSelection(),afterUpdate:(callback,key)=>this.scheduleAfterUpdate(callback,key)})}spatialMessages(){return{customError:this.localize("graphCustomNodesError"),customUnavailable:this.localize("graphCustomNodesUnavailable"),glowUnavailable:this.localize("graphGlowUnavailable"),controls:this.localize("graphSpatialControls"),view3d:this.localize("graphView3d"),viewList:this.localize("graphViewList"),fit:this.localize("graphFit"),left:this.localize("graphOrbitLeft"),right:this.localize("graphOrbitRight"),up:this.localize("graphOrbitUp"),down:this.localize("graphOrbitDown"),instructions:this.localize("graphSpatialInstructions"),unavailable:this.localize("graphSpatialUnavailable"),zoomIn:this.localize("zoomIn"),zoomOut:this.localize("zoomOut"),previous:this.localize("previous"),next:this.localize("next"),dataList:this.localize("graphDataList"),noData:this.localize("noData")}}constructor(){super(),this.sourceEpoch=0,this.sourceNavigation=0,this.sourceSyncing=!1,this.sourceQuery=EMPTY_SOURCE_QUERY,this.sourceCenter=null,this.sourceKeys=[],this.sourceMissing=!1,this.sourceRestoreFocus=!1,this.sourceRestorePager=!1,this.sourcePagePromise=Promise.resolve(!1),this.sourceState=0,this.sourceModelVersion=0,this.sourcePaint=0,this.sourceScene=new GraphSourceController(this,{onChange:()=>{this.sourceState++}}),this.sourcePages=new SourcePageController(this,{normalizeRecord:record=>record,normalizeSummary:value=>graphSourceSummary(value),validateMetadata:(result,query2)=>{const count=result.summary[query2.kind];if(result.total>count||!query2.search&&query2.centerKey===null&&!query2.nodeTypes.length&&result.total!==count||result.rows.some(row=>row.value.kind!==(query2.kind==="nodes"?"node":"edge")))throw new TypeError("Invalid global graph count or kind");this.assertSourceTotals(result.summary)},onChange:()=>{this.sourceState++}}),this.sourceComposition=new GraphSourceCompositionController(this,()=>{const profile=this.sourceComposition.profile;profile&&this.setSourceQuery({...EMPTY_SOURCE_QUERY,search:profile.search,nodeTypes:profile.nodeTypes}),this.sourceState++},async keys=>{if(!this.sourceMode||this.sourceComposition.profile?.empty)return;const profile=this.sourceComposition.profile,currentSource=this.sourceAuthority(),current=()=>currentSource()&&this.sourceComposition.profile===profile,records=await this.sourcePages.resolveSelection(keys);return records&&current()?Object.freeze({records,current}):void 0},async key=>{if(!this.sourceMode||this.sourceComposition.profile?.empty)return;const source=this.graphSource,epoch=this.sourceEpoch,profile=this.sourceComposition.profile;this.sourceNavigation++;const current=this.sourceAuthority();if((this.sourceScene.state.pending||!this.sourceScene.state.scene?.nodes.some(node=>node.key===key))&&(!await this.ensureSourceScene(key,current)||!current()))return;if(this.sourceList){if(![...this.renderRoot.querySelectorAll("[data-source-key]")].some(row=>row.dataset.sourceKey===key)&&!await this.revealSourceRecord(key,!1))return}else if(!await this.focusSceneNode(key.slice(5),void 0,current))return;const finalCurrent=this.sourceAuthority(),accepted=()=>finalCurrent()&&this.graphSource===source&&this.sourceEpoch===epoch&&this.sourceComposition.profile===profile;return accepted()?accepted:void 0}),this.sourcePage=0,this.sourcePageSize=100,this.nodes=[],this.edges=[],this.nodeTypes=[],this.hiddenTypes=[],this.communities=[],this.nodeRenderer=void 0,this.glow=!1,this._engine="builtin",this.engineColumnsInvalid=!1,this._view="2d",this._layout="force",this.renderer="svg",this.fitTo="none",this.width=800,this.height=600,this.chargeStrength=-300,this.edgeDistance=100,this.minZoom=.1,this.maxZoom=8,this.label=null,this.accessibleLabel=null,this.withEdgeLabels=!1,this.edgeLabelMinZoom=.6,this.focusNodeId=null,this.selectionMode="none",this.selectedNodeIds=[],this.selectedEdgeIds=[],this.dimmedNodeIds=[],this.dimmedEdgeIds=[],this.arrowMarkerId=nextId("graph-arrow"),this.loading=!0,this.loadFailed=!1,this.loadLibrary=loadD3,this.loadGeneration=0,this.containerSize=null,this.simNodes=[],this.simLinks=[],this.simNodeById=new Map,this.danglingLinks=[],this.lastPositionById=new Map,this.lastHiddenNodeCount=0,this.activeGraphItem=0,this.graphLiveText="",this.announcements=new AnnouncementSinkController(this,{eager:["polite","assertive"]}),this.graphAnnouncementsReady=!1,this.isMounting=!0,this.authorRole=null,this.syncingGraphHostRole=!1,this.detachedGraphChanges=new Map,this.boundNodeEls=new WeakSet,this.nodeEls=[],this.nodeHitEls=[],this.nodeLabelEls=[],this.expandIndicatorEls=[],this.lastKeyActivateIndex=null,this.lastKeyActivateTime=0,this.lastAppliedFocusNodeId=null,this.communityHullEls=[],this.communityHullHitEls=[],this.communityLabelEls=[],this.visible=!0,this.canvasDrawPending=!1,this.pickDirty=!0,this.canvasCamera={k:1,x:0,y:0},this.pickItems=[],this.canvasDragGeneration=0,this.canvasSceneHasEdgeLabels=!1,this.isCameraTweening=!1,this.linkEls=[],this.linkHitEls=[],this.linkLabelEls=[],this.linkLabelHiddenByLength=[],this.edgeLabelWidthCache=new Map,this.danglingLinkEls=[],this.linkPaintVisibilityCache=new Map,this.resolvedCssColorCache=new Map,this.reducedMotion=!1,this.spatialGeneration=0,this.layeredGeneration=0,this.d3LoadFailed=!1,this.isApplyingZoomTransform=!1,this.onCanvasDprChange=()=>{this.watchCanvasDpr(),this.markCanvasDirty()},this.canvasNodesById=new Map,this.canvasLinksById=new Map,this.canvasLabelNodes=[],this.canvasExpandableNodes=[],this.onCanvasPointerDown=e=>{if(e.button!==0||(this.canvasPointerDownAt={x:e.clientX,y:e.clientY},this.canvasPointerDownId=e.pointerId,this.layout==="layered"))return;const hit=this.hitTest(e.clientX,e.clientY);if(hit?.kind==="node"){this.canvasDragNode=hit.node,this.canvasPointerId=e.pointerId;try{this.canvasEl.setPointerCapture(e.pointerId)}catch{}hit.node.fx=hit.node.x,hit.node.fy=hit.node.y,this.simulation?.alphaTarget(.3).restart()}},this.onCanvasPointerMove=e=>{if(this.canvasDragNode&&this.canvasPointerId===e.pointerId){if(this.pendingCanvasDrag={x:e.clientX,y:e.clientY},this.canvasDragFrame===void 0){const owner=this.ownerWindow;if(owner){const generation=this.canvasDragGeneration;this.canvasDragFrameOwner=owner,this.canvasDragFrame=owner.requestAnimationFrame(()=>{generation===this.canvasDragGeneration&&this.flushCanvasDrag()})}}return}if(this.pendingHover={x:e.clientX,y:e.clientY},this.hoverRafId!=null)return;const frameOwner=this.ownerWindow;frameOwner&&(this.hoverRafOwner=frameOwner,this.hoverRafId=frameOwner.requestAnimationFrame(()=>{if(this.hoverRafId=void 0,this.hoverRafOwner=void 0,!this.isConnected||this.ownerWindow!==frameOwner)return;const pending=this.pendingHover;if(this.pendingHover=void 0,!pending||this.canvasHoverSuppressed()||this.pickDirty&&this.simulationIsTicking())return;const hit=this.hitTest(pending.x,pending.y);this.updateCanvasTooltip(hit,pending.x,pending.y),this.updateCanvasHover(hit)}))},this.onCanvasPointerUp=e=>{this.finishCanvasNodeDrag(e.pointerId);const down=this.takeCanvasPointerDown(e.pointerId);if(!down||Math.hypot(e.clientX-down.x,e.clientY-down.y)>5)return;const hit=this.hitTest(e.clientX,e.clientY);if(!hit){this.clearSelection();return}hit.kind==="node"?this.onNodeClick(hit.node,e):hit.kind==="link"?this.onLinkClick(hit.link,e):this.onCommunityClick(hit.entry.community)},this.onCanvasPointerCancel=e=>{this.finishCanvasNodeDrag(e.pointerId),this.takeCanvasPointerDown(e.pointerId)},this.onCanvasLostPointerCapture=e=>{this.finishCanvasNodeDrag(e.pointerId,!1),this.takeCanvasPointerDown(e.pointerId)},this.onCanvasPointerLeave=()=>{this.pendingHover=void 0,this.hoverRafId!=null&&(this.hoverRafOwner?.cancelAnimationFrame(this.hoverRafId),this.hoverRafId=void 0,this.hoverRafOwner=void 0),this.updateCanvasTooltip(void 0,0,0),this.canvasHoverSuppressed()?this.canvasHover=void 0:this.updateCanvasHover(void 0)},this.onCanvasDblClick=e=>{const hit=this.hitTest(e.clientX,e.clientY),node=hit?.kind==="node"?hit.node:this.nodeAtCanvasPoint(e.clientX,e.clientY);node&&(e.stopImmediatePropagation(),this.emit("lr-node-expand",{nodeId:node.id}))},this.explicitRefresh=!1,this.cursorUpdate=!1,this.paintUpdate=!0,this.svgCursorItems=[],this.isDragging=!1,this.isPanning=!1,new ThemeWatcher(this,()=>{const reduced=prefersReducedMotion(this);reduced!==this.reducedMotion&&(this.reducedMotion=reduced,reduced?this.simulation?.stop():this.visible&&this.view==="2d"&&this.safeSeed==null&&this.simulation?.restart()),this.linkPaintVisibilityCache.clear(),this.resolvedCssColorCache.clear(),this.view!=="2d"?this.spatial?.invalidate():this.renderer==="canvas"&&this.markCanvasDirty()},["(prefers-reduced-motion: reduce)"])}attributeChangedCallback(name,oldValue,value){super.attributeChangedCallback(name,oldValue,value),name==="role"&&oldValue!==value&&!this.syncingGraphHostRole&&(this.authorRole=value)}hostOwnsGraphSemantics(){return this.hasAttribute("aria-label")}syncGraphHostRole(){if(this.authorRole===null){this.syncingGraphHostRole=!0;try{this.hostOwnsGraphSemantics()?this.setAttribute("role","group"):this.removeAttribute("role")}finally{this.syncingGraphHostRole=!1}}}get ownerWindow(){return this.ownerDocument.defaultView??void 0}computedStyle(){const view=this.ownerWindow;return view?view.getComputedStyle(this):this.style}connectedCallback(){if(super.connectedCallback(),this.sourceInputs=void 0,this.syncGraphSource(),this.detachedGraphChanges.size){for(const[key,previous]of this.detachedGraphChanges)this.requestUpdate(key,previous);this.detachedGraphChanges.clear(),this.paintGraph()}this.reducedMotion=prefersReducedMotion(this);const IntersectionObserverCtor=this.ownerWindow?.IntersectionObserver;this.view==="2d"&&IntersectionObserverCtor&&(this.intersectionObserver=new IntersectionObserverCtor(entries=>{this.setGraphVisibility(entries[0]?.isIntersecting??!0)}),this.intersectionObserver.observe(this)),this.fitTo==="container"&&(this.syncHostResizeObserver(),this.measureHostBox()),this.view==="2d"?this.connect2d():(this.loading=!1,this.ensureSpatial(),this.paintGraph())}setGraphVisibility(visible){const wasVisible=this.visible;this.visible=visible,visible?wasVisible||(!this.reducedMotion&&this.safeSeed==null&&this.view==="2d"&&this.simulation&&this.simulation.alpha()>this.simulation.alphaMin()&&this.simulation.restart(),this.canvasDrawPending&&(this.canvasDrawPending=!1,this.scheduleCanvasDraw())):this.simulation?.stop()}connect2d(){const Observer=this.ownerWindow?.IntersectionObserver;if(!this.intersectionObserver&&Observer&&(this.intersectionObserver=new Observer(entries=>{this.setGraphVisibility(entries[0]?.isIntersecting??!0)}),this.intersectionObserver.observe(this)),this.d3){this.visible&&!this.reducedMotion&&this.safeSeed==null&&this.simulation?.restart(),this.renderer==="canvas"&&this.canvasEl&&this.canvasEl===this.zoomedEl&&(this.ensureCanvasOwnerRealm(),this.syncHostResizeObserver(),this.watchCanvasDpr(),this.markCanvasDirty());return}const generation=++this.loadGeneration,pending=this.loadLibrary().then(async mods=>{try{await super.getUpdateComplete()}catch{return}if(await new Promise(resolve=>this.updateBrowserDerivedState(resolve)),!(generation!==this.loadGeneration||!this.isConnected)){if(this.loading=!1,!mods){this.d3LoadFailed=!0,this.loadFailed=!0;return}this.d3LoadFailed=!1,this.loadFailed=!1,this.d3=mods,this.rebuildSimulation()}}).finally(()=>{this.libraryLoad===pending&&(this.libraryLoad=void 0)});this.libraryLoad=pending}disconnectedCallback(){this.sourceNavigation++,this.sourceEpoch++,this.sourceInputs=void 0,this.sourcePageInputs=void 0,super.disconnectedCallback(),this.spatialGeneration++,this.layeredGeneration++,this.spatialLoad=void 0,this.layeredLoad=void 0,this.spatial?.disconnect(),this.loadGeneration+=1,this.simulation?.stop(),this.finishCanvasNodeDrag(void 0,!0,!1),this.takeCanvasPointerDown(),this.cancelCameraTween(),this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0,this.hostResizeObserver?.disconnect(),this.hostResizeObserver=void 0,this.hostResizeObserverDocument=void 0,this.canvasDprQuery?.removeEventListener("change",this.onCanvasDprChange),this.canvasDprQuery=void 0,this.canvasDrawRafId!=null&&(this.canvasDrawRafOwner?.cancelAnimationFrame(this.canvasDrawRafId),this.canvasDrawRafId=void 0,this.canvasDrawRafOwner=void 0),this.hoverRafId!=null&&(this.hoverRafOwner?.cancelAnimationFrame(this.hoverRafId),this.hoverRafId=void 0,this.hoverRafOwner=void 0),this.pendingHover=void 0,this.canvasHover=void 0,this.canvasTooltipEl?.setAttribute("hidden",""),this.pendingGraphItemFocus=void 0,this.viewportChangeRafId!=null&&(this.viewportChangeRafOwner?.cancelAnimationFrame(this.viewportChangeRafId),this.viewportChangeRafId=void 0,this.viewportChangeRafOwner=void 0)}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted(),this.sourceEpoch++,this.sourceNavigation++,this.sourceInputs=void 0,this.sourceScene.adopted(),this.sourcePages.adopted(),this.sourceState++,this.ensureCanvasOwnerRealm()}scheduleViewportChange(){if(this.view!=="2d"||this.viewportChangeRafId!=null)return;const frameOwner=this.ownerWindow;frameOwner&&(this.viewportChangeRafOwner=frameOwner,this.viewportChangeRafId=frameOwner.requestAnimationFrame(()=>{if(this.viewportChangeRafId=void 0,this.viewportChangeRafOwner=void 0,!this.isConnected||this.ownerWindow!==frameOwner)return;const transform=this.renderer==="canvas"||!this.d3||!this.zoomedEl?this.canvasCamera:this.d3.zoomTransform(this.zoomedEl);this.emit("lr-viewport-change",{zoom:transform.k,x:transform.x,y:transform.y,k:transform.k})}))}nodeRadius(n){const r=n.radius??(MIN_RADIUS+MAX_RADIUS)/2;return Number.isFinite(r)?Math.min(MAX_RADIUS,Math.max(MIN_RADIUS,r)):(MIN_RADIUS+MAX_RADIUS)/2}safeLinkWidth(link){return finiteRange(link.width??1.5,1.5,0)}isInteractiveLink(link,resolveColor,defaultPaint){if(this.safeLinkWidth(link)<=0)return!1;const effectivePaint=sanitizeNodeColor(link.color)??defaultPaint,color=effectivePaint?resolveColor(effectivePaint).trim().toLowerCase():void 0;if(!color)return!0;if(color==="transparent"||/^#[\da-f]{4}$/.test(color)&&color.endsWith("0")||/^#[\da-f]{8}$/.test(color)&&color.endsWith("00")||/\/\s*0(?:\.0+)?%?\s*\)$/.test(color)||/^(?:rgba|hsla)\(/.test(color)&&/,\s*0(?:\.0+)?\s*\)$/.test(color))return!1;const cached=this.linkPaintVisibilityCache.get(color);if(cached!==void 0)return cached;this.linkPaintProbe??=this.ownerDocument.createElement("canvas"),this.linkPaintProbe.width=1,this.linkPaintProbe.height=1;const context=this.linkPaintProbe.getContext("2d",{willReadFrequently:!0});if(!context)return!0;let visible=!0;try{context.clearRect(0,0,1,1),context.fillStyle="rgb(1 2 3)",context.fillStyle=color,context.fillRect(0,0,1,1),visible=context.getImageData(0,0,1,1).data[3]!==0}catch{visible=!0}return this.linkPaintVisibilityCache.set(color,visible),visible}navigableLinks(){return this.navigableLinksCache||(this.navigableLinksCache=this.simLinks.length?this.withCanvasColorResolver(resolveColor=>{const computed=this.computedStyle(),defaultPaint=computed.getPropertyValue("--lr-graph-edge-color").trim()||computed.getPropertyValue("--lr-color-border").trim();return this.simLinks.filter(link=>this.isInteractiveLink(link,resolveColor,defaultPaint))}):[]),this.navigableLinksCache}lengthInPixels(value){return typeof value=="string"?resolveCssTokenLength(value,{host:this})??Number.NaN:value}get requestedWidth(){return finiteRange(this.lengthInPixels(this.width),800,1)}get requestedHeight(){return finiteRange(this.lengthInPixels(this.height),600,1)}get safeWidth(){const requested=this.requestedWidth,measured=this.fitTo==="container"&&this.containerSize;return measured?finiteRange(measured.width,requested,1):requested}get safeHeight(){const requested=this.requestedHeight,measured=this.fitTo==="container"&&this.containerSize;return measured?finiteRange(measured.height,requested,1):requested}recordContainerSize(width,height){const w=Math.round(finiteRange(width,0,0)),h=Math.round(finiteRange(height,0,0));return w<=0||h<=0||this.containerSize?.width===w&&this.containerSize?.height===h?!1:(this.containerSize={width:w,height:h},!0)}measureHostBox(){return this.isConnected?(this.syncRequestedHeightVar(),this.recordContainerSize(this.clientWidth,this.clientHeight)):!1}syncRequestedHeightVar(){this.style.setProperty("--_lr-graph-requested-height",`${this.requestedHeight}px`)}get safeMinZoom(){return finiteRange(this.minZoom,.1,.001,1e3)}get safeMaxZoom(){return finiteRange(this.maxZoom,8,.001,1e3)}get effectiveZoomBounds(){const min=this.safeMinZoom,max=this.safeMaxZoom;return Object.freeze({min:Math.min(min,max),max:Math.max(min,max)})}get safeEdgeLabelMinZoom(){return finiteRange(this.edgeLabelMinZoom,.6,.001,1e3)}get resolvedNodeLabelsMode(){return this.nodeLabels??(this.renderer==="canvas"?"zoom":"always")}canvasNodeLabelsVisible(){const mode=this.resolvedNodeLabelsMode;return mode==="none"?!1:mode==="zoom"?this.canvasCamera.k>=NODE_LABEL_MIN_ZOOM:!0}get safeSeed(){return this.seed==null?void 0:finiteInteger(this.seed,0)}get safeChargeStrength(){return finiteNumber(this.chargeStrength,-300)}get safeLinkDistance(){return finiteRange(this.edgeDistance,100,0)}nodeTypeEntry(node){const types=this.graphModel.nodeTypes;if(this.nodeTypeIndex?.[0]!==types){const labeled=this.labeledNodeTypes();this.nodeTypeIndex=[types,new Map(types.map((type,index)=>{const slot=labeled.indexOf(type);return[type.id,[type,slot<0?index:slot]]}))]}return node.type==null?void 0:this.nodeTypeIndex[1].get(node.type)}resolveNodeType(node){return this.nodeTypeEntry(node)?.[0]}nodeShape(node){return this.resolveNodeType(node)?.shape??"circle"}labeledNodeTypes(){return this.graphModel.nodeTypes.filter(candidate=>typeof candidate?.label=="string"&&candidate.label.trim().length>0)}nodeFill(node){const ownColor=sanitizeNodeColor(node.color);if(ownColor)return ownColor;const entry=this.nodeTypeEntry(node);if(entry)return sanitizeNodeColor(entry[0].color)||categoricalPaletteColor(entry[1])}visibleNodes(){const hiddenTypes=canonicalIdentityList(this.hiddenTypes);if(!hiddenTypes.length)return this.graphModel.nodes;const hidden=new Set(hiddenTypes);return this.graphModel.nodes.filter(n=>n.type==null||!hidden.has(n.type))}resolveLinksAgainst(byId){const nodeExists=new Set(this.graphModel.nodes.map(n=>n.id)),resolved=[],dangling=[];for(const l of this.graphModel.links){const source=byId.get(l.source);if(!source)continue;const target=byId.get(l.target);target?resolved.push(copyGraphLinkIdentity(l,{...l,source,target})):nodeExists.has(l.target)||dangling.push(copyGraphLinkIdentity(l,{...l,source,target:{id:l.target,x:source.x,y:source.y},dangling:!0}))}return{resolved,dangling}}visibleCommunities(){if(!this.visibleCommunitiesCache){const byCommunity=new Map,positions=new Map;this.simNodes.forEach((node,index)=>{if(positions.set(node.id,index),node.communityId!=null){const members=byCommunity.get(node.communityId);members?members.push(node):byCommunity.set(node.communityId,[node])}}),this.visibleCommunitiesCache=this.graphModel.communities.flatMap(community=>{const members=new Map;for(const node of byCommunity.get(community.id)??[])members.set(node.id,node);for(const id of community.memberIds??[]){const node=this.simNodeById.get(id);node&&members.set(id,node)}const ordered=[...members.values()].sort((a,b)=>positions.get(a.id)-positions.get(b.id));return ordered.length?[{community,members:ordered}]:[]})}return this.visibleCommunitiesCache}communityHull(members){return convexHull(members.map(n=>({x:n.x??0,y:n.y??0})))}onCommunityClick(community){this.emit("lr-community-activate",{communityId:community.id})}cameraTransitionMs(){const parsed=parseFloat(this.computedStyle().getPropertyValue("--lr-transition-base"));return Number.isFinite(parsed)?parsed:180}cancelCameraTween(){this.cameraTweenId!=null&&(this.cameraTweenFrameOwner?.cancelAnimationFrame(this.cameraTweenId),this.cameraTweenId=void 0,this.cameraTweenFrameOwner=void 0),this.isCameraTweening=!1;const resolve=this.cameraTweenResolve;resolve&&(this.cameraTweenResolve=void 0,resolve(!1))}applyZoomTransform(transform){if(!(!this.d3||!this.zoomedEl||!this.zoomBehavior)){this.isApplyingZoomTransform=!0;try{this.zoomBehavior.transform(this.d3.select(this.zoomedEl),transform)}finally{this.isApplyingZoomTransform=!1}}}tweenCamera(computeTarget){return new Promise(resolve=>{if(!this.d3||!this.zoomedEl||!this.zoomBehavior){resolve(!1);return}this.cancelCameraTween(),this.cameraTweenResolve=resolve,this.isCameraTweening=!0;const frameOwner=this.ownerWindow;if(!frameOwner){this.isCameraTweening=!1,this.cameraTweenResolve=void 0,resolve(!1);return}if(prefersReducedMotion(this)){this.applyZoomTransform(computeTarget()),this.isCameraTweening=!1,this.cameraTweenResolve=void 0,resolve(!0);return}const current=this.d3.zoomTransform(this.zoomedEl),duration=this.cameraTransitionMs(),start=frameOwner.performance.now(),startK=current.k,startX=current.x,startY=current.y,step=now=>{if(this.cameraTweenResolve!==resolve)return;if(!this.isConnected||this.ownerWindow!==frameOwner){this.cameraTweenId=void 0,this.cameraTweenFrameOwner=void 0,this.isCameraTweening=!1,this.cameraTweenResolve=void 0,resolve(!1);return}const t=!prefersReducedMotion(this)&&duration>0?Math.min(1,(now-start)/duration):1,target=computeTarget(),targetK=target.k,targetX=target.x,targetY=target.y;this.applyZoomTransform(this.d3.zoomIdentity.translate(startX+(targetX-startX)*t,startY+(targetY-startY)*t).scale(startK+(targetK-startK)*t)),t<1?(this.cameraTweenFrameOwner=frameOwner,this.cameraTweenId=frameOwner.requestAnimationFrame(step)):(this.cameraTweenId=void 0,this.cameraTweenFrameOwner=void 0,this.isCameraTweening=!1,this.cameraTweenResolve=void 0,resolve(!0))};this.cameraTweenFrameOwner=frameOwner,this.cameraTweenId=frameOwner.requestAnimationFrame(step)})}async focusNode(id,options){if(this.sourceMode){if(typeof id!="string"||!id.length||id.length+5>65536)return!1;if(this.sourceList)return this.revealSourceRecord(`node:${id}`,!1);this.sourceNavigation++;const current=this.sourceAuthority();return!await this.ensureSourceScene(`node:${id}`,current)||!current()?!1:this.focusSceneNode(id,options,current)}return!this.sourceMode&&this.graphColumns!==void 0&&(this.engineColumnsInvalid||this.view==="2d")?!1:this.focusSceneNode(id,options)}async focusSceneNode(id,options,currentSource=()=>!0){if(this.sourceMode&&this.view==="2d"&&this.libraryLoad&&(await this.libraryLoad,!currentSource()||!this.isConnected||this.view!=="2d"||(await this.updateComplete,!currentSource()||!this.isConnected||this.view!=="2d")))return!1;if(this.view!=="2d"){if(!this.isConnected||(await this.ensureSpatial(),!this.isConnected||this._view==="2d"||!currentSource()))return!1;const focused=this.spatial?.focusNode(id,options?.zoom);if(focused){const columnRow=this.sourceMode?void 0:this.engineColumns?.row(id),node2=columnRow===void 0?this.graphModel.nodes.find(candidate=>candidate.id===id):{id,label:this.engineColumns?.columns.labels?.[columnRow]};node2&&this.announcements.announcePolite(this.localize("graphNodeFocused",void 0,{label:this.nodeAccessibleText(node2)}))}return focused??!1}const node=this.simNodes.find(n=>n.id===id);if(!node||!this.d3||!this.zoomedEl||!this.zoomBehavior)return!1;const current=this.d3.zoomTransform(this.zoomedEl),bounds=this.effectiveZoomBounds,k=finiteRange(options?.zoom??current.k,current.k,bounds.min,bounds.max),arrived=await this.tweenCamera(()=>this.d3.zoomIdentity.translate(this.safeWidth/2-k*(node.x??0),this.safeHeight/2-k*(node.y??0)).scale(k));return arrived&&currentSource()&&(this.graphLiveText=this.localize("graphNodeFocused",void 0,{label:this.nodeAccessibleText(node)})),arrived&&currentSource()}fit(options){if(!this.sourceMode&&this.graphColumns!==void 0&&(this.engineColumnsInvalid||this.view==="2d"))return;if(this.view!=="2d"){this.spatial?this.spatial.fit(options?.padding):this.isConnected&&this.ensureSpatial().then(()=>this.updateComplete).then(()=>{this.isConnected&&this.view!=="2d"&&this.spatial?.fit(options?.padding)});return}if(!this.d3||!this.zoomedEl||!this.zoomBehavior||!this.simNodes.length)return;const padding=finiteRange(options?.padding??24,24,0);this.tweenCamera(()=>{const fitPoints=[];for(const n of this.simNodes){const r=this.nodeRadius(n);fitPoints.push({x:(n.x??0)-r,y:(n.y??0)-r}),fitPoints.push({x:(n.x??0)+r,y:(n.y??0)+r})}for(const entry of this.visibleCommunities())for(const p of this.communityHull(entry.members))fitPoints.push({x:p.x-HULL_PADDING,y:p.y-HULL_PADDING}),fitPoints.push({x:p.x+HULL_PADDING,y:p.y+HULL_PADDING});const{minX,maxX,minY,maxY}=extent(fitPoints,point=>point.x,point=>point.y),bounds=this.effectiveZoomBounds,transform=fitTransform({minX,minY,maxX,maxY},{width:this.safeWidth,height:this.safeHeight},padding,bounds);return this.d3.zoomIdentity.translate(transform.x,transform.y).scale(transform.zoom)})}updateFocusHalo(){if(!this.focusHaloEl)return;const node=this.focusNodeId!=null?this.simNodeById.get(this.focusNodeId):void 0;node?(this.focusHaloEl.setAttribute("cx",String(node.x??0)),this.focusHaloEl.setAttribute("cy",String(node.y??0)),this.focusHaloEl.setAttribute("r",String(this.nodeRadius(node)+FOCUS_HALO_PADDING)),this.focusHaloEl.removeAttribute("hidden")):this.focusHaloEl.setAttribute("hidden","")}setUpCanvasSurface(){this.canvasCtx=this.canvasEl.getContext("2d")??void 0,this.ensureCanvasOwnerRealm(),this.syncHostResizeObserver(),this.watchCanvasDpr(),this.canvasTooltipEl=this.renderRoot.querySelector('[part="tooltip"]')??void 0,this.bindCanvasPointer(),this.bindCanvasZoom()}ensureCanvasOwnerRealm(){const ownerDocument=this.ownerDocument;this.edgeLabelMeasureCanvas?.ownerDocument!==ownerDocument&&(this.edgeLabelMeasureCanvas=void 0,this.edgeLabelMeasureCtx=void 0,this.edgeLabelWidthCache.clear()),!(!this.pickCanvas&&this.renderer!=="canvas")&&this.pickCanvas?.ownerDocument!==ownerDocument&&(this.pickCanvas=ownerDocument.createElement("canvas"),this.pickCtx=this.pickCanvas.getContext("2d",{willReadFrequently:!0}),this.pickDirty=!0)}syncHostResizeObserver(){if(this.view!=="2d"||this.renderer!=="canvas"&&this.fitTo!=="container"){this.hostResizeObserver?.disconnect(),this.hostResizeObserver=void 0,this.hostResizeObserverDocument=void 0;return}this.hostResizeObserver&&this.hostResizeObserverDocument===this.ownerDocument||this.watchHostResize()}watchHostResize(){this.hostResizeObserver?.disconnect();const ResizeObserverCtor=this.ownerWindow?.ResizeObserver;if(!ResizeObserverCtor){this.hostResizeObserver=void 0,this.hostResizeObserverDocument=void 0;return}this.hostResizeObserver=new ResizeObserverCtor(entries=>{const box=entries[entries.length-1]?.contentRect;this.fitTo==="container"&&box&&this.recordContainerSize(box.width,box.height),this.renderer==="canvas"&&this.canvasEl&&this.markCanvasDirty()}),this.hostResizeObserverDocument=this.ownerDocument,this.hostResizeObserver.observe(this)}watchCanvasDpr(){this.canvasDprQuery?.removeEventListener("change",this.onCanvasDprChange);const view=this.ownerWindow;if(!view?.matchMedia){this.canvasDprQuery=void 0;return}this.canvasDprQuery=view.matchMedia(`(resolution: ${view.devicePixelRatio}dppx)`),this.canvasDprQuery.addEventListener("change",this.onCanvasDprChange)}markCanvasDirty(){this.canvasScene=void 0,this.pickDirty=!0,this.scheduleCanvasDraw()}markCanvasCameraDirty(){this.pickDirty=!0,this.scheduleCanvasDraw()}scheduleCanvasDraw(){if(this.view!=="2d")return;if(!this.visible){this.canvasDrawPending=!0;return}if(this.canvasDrawRafId!=null)return;const frameOwner=this.ownerWindow;frameOwner&&(this.canvasDrawRafOwner=frameOwner,this.canvasDrawRafId=frameOwner.requestAnimationFrame(()=>{this.canvasDrawRafId=void 0,this.canvasDrawRafOwner=void 0,!(!this.isConnected||this.ownerWindow!==frameOwner)&&this.drawCanvas()}))}resolveCssColorWithProbe(value,probe){const cached=this.resolvedCssColorCache.get(value);if(cached!==void 0)return cached;probe.style.color="",probe.style.color=value;const result=getComputedStyle(probe).color.trim()||getComputedStyle(this).color||"transparent";return this.resolvedCssColorCache.set(value,result),result}createCanvasColorProbe(){const probe=this.ownerDocument.createElement("span");return probe.setAttribute("aria-hidden","true"),probe.style.position="absolute",probe.style.inlineSize="0",probe.style.blockSize="0",probe.style.overflow="hidden",probe.style.visibility="hidden",probe.style.pointerEvents="none",this.renderRoot.append(probe),probe}withCanvasColorResolver(callback){let probe;try{return callback(value=>{const cached=this.resolvedCssColorCache.get(value);return cached!==void 0?cached:(probe??=this.createCanvasColorProbe(),this.resolveCssColorWithProbe(value,probe))})}finally{probe?.remove()}}refreshCanvasGeometry(scene){for(let i=0;i<this.simNodes.length;i++){const node=this.simNodes[i];scene.nodes[i].x=node.x??0,scene.nodes[i].y=node.y??0}for(let i=0;i<this.simLinks.length;i++)Object.assign(scene.links[i],this.linkCoordinates(this.simLinks[i]));for(let i=0;i<this.canvasLabelNodes.length;i++){const node=this.canvasLabelNodes[i];scene.nodeLabels[i].x=(node.x??0)+this.nodeRadius(node)+2,scene.nodeLabels[i].y=node.y??0}for(let i=0;i<this.canvasExpandableNodes.length;i++){const node=this.canvasExpandableNodes[i],indicator=scene.expandIndicators[i];indicator.x=node.x??0,indicator.y=node.y??0}const communities=this.visibleCommunities();for(let i=0;i<communities.length;i++)scene.hulls[i].d=hullPathD(this.communityHull(communities[i].members));const focus=this.focusNodeId==null?void 0:this.simNodeById.get(this.focusNodeId);if(focus&&scene.focusHalo&&(scene.focusHalo.x=focus.x??0,scene.focusHalo.y=focus.y??0),scene.edgeLabels.length=0,this.withEdgeLabels&&this.canvasCamera.k>=this.safeEdgeLabelMinZoom)for(const link of this.simLinks){const label=ownGraphText(link,"label");if(!label)continue;const coordinates=this.linkCoordinates(link);this.edgeLabelWidth(label)>Math.hypot(coordinates.x2-coordinates.x1,coordinates.y2-coordinates.y1)*EDGE_LABEL_LENGTH_GATE_RATIO||scene.edgeLabels.push({...this.edgeLabelPosition(link),text:label})}}buildCanvasScene(cs){return this.canvasLabelNodes=this.simNodes.filter(node=>!!ownGraphText(node,"label")),this.canvasExpandableNodes=this.simNodes.filter(node=>node.expandable),this.withCanvasColorResolver(resolveColor=>{const hullFillDefault=cs.getPropertyValue("--lr-graph-hull-fill").trim()||cs.getPropertyValue("--lr-color-brand").trim(),hulls=this.visibleCommunities().map(entry=>({d:hullPathD(this.communityHull(entry.members)),fill:resolveColor(sanitizeNodeColor(entry.community.color)??hullFillDefault)})),linkColorDefault=cs.getPropertyValue("--lr-graph-edge-color").trim()||cs.getPropertyValue("--lr-color-border").trim(),links=this.simLinks.map(l=>{const coords=this.linkCoordinates(l),own=sanitizeNodeColor(l.color);return{x1:coords.x1,y1:coords.y1,x2:coords.x2,y2:coords.y2,color:resolveColor(own??linkColorDefault),width:this.safeLinkWidth(l),dash:l.dash,directed:l.directed,selected:this.isSelected("link",this.linkKey(l)),dimmed:this.isDimmed("link",this.linkKey(l))}}),edgeLabels=this.withEdgeLabels&&this.canvasCamera.k>=this.safeEdgeLabelMinZoom?this.simLinks.flatMap(l=>{const label=ownGraphText(l,"label");if(!label)return[];const pos=this.edgeLabelPosition(l),coords=this.linkCoordinates(l),edgeLength=Math.hypot(coords.x2-coords.x1,coords.y2-coords.y1);return this.edgeLabelWidth(label)>edgeLength*EDGE_LABEL_LENGTH_GATE_RATIO?[]:[{x:pos.x,y:pos.y,text:label}]}):[],nodeFillDefault=cs.getPropertyValue("--lr-graph-node-fill").trim()||cs.getPropertyValue("--lr-color-brand").trim(),nodes=this.simNodes.map(n=>{const fill=this.nodeFill(n);return{x:n.x??0,y:n.y??0,r:this.nodeRadius(n),shape:this.nodeShape(n),fill:resolveColor(fill??nodeFillDefault),selected:this.isSelected("node",n.id),dimmed:this.isDimmed("node",n.id)}}),nodeLabels=this.simNodes.flatMap(n=>{const label=ownGraphText(n,"label");return label?[{x:(n.x??0)+this.nodeRadius(n)+2,y:n.y??0,text:label}]:[]}),expandIndicators=this.simNodes.filter(n=>n.expandable).map(n=>({x:n.x??0,y:n.y??0,r:this.nodeRadius(n)})),focusNode=this.focusNodeId!=null?this.simNodeById.get(this.focusNodeId):void 0,scene={hulls,links,edgeLabels,nodes,nodeLabels,expandIndicators,focusHalo:focusNode?{x:focusNode.x??0,y:focusNode.y??0,r:this.nodeRadius(focusNode)+FOCUS_HALO_PADDING}:void 0,showNodeLabels:this.canvasNodeLabelsVisible(),haloColor:resolveColor(this.ownerWindow?.matchMedia?.("(forced-colors: active)").matches?"CanvasText":cs.getPropertyValue("--lr-graph-focus-halo-color").trim()||cs.getPropertyValue("--lr-color-brand").trim()),selectedColor:resolveColor(cs.getPropertyValue("--lr-graph-selected-color").trim()||cs.getPropertyValue("--lr-color-success").trim()),dimmedOpacity:(()=>{const value=Number(cs.getPropertyValue("--lr-graph-dimmed-opacity").trim());return Number.isFinite(value)?Math.min(1,Math.max(0,value)):.35})(),hullOpacity:(()=>{const value=Number(cs.getPropertyValue("--lr-graph-hull-opacity").trim());return Number.isFinite(value)?Math.min(1,Math.max(0,value)):.12})(),labelColor:resolveColor(cs.getPropertyValue("--lr-color-text").trim()),labelHaloColor:resolveColor(cs.getPropertyValue("--lr-graph-edge-label-halo").trim()||cs.getPropertyValue("--lr-color-surface").trim()),expandBadgeFill:resolveColor(cs.getPropertyValue("--lr-color-surface").trim()),expandBadgeStroke:resolveColor(cs.getPropertyValue("--lr-color-border-strong").trim()),font:`${this.edgeLabelFontPx()}px ${cs.getPropertyValue("--lr-font").trim()||"sans-serif"}`,borderWidths:["thin","medium","thick"].map((size,index)=>resolveCssTokenLength(cs.getPropertyValue(`--lr-border-width-${size}`).trim(),{host:this})??index+1)};return this.canvasNodesById=new Map(this.simNodes.map((node,index)=>[node.id,scene.nodes[index]])),this.canvasLinksById=new Map(this.simLinks.map((link,index)=>[this.linkKey(link),scene.links[index]])),this.updateCanvasFocus(scene),scene})}updateCanvasFocus(scene){const index=shadowFocusTarget(this)?.getAttribute("part")==="cursor-item"?this.normalizedGraphItem():-1,node=index>=0&&index<this.linkIndexBase()?this.simNodes[index]:void 0,link=index>=this.linkIndexBase()&&index<this.communityIndexBase()?this.navigableLinks()[index-this.linkIndexBase()]:void 0,community=index>=this.communityIndexBase()?this.visibleCommunities()[index-this.communityIndexBase()]:void 0;scene.keyboardFocusRing=node?{x:node.x??0,y:node.y??0,r:this.nodeRadius(node)+4}:void 0,scene.keyboardFocusLink=link?{...this.linkCoordinates(link),width:this.safeLinkWidth(link)}:void 0,scene.keyboardFocusHull=community?{d:hullPathD(this.communityHull(community.members))}:void 0}drawCanvas(){if(!this.canvasEl||!this.canvasCtx)return;const dpr=this.ownerWindow?.devicePixelRatio||1,w=this.canvasEl.clientWidth||this.safeWidth,h=this.canvasEl.clientHeight||this.safeHeight,backingW=Math.round(w*dpr),backingH=Math.round(h*dpr);(this.canvasEl.width!==backingW||this.canvasEl.height!==backingH)&&(this.canvasEl.width=backingW,this.canvasEl.height=backingH);const ctx=this.canvasCtx;ctx.setTransform(dpr,0,0,dpr,0,0),ctx.clearRect(0,0,w,h);const edgeLabelsVisible=this.withEdgeLabels&&this.canvasCamera.k>=this.safeEdgeLabelMinZoom,nodeLabelsVisible=this.canvasNodeLabelsVisible();(!this.canvasScene||this.canvasScene.showNodeLabels!==nodeLabelsVisible||this.canvasSceneHasEdgeLabels!==edgeLabelsVisible)&&(this.canvasScene=this.buildCanvasScene(this.computedStyle()),this.canvasSceneHasEdgeLabels=edgeLabelsVisible),this.updateCanvasFocus(this.canvasScene),drawGraphScene(ctx,this.canvasCamera,this.canvasScene,{width:w,height:h})}rebuildPickItems(){this.pickItems=[...this.visibleCommunities().map(entry=>({kind:"hull",entry})),...this.navigableLinks().map(link=>({kind:"link",link})),...this.simNodes.map(node=>({kind:"node",node}))]}redrawPickCanvas(){if(!this.pickCtx||!this.canvasEl||!this.pickCanvas)return;(this.pickCanvas.width!==this.canvasEl.width||this.pickCanvas.height!==this.canvasEl.height)&&(this.pickCanvas.width=this.canvasEl.width,this.pickCanvas.height=this.canvasEl.height),this.rebuildPickItems();const dpr=this.ownerWindow?.devicePixelRatio||1;this.pickCtx.setTransform(dpr,0,0,dpr,0,0),drawPickingScene(this.pickCtx,this.canvasCamera,{hulls:this.pickItems.filter(i=>i.kind==="hull").map(i=>({d:hullPathD(this.communityHull(i.entry.members))})),links:this.pickItems.filter(i=>i.kind==="link").map(i=>{const c=this.linkCoordinates(i.link);return{x1:c.x1,y1:c.y1,x2:c.x2,y2:c.y2,width:this.safeLinkWidth(i.link)}}),nodes:this.pickItems.filter(i=>i.kind==="node").map(i=>({x:i.node.x??0,y:i.node.y??0,r:this.nodeRadius(i.node)+2,shape:this.nodeShape(i.node)}))}),this.pickDirty=!1}hitTest(clientX,clientY){if(!this.canvasEl||!this.pickCtx)return;this.pickDirty&&this.redrawPickCanvas();const rect=this.canvasEl.getBoundingClientRect(),dpr=this.ownerWindow?.devicePixelRatio||1,px=Math.round((clientX-rect.left)*dpr),py=Math.round((clientY-rect.top)*dpr);if(px<0||py<0||px>=this.pickCtx.canvas.width||py>=this.pickCtx.canvas.height)return;const data=this.pickCtx.getImageData(px,py,1,1).data,index=pickColorToIndex(data[0],data[1],data[2]);return index>=0?this.pickItems[index]:void 0}bindCanvasZoom(){if(!this.d3||!this.canvasEl)return;const bounds=this.effectiveZoomBounds,zoomBehavior=this.d3.zoom().scaleExtent([bounds.min,bounds.max]).on("start",()=>{this.isApplyingZoomTransform||(this.isPanning=!0,this.cancelCameraTween())}).on("zoom",event=>{this.canvasCamera={k:event.transform.k,x:event.transform.x,y:event.transform.y},this.markCanvasCameraDirty(),this.scheduleViewportChange()}).on("end",()=>{this.isPanning=!1});this.zoomBehavior=zoomBehavior,this.d3.select(this.canvasEl).call(zoomBehavior)}bindCanvasPointer(){const canvas=this.canvasEl;canvas.addEventListener("pointerdown",this.onCanvasPointerDown),canvas.addEventListener("pointermove",this.onCanvasPointerMove),canvas.addEventListener("pointerup",this.onCanvasPointerUp),canvas.addEventListener("pointercancel",this.onCanvasPointerCancel),canvas.addEventListener("lostpointercapture",this.onCanvasLostPointerCapture),canvas.addEventListener("pointerleave",this.onCanvasPointerLeave),canvas.addEventListener("dblclick",this.onCanvasDblClick)}simulationIsTicking(){return this.simulation!=null&&this.simulation.alpha()>this.simulation.alphaMin()}flushCanvasDrag(redraw=!0){this.canvasDragGeneration++,this.canvasDragFrame!==void 0&&this.canvasDragFrameOwner?.cancelAnimationFrame(this.canvasDragFrame),this.canvasDragFrame=void 0,this.canvasDragFrameOwner=void 0;const pending=this.pendingCanvasDrag;if(this.pendingCanvasDrag=void 0,!pending||!redraw||!this.isConnected||!this.canvasEl)return;const node=this.canvasDragNode&&this.simNodeById.get(this.canvasDragNode.id);if(!node)return;const rect=this.canvasEl.getBoundingClientRect();node.fx=(pending.x-rect.left-this.canvasCamera.x)/this.canvasCamera.k,node.fy=(pending.y-rect.top-this.canvasCamera.y)/this.canvasCamera.k,this.markCanvasCameraDirty()}finishCanvasNodeDrag(pointerId,releaseCapture=!0,redraw=!0){const activePointerId=this.canvasPointerId;if(activePointerId==null||pointerId!=null&&pointerId!==activePointerId)return;this.flushCanvasDrag(redraw);const node=this.canvasDragNode&&this.simNodeById.get(this.canvasDragNode.id);if(this.canvasDragNode=void 0,this.canvasPointerId=void 0,this.simulation?.alphaTarget(0),node){if(redraw&&this.isConnected&&node.fx!=null&&node.fy!=null){node.x=node.fx,node.y=node.fy,node.vx=0,node.vy=0;const position=this.lastPositionById.get(node.id);position&&(position.x=node.x,position.y=node.y)}node.fx=null,node.fy=null}if(releaseCapture&&this.canvasEl)try{this.canvasEl.releasePointerCapture(activePointerId)}catch{}redraw?this.markCanvasDirty():(this.canvasScene=void 0,this.pickDirty=!0)}takeCanvasPointerDown(pointerId){if(pointerId!=null&&this.canvasPointerDownId!==pointerId)return;const down=this.canvasPointerDownAt;return this.canvasPointerDownAt=void 0,this.canvasPointerDownId=void 0,down}canvasHoverSuppressed(){return!!this.canvasDragNode||this.isDragging||this.isPanning||this.isCameraTweening}updateCanvasHover(hit){const next=hit?.kind==="node"?{kind:"node",id:hit.node.id}:hit?.kind==="link"?{kind:"link",id:this.linkKey(hit.link),detail:this.linkHoverDetail(hit.link)}:void 0,previous=this.canvasHover;previous?.kind===next?.kind&&previous?.id===next?.id||(this.canvasHover=next,previous?.kind==="node"?this.emit("lr-node-leave",{nodeId:previous.id}):previous?.kind==="link"&&this.emitEdgeHover("leave",previous.detail),!(!this.isConnected||this.renderer!=="canvas"||this.canvasHover!==next)&&(next?.kind==="node"?this.emit("lr-node-enter",{nodeId:next.id}):next?.kind==="link"&&this.emitEdgeHover("enter",next.detail)))}nodeAtCanvasPoint(clientX,clientY){if(!this.canvasEl)return;const rect=this.canvasEl.getBoundingClientRect(),worldX=(clientX-rect.left-this.canvasCamera.x)/this.canvasCamera.k,worldY=(clientY-rect.top-this.canvasCamera.y)/this.canvasCamera.k;let closest,closestDistance=1/0;for(const node of this.simNodes){const distance=Math.hypot((node.x??0)-worldX,(node.y??0)-worldY);distance<=this.nodeRadius(node)+2/this.canvasCamera.k&&distance<closestDistance&&(closest=node,closestDistance=distance)}return closest}updateCanvasTooltip(hit,clientX,clientY){if(!this.canvasTooltipEl)return;if(!hit||hit.kind==="hull"){this.canvasTooltipEl.setAttribute("hidden","");return}const rect=this.canvasEl.getBoundingClientRect();this.canvasTooltipEl.textContent=hit.kind==="node"?this.nodeTooltipText(hit.node):this.linkTooltipText(hit.link);let left=clientX-rect.left,top=clientY-rect.top;this.canvasTooltipEl.style.left=`${left}px`,this.canvasTooltipEl.style.top=`${top}px`,this.canvasTooltipEl.removeAttribute("hidden");const tooltipRect=this.canvasTooltipEl.getBoundingClientRect(),view=this.ownerWindow;if(!view)return;const minLeft=Math.max(0,rect.left),maxRight=Math.min(view.innerWidth,rect.right),minTop=Math.max(0,rect.top),maxBottom=Math.min(view.innerHeight,rect.bottom);tooltipRect.right>maxRight&&(left-=tooltipRect.right-maxRight),tooltipRect.left<minLeft&&(left+=minLeft-tooltipRect.left),tooltipRect.bottom>maxBottom&&(top-=tooltipRect.bottom-maxBottom),tooltipRect.top<minTop&&(top+=minTop-tooltipRect.top),this.canvasTooltipEl.style.left=`${left}px`,this.canvasTooltipEl.style.top=`${top}px`}isSelected(kind,id){return identitySet(kind==="node"?this.selectedNodeIds:this.selectedEdgeIds).has(id)}paintedCurrent(kind,id){return this.selectionMode==="none"&&this.isSelected(kind,id)?"true":nothing}isDimmed(kind,id){return identitySet(kind==="node"?this.dimmedNodeIds:this.dimmedEdgeIds).has(id)}linkKey(link){return graphLinkIdentity(link)}emitSelectionIntent(kind,id,toggle){if(this.selectionMode==="none")return;const selected=this.isSelected(kind,id),time=this.ownerWindow?.performance.now()??0,repeat=this.lastActivation?.id===id&&time-this.lastActivation.time<=EXPAND_KEY_INTERVAL_MS;if(this.lastActivation={id,time},this.selectionMode==="single"||!toggle){if(this.selectionMode==="single"&&selected){repeat||this.emit("lr-selection-change",{selectedNodeIds:[],selectedEdgeIds:[]});return}this.emit("lr-selection-change",kind==="node"?{selectedNodeIds:[id],selectedEdgeIds:[]}:{selectedNodeIds:[],selectedEdgeIds:[id]});return}const selectedNodeIds=canonicalIdentityList(this.selectedNodeIds),selectedLinkIds=canonicalIdentityList(this.selectedEdgeIds),nodeIds=kind==="node"?selected?selectedNodeIds.filter(x=>x!==id):[...selectedNodeIds,id]:selectedNodeIds,linkIds=kind==="link"?selected?selectedLinkIds.filter(x=>x!==id):[...selectedLinkIds,id]:selectedLinkIds;this.emit("lr-selection-change",{selectedNodeIds:nodeIds,selectedEdgeIds:linkIds})}clearSelection(){this.selectionMode!=="none"&&(!canonicalIdentityList(this.selectedNodeIds).length&&!canonicalIdentityList(this.selectedEdgeIds).length||this.emit("lr-selection-change",{selectedNodeIds:[],selectedEdgeIds:[]}))}requestUpdate(...args){if(args[0]===void 0&&(this.explicitRefresh=!0,this.sourceEpoch=(this.sourceEpoch??0)+1,this.sourceNavigation=(this.sourceNavigation??0)+1),!this.sourceSyncing&&["sourcePage","sourcePageSize"].includes(String(args[0]))){this.sourceNavigation=(this.sourceNavigation??0)+1;const active=this.shadowRoot?.activeElement;this.sourceRestoreFocus=!!active&&!!this.shadowRoot?.querySelector('[part="source-navigator"]')?.contains(active),this.sourceRestorePager=active===this.shadowRoot?.querySelector(tag("pagination"))}(args[0]===void 0||["graphSource","sourcePage","sourcePageSize"].includes(String(args[0])))&&this.syncGraphSource(),super.requestUpdate(...args)}willUpdate(changed){this.syncGraphSource();const acceptedScene=this.sourceScene.state.scene,sourceSceneChanged=this.sourceMode&&(this.sourceModelScene!==acceptedScene||changed.has("graphSource")||changed.has("nodeTypes")||changed.has("communities"));if(sourceSceneChanged&&(this.sourceModelScene=acceptedScene,this.sourceModel=void 0,this.sourceModelVersion++),this.sourceMode&&this.sourcePages.state.result){try{this.assertSourceTotals(this.sourcePages.state.result.summary)}catch(error){this.sourceBindingError=error,this.sourceModel=void 0}this.sourcePage!==this.sourcePages.state.page&&(this.sourceSyncing=!0,this.sourcePage=this.sourcePages.state.page,this.sourceSyncing=!1,this.sourcePageInputs&&(this.sourcePageInputs=[this.sourcePage,...this.sourcePageInputs.slice(1)]))}if(this.sourceMode){const records=this.sourcePages.state,recordStatus=this.sourceBindingError||records.error||records.selectionError?"error":records.pending?"loading":"ready";this.announcements.transition("source-records",recordStatus,recordStatus==="error"?this.localize("graphSourceRecordsError"):recordStatus==="loading"?this.localize("loading"):"");const scene=this.sourceScene.state,sceneStatus=this.sourceBindingError||scene.error?"error":scene.pending?"loading":"ready";this.announcements.transition("source-scene",sceneStatus,sceneStatus==="error"?this.localize("graphSourceSceneError"):sceneStatus==="loading"?this.localize("loading"):"")}this.sourceMode&&!this.sourceComposition.profile?.empty&&changed.has("view")&&this.view!=="list"&&!this.sourceScene.state.scene&&!this.sourceScene.state.pending&&!this.sourceBindingError&&this.sourceScene.request({mode:"neighborhood",centerKey:this.sourceCenter,bounds:null,includeKeys:this.sourceKeys}),changed.has("view")&&(this.spatialGeneration++,this.spatialLoad=void 0,this.view!=="2d"&&(this.layeredGeneration++,this.layeredLoad=void 0)),(this.optionalLoadFailure==="spatial"&&this.view==="2d"||this.optionalLoadFailure==="layered"&&(this.view!=="2d"||this.layout!=="layered"))&&(this.optionalLoadFailure=void 0),this.loadFailed=this.view!=="2d"?this.optionalLoadFailure==="spatial":this.d3LoadFailed||this.layout==="layered"&&this.optionalLoadFailure==="layered",changed.has("layout")&&this.layout!=="layered"&&(this.layeredGeneration++,this.layeredLoad=void 0,this.view==="2d"&&(this.loading=!this.d3&&!this.loadFailed)),this.view!=="2d"&&!this.loadFailed&&!this.sourceList&&this.ensureSpatial(),this.view==="2d"&&this.layout==="layered"&&!this.loadFailed&&this.ensureLayered(),super.willUpdate(changed),changed.has("view")&&this.isConnected&&(this.view!=="2d"?(this.loadGeneration+=1,this.simulation?.stop(),this.cancelCameraTween(),this.finishCanvasNodeDrag(void 0,!0,!1),this.takeCanvasPointerDown(),this.canvasDrawRafId!=null&&this.canvasDrawRafOwner?.cancelAnimationFrame(this.canvasDrawRafId),this.canvasDrawRafId=void 0,this.canvasDrawRafOwner=void 0,this.hoverRafId!=null&&this.hoverRafOwner?.cancelAnimationFrame(this.hoverRafId),this.hoverRafId=void 0,this.hoverRafOwner=void 0,this.pendingHover=void 0,this.viewportChangeRafId!=null&&this.viewportChangeRafOwner?.cancelAnimationFrame(this.viewportChangeRafId),this.viewportChangeRafId=void 0,this.viewportChangeRafOwner=void 0,this.canvasDprQuery?.removeEventListener("change",this.onCanvasDprChange),this.canvasDprQuery=void 0,this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0,this.zoomedEl=void 0,this.gEl=void 0,this.boundNodeEls=new WeakSet,this.syncHostResizeObserver()):changed.get("view")!==void 0&&(this.spatial?.disconnect(),this.connect2d(),this.d3&&this.rebuildSimulation())),this.loading=this.view==="2d"&&!this.loadFailed&&(!this.d3||this.layout==="layered"&&!this.layeredEngine),changed.has("height")&&this.syncRequestedHeightVar(),changed.has("fitTo")&&this.fitTo!=="container"&&(this.containerSize=null),this.fitTo==="container"&&!this.containerSize&&this.measureHostBox();const cursorOnly=!this.explicitRefresh&&changed.size>0&&[...changed.keys()].every(key=>key==="activeGraphItem"||key==="graphLiveText");if(this.paintUpdate=this.explicitRefresh||![...changed.keys()].every(key=>["activeGraphItem","graphLiveText","selectedNodeIds","selectedEdgeIds","dimmedNodeIds","dimmedEdgeIds","minZoom","maxZoom","camera","focusNodeId","selectionMode"].includes(String(key))),this.cursorUpdate=cursorOnly,this.paintUpdate)if(!this.explicitRefresh&&[...changed.keys()].every(key=>["width","height","containerSize","fitTo"].includes(String(key))))for(const value of this.resolvedCssColorCache.keys())/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\([\d\s.,%+/-]+\))$/i.test(value)||this.resolvedCssColorCache.delete(value);else this.resolvedCssColorCache.clear();if(this.explicitRefresh=!1,this.paintUpdate&&(this.navigableLinksCache=void 0),this.syncGraphHostRole(),!this.isMounting&&this.view==="2d"&&(changed.has("nodeRenderer")||changed.has("view"))&&this.nodeRenderer!=null&&this.scheduleAfterUpdate(()=>{this.isConnected&&this.view==="2d"&&this.nodeRenderer!=null&&this.announcements.announceAssertive(this.localize("graphCustomNodesUnavailable"))},"graph-custom-nodes-unavailable"),!this.isMounting&&this.view==="2d"&&(changed.has("glow")||changed.has("view"))&&this.glow===!0&&this.scheduleAfterUpdate(()=>{this.isConnected&&this.view==="2d"&&this.glow===!0&&this.announcements.announceAssertive(this.localize("graphGlowUnavailable"))},"graph-glow-unavailable"),this.view!=="2d"){this.spatial?.prepare(),this.focusNodeId==null?this.lastAppliedFocusNodeId=null:!this.sourceMode&&this.focusNodeId!==this.lastAppliedFocusNodeId&&this.spatial?.focusNode(this.focusNodeId)&&(this.lastAppliedFocusNodeId=this.focusNodeId),this.isMounting=!1;return}const wasMounting=this.isMounting;this.isMounting=!1;const hiddenTypesChanged=changed.has("hiddenTypes")&&!sameIds(canonicalIdentityList(changed.get("hiddenTypes")??[]),canonicalIdentityList(this.hiddenTypes)),structureChanged=this.d3&&(sourceSceneChanged||changed.has("sourceModelVersion")||!this.sourceMode&&(changed.has("nodes")||changed.has("edges"))||hiddenTypesChanged||changed.has("layout")||this.layout==="layered"&&changed.has("edgeDistance")),graphItemsChanged=!!(structureChanged||changed.has("simNodes")||changed.has("communities")),activePart=shadowFocusTarget(this)?.getAttribute("part")??"",hadGraphItemFocus=graphItemsChanged&&["node","link","hull","cursor-item"].includes(activePart),previousIndex=this.normalizedGraphItem(),previousIdentity=graphItemsChanged?this.graphItemIdentity(previousIndex):void 0;if(structureChanged&&this.isConnected){this.rebuildSimulation(),this.renderer==="svg"&&this.simNodes.length+this.simLinks.length>1e3&&devWarnOnce("lr-graph-svg-scale",'<lr-graph>: renderer="svg" draws every node and link as DOM; use renderer="canvas" above about 1,000 of them.');const hovered=this.svgHoverNodeId;hovered!=null&&!this.simNodeById.has(hovered)&&(this.svgHoverNodeId=void 0,this.emit("lr-node-leave",{nodeId:hovered})),this.canvasHover?.kind==="node"&&!this.simNodeById.has(this.canvasHover.id)&&this.updateCanvasHover(void 0),this.navigableLinksCache=void 0}if(graphItemsChanged){this.visibleCommunitiesCache=void 0;const retainedIndex=previousIdentity?this.graphItemIndex(previousIdentity):-1,nextIndex=retainedIndex>=0?retainedIndex:this.normalizedGraphItem(previousIndex);this.activeGraphItem=nextIndex>=0?nextIndex:0,hadGraphItemFocus&&(this.pendingGraphItemFocus=nextIndex>=0?nextIndex:"base",nextIndex>=0&&(this.graphLiveText=this.graphItemAnnouncement(nextIndex)))}const selectedNodeIdsChanged=changed.has("selectedNodeIds")&&!sameIds(changed.get("selectedNodeIds"),this.selectedNodeIds),selectedLinkIdsChanged=changed.has("selectedEdgeIds")&&!sameIds(changed.get("selectedEdgeIds"),this.selectedEdgeIds);(selectedNodeIdsChanged||selectedLinkIdsChanged)&&!wasMounting&&(this.graphLiveText=this.localize("graphSelectionCount",void 0,{count:getNumberFormat(this.effectiveLocale).format(canonicalIdentityList(this.selectedNodeIds).length+canonicalIdentityList(this.selectedEdgeIds).length)}))}updated(changed){if(super.updated(changed),this.publishSourceComposition(),this.sourceMode&&!this.sourcePages.state.pending&&this.sourceRestoreFocus){this.sourceRestoreFocus=!1;const target=this.sourceRestorePager?this.renderRoot.querySelector(tag("pagination")):void 0;if(this.sourceRestorePager=!1,target){const current=this.sourceAuthority();target.updateComplete.then(()=>{current()&&target.focus()})}else(this.renderRoot.querySelector("[data-source-key]")??this.renderRoot.querySelector('[part="source-navigator"]'))?.focus()}if(this.sourceMode&&this.focusNodeId&&this.focusNodeId!==this.lastAppliedFocusNodeId&&(!this.loading||this.view!=="2d")&&this.scheduleAfterUpdate(()=>{const id=this.focusNodeId;this.sourceMode&&id&&id!==this.lastAppliedFocusNodeId&&(!this.loading||this.view!=="2d")&&(this.lastAppliedFocusNodeId=id,this.focusNode(id))},"graph-source-focus"),!this.isConnected){for(const[key,previous]of changed)this.detachedGraphChanges.has(key)||this.detachedGraphChanges.set(key,previous);return}if(this.view!=="2d"){this.setAttribute("aria-busy","false"),this.spatial?.update(this.paintUpdate);return}this.setAttribute("aria-busy",String(this.loading));const announceGraphText=this.graphAnnouncementsReady&&changed.has("graphLiveText")&&this.graphLiveText!=="";if(!this.loading&&!this.loadFailed&&(this.graphAnnouncementsReady=!0),announceGraphText&&this.announcements.announcePolite(this.graphLiveText),changed.has("loadFailed")&&changed.get("loadFailed")!==void 0&&this.loadFailed&&this.announcements.announceAssertive(this.localize("graphMissingLibrary")),(changed.has("fitTo")||changed.has("renderer"))&&this.syncHostResizeObserver(),!this.d3)return;!changed.has("nodes")&&!changed.has("edges")&&!changed.has("hiddenTypes")&&((changed.has("width")||changed.has("height")||changed.has("containerSize")||changed.has("fitTo"))&&(this.simulation?.force("center",this.d3.forceCenter(this.safeWidth/2,this.safeHeight/2)),this.simulation?.alpha(.1).restart()),(changed.has("chargeStrength")||changed.has("edgeDistance"))&&(changed.has("chargeStrength")&&this.chargeForce?.strength(this.safeChargeStrength),changed.has("edgeDistance")&&this.linkForce?.distance(this.safeLinkDistance),this.simulation?.alpha(.3).restart())),this.applyInteractions(changed);const cursorOnly=this.cursorUpdate;if(this.renderer==="svg"){cursorOnly||(this.svgCursorItems=[...this.renderRoot.querySelectorAll('[part="node"]'),...this.renderRoot.querySelectorAll('[part="link"][tabindex]'),...this.renderRoot.querySelectorAll('[part="hull"]')]);const next=this.svgCursorItems[this.normalizedGraphItem()];this.svgCursorElement!==next&&this.svgCursorElement?.setAttribute("tabindex","-1"),next?.setAttribute("tabindex","0"),this.svgCursorElement=next}this.renderer==="canvas"&&cursorOnly?this.scheduleCanvasDraw():this.applyCanvasInteractions(changed),this.focusNodeId==null?this.lastAppliedFocusNodeId=null:!this.sourceMode&&this.focusNodeId!==this.lastAppliedFocusNodeId&&this.simNodeById.has(this.focusNodeId)&&(this.lastAppliedFocusNodeId=this.focusNodeId,this.focusNode(this.focusNodeId)),this.visible||this.simulation?.stop(),this.updateFocusHalo();const pendingFocus=this.pendingGraphItemFocus;pendingFocus!==void 0&&(this.pendingGraphItemFocus=void 0,pendingFocus==="base"?this.renderRoot.querySelector('[part="canvas"], [part="svg"]')?.focus():this.focusGraphItemElement(pendingFocus))}applyInteractions(changed){if(!this.d3||this.renderer!=="svg")return;const svgEl=this.renderRoot.querySelector("svg"),reboundSurface=svgEl&&svgEl!==this.zoomedEl;if(svgEl&&reboundSurface){this.syncHostResizeObserver(),this.canvasHover=void 0,this.zoomedEl=svgEl,this.gEl=this.renderRoot.querySelector("g"),this.focusHaloEl=this.renderRoot.querySelector('[part="focus-halo"]');const bounds=this.effectiveZoomBounds,zoomBehavior=this.d3.zoom().scaleExtent([bounds.min,bounds.max]).on("start",()=>{this.isApplyingZoomTransform||(this.isPanning=!0,this.cancelCameraTween())}).on("zoom",event=>{this.gEl?.setAttribute("transform",event.transform.toString()),this.updateHitAreaZoomScale(event.transform.k),this.updateEdgeLabelZoomGate(event.transform.k),this.updateNodeLabelZoomGate(event.transform.k),this.scheduleViewportChange()}).on("end",()=>{this.isPanning=!1});this.zoomBehavior=zoomBehavior,this.d3.select(svgEl).call(zoomBehavior),this.updateHitAreaZoomScale(1),this.updateEdgeLabelZoomGate(1),this.updateNodeLabelZoomGate(1)}else if(this.zoomBehavior&&(changed.has("minZoom")||changed.has("maxZoom"))){const bounds=this.effectiveZoomBounds;this.zoomBehavior.scaleExtent([bounds.min,bounds.max])}if(changed.has("nodeLabels")&&this.zoomedEl&&this.updateNodeLabelZoomGate(this.d3.zoomTransform(this.zoomedEl).k),!(reboundSurface||changed.has("simNodes")||changed.has("simLinks")||changed.has("nodeTypes")||changed.has("withEdgeLabels")||changed.has("nodeLabels")||changed.has("communities")))return;const nodeEls=Array.from(this.renderRoot.querySelectorAll('[part="node"]'));this.nodeEls=nodeEls,this.nodeHitEls=Array.from(this.renderRoot.querySelectorAll('[data-hit-area="node"]')),this.nodeLabelEls=nodeEls.map(el=>el.parentElement?.querySelector('[part="label"]')??null),this.expandIndicatorEls=nodeEls.map(el=>el.parentElement?.querySelector('[part="expand-indicator"]')??null),this.linkEls=Array.from(this.renderRoot.querySelectorAll('[part="link"]:not([data-dangling])')),this.linkHitEls=Array.from(this.renderRoot.querySelectorAll('[data-hit-area="link"]')),this.linkLabelEls=this.linkEls.map(el=>el.parentElement?.querySelector('[part="link-label"]')??null),this.linkLabelHiddenByLength=[],this.danglingLinkEls=Array.from(this.renderRoot.querySelectorAll('[part="link"][data-dangling]')),this.communityHullEls=Array.from(this.renderRoot.querySelectorAll('[part="hull"]')),this.communityHullHitEls=Array.from(this.renderRoot.querySelectorAll('[data-hit-area="hull"]')),this.communityLabelEls=Array.from(this.renderRoot.querySelectorAll('[part="community-label"]')),this.layout!=="layered"&&nodeEls.forEach((el,i)=>{const id=this.simNodes[i]?.id;if(id!=null)for(const dragTarget of[el,this.nodeHitEls[i]])!dragTarget||this.boundNodeEls.has(dragTarget)||(this.boundNodeEls.add(dragTarget),this.d3.select(dragTarget).call(this.d3.drag().on("start",event=>{this.isDragging=!0,event.sourceEvent?.stopPropagation(),event.active||this.simulation?.alphaTarget(.3).restart();const n=this.simNodeById.get(id);n&&(n.fx=n.x,n.fy=n.y)}).on("drag",event=>{const n=this.simNodeById.get(id);n&&(n.fx=event.x,n.fy=event.y)}).on("end",event=>{this.isDragging=!1,event.active||this.simulation?.alphaTarget(0);const n=this.simNodeById.get(id);n&&(n.fx=null,n.fy=null)})))})}updateHitAreaZoomScale(zoom){const safeZoom=finiteRange(zoom,1,Number.EPSILON);this.gEl?.style.setProperty("--_lr-graph-hit-area-scale",String(1/safeZoom))}applyCanvasInteractions(changed){if(this.renderer!=="canvas"||!this.canvasEl)return;this.canvasEl!==this.zoomedEl&&(this.zoomedEl=this.canvasEl,this.setUpCanvasSurface());const bounds=this.effectiveZoomBounds;if(this.zoomBehavior?.scaleExtent([bounds.min,bounds.max]),!this.paintUpdate&&this.canvasScene){for(const[property2,map,flag]of[["selectedNodeIds",this.canvasNodesById,"selected"],["selectedEdgeIds",this.canvasLinksById,"selected"],["dimmedNodeIds",this.canvasNodesById,"dimmed"],["dimmedEdgeIds",this.canvasLinksById,"dimmed"]]){if(!changed.has(property2))continue;const before=identitySet(changed.get(property2)??[]),after=identitySet(this[property2]);for(const id of before){const item=map.get(id);item&&(item[flag]=after.has(id))}for(const id of after){const item=map.get(id);item&&(item[flag]=!0)}}if(changed.has("focusNodeId")){const node=this.focusNodeId==null?void 0:this.simNodeById.get(this.focusNodeId);this.canvasScene.focusHalo=node?{x:node.x??0,y:node.y??0,r:this.nodeRadius(node)+FOCUS_HALO_PADDING}:void 0}this.scheduleCanvasDraw()}else this.markCanvasDirty()}onTick(){for(const l of this.danglingLinks){const source=l.source,target=l.target;target.x=(source.x??0)+STUB_OFFSET_PX,target.y=(source.y??0)+STUB_OFFSET_PX}for(const n of this.simNodes)if(n.x!=null&&n.y!=null){const position=this.lastPositionById.get(n.id)??{x:n.x,y:n.y};position.x=n.x,position.y=n.y,this.lastPositionById.set(n.id,position)}if(this.renderer==="canvas"){this.canvasScene&&this.refreshCanvasGeometry(this.canvasScene),this.markCanvasCameraDirty(),this.scheduleViewportChange();return}this.simNodes.forEach((n,i)=>{const el=this.nodeEls[i];el&&(el.tagName==="circle"?(el.setAttribute("cx",String(n.x??0)),el.setAttribute("cy",String(n.y??0))):el.setAttribute("transform",`translate(${n.x??0},${n.y??0})`));const hit=this.nodeHitEls[i];hit&&(hit.setAttribute("x1",String((n.x??0)-NODE_HIT_SEGMENT_HALF)),hit.setAttribute("y1",String(n.y??0)),hit.setAttribute("x2",String((n.x??0)+NODE_HIT_SEGMENT_HALF)),hit.setAttribute("y2",String(n.y??0)));const label=this.nodeLabelEls[i];label&&(label.setAttribute("x",String((n.x??0)+this.nodeRadius(n)+2)),label.setAttribute("y",String(n.y??0)))}),this.simLinks.forEach((l,i)=>{const line=this.linkEls[i],coordinates=this.linkCoordinates(l);for(const target of[line,this.linkHitEls[i]])target&&(target.setAttribute("x1",String(coordinates.x1)),target.setAttribute("y1",String(coordinates.y1)),target.setAttribute("x2",String(coordinates.x2)),target.setAttribute("y2",String(coordinates.y2)))}),this.withEdgeLabels&&this.simLinks.forEach((l,i)=>{const labelEl=this.linkLabelEls[i];if(!labelEl)return;const label=ownGraphText(l,"label"),pos=this.edgeLabelPosition(l);labelEl.setAttribute("x",String(pos.x)),labelEl.setAttribute("y",String(pos.y));const{x1,y1,x2,y2}=this.linkCoordinates(l),edgeLength=Math.hypot(x2-x1,y2-y1),tooLong=this.edgeLabelWidth(label??"")>edgeLength*EDGE_LABEL_LENGTH_GATE_RATIO;this.linkLabelHiddenByLength[i]!==tooLong&&(this.linkLabelHiddenByLength[i]=tooLong,labelEl.setAttribute("visibility",tooLong?"hidden":"visible"))}),this.simNodes.forEach((n,i)=>{const indicator=this.expandIndicatorEls[i];indicator&&indicator.setAttribute("transform",`translate(${n.x??0},${n.y??0})`)}),this.danglingLinks.forEach((l,i)=>{const line=this.danglingLinkEls[i];if(!line)return;const coordinates=this.linkCoordinates(l);line.setAttribute("x1",String(coordinates.x1)),line.setAttribute("y1",String(coordinates.y1)),line.setAttribute("x2",String(coordinates.x2)),line.setAttribute("y2",String(coordinates.y2))}),this.updateFocusHalo(),this.visibleCommunities().forEach((entry,i)=>{const hullEl=this.communityHullEls[i],hullHitEl=this.communityHullHitEls[i],labelEl=this.communityLabelEls[i];if(!hullEl&&!hullHitEl&&!labelEl)return;const hull=this.communityHull(entry.members);hullEl&&hullEl.setAttribute("d",hullPathD(hull)),hullHitEl&&hullHitEl.setAttribute("d",hullPathD(hull)),labelEl&&(labelEl.setAttribute("x",String(hullCentroidX(hull))),labelEl.setAttribute("y",String(hullTopY(hull)-HULL_PADDING)))}),this.scheduleViewportChange()}rebuildSimulation(){if(this.view!=="2d"||!this.d3)return;this.simulation?.stop(),this.boundNodeEls=new WeakSet;const liveIds=new Set(this.graphModel.nodes.map(n=>n.id));for(const id of this.lastPositionById.keys())liveIds.has(id)||this.lastPositionById.delete(id);const visible=this.visibleNodes();if(this.layout==="layered"){if(!this.layeredEngine){this.ensureLayered();return}this.rebuildLayeredLayout(visible);return}const prevById=new Map(this.simNodes.map(n=>[n.id,n])),nodes=visible.map(n=>{const prev=prevById.get(n.id);if(prev)return{...prev,...n};const remembered=this.lastPositionById.get(n.id);return remembered?{...n,x:remembered.x,y:remembered.y}:{...n}}),byId=new Map(nodes.map(n=>[n.id,n])),{resolved:resolvedLinks,dangling:danglingLinks}=this.resolveLinksAgainst(byId),links=resolvedLinks;this.danglingLinks=danglingLinks;const seedForSpawn=this.safeSeed,incidentLinks=new Map;if(nodes.some(n=>n.x!=null))for(const l of resolvedLinks)for(const id of new Set([l.source.id,l.target.id])){const incident=incidentLinks.get(id);incident?incident.push(l):incidentLinks.set(id,[l])}for(const n of nodes){if(n.x!=null&&n.y!=null)continue;const neighborLink=incidentLinks.get(n.id)?.find(l=>{const source2=l.source,target2=l.target;return source2.id===n.id&&target2.x!=null||target2.id===n.id&&source2.x!=null});if(!neighborLink)continue;const source=neighborLink.source,target=neighborLink.target,neighbor=source.id===n.id?target:source,jitterRadius=this.safeLinkDistance/2,angle=seedForSpawn!=null?hashNodeSeed(seedForSpawn,n.id)/4294967296*Math.PI*2:Math.random()*Math.PI*2;n.x=(neighbor.x??0)+Math.cos(angle)*jitterRadius,n.y=(neighbor.y??0)+Math.sin(angle)*jitterRadius}if(seedForSpawn!=null)for(const n of nodes){if(n.x!=null&&n.y!=null)continue;const rng=mulberry32(hashNodeSeed(seedForSpawn,n.id));n.x=rng()*this.safeWidth,n.y=rng()*this.safeHeight}this.linkForce=this.d3.forceLink(links).distance(this.safeLinkDistance),this.chargeForce=this.d3.forceManyBody().strength(this.safeChargeStrength);const simulation=this.d3.forceSimulation(nodes).force("link",this.linkForce).force("charge",this.chargeForce).force("center",this.d3.forceCenter(this.safeWidth/2,this.safeHeight/2)).force("collide",this.d3.forceCollide().radius(n=>this.nodeRadius(n)+10)).on("tick",()=>this.onTick());if(this.simulation=simulation,this.visible||simulation.stop(),prefersReducedMotion(this)||this.safeSeed!=null){const pinnedForSettle=new Set;for(const n of nodes)(prevById.has(n.id)||this.lastPositionById.has(n.id))&&n.x!=null&&n.y!=null&&n.fx==null&&n.fy==null&&(n.fx=n.x,n.fy=n.y,pinnedForSettle.add(n.id));for(simulation.stop();simulation.alpha()>simulation.alphaMin();)simulation.tick();for(const n of nodes)pinnedForSettle.has(n.id)&&(n.fx=null,n.fy=null)}this.simNodes=nodes,this.simNodeById=byId,this.simLinks=links;for(const n of nodes)n.x!=null&&n.y!=null&&this.lastPositionById.set(n.id,{x:n.x,y:n.y});this.announceHiddenNodeCount(nodes.length)}announceHiddenNodeCount(visibleNodeCount){const totalNodeCount=this.graphModel.nodes.length,hiddenNodeCount=totalNodeCount-visibleNodeCount;totalNodeCount>0&&(hiddenNodeCount>0||this.lastHiddenNodeCount>0)&&(this.graphLiveText=this.localize("graphNodesHidden",void 0,{hidden:getNumberFormat(this.effectiveLocale).format(hiddenNodeCount),total:getNumberFormat(this.effectiveLocale).format(totalNodeCount)})),this.lastHiddenNodeCount=hiddenNodeCount}rebuildLayeredLayout(visible){const boxes=visible.map(n=>{const r=this.nodeRadius(n);return{id:n.id,width:r*2,height:r*2}}),visibleIds=new Set(visible.map(n=>n.id)),edges=this.graphModel.links.filter(l=>visibleIds.has(l.source)&&visibleIds.has(l.target)).map(l=>({source:l.source,target:l.target})),{positions:raw}=this.layeredEngine({nodes:boxes,edges,options:{gapX:12,gapY:this.safeLinkDistance}}),bounds=extent(raw.values(),point=>point.x,point=>point.y),offsetX=raw.size?this.safeWidth/2-(bounds.minX+(bounds.maxX-bounds.minX)/2):this.safeWidth/2,offsetY=raw.size?this.safeHeight/2-(bounds.minY+(bounds.maxY-bounds.minY)/2):this.safeHeight/2,nodes=visible.map(n=>{const p=raw.get(n.id);return{...n,x:p.x+offsetX,y:p.y+offsetY}}),byId=new Map(nodes.map(n=>[n.id,n])),{resolved,dangling}=this.resolveLinksAgainst(byId);this.danglingLinks=dangling,this.simulation=void 0,this.simNodes=nodes,this.simNodeById=byId,this.simLinks=resolved;for(const n of nodes)n.x!=null&&n.y!=null&&this.lastPositionById.set(n.id,{x:n.x,y:n.y});this.announceHiddenNodeCount(nodes.length)}selectionActionAuthority(){const current=this.sourceAuthority(),selectedNodes=this.selectedNodeIds,selectedEdges=this.selectedEdgeIds,nodes=this.nodes,edges=this.edges,columns=this.graphColumns,view=this.view,renderer=this.renderer,mode=this.selectionMode,hiddenTypes=this.hiddenTypes;return()=>current()&&selectedNodes===this.selectedNodeIds&&selectedEdges===this.selectedEdgeIds&&view===this.view&&renderer===this.renderer&&mode===this.selectionMode&&hiddenTypes===this.hiddenTypes&&(this.sourceMode||columns===this.graphColumns&&!this.engineColumnsInvalid&&(columns!==void 0||nodes===this.nodes&&edges===this.edges))}onNodeClick(node,e){if(this.sourceDiagramBlocked)return;const current=this.selectionActionAuthority(),detail={nodeId:node.id,x:node.x??0,y:node.y??0};this.emit("lr-node-activate",{...detail}),current()&&this.emitSelectionIntent("node",node.id,!!(e?.ctrlKey||e?.metaKey))}getNodePosition(id){if(!this.sourceMode&&this.graphColumns!==void 0&&(this.engineColumnsInvalid||this.view==="2d"))return;if(this.view!=="2d"){const position=this.getNodePosition3d(id);return position?{x:position.x,y:position.y}:void 0}const node=this.simNodes.find(candidate=>candidate.id===id);if(!(!node||!Number.isFinite(node.x)||!Number.isFinite(node.y)))return{x:node.x,y:node.y}}getNodePosition3d(id){if(!this.sourceMode&&this.graphColumns!==void 0&&this.engineColumnsInvalid||this.view==="2d")return;if(this.spatial)return this.spatial.position(id);if(!this.sourceMode&&this.engineColumns){const row=this.engineColumns.row(id),positions=this.engineColumns.data.positions;return row===void 0?void 0:positions?Object.freeze({x:positions[row*3],y:positions[row*3+1],z:positions[row*3+2]}):spatialNodePosition({id})}const node=this.visibleNodes().find(candidate=>candidate.id===id);return node?spatialNodePosition(node):void 0}getNodeScreenPosition(id){if(!this.sourceMode&&this.graphColumns!==void 0&&(this.engineColumnsInvalid||this.view==="2d"))return;if(this.view!=="2d")return this.spatial?.screenPosition(id);const position=this.getNodePosition(id);if(!position||!this.zoomedEl||!this.d3)return;const hostRect=this.getBoundingClientRect(),rect=this.zoomedEl.getBoundingClientRect(),camera=this.d3.zoomTransform(this.zoomedEl),x=position.x*camera.k+camera.x,y=position.y*camera.k+camera.y;if("getScreenCTM"in this.zoomedEl){const matrix=this.zoomedEl.getScreenCTM();return matrix?{x:matrix.a*x+matrix.c*y+matrix.e-hostRect.left,y:matrix.b*x+matrix.d*y+matrix.f-hostRect.top}:void 0}return{x:rect.left-hostRect.left+x,y:rect.top-hostRect.top+y}}onLinkClick(link,e){if(this.sourceDiagramBlocked)return;const source=typeof link.source=="object"?link.source.id:String(link.source),target=typeof link.target=="object"?link.target.id:String(link.target),current=this.selectionActionAuthority();this.emit("lr-edge-activate",{sourceNodeId:source,targetNodeId:target,...link.id?{edgeId:link.id}:{}}),current()&&this.emitSelectionIntent("link",this.linkKey(link),!!(e?.ctrlKey||e?.metaKey))}onNodeEnter(node,e){this.isDragging||this.isPanning||this.isCameraTweening||(e.currentTarget.setAttribute("data-hovered",""),this.svgHoverNodeId=node.id,this.emit("lr-node-enter",{nodeId:node.id}))}onNodeLeave(node,e){this.isDragging||this.isPanning||this.isCameraTweening||(e.currentTarget.removeAttribute("data-hovered"),this.svgHoverNodeId=void 0,this.emit("lr-node-leave",{nodeId:node.id}))}onNodeDblClick(node,e){e.stopPropagation(),this.emit("lr-node-expand",{nodeId:node.id})}onLinkEnter(link,e){this.isDragging||this.isPanning||this.isCameraTweening||(e.currentTarget.setAttribute("data-hovered",""),this.emitEdgeHover("enter",this.linkHoverDetail(link)))}linkHoverDetail(link){const source=typeof link.source=="object"?link.source.id:String(link.source),target=typeof link.target=="object"?link.target.id:String(link.target);return{sourceNodeId:source,targetNodeId:target,...link.id?{edgeId:link.id}:{}}}onLinkLeave(link,e){this.isDragging||this.isPanning||this.isCameraTweening||(e.currentTarget.removeAttribute("data-hovered"),this.emitEdgeHover("leave",this.linkHoverDetail(link)))}emitEdgeHover(phase,detail){this.emit(phase==="enter"?"lr-edge-enter":"lr-edge-leave",{...detail})}nodeAccessibleText(node){let text=ownGraphText(node,"accessibleLabel")||ownGraphText(node,"label")||node.id;const type=this.resolveNodeType(node),typeLabel=type?ownGraphText(type,"label"):void 0;return typeLabel!==void 0&&(text=this.localize("graphTypedNode",void 0,{label:text,type:typeLabel})),node.expandable&&(text=this.localize("graphExpandableItem",void 0,{item:text})),text}boundedGraphText(value){if(typeof value!="string")return"";const normalized=value.replace(/\s+/g," ").trim();return normalized.length>512?`${normalized.slice(0,512)}…`:normalized}nodeTooltipText(node){return this.boundedGraphText(ownGraphText(node,"description")||ownGraphText(node,"label")||ownGraphText(node,"accessibleLabel")||node.id)}linkAccessibleText(link){const accessibleLabel=ownGraphText(link,"accessibleLabel");if(accessibleLabel)return accessibleLabel;const endpointText=endpoint=>typeof endpoint=="object"?this.nodeAccessibleText(endpoint):String(endpoint),source=endpointText(link.source),target=endpointText(link.target);return ownGraphText(link,"label")||this.localize("graphLink",void 0,{source,target})}linkTooltipText(link){return this.boundedGraphText(ownGraphText(link,"description")||ownGraphText(link,"label")||ownGraphText(link,"accessibleLabel")||this.linkAccessibleText(link))}linkCoordinates(link){const source=link.source,target=link.target,x1=source.x??0,y1=source.y??0,targetX=target.x??0,targetY=target.y??0;if(!link.directed||link.dangling)return{x1,y1,x2:targetX,y2:targetY};const dx=targetX-x1,dy=targetY-y1,distance=Math.hypot(dx,dy);if(distance===0)return{x1,y1,x2:targetX,y2:targetY};const inset=Math.min(this.nodeRadius(target),distance);return{x1,y1,x2:targetX-dx/distance*inset,y2:targetY-dy/distance*inset}}edgeLabelPosition(link){const{x1,y1,x2,y2}=this.linkCoordinates(link),dx=x2-x1,dy=y2-y1,len=Math.hypot(dx,dy),mx=(x1+x2)/2,my=(y1+y2)/2;return len===0?{x:mx,y:my}:{x:mx+-dy/len*EDGE_LABEL_OFFSET_PX,y:my+dx/len*EDGE_LABEL_OFFSET_PX}}edgeLabelFontPx(){const raw=this.computedStyle().getPropertyValue("--lr-font-size-2xs").trim();return resolveCssTokenLength(raw,{host:this})??DEFAULT_EDGE_LABEL_FONT_PX}edgeLabelContext(){return this.edgeLabelMeasureCanvas?.ownerDocument!==this.ownerDocument&&(this.edgeLabelMeasureCanvas=this.ownerDocument.createElement("canvas"),this.edgeLabelMeasureCtx=this.edgeLabelMeasureCanvas.getContext("2d")),this.edgeLabelMeasureCtx??null}edgeLabelWidth(text){const cached=this.edgeLabelWidthCache.get(text);if(cached!=null)return cached;const ctx=this.edgeLabelContext();let width;if(ctx){const fontFamily=this.computedStyle().getPropertyValue("--lr-font").trim()||"sans-serif";ctx.font=`${this.edgeLabelFontPx()}px ${fontFamily}`,width=ctx.measureText(text).width}else width=text.length*this.edgeLabelFontPx()*.6;if(this.edgeLabelWidthCache.size>=EDGE_LABEL_WIDTH_CACHE_MAX){const oldest=this.edgeLabelWidthCache.keys().next().value;oldest!==void 0&&this.edgeLabelWidthCache.delete(oldest)}return this.edgeLabelWidthCache.set(text,width),width}updateEdgeLabelZoomGate(k){this.gEl&&(k<this.safeEdgeLabelMinZoom?this.gEl.setAttribute("data-edge-labels-hidden",""):this.gEl.removeAttribute("data-edge-labels-hidden"))}updateNodeLabelZoomGate(k){this.gEl&&(this.resolvedNodeLabelsMode==="zoom"&&k<NODE_LABEL_MIN_ZOOM?this.gEl.setAttribute("data-node-labels-hidden",""):this.gEl.removeAttribute("data-node-labels-hidden"))}linkIndexBase(){return this.simNodes.length}communityIndexBase(){return this.linkIndexBase()+this.navigableLinks().length}graphItemCount(){return this.communityIndexBase()+this.visibleCommunities().length}normalizedGraphItem(index=this.activeGraphItem){const count=this.graphItemCount();return count?Math.min(Math.max(index,0),count-1):-1}graphItemIdentity(index){if(index<0)return;if(index<this.linkIndexBase()){const node=this.simNodes[index];return node?{kind:"node",id:node.id}:void 0}if(index<this.communityIndexBase()){const link=this.navigableLinks()[index-this.linkIndexBase()];return link?{kind:"link",id:this.linkKey(link)}:void 0}const community=this.visibleCommunities()[index-this.communityIndexBase()]?.community;return community?{kind:"community",id:community.id}:void 0}graphItemIndex(identity){if(identity.kind==="node")return this.simNodes.findIndex(node=>node.id===identity.id);if(identity.kind==="link"){const index2=this.navigableLinks().findIndex(link=>this.linkKey(link)===identity.id);return index2<0?-1:this.linkIndexBase()+index2}const index=this.visibleCommunities().findIndex(entry=>entry.community.id===identity.id);return index<0?-1:this.communityIndexBase()+index}communityText(community){return ownGraphText(community,"label")??community.id}graphItemText(index){if(index<this.linkIndexBase()){const node=this.simNodes[index];return node?this.localize("graphNode",void 0,{label:this.nodeTooltipText(node)}):""}if(index<this.communityIndexBase()){const link=this.navigableLinks()[index-this.linkIndexBase()];return link?this.linkTooltipText(link):""}const entry=this.visibleCommunities()[index-this.communityIndexBase()];return entry?this.localize("graphCommunity",void 0,{label:this.communityText(entry.community),count:getNumberFormat(this.effectiveLocale).format(entry.members.length)}):""}graphItemAnnouncement(index){return this.localize("graphItemAnnouncement",void 0,{item:this.graphItemText(index),index:getNumberFormat(this.effectiveLocale).format(index+1),total:getNumberFormat(this.effectiveLocale).format(this.graphItemCount())})}onGraphItemFocus(index){this.normalizedGraphItem(index)<0||(this.activeGraphItem=index,this.graphLiveText=this.graphItemAnnouncement(index))}focusGraphItem(index){const normalized=this.normalizedGraphItem(index);normalized<0||(this.activeGraphItem=normalized,this.graphLiveText=this.graphItemAnnouncement(normalized),this.updateComplete.then(()=>this.focusGraphItemElement(normalized)))}focusGraphItemElement(index){if(this.renderer==="canvas"){this.renderRoot.querySelector('[part="cursor-item"]')?.focus(),this.scheduleCanvasDraw();return}this.svgCursorItems[index]?.focus()}onGraphKeyDown(e,index,activate){if(e.key==="Enter"||e.key===" "){if(e.preventDefault(),e.repeat)return;if(this.onGraphItemFocus(index),activate(e),index<this.simNodes.length){const now=this.ownerWindow?.performance.now()??0;if(this.lastKeyActivateIndex===index&&now-this.lastKeyActivateTime<=EXPAND_KEY_INTERVAL_MS){const node=this.simNodes[index];node&&this.emit("lr-node-expand",{nodeId:node.id}),this.lastKeyActivateIndex=null}else this.lastKeyActivateIndex=index,this.lastKeyActivateTime=now}return}const count=this.graphItemCount();if(!count)return;const rtl=isRtl(this),forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";let next=index;if(e.key===forwardKey||e.key==="ArrowDown")next=Math.min(count-1,index+1);else if(e.key===backwardKey||e.key==="ArrowUp")next=Math.max(0,index-1);else if(e.key==="Home")next=0;else if(e.key==="End")next=count-1;else return;e.preventDefault(),this.focusGraphItem(next)}render(){if(this.sourceList||this.sourceMode&&this.sourceComposition.profile?.empty)return html`<div class="source-layout source-list">${this.renderSourceNavigator()}</div>`;const svg2=this.view==="2d"&&this.renderer==="svg",result=svg2&&this.cursorUpdate&&this.svgTemplate?this.svgTemplate:this.renderGraph();this.svgTemplate=svg2?result:void 0;const sceneState=this.sourceScene.state,bindingError=this.sourceBindingError,current=this.sourceAuthority(),retryScene=()=>{current()&&this.sourceScene.state===sceneState&&this.sourceBindingError===bindingError&&!sceneState.pending&&(sceneState.error||bindingError)&&this.requestUpdate()},diagram=this.sourceMode&&(this.sourceScene.state.pending||this.sourceScene.state.error||this.sourceBindingError)?html`<div part="source-status" aria-busy=${this.sourceScene.state.pending?"true":"false"}>${this.localize(this.sourceScene.state.pending?"loading":"graphSourceSceneError")}
25
25
  ${this.sourceScene.state.pending?nothing:html`<button type="button" @click=${retryScene}>${this.localize("retry")}</button>`}</div>`:result,content=this.sourceMode?html`<div class="source-layout"><div class="source-diagram">${diagram}</div>${this.renderSourceNavigator()}</div>`:result;return html`${content}${svg2?html`<div part="live-region" class="sr-only" aria-hidden="true">${this.graphLiveText||(this.normalizedGraphItem()>=0?this.graphItemAnnouncement(this.normalizedGraphItem()):"")}</div>`:nothing}`}renderGraph(){if(!this.sourceMode&&this.graphColumns!==void 0&&(this.engineColumnsInvalid||this.view==="2d"))return html`<div part="base"><p part="error">${this.localize("largeDataInvalid")}</p></div>`;const nodeLimit=this.sourceMode||this.graphColumns!==void 0?void 0:publicCollectionTruncation(this,"nodes"),edgeLimit=this.sourceMode||this.graphColumns!==void 0?void 0:publicCollectionTruncation(this,"edges"),limitNotices=html`${this.view==="2d"&&this.nodeRenderer!=null?html`<p part="custom-node-notice">${this.localize("graphCustomNodesUnavailable")}</p>`:nothing}${this.view==="2d"&&this.glow===!0?html`<p part="glow-notice">${this.localize("graphGlowUnavailable")}</p>`:nothing}${nodeLimit?html`<p part="limit" role="note">${this.localize("graphNodeLimit",void 0,{shown:getNumberFormat(this.effectiveLocale).format(nodeLimit.retained),total:getNumberFormat(this.effectiveLocale).format(nodeLimit.source)})}</p>`:nothing}${edgeLimit?html`<p part="limit" role="note">${this.localize("graphEdgeLimit",void 0,{shown:getNumberFormat(this.effectiveLocale).format(edgeLimit.retained),total:getNumberFormat(this.effectiveLocale).format(edgeLimit.source)})}</p>`:nothing}`;if(this.view!=="2d"&&this.spatial)return this.spatial.render(limitNotices);if(this.view!=="2d")return html`<div part="base"><span part=${this.loadFailed?"error":"loading"}>${this.localize(this.loadFailed?"graphSpatialUnavailable":"loading")}</span>${limitNotices}</div>`;if(this.loading)return html`
26
26
  <div part="base">
27
27
  <lr-skeleton
@@ -0,0 +1,11 @@
1
+ import{type LyraVariant}from'../../../internal/variants.js';
2
+ /** Caller-localized presentation for an explicitly custom ingestion stage.*/
3
+ export interface IngestionQueueStagePresentation{readonly id:string;readonly label:string;readonly variant?:LyraVariant;readonly showProgress?:boolean;}
4
+ /** An explicit list replaces the row's default actions. Built-ins retain stage eligibility.*/
5
+ export type IngestionQueueAction={readonly type:'retry'|'cancel';readonly disabled?:boolean;}|{readonly type:'custom';readonly id:string;readonly label:string;readonly disabled?:boolean;};
6
+ /** Controlled host action intent; the queue performs no transport or authorization.*/
7
+ export interface IngestionItemActionEventDetail{readonly itemId:string;readonly actionId:string;}
8
+ /** Maximum inspected action positions in one row.*/
9
+ export declare const INGESTION_ITEM_ACTION_LIMIT=32;export interface IngestionPresentationProjection{readonly customStage?:IngestionQueueStagePresentation;readonly actions?:readonly IngestionQueueAction[];readonly actionLimit?:Readonly<{source:number;retained:number;}>;}
10
+ /** Descriptor-safe bounded display projection, shared by array and provider rows.*/
11
+ export declare function projectIngestionPresentation(raw:object,stage:unknown,isCurrent?:()=>boolean,maxTextUnits?:number):IngestionPresentationProjection;export declare function ingestionActionKey(action:IngestionQueueAction):string;
@@ -0,0 +1 @@
1
+ import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{LYRA_VARIANT_VALUES}from"../../../internal/variants.js";import{finiteInteger}from"../../../internal/numbers.js";const INGESTION_ITEM_ACTION_LIMIT=32,MAX_PRESENTATION_TEXT=65536,EMPTY_ACTIONS=Object.freeze([]),EMPTY_PRESENTATION=Object.freeze({});function record(value){try{return value!==null&&typeof value=="object"&&!Array.isArray(value)}catch{return!1}}function projectIngestionPresentation(raw,stage,isCurrent=()=>!0,maxTextUnits=MAX_PRESENTATION_TEXT){const read=(value,key)=>{if(!isCurrent())throw new TypeError("Obsolete ingestion presentation");const descriptor=getOwnDataDescriptor(value,key);if(!isCurrent())throw new TypeError("Obsolete ingestion presentation");return descriptor===MISSING_OWN_DATA_DESCRIPTOR?void 0:descriptor===UNSAFE_OWN_DATA_DESCRIPTOR?UNSAFE_OWN_DATA_DESCRIPTOR:descriptor.value};let candidate;if(stage!=="custom"&&(candidate=read(raw,"actions"),candidate===void 0))return EMPTY_PRESENTATION;let remaining=finiteInteger(maxTextUnits,MAX_PRESENTATION_TEXT,0,MAX_PRESENTATION_TEXT);const text=value=>{if(!(typeof value!="string"||value.trim()===""||value.length>remaining))return remaining-=value.length,value};let customStage;if(stage==="custom"){const presentation=read(raw,"customStage");if(record(presentation)){const id=text(read(presentation,"id")),label=text(read(presentation,"label")),candidateVariant=read(presentation,"variant"),variant=LYRA_VARIANT_VALUES.find(value=>value===candidateVariant)??"neutral",showProgress=read(presentation,"showProgress")===!0;id!==void 0&&label!==void 0&&(customStage=Object.freeze({id,label,variant,showProgress}))}}if(stage==="custom"&&(candidate=read(raw,"actions")),candidate===void 0)return customStage?Object.freeze({customStage}):EMPTY_PRESENTATION;const result=[],finish=actionLimit=>Object.freeze({...customStage?{customStage}:{},actions:result.length?Object.freeze(result):EMPTY_ACTIONS,...actionLimit?{actionLimit}:{}});let array=!1;try{array=Array.isArray(candidate)}catch{}if(!array)return finish();const length=read(candidate,"length");if(typeof length!="number"||!Number.isSafeInteger(length)||length<0)return finish();const seen=new Set;for(let index=0;index<Math.min(length,INGESTION_ITEM_ACTION_LIMIT);index++){const entry=read(candidate,index);if(!record(entry))continue;const type=read(entry,"type"),disabled=read(entry,"disabled");if(!(disabled!==void 0&&typeof disabled!="boolean")){if(type==="retry"||type==="cancel"){if(seen.has(type))continue;seen.add(type),result.push(Object.freeze({type,...disabled===void 0?{}:{disabled}}))}else if(type==="custom"){const id=text(read(entry,"id")),label=text(read(entry,"label"));if(id===void 0||label===void 0||seen.has(`custom:${id}`))continue;seen.add(`custom:${id}`),result.push(Object.freeze({type,id,label,...disabled===void 0?{}:{disabled}}))}}}return finish(length>INGESTION_ITEM_ACTION_LIMIT?Object.freeze({source:length,retained:result.length}):void 0)}function ingestionActionKey(action){return action.type==="custom"?`custom:${action.id}`:action.type}export{INGESTION_ITEM_ACTION_LIMIT,ingestionActionKey,projectIngestionPresentation};
@@ -1,9 +1,9 @@
1
- import{type PropertyValues,type TemplateResult}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';import type{LyraPageSource}from'../../../data-sources.js';import type{CancelEventDetail,DocumentRef,RetryEventDetail}from'../../../ai/types.js';
1
+ import{type PropertyValues,type TemplateResult}from'lit';import{type IngestionQueueAction,type IngestionQueueStagePresentation,type IngestionItemActionEventDetail}from'./ingestion-queue-presentation.js';export type{IngestionQueueAction,IngestionQueueStagePresentation,IngestionItemActionEventDetail}from'./ingestion-queue-presentation.js';import{LyraElement}from'../../../internal/lyra-element.js';import type{LyraPageSource}from'../../../data-sources.js';import type{CancelEventDetail,DocumentRef,RetryEventDetail}from'../../../ai/types.js';
2
2
  /**
3
3
  * A document's position in the ingestion pipeline. `'queued'` through `'indexing'` are the
4
4
  * in-flight stages (in pipeline order); `'done'`, `'failed'`, and `'cancelled'` are terminal.
5
5
  */
6
- export type IngestionStage='queued'|'uploading'|'extracting'|'chunking'|'embedding'|'indexing'|'done'|'failed'|'cancelled';
6
+ export type IngestionStage='queued'|'uploading'|'extracting'|'chunking'|'embedding'|'indexing'|'done'|'failed'|'cancelled'|'custom';
7
7
  /**
8
8
  * One document moving through the ingestion pipeline. `document` reuses the shared `DocumentRef`
9
9
  * shape (`src/ai/types.ts`) rather than a divergent `name`/`mimeType` pair of its own, so a caller
@@ -23,7 +23,11 @@ embeddedChunkCount?:number;
23
23
  /** Retry attempts already made (0/undefined = never retried).*/
24
24
  attempts?:number;
25
25
  /** Failure detail, rendered only while `stage === 'failed'`.*/
26
- error?:string;}
26
+ error?:string;
27
+ /** Caller-localized display for stage='custom'. Invalid metadata leaves an inert Unknown stage.*/
28
+ customStage?:IngestionQueueStagePresentation;
29
+ /** Explicit replacement action list. Omit for existing stage-derived Retry/Cancel; [] hides all.*/
30
+ actions?:readonly IngestionQueueAction[];}
27
31
  /** Provider query for the unfiltered, provider-ordered ingestion queue.*/
28
32
  export interface IngestionQueueSourceQuery{readonly[key:string]:never;}export type IngestionQueueSource=LyraPageSource<IngestionQueueItem,IngestionQueueSourceQuery>;
29
33
  /** `lr-retry`'s `detail` -- extends the shared `RetryEventDetail` (`src/ai/types.ts`) with the
@@ -34,7 +38,7 @@ export interface IngestionRetryEventDetail extends RetryEventDetail{itemId:strin
34
38
  /** `lr-cancel`'s `detail` -- extends the shared `CancelEventDetail` (`src/ai/types.ts`) with the
35
39
  * `itemId` identifying *which* queue item the request is about. This component never supplies a
36
40
  * `reason` itself; it is left for a host wrapping the cancel affordance with its own prompt. */
37
- export interface IngestionCancelEventDetail extends CancelEventDetail{itemId:string;}export interface LyraIngestionQueueEventMap{'lr-retry':CustomEvent<IngestionRetryEventDetail>;'lr-cancel':CustomEvent<IngestionCancelEventDetail>;}
41
+ export interface IngestionCancelEventDetail extends CancelEventDetail{itemId:string;}export interface LyraIngestionQueueEventMap{'lr-retry':CustomEvent<IngestionRetryEventDetail>;'lr-cancel':CustomEvent<IngestionCancelEventDetail>;'lr-item-action':CustomEvent<IngestionItemActionEventDetail>;}
38
42
  /**
39
43
  * `<lr-ingestion-queue>` — a controlled list of documents moving through an ingestion pipeline
40
44
  * (upload → text extraction → chunking → embedding → indexing), each row showing its stage,
@@ -57,6 +61,10 @@ export interface IngestionCancelEventDetail extends CancelEventDetail{itemId:str
57
61
  * becomes a blank or misleadingly actionable row.
58
62
  * Nonstring failure details use the localized failed-stage label before rendering and fresh
59
63
  * failure announcements. Omitted details stay omitted; historical failures remain silent on mount.
64
+ * stage='custom' uses bounded caller-supplied customStage text/tone/progress and derives no actions.
65
+ * An explicit actions list replaces defaults; built-ins retain lifecycle eligibility and custom
66
+ * actions emit requests only. Publish a new collection/source revision to change availability;
67
+ * the host remains responsible for every operation and server authorization.
60
68
  *
61
69
  * Input retains the first 10,000 queue items; the limit note reports the assigned source count.
62
70
  * Closed display fields are copied after identity admission, so nested records do not consume the
@@ -76,6 +84,9 @@ export interface IngestionCancelEventDetail extends CancelEventDetail{itemId:str
76
84
  * @csspart source-retry - Retry the current provider page.
77
85
  * @csspart source-pagination - Provider page navigation.
78
86
  * @customElement lr-ingestion-queue
87
+ * @event lr-item-action - A current enabled custom action was activated. Frozen detail: { itemId, actionId }.
88
+ * @csspart item-action-button - A host-defined native row action; also forwarded when virtualized.
89
+ * @csspart item-action-limit - Visible notice when a row's action list exceeds the inspected prefix.
79
90
  * @event lr-retry - A row's retry affordance was activated (only rendered for `stage="failed"`
80
91
  * rows). `detail: { itemId, attempt }` -- `attempt` is the attempt number about to be made.
81
92
  * @event lr-cancel - A row's cancel affordance was activated (rendered for every non-terminal
@@ -118,10 +129,10 @@ export interface IngestionCancelEventDetail extends CancelEventDetail{itemId:str
118
129
  * @status stable
119
130
  * @since 4.1.0
120
131
  */
121
- export declare class LyraIngestionQueue extends LyraElement<LyraIngestionQueueEventMap>{protected static collectionSupport:import("../../../internal/lyra-element.js").LyraCollectionSupport;protected static readonly identityCollectionProperties:readonly string[];protected static readonly ownedCollectionProperties:readonly string[];static styles:import("lit").CSSResultGroup[];
132
+ export declare class LyraIngestionQueue extends LyraElement<LyraIngestionQueueEventMap>{protected static collectionSupport:import("../../../internal/lyra-element.js").LyraCollectionSupport;protected static readonly immutableEventDetails:readonly string[];protected static readonly identityCollectionProperties:readonly string[];protected static readonly ownedCollectionProperties:readonly string[];static styles:import("lit").CSSResultGroup[];
122
133
  /** The queue to render, in display order. Controlled and never mutated by this component --
123
134
  * pass a new array (e.g. as ingestion progresses) to update it. Assign a new array to update: mutating an array and assigning it again does not. */
124
- items:readonly IngestionQueueItem[];private _dataSource?;private sourceEpoch;private sourceSyncing;private sourceInputs?;private sourceSize?;private sourceResult?;private sourceRows;private readonly sourceItemIdentities;private sourceStateVersion;private readonly sourcePages;
135
+ items:readonly IngestionQueueItem[];private _dataSource?;private sourceEpoch;private sourceSyncing;private sourceInputs?;private sourceSize?;private sourceResult?;private sourceRows;private readonly presentations;private actionFocusRepair?;private focusRepairGeneration;private sourceStateVersion;private readonly sourcePages;
125
136
  /** Full queue provider. A present invalid source fails visibly; undefined restores items.
126
137
  * Reassign even the same source or call requestUpdate() to publish a new provider snapshot. */
127
138
  get dataSource():IngestionQueueSource|undefined;set dataSource(value:IngestionQueueSource|undefined);
@@ -150,4 +161,4 @@ virtualizeAt:number;
150
161
  * `role="status"`/`role="alert"` hand-added before this property existed once it is set --
151
162
  * otherwise the initial failures are announced twice, through the native role and again
152
163
  * through the shared sink. */
153
- announce:boolean;private failureLiveText;private isMounting;private initialFailuresAnnounced;private sink?;private readonly limitAnnouncements;private limitInitialized;private previouslyInputTruncated;adoptedCallback():void;private inputLimitText;private sourceStatusInitialized;private previousSourceStatus;protected updated(changed:PropertyValues):void;private renderInputLimit;private get effectiveVirtualizeAt();private readonly fallbackFailureItems;private normalizeItems;private normalizedItemsCache?;private get normalizedItems();private readonly ingestionItemKey;connectedCallback():void;disconnectedCallback():void;protected willUpdate(changed:PropertyValues):void;private announceFailures;private stageLabel;private chunkCountText;private normalizedAttempts;private readonly stopOwnedEvent;private onRetryClick;private onCancelClick;private itemTemplate;private renderRows;private renderSource;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-ingestion-queue':LyraIngestionQueue;}}
164
+ announce:boolean;private failureLiveText;private isMounting;private initialFailuresAnnounced;private sink?;private readonly limitAnnouncements;private limitInitialized;private previouslyInputTruncated;adoptedCallback():void;private inputLimitText;private sourceStatusInitialized;private previousSourceStatus;protected updated(changed:PropertyValues):void;private renderInputLimit;private get effectiveVirtualizeAt();private readonly fallbackFailureItems;private normalizeItems;private normalizedItemsCache?;private get normalizedItems();private readonly ingestionItemKey;connectedCallback():void;disconnectedCallback():void;protected willUpdate(changed:PropertyValues):void;private announceFailures;private stageLabel;private chunkCountText;private normalizedAttempts;private readonly stopOwnedEvent;private itemStage;private rowActions;private currentRows;private activateRowAction;private renderedActionButtons;private captureActionFocus;private restoreActionFocus;private renderRowAction;private renderActionLimit;private itemTemplate;private renderRows;private renderSource;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-ingestion-queue':LyraIngestionQueue;}}