@aceshooting/lyra-ui 28.1.0 → 28.1.2

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 (88) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/dist/components/agent-tools/commit-card/commit-card.class.d.ts +2 -2
  3. package/dist/components/agent-tools/commit-card/commit-card.class.js +7 -8
  4. package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +1 -1
  5. package/dist/components/agent-tools/schema-viewer/schema-viewer.class.js +1 -1
  6. package/dist/components/agent-tools/span-waterfall/span-waterfall.class.js +1 -1
  7. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +4 -4
  8. package/dist/components/charts/chart/box-plot.class.d.ts +2 -2
  9. package/dist/components/charts/chart/box-plot.class.js +14 -14
  10. package/dist/components/charts/chart/chart.class.d.ts +2 -2
  11. package/dist/components/charts/chart/chart.class.js +14 -14
  12. package/dist/components/charts/chart/lite-chart.class.d.ts +1 -1
  13. package/dist/components/charts/chart/lite-chart.class.js +8 -8
  14. package/dist/components/conversation/message-feedback/message-feedback.class.js +2 -2
  15. package/dist/components/conversation/push-to-talk/push-to-talk.class.d.ts +2 -1
  16. package/dist/components/conversation/push-to-talk/push-to-talk.class.js +1 -1
  17. package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
  18. package/dist/components/data/data-grid/data-grid-processing.js +1 -1
  19. package/dist/components/data/flow-canvas/flow-canvas.class.js +1 -1
  20. package/dist/components/data/gauge/gauge.class.js +1 -1
  21. package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +1 -1
  22. package/dist/components/data/graph-query-builder/graph-query-builder.class.js +2 -2
  23. package/dist/components/data/heatmap/heatmap-label-cache.js +1 -0
  24. package/dist/components/data/heatmap/heatmap.class.d.ts +2 -2
  25. package/dist/components/data/heatmap/heatmap.class.js +2 -2
  26. package/dist/components/data/stat/stat.class.d.ts +11 -9
  27. package/dist/components/data/stat/stat.class.js +4 -2
  28. package/dist/components/data/tree/tree.class.js +1 -1
  29. package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
  30. package/dist/components/forms/color-picker/color-picker.class.js +3 -3
  31. package/dist/components/forms/combobox/combobox.class.d.ts +2 -4
  32. package/dist/components/forms/combobox/combobox.class.js +1 -1
  33. package/dist/components/forms/emoji-picker/emoji-picker.class.js +5 -5
  34. package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
  35. package/dist/components/forms/select/select.class.js +4 -3
  36. package/dist/components/forms/textarea/textarea.class.js +1 -1
  37. package/dist/components/forms/toggle-group/toggle-group.class.js +1 -1
  38. package/dist/components/layout/command-palette/command-palette.styles.js +1 -1
  39. package/dist/components/layout/details/accordion.class.js +1 -1
  40. package/dist/components/layout/filter-bar/filter-bar.class.js +3 -3
  41. package/dist/components/layout/menu/menu.class.d.ts +1 -1
  42. package/dist/components/layout/menu/menu.class.js +1 -1
  43. package/dist/components/layout/menubar/menubar.class.js +1 -1
  44. package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.d.ts +1 -1
  45. package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.js +1 -1
  46. package/dist/components/layout/page/page.class.d.ts +1 -1
  47. package/dist/components/layout/page/page.class.js +1 -1
  48. package/dist/components/layout/responsive-panel/responsive-panel.class.js +1 -1
  49. package/dist/components/layout/tab-group/tab-group.class.js +1 -1
  50. package/dist/components/layout/widget/widget.class.js +1 -1
  51. package/dist/components/media/attachment-trigger/attachment-trigger.class.js +1 -1
  52. package/dist/components/media/file-input/file-input.class.js +1 -1
  53. package/dist/components/media/image-viewer/image-viewer.class.js +1 -1
  54. package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
  55. package/dist/components/overlays/overlay/dropdown.class.js +1 -1
  56. package/dist/components/overlays/overlay/popover.class.js +1 -1
  57. package/dist/components/retrieval/chunk-inspector/chunk-inspector.class.d.ts +1 -1
  58. package/dist/components/retrieval/chunk-inspector/chunk-inspector.class.js +2 -2
  59. package/dist/components/retrieval/citation-badge/citation-badge.class.js +1 -1
  60. package/dist/components/retrieval/entity-chip/entity-chip.class.js +1 -1
  61. package/dist/components/retrieval/graph/graph-canvas.js +1 -1
  62. package/dist/components/retrieval/graph/graph.class.d.ts +1 -1
  63. package/dist/components/retrieval/graph/graph.class.js +1 -1
  64. package/dist/components/retrieval/graph-legend/graph-legend.class.js +2 -2
  65. package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.js +1 -1
  66. package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +1 -1
  67. package/dist/components/retrieval/retrieval-results/retrieval-results.class.d.ts +1 -1
  68. package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +4 -4
  69. package/dist/components/retrieval/source-picker/source-picker.class.d.ts +1 -1
  70. package/dist/components/retrieval/source-picker/source-picker.class.js +1 -1
  71. package/dist/components/utility/tour/tour.class.js +4 -4
  72. package/dist/components/viewers/email-viewer/email-viewer.class.js +1 -1
  73. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +1 -1
  74. package/dist/internal/dev-mode-attribute-warning.development.js +1 -1
  75. package/dist/internal/native-modal-carrier.js +2 -2
  76. package/dist/internal/overlay-manager.d.ts +2 -0
  77. package/dist/internal/overlay-manager.js +1 -1
  78. package/dist/internal/package-metadata.js +1 -1
  79. package/llms/components/lr-color-picker.md +2 -0
  80. package/llms/components/lr-commit-card.md +3 -2
  81. package/llms/components/lr-push-to-talk.md +3 -0
  82. package/llms/components/lr-select.md +2 -0
  83. package/llms/components/lr-stat.md +4 -0
  84. package/llms/peers.md +1 -1
  85. package/llms/shared/ai-and-peers.md +44 -0
  86. package/llms/shared.md +44 -0
  87. package/package.json +5 -5
  88. package/registrations.json +1 -1
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{collectionSupport,publicCollectionTruncation}from"../../../internal/collection-snapshot.js";import{html,nothing,svg}from"lit";import{property,state,query}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{fitTransform}from"../../../internal/fit-transform.js";import{specialistTokens}from"../../../internal/specialist-host-tokens.styles.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{isRtl}from"../../../internal/rtl.js";import{literalSetConverter}from"../../../internal/converters.js";import{resolveCssTokenLength}from"../../../internal/css-token-length.js";import{styles}from"./graph.styles.js";import{loadD3}from"./graph-loader.js";import{convexHull,hullPathD,hullCentroidX,hullTopY}from"./graph-hull.js";import{EXPAND_BADGE_OFFSET,EXPAND_BADGE_R,drawGraphScene,drawPickingScene,pickColorToIndex,shapeHalfSide}from"./graph-canvas.js";import{layeredLayout}from"../../../internal/layered-layout.js";import{finiteNumber,finiteRange,finiteInteger,extent}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{devWarnOnce}from"../../../internal/dev-warning.js";import{copyGraphLinkIdentity,graphLengthConverter,graphLinkIdentity,normalizeGraphModel}from"./graph-model.js";import{canonicalIdentityList}from"../retrieval-identity.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import"../../overlays/skeleton/skeleton.class.js";import{LYRA_DEFAULT_graphCommunity,LYRA_DEFAULT_graphDataList,LYRA_DEFAULT_graphDataListLimit,LYRA_DEFAULT_graphDiagram,LYRA_DEFAULT_graphEdgeLimit,LYRA_DEFAULT_graphExpandableItem,LYRA_DEFAULT_graphItemAnnouncement,LYRA_DEFAULT_graphLink,LYRA_DEFAULT_graphMissingLibrary,LYRA_DEFAULT_graphNode,LYRA_DEFAULT_graphNodeFocused,LYRA_DEFAULT_graphNodeLimit,LYRA_DEFAULT_graphNodesHidden,LYRA_DEFAULT_graphSelectionCount,LYRA_DEFAULT_graphTypedNode}from"../../../internal/default-strings/retrieval.generated.js";import{LYRA_DEFAULT_loading,LYRA_DEFAULT_noData}from"../../../internal/default-strings/shared.generated.js";const GRAPH_LAYOUT=literalSetConverter(["force","layered"],"force"),STUB_OFFSET_PX=14,EDGE_LABEL_OFFSET_PX=4,DEFAULT_EDGE_LABEL_FONT_PX=10,EDGE_LABEL_LENGTH_GATE_RATIO=.85,EDGE_LABEL_WIDTH_CACHE_MAX=512,EXPAND_KEY_INTERVAL_MS=500,FOCUS_HALO_PADDING=6,HULL_PADDING=24,NODE_LABEL_MIN_ZOOM=.5,NODE_HIT_SEGMENT_HALF=.5;function ownGraphText(value,property2){const descriptor=getOwnDataDescriptor(value,property2);return descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||typeof descriptor.value!="string"?void 0:descriptor.value}function ownGraphValue(value,property2){const descriptor=getOwnDataDescriptor(value,property2);return descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:descriptor.value}function mulberry32(seed){let a=seed>>>0;return()=>{a=a+1831565813|0;let t=Math.imul(a^a>>>15,a|1);return t=t+Math.imul(t^t>>>7,t|61)^t,((t^t>>>14)>>>0)/4294967296}}function hashNodeSeed(seed,id){let h=seed>>>0;for(let i=0;i<id.length;i++)h=Math.imul(h^id.charCodeAt(i),2654435761),h^=h>>>15;return h>>>0}const MIN_RADIUS=6,MAX_RADIUS=24;function sanitizeNodeColor(color){return sanitizeCssColor(color)}function normalizeLinkDash(dash){if(!(!dash?.length||dash.some(value=>!Number.isFinite(value)||value<0)))return dash.join(" ")}function categoricalPaletteColor(index){return`var(--lr-graph-cat-${index%8+1})`}function squarePath(r){const s=shapeHalfSide(r);return`M ${-s} ${-s} L ${s} ${-s} L ${s} ${s} L ${-s} ${s} Z`}function diamondPath(r){const d=shapeHalfSide(r)*Math.SQRT2;return`M 0 ${-d} L ${d} 0 L 0 ${d} L ${-d} 0 Z`}function sameIds(a,b){return a===b?!0:!a||!b||a.length!==b.length?!1:a.every((id,index)=>id===b[index])}const identitySets=new WeakMap;function identitySet(values){const ids=canonicalIdentityList(values);let set=identitySets.get(ids);return set||identitySets.set(ids,set=new Set(ids)),set}class LyraGraph extends LyraElement{static{this.defaultStrings={...super.defaultStrings,graphCommunity:LYRA_DEFAULT_graphCommunity,graphDataList:LYRA_DEFAULT_graphDataList,graphDataListLimit:LYRA_DEFAULT_graphDataListLimit,graphDiagram:LYRA_DEFAULT_graphDiagram,graphEdgeLimit:LYRA_DEFAULT_graphEdgeLimit,graphExpandableItem:LYRA_DEFAULT_graphExpandableItem,graphItemAnnouncement:LYRA_DEFAULT_graphItemAnnouncement,graphLink:LYRA_DEFAULT_graphLink,graphMissingLibrary:LYRA_DEFAULT_graphMissingLibrary,graphNode:LYRA_DEFAULT_graphNode,graphNodeFocused:LYRA_DEFAULT_graphNodeFocused,graphNodeLimit:LYRA_DEFAULT_graphNodeLimit,graphNodesHidden:LYRA_DEFAULT_graphNodesHidden,graphSelectionCount:LYRA_DEFAULT_graphSelectionCount,graphTypedNode:LYRA_DEFAULT_graphTypedNode,loading:LYRA_DEFAULT_loading,noData:LYRA_DEFAULT_noData}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["nodes","edges","nodeTypes","hiddenTypes","communities","selectedNodeIds","selectedEdgeIds","dimmedNodeIds","dimmedEdgeIds"])}static get observedAttributes(){return[...new Set([...super.observedAttributes,"role"])]}static{this.styles=[LyraElement.styles,specialistTokens,styles,srOnly]}static{this.immutableEventDetails=Object.freeze(["lr-selection-change"])}get graphModel(){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 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))}constructor(){super(),this.nodes=[],this.edges=[],this.nodeTypes=[],this.hiddenTypes=[],this.communities=[],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.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.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.isApplyingZoomTransform=!1,this.onCanvasDprChange=()=>{this.watchCanvasDpr(),this.markCanvasDirty()},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){const node=this.simNodeById.get(this.canvasDragNode.id);if(node){const rect=this.canvasEl.getBoundingClientRect();node.fx=(e.clientX-rect.left-this.canvasCamera.x)/this.canvasCamera.k,node.fy=(e.clientY-rect.top-this.canvasCamera.y)/this.canvasCamera.k,this.markCanvasDirty()}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.isDragging=!1,this.isPanning=!1,new ThemeWatcher(this,()=>{const reduced=prefersReducedMotion(this);reduced!==this.reducedMotion&&(this.reducedMotion=reduced,reduced?this.simulation?.stop():this.safeSeed==null&&this.simulation?.restart()),this.linkPaintVisibilityCache.clear(),this.resolvedCssColorCache.clear(),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(element=this){const view=this.ownerWindow;return view?view.getComputedStyle(element):"style"in element?element.style:this.style}connectedCallback(){super.connectedCallback(),this.reducedMotion=prefersReducedMotion(this);const IntersectionObserverCtor=this.ownerWindow?.IntersectionObserver;if(IntersectionObserverCtor&&(this.intersectionObserver=new IntersectionObserverCtor(entries=>{const wasVisible=this.visible;this.visible=entries[0]?.isIntersecting??!0,this.visible&&!wasVisible&&this.canvasDrawPending&&(this.canvasDrawPending=!1,this.scheduleCanvasDraw())}),this.intersectionObserver.observe(this)),this.fitTo==="container"&&(this.syncHostResizeObserver(),this.measureHostBox()),this.d3){!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 this.updateComplete}catch{return}if(await new Promise(resolve=>this.updateBrowserDerivedState(resolve)),!(generation!==this.loadGeneration||!this.isConnected)){if(this.loading=!1,!mods){this.loadFailed=!0;return}this.loadFailed=!1,this.d3=mods,this.rebuildSimulation()}})}disconnectedCallback(){super.disconnectedCallback(),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.ensureCanvasOwnerRealm()}scheduleViewportChange(){if(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}}communityMembers(community){const idSet=new Set(community.memberIds);return this.simNodes.filter(n=>idSet.has(n.id)||n.communityId===community.id)}visibleCommunities(){return this.visibleCommunitiesCache||(this.visibleCommunitiesCache=this.graphModel.communities.map(community=>({community,members:this.communityMembers(community)})).filter(entry=>entry.members.length>0)),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){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&&(this.graphLiveText=this.localize("graphNodeFocused",void 0,{label:this.nodeAccessibleText(node)})),arrived}fit(options){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.simNodes.find(n=>n.id===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.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.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()}}buildCanvasScene(cs){return 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.simNodes.find(n=>n.id===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.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)}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()}finishCanvasNodeDrag(pointerId,releaseCapture=!0,redraw=!0){const activePointerId=this.canvasPointerId;if(activePointerId==null||pointerId!=null&&pointerId!==activePointerId)return;const node=this.canvasDragNode&&this.simNodeById.get(this.canvasDragNode.id);if(this.canvasDragNode=void 0,this.canvasPointerId=void 0,this.simulation?.alphaTarget(0),node&&(node.fx=null,node.fy=null),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:[]}))}willUpdate(changed){super.willUpdate(changed),changed.has("height")&&this.syncRequestedHeightVar(),changed.has("fitTo")&&this.fitTo!=="container"&&(this.containerSize=null),this.fitTo==="container"&&!this.containerSize&&this.measureHostBox();const cursorOnly=changed.size>0&&[...changed.keys()].every(key=>key==="activeGraphItem"||key==="graphLiveText");cursorOnly||this.resolvedCssColorCache.clear(),cursorOnly||(this.navigableLinksCache=void 0),this.syncGraphHostRole();const wasMounting=this.isMounting;this.isMounting=!1;const hiddenTypesChanged=changed.has("hiddenTypes")&&!sameIds(canonicalIdentityList(changed.get("hiddenTypes")??[]),canonicalIdentityList(this.hiddenTypes)),structureChanged=this.d3&&(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.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){super.updated(changed),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=changed.size>0&&[...changed.keys()].every(key=>key==="activeGraphItem"||key==="graphLiveText");this.renderer==="canvas"&&cursorOnly?this.scheduleCanvasDraw():this.applyCanvasInteractions(),this.focusNodeId==null?this.lastAppliedFocusNodeId=null:this.focusNodeId!==this.lastAppliedFocusNodeId&&this.simNodes.some(n=>n.id===this.focusNodeId)&&(this.lastAppliedFocusNodeId=this.focusNodeId,this.focusNode(this.focusNodeId)),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");if(svgEl&&svgEl!==this.zoomedEl){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),!(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(){if(this.renderer!=="canvas"||!this.canvasEl)return;this.canvasEl!==this.zoomedEl&&(this.zoomedEl=this.canvasEl,this.setUpCanvasSurface());const bounds=this.effectiveZoomBounds;this.zoomBehavior?.scaleExtent([bounds.min,bounds.max]),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)n.x!=null&&n.y!=null&&this.lastPositionById.set(n.id,{x:n.x,y:n.y});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.renderer==="canvas"&&this.markCanvasDirty(),this.scheduleViewportChange()}rebuildSimulation(){if(!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"){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,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}=layeredLayout({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)}onNodeClick(node,e){const detail={nodeId:node.id,x:node.x??0,y:node.y??0};this.emit("lr-node-activate",{...detail}),this.emitSelectionIntent("node",node.id,!!(e?.ctrlKey||e?.metaKey))}getNodePosition(id){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}}onLinkClick(link,e){const source=typeof link.source=="object"?link.source.id:String(link.source),target=typeof link.target=="object"?link.target.id:String(link.target);this.emit("lr-edge-activate",{sourceNodeId:source,targetNodeId:target,...link.id?{edgeId:link.id}:{}}),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 sourceValue=ownGraphValue(link,"source"),targetValue=ownGraphValue(link,"target"),source=sourceValue!==null&&typeof sourceValue=="object"?this.nodeAccessibleText(sourceValue):typeof sourceValue=="string"?sourceValue:"",target=targetValue!==null&&typeof targetValue=="object"?this.nodeAccessibleText(targetValue):typeof targetValue=="string"?targetValue:"";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.renderRoot.querySelectorAll('[part="node"]'),...this.renderRoot.querySelectorAll('[part="link"][tabindex]'),...this.renderRoot.querySelectorAll('[part="hull"]')][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(){const nodeLimit=publicCollectionTruncation(this,"nodes"),edgeLimit=publicCollectionTruncation(this,"edges"),limitNotices=html`${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.loading)return html`
1
+ import{__decorate}from"tslib";import{collectionSupport,publicCollectionTruncation}from"../../../internal/collection-snapshot.js";import{html,nothing,svg}from"lit";import{property,state,query}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{fitTransform}from"../../../internal/fit-transform.js";import{specialistTokens}from"../../../internal/specialist-host-tokens.styles.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{isRtl}from"../../../internal/rtl.js";import{literalSetConverter}from"../../../internal/converters.js";import{resolveCssTokenLength}from"../../../internal/css-token-length.js";import{styles}from"./graph.styles.js";import{loadD3}from"./graph-loader.js";import{convexHull,hullPathD,hullCentroidX,hullTopY}from"./graph-hull.js";import{EXPAND_BADGE_OFFSET,EXPAND_BADGE_R,drawGraphScene,drawPickingScene,pickColorToIndex,shapeHalfSide}from"./graph-canvas.js";import{layeredLayout}from"../../../internal/layered-layout.js";import{finiteNumber,finiteRange,finiteInteger,extent}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{devWarnOnce}from"../../../internal/dev-warning.js";import{copyGraphLinkIdentity,graphLengthConverter,graphLinkIdentity,normalizeGraphModel}from"./graph-model.js";import{canonicalIdentityList}from"../retrieval-identity.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import"../../overlays/skeleton/skeleton.class.js";import{LYRA_DEFAULT_graphCommunity,LYRA_DEFAULT_graphDataList,LYRA_DEFAULT_graphDataListLimit,LYRA_DEFAULT_graphDiagram,LYRA_DEFAULT_graphEdgeLimit,LYRA_DEFAULT_graphExpandableItem,LYRA_DEFAULT_graphItemAnnouncement,LYRA_DEFAULT_graphLink,LYRA_DEFAULT_graphMissingLibrary,LYRA_DEFAULT_graphNode,LYRA_DEFAULT_graphNodeFocused,LYRA_DEFAULT_graphNodeLimit,LYRA_DEFAULT_graphNodesHidden,LYRA_DEFAULT_graphSelectionCount,LYRA_DEFAULT_graphTypedNode}from"../../../internal/default-strings/retrieval.generated.js";import{LYRA_DEFAULT_loading,LYRA_DEFAULT_noData}from"../../../internal/default-strings/shared.generated.js";const GRAPH_LAYOUT=literalSetConverter(["force","layered"],"force"),STUB_OFFSET_PX=14,EDGE_LABEL_OFFSET_PX=4,DEFAULT_EDGE_LABEL_FONT_PX=10,EDGE_LABEL_LENGTH_GATE_RATIO=.85,EDGE_LABEL_WIDTH_CACHE_MAX=512,EXPAND_KEY_INTERVAL_MS=500,FOCUS_HALO_PADDING=6,HULL_PADDING=24,NODE_LABEL_MIN_ZOOM=.5,NODE_HIT_SEGMENT_HALF=.5;function ownGraphText(value,property2){const descriptor=getOwnDataDescriptor(value,property2);return descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||typeof descriptor.value!="string"?void 0:descriptor.value}function ownGraphValue(value,property2){const descriptor=getOwnDataDescriptor(value,property2);return descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:descriptor.value}function mulberry32(seed){let a=seed>>>0;return()=>{a=a+1831565813|0;let t=Math.imul(a^a>>>15,a|1);return t=t+Math.imul(t^t>>>7,t|61)^t,((t^t>>>14)>>>0)/4294967296}}function hashNodeSeed(seed,id){let h=seed>>>0;for(let i=0;i<id.length;i++)h=Math.imul(h^id.charCodeAt(i),2654435761),h^=h>>>15;return h>>>0}const MIN_RADIUS=6,MAX_RADIUS=24;function sanitizeNodeColor(color){return sanitizeCssColor(color)}function normalizeLinkDash(dash){if(!(!dash?.length||dash.some(value=>!Number.isFinite(value)||value<0)))return dash.join(" ")}function categoricalPaletteColor(index){return`var(--lr-graph-cat-${index%8+1})`}function squarePath(r){const s=shapeHalfSide(r);return`M ${-s} ${-s} L ${s} ${-s} L ${s} ${s} L ${-s} ${s} Z`}function diamondPath(r){const d=shapeHalfSide(r)*Math.SQRT2;return`M 0 ${-d} L ${d} 0 L 0 ${d} L ${-d} 0 Z`}function sameIds(a,b){return a===b?!0:!a||!b||a.length!==b.length?!1:a.every((id,index)=>id===b[index])}const identitySets=new WeakMap;function identitySet(values){const ids=canonicalIdentityList(values);let set=identitySets.get(ids);return set||identitySets.set(ids,set=new Set(ids)),set}class LyraGraph extends LyraElement{static{this.defaultStrings={...super.defaultStrings,graphCommunity:LYRA_DEFAULT_graphCommunity,graphDataList:LYRA_DEFAULT_graphDataList,graphDataListLimit:LYRA_DEFAULT_graphDataListLimit,graphDiagram:LYRA_DEFAULT_graphDiagram,graphEdgeLimit:LYRA_DEFAULT_graphEdgeLimit,graphExpandableItem:LYRA_DEFAULT_graphExpandableItem,graphItemAnnouncement:LYRA_DEFAULT_graphItemAnnouncement,graphLink:LYRA_DEFAULT_graphLink,graphMissingLibrary:LYRA_DEFAULT_graphMissingLibrary,graphNode:LYRA_DEFAULT_graphNode,graphNodeFocused:LYRA_DEFAULT_graphNodeFocused,graphNodeLimit:LYRA_DEFAULT_graphNodeLimit,graphNodesHidden:LYRA_DEFAULT_graphNodesHidden,graphSelectionCount:LYRA_DEFAULT_graphSelectionCount,graphTypedNode:LYRA_DEFAULT_graphTypedNode,loading:LYRA_DEFAULT_loading,noData:LYRA_DEFAULT_noData}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["nodes","edges","nodeTypes","hiddenTypes","communities","selectedNodeIds","selectedEdgeIds","dimmedNodeIds","dimmedEdgeIds"])}static get observedAttributes(){return[...new Set([...super.observedAttributes,"role"])]}static{this.styles=[LyraElement.styles,specialistTokens,styles,srOnly]}static{this.immutableEventDetails=Object.freeze(["lr-selection-change"])}get graphModel(){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 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))}constructor(){super(),this.nodes=[],this.edges=[],this.nodeTypes=[],this.hiddenTypes=[],this.communities=[],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.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.isApplyingZoomTransform=!1,this.onCanvasDprChange=()=>{this.watchCanvasDpr(),this.markCanvasDirty()},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){const node=this.simNodeById.get(this.canvasDragNode.id);if(node){const rect=this.canvasEl.getBoundingClientRect();node.fx=(e.clientX-rect.left-this.canvasCamera.x)/this.canvasCamera.k,node.fy=(e.clientY-rect.top-this.canvasCamera.y)/this.canvasCamera.k,this.markCanvasDirty()}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.isDragging=!1,this.isPanning=!1,new ThemeWatcher(this,()=>{const reduced=prefersReducedMotion(this);reduced!==this.reducedMotion&&(this.reducedMotion=reduced,reduced?this.simulation?.stop():this.safeSeed==null&&this.simulation?.restart()),this.linkPaintVisibilityCache.clear(),this.resolvedCssColorCache.clear(),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(element=this){const view=this.ownerWindow;return view?view.getComputedStyle(element):"style"in element?element.style:this.style}connectedCallback(){if(super.connectedCallback(),this.detachedGraphChanges.size){for(const[key,previous]of this.detachedGraphChanges)this.requestUpdate(key,previous);this.detachedGraphChanges.clear(),this.requestUpdate()}this.reducedMotion=prefersReducedMotion(this);const IntersectionObserverCtor=this.ownerWindow?.IntersectionObserver;if(IntersectionObserverCtor&&(this.intersectionObserver=new IntersectionObserverCtor(entries=>{const wasVisible=this.visible;this.visible=entries[0]?.isIntersecting??!0,this.visible&&!wasVisible&&this.canvasDrawPending&&(this.canvasDrawPending=!1,this.scheduleCanvasDraw())}),this.intersectionObserver.observe(this)),this.fitTo==="container"&&(this.syncHostResizeObserver(),this.measureHostBox()),this.d3){!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 this.updateComplete}catch{return}if(await new Promise(resolve=>this.updateBrowserDerivedState(resolve)),!(generation!==this.loadGeneration||!this.isConnected)){if(this.loading=!1,!mods){this.loadFailed=!0;return}this.loadFailed=!1,this.d3=mods,this.rebuildSimulation()}})}disconnectedCallback(){super.disconnectedCallback(),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.ensureCanvasOwnerRealm()}scheduleViewportChange(){if(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}}communityMembers(community){const idSet=new Set(community.memberIds);return this.simNodes.filter(n=>idSet.has(n.id)||n.communityId===community.id)}visibleCommunities(){return this.visibleCommunitiesCache||(this.visibleCommunitiesCache=this.graphModel.communities.map(community=>({community,members:this.communityMembers(community)})).filter(entry=>entry.members.length>0)),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){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&&(this.graphLiveText=this.localize("graphNodeFocused",void 0,{label:this.nodeAccessibleText(node)})),arrived}fit(options){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.simNodes.find(n=>n.id===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.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.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()}}buildCanvasScene(cs){return 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.simNodes.find(n=>n.id===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.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)}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()}finishCanvasNodeDrag(pointerId,releaseCapture=!0,redraw=!0){const activePointerId=this.canvasPointerId;if(activePointerId==null||pointerId!=null&&pointerId!==activePointerId)return;const node=this.canvasDragNode&&this.simNodeById.get(this.canvasDragNode.id);if(this.canvasDragNode=void 0,this.canvasPointerId=void 0,this.simulation?.alphaTarget(0),node&&(node.fx=null,node.fy=null),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:[]}))}willUpdate(changed){super.willUpdate(changed),changed.has("height")&&this.syncRequestedHeightVar(),changed.has("fitTo")&&this.fitTo!=="container"&&(this.containerSize=null),this.fitTo==="container"&&!this.containerSize&&this.measureHostBox();const cursorOnly=changed.size>0&&[...changed.keys()].every(key=>key==="activeGraphItem"||key==="graphLiveText");cursorOnly||this.resolvedCssColorCache.clear(),cursorOnly||(this.navigableLinksCache=void 0),this.syncGraphHostRole();const wasMounting=this.isMounting;this.isMounting=!1;const hiddenTypesChanged=changed.has("hiddenTypes")&&!sameIds(canonicalIdentityList(changed.get("hiddenTypes")??[]),canonicalIdentityList(this.hiddenTypes)),structureChanged=this.d3&&(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.isConnected){for(const[key,previous]of changed)this.detachedGraphChanges.has(key)||this.detachedGraphChanges.set(key,previous);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=changed.size>0&&[...changed.keys()].every(key=>key==="activeGraphItem"||key==="graphLiveText");this.renderer==="canvas"&&cursorOnly?this.scheduleCanvasDraw():this.applyCanvasInteractions(),this.focusNodeId==null?this.lastAppliedFocusNodeId=null:this.focusNodeId!==this.lastAppliedFocusNodeId&&this.simNodes.some(n=>n.id===this.focusNodeId)&&(this.lastAppliedFocusNodeId=this.focusNodeId,this.focusNode(this.focusNodeId)),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(){if(this.renderer!=="canvas"||!this.canvasEl)return;this.canvasEl!==this.zoomedEl&&(this.zoomedEl=this.canvasEl,this.setUpCanvasSurface());const bounds=this.effectiveZoomBounds;this.zoomBehavior?.scaleExtent([bounds.min,bounds.max]),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)n.x!=null&&n.y!=null&&this.lastPositionById.set(n.id,{x:n.x,y:n.y});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.renderer==="canvas"&&this.markCanvasDirty(),this.scheduleViewportChange()}rebuildSimulation(){if(!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"){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,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}=layeredLayout({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)}onNodeClick(node,e){const detail={nodeId:node.id,x:node.x??0,y:node.y??0};this.emit("lr-node-activate",{...detail}),this.emitSelectionIntent("node",node.id,!!(e?.ctrlKey||e?.metaKey))}getNodePosition(id){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}}onLinkClick(link,e){const source=typeof link.source=="object"?link.source.id:String(link.source),target=typeof link.target=="object"?link.target.id:String(link.target);this.emit("lr-edge-activate",{sourceNodeId:source,targetNodeId:target,...link.id?{edgeId:link.id}:{}}),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 sourceValue=ownGraphValue(link,"source"),targetValue=ownGraphValue(link,"target"),source=sourceValue!==null&&typeof sourceValue=="object"?this.nodeAccessibleText(sourceValue):typeof sourceValue=="string"?sourceValue:"",target=targetValue!==null&&typeof targetValue=="object"?this.nodeAccessibleText(targetValue):typeof targetValue=="string"?targetValue:"";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.renderRoot.querySelectorAll('[part="node"]'),...this.renderRoot.querySelectorAll('[part="link"][tabindex]'),...this.renderRoot.querySelectorAll('[part="hull"]')][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(){const nodeLimit=publicCollectionTruncation(this,"nodes"),edgeLimit=publicCollectionTruncation(this,"edges"),limitNotices=html`${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.loading)return html`
2
2
  <div part="base">
3
3
  <lr-skeleton
4
4
  shape="rect"
@@ -1,10 +1,10 @@
1
- import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing,svg}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{canonicalIdentityList,firstByRetrievalIdentity}from"../retrieval-identity.js";import{specialistTokens}from"../../../internal/specialist-host-tokens.styles.js";import{srOnly}from"../../../internal/a11y.js";import{styles}from"./graph-legend.styles.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteCount}from"../../../internal/numbers.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_graphLegendLabel}from"../../../internal/default-strings/retrieval.generated.js";import{LYRA_DEFAULT_legendTypeHidden,LYRA_DEFAULT_legendTypeShown}from"../../../internal/default-strings/shared.generated.js";class LyraGraphLegend extends LyraElement{constructor(){super(...arguments),this.types=[],this.hiddenTypes=[],this.withoutInteraction=!1,this.liveText=""}static{this.defaultStrings={...super.defaultStrings,graphLegendLabel:LYRA_DEFAULT_graphLegendLabel,legendTypeHidden:LYRA_DEFAULT_legendTypeHidden,legendTypeShown:LYRA_DEFAULT_legendTypeShown}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["types","hiddenTypes","counts"])}static{this.styles=[LyraElement.styles,specialistTokens,styles,srOnly]}static{this.immutableEventDetails=Object.freeze(["lr-visibility-change-request","lr-visibility-change"])}connectedCallback(){super.connectedCallback(),this.announcementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.announcementSink?.release(),this.announcementSink=void 0,super.disconnectedCallback()}isVisible(id){return!canonicalIdentityList(this.hiddenTypes).includes(id)}toggle(type){if(this.withoutInteraction)return;const hiddenTypes=canonicalIdentityList(this.hiddenTypes),wasVisible=this.isVisible(type.id),next=wasVisible?[...hiddenTypes,type.id]:hiddenTypes.filter(id=>id!==type.id);this.emit("lr-visibility-change-request",{hiddenTypes:next},{cancelable:!0}).defaultPrevented||(this.hiddenTypes=next,this.liveText=this.localize(wasVisible?"legendTypeHidden":"legendTypeShown",void 0,{label:type.label}),this.announcementSink?.announce(this.liveText),this.emit("lr-visibility-change",{hiddenTypes:next}))}renderSwatchShape(shape,color){return shape==="square"?svg`<rect x="1" y="1" width="10" height="10" style="fill: ${color}"></rect>`:shape==="diamond"?svg`<polygon points="6,0 12,6 6,12 0,6" style="fill: ${color}"></polygon>`:svg`<circle cx="6" cy="6" r="5" style="fill: ${color}"></circle>`}render(){const types=firstByRetrievalIdentity(this.types,type=>type?.id).filter(type=>typeof type?.label=="string"&&type.label.trim().length>0),groupLabel=retrievalSemanticLabel(this,this.label==null?this.localize("graphLegendLabel"):this.label),groupRole=retrievalSemanticRole(this,"group");return html`
1
+ import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing,svg}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{canonicalIdentityList,firstByRetrievalIdentity}from"../retrieval-identity.js";import{specialistTokens}from"../../../internal/specialist-host-tokens.styles.js";import{srOnly}from"../../../internal/a11y.js";import{styles}from"./graph-legend.styles.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteCount}from"../../../internal/numbers.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_graphLegendLabel}from"../../../internal/default-strings/retrieval.generated.js";import{LYRA_DEFAULT_legendTypeHidden,LYRA_DEFAULT_legendTypeShown}from"../../../internal/default-strings/shared.generated.js";class LyraGraphLegend extends LyraElement{constructor(){super(...arguments),this.types=[],this.hiddenTypes=[],this.withoutInteraction=!1,this.liveText=""}static{this.defaultStrings={...super.defaultStrings,graphLegendLabel:LYRA_DEFAULT_graphLegendLabel,legendTypeHidden:LYRA_DEFAULT_legendTypeHidden,legendTypeShown:LYRA_DEFAULT_legendTypeShown}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["types","hiddenTypes","counts"])}static{this.styles=[LyraElement.styles,specialistTokens,styles,srOnly]}static{this.immutableEventDetails=Object.freeze(["lr-visibility-change-request","lr-visibility-change"])}connectedCallback(){super.connectedCallback(),this.announcementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.announcementSink?.release(),this.announcementSink=void 0,super.disconnectedCallback()}isVisible(id){return!canonicalIdentityList(this.hiddenTypes).includes(id)}toggle(type){if(this.withoutInteraction)return;const hiddenTypes=canonicalIdentityList(this.hiddenTypes),wasVisible=this.isVisible(type.id),next=wasVisible?[...hiddenTypes,type.id]:hiddenTypes.filter(id=>id!==type.id);this.emit("lr-visibility-change-request",{hiddenTypes:next},{cancelable:!0}).defaultPrevented||(this.hiddenTypes=next,this.liveText=this.localize(wasVisible?"legendTypeHidden":"legendTypeShown",void 0,{label:type.label}),this.announcementSink?.announce(this.liveText),this.emit("lr-visibility-change",{hiddenTypes:next}))}renderSwatchShape(shape,color){return shape==="square"?svg`<rect x="1" y="1" width="10" height="10" style="fill: ${color}"></rect>`:shape==="diamond"?svg`<polygon points="6,0 12,6 6,12 0,6" style="fill: ${color}"></polygon>`:svg`<circle cx="6" cy="6" r="5" style="fill: ${color}"></circle>`}render(){const types=firstByRetrievalIdentity(this.types,type=>type?.id).filter(type=>typeof type?.label=="string"&&type.label.trim().length>0),groupLabel=retrievalSemanticLabel(this,this.label==null?this.localize("graphLegendLabel"):this.label),groupRole=retrievalSemanticRole(this,"group"),hiddenTypes=new Set(canonicalIdentityList(this.hiddenTypes));return html`
2
2
  <div
3
3
  part="base"
4
4
  role=${groupRole??nothing}
5
5
  aria-label=${groupLabel??nothing}
6
6
  >
7
- ${types.map((type,index)=>{const visible=this.isVisible(type.id),color=sanitizeCssColor(type.color)??`var(--lr-graph-cat-${index%8+1})`,count=this.counts?.[type.id],content=html`
7
+ ${types.map((type,index)=>{const visible=!hiddenTypes.has(type.id),color=sanitizeCssColor(type.color)??`var(--lr-graph-cat-${index%8+1})`,count=this.counts?.[type.id],content=html`
8
8
  <svg
9
9
  part="swatch"
10
10
  viewBox="0 0 12 12"
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{collectionSupport,publicCollectionTruncation}from"../../../internal/collection-snapshot.js";import{tag}from"../../../internal/prefix.js";import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{guard}from"lit/directives/guard.js";import{LyraElement}from"../../../internal/lyra-element.js";import{finiteRange}from"../../../internal/numbers.js";import{srOnly}from"../../../internal/a11y.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./knowledge-graph-explorer.styles.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{graphLengthConverter,graphLinkIdentity,normalizeGraphModel}from"../graph/graph-model.js";import{canonicalIdentityList,isNonBlankIdentity}from"../retrieval-identity.js";import"../graph/graph.class.js";import"../graph-legend/graph-legend.class.js";import"../entity-card/entity-card.class.js";import"../neighbor-list/neighbor-list.class.js";import"../path-strip/path-strip.class.js";import"../../overlays/overlay/popover.class.js";import"../../forms/input/input.class.js";import"../../overlays/chip/chip.class.js";import"../../forms/button/button.class.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{LYRA_DEFAULT_graphDataListLimit,LYRA_DEFAULT_graphExplorerFindPath,LYRA_DEFAULT_graphExplorerLabel,LYRA_DEFAULT_graphExplorerPin,LYRA_DEFAULT_graphExplorerPinned,LYRA_DEFAULT_graphExplorerPinnedHeading,LYRA_DEFAULT_graphExplorerSearchLimit,LYRA_DEFAULT_graphExplorerSearchPlaceholder,LYRA_DEFAULT_graphExplorerSearchResultsLabel,LYRA_DEFAULT_graphExplorerUnpin,LYRA_DEFAULT_graphExplorerUnpinned}from"../../../internal/default-strings/retrieval.generated.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}from"../../../internal/default-strings/shared.generated.js";const SEARCH_RESULT_LIMIT=50;function isElementNode(value){if(typeof value!="object"||value===null)return!1;const candidate=value;return candidate.nodeType===1&&typeof candidate.matches=="function"&&typeof candidate.getBoundingClientRect=="function"}class LyraKnowledgeGraphExplorer extends LyraElement{constructor(){super(...arguments),this.nodes=[],this.edges=[],this.nodeTypes=[],this.communities=[],this.entityDetails={},this.pinnedNodeIds=[],this.path=[],this.hiddenTypes=[],this.selectedNodeId=null,this.renderer="svg",this.fitTo="none",this.width=800,this.height=600,this.highlight="selection",this.query="",this.pinLiveText="",this.hoveredNodeId=null,this.activeResult=0,this.activationGeneration=0,this.nodeById=new Map,this.linksByNodeId=new Map,this.degreeByNodeId=new Map,this.communityLabelById=new Map,this.announcements=new AnnouncementSinkController(this,{eager:["polite"]}),this.onVisibilityChange=event=>{event.stopPropagation(),this.hiddenTypes=event.detail.hiddenTypes,this.emit("lr-hidden-types-change",{hiddenTypes:this.hiddenTypes})},this.onVisibilityChangeProposal=event=>{event.stopPropagation()},this.onSearchInput=event=>{event.stopPropagation();const value=event.detail.value;this.query!==value&&(this.query=value,this.emit("lr-search-change",{query:value,matchCount:this.matchingNodes()?.length??0,matchCountExact:!0,activeIndex:-1}))},this.onEntityActivate=event=>{event.stopPropagation(),this.activateEntity(event.detail.entityId)},this.onGraphNodeClick=event=>{const id=event.detail.nodeId;if(!this.canActivateNode(id))return;const generation=this.invalidateActivation();this.setInternalSelectedNodeId(id),this.pendingNodeId=id;const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;ownerWindow&&ownerWindow.queueMicrotask(()=>{generation===this.activationGeneration&&this.isConnected&&this.ownerDocument===ownerDocument&&this.pendingNodeId===id&&(this.pendingNodeId=void 0,this.selectedNodeId===id&&this.isVisibleNode(id)&&this.activateEntity(id))})},this.onGraphNativeClick=event=>{const id=this.pendingNodeId;id&&(this.pendingNodeId=void 0,this.openDetailAt(id,this.resolveDirectClickAnchor(event)))},this.onGraphViewportChange=()=>{const el=this.trackedNodeEl,popover=this.popoverEl;if(!el?.isConnected||!popover?.open)return;const rect=el.getBoundingClientRect();popover.showAt({x:rect.left+rect.width/2,y:rect.top,width:rect.width,height:rect.height})},this.onGraphNodeEnter=event=>{this.highlight==="hover"&&(this.hoveredNodeId=event.detail.nodeId)},this.onGraphNodeLeave=event=>{this.highlight==="hover"&&this.hoveredNodeId===event.detail.nodeId&&(this.hoveredNodeId=null)},this.onResultKeyDown=event=>{const buttons=[...this.renderRoot.querySelectorAll('[part="search-result"] button')],index=buttons.indexOf(event.target),next={ArrowDown:index+1,ArrowUp:index-1,Home:0,End:buttons.length-1}[event.key];index<0||next===void 0||(event.preventDefault(),this.activeResult=Math.max(0,Math.min(buttons.length-1,next)),buttons[this.activeResult].focus())},this.onPopoverHide=()=>{this.invalidateActivation(),this.trackedNodeEl=void 0,this.setInternalSelectedNodeId(null)}}static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,graphDataListLimit:LYRA_DEFAULT_graphDataListLimit,graphExplorerFindPath:LYRA_DEFAULT_graphExplorerFindPath,graphExplorerLabel:LYRA_DEFAULT_graphExplorerLabel,graphExplorerPin:LYRA_DEFAULT_graphExplorerPin,graphExplorerPinned:LYRA_DEFAULT_graphExplorerPinned,graphExplorerPinnedHeading:LYRA_DEFAULT_graphExplorerPinnedHeading,graphExplorerSearchLimit:LYRA_DEFAULT_graphExplorerSearchLimit,graphExplorerSearchPlaceholder:LYRA_DEFAULT_graphExplorerSearchPlaceholder,graphExplorerSearchResultsLabel:LYRA_DEFAULT_graphExplorerSearchResultsLabel,graphExplorerUnpin:LYRA_DEFAULT_graphExplorerUnpin,graphExplorerUnpinned:LYRA_DEFAULT_graphExplorerUnpinned,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["nodes","edges","nodeTypes","communities","entityDetails","pinnedNodeIds","path","hiddenTypes"])}static{this.styles=[LyraElement.styles,styles,srOnly]}static{this.immutableEventDetails=Object.freeze(["lr-selection-change","lr-pin-change","lr-hidden-types-change"])}get graphModel(){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 canonicalPinnedNodeIds(){return canonicalIdentityList(this.pinnedNodeIds)}get canonicalHiddenTypes(){return canonicalIdentityList(this.hiddenTypes)}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.resumePresetActivation()}willUpdate(changed){super.willUpdate(changed),(changed.has("nodes")||changed.has("edges")||changed.has("communities"))&&this.rebuildDerivedCollections(),this.hoveredNodeId&&!this.isVisibleNode(this.hoveredNodeId)&&(this.hoveredNodeId=null),(changed.has("nodes")||changed.has("hiddenTypes"))&&this.selectedNodeId&&!this.isVisibleNode(this.selectedNodeId)&&(this.invalidateActivation(),this.setInternalSelectedNodeId(null),this.popoverEl&&(this.popoverEl.open=!1)),this.hasUpdated&&(this.query??"").trim()&&(changed.has("query")||changed.has("nodes")||changed.has("hiddenTypes")||changed.has("locale")||changed.has("strings"))&&this.announcements.announcePolite(this.searchResultAnnouncement())}updated(changed){if(super.updated(changed),!changed.has("selectedNodeId"))return;const internallyAssigned=this.internalSelectionAssignment!==void 0&&Object.is(this.internalSelectionAssignment.value,this.selectedNodeId);if(this.internalSelectionAssignment=void 0,internallyAssigned)return;const generation=this.invalidateActivation(),id=this.selectedNodeId;if(!isNonBlankIdentity(id)){id!==null&&(this.selectedNodeId=null),this.popoverEl&&(this.popoverEl.open=!1);return}const graph=this.graphEl;graph&&this.isVisibleNode(id)&&this.activatePresetWhenGraphReady(id,graph,generation)}async activatePresetWhenGraphReady(id,graph,generation){for(await graph.updateComplete;generation===this.activationGeneration&&this.isConnected&&graph.isConnected&&this.selectedNodeId===id&&graph.shadowRoot?.querySelector(tag("skeleton"));)if(!await this.waitForActivationFrame(generation))return;generation===this.activationGeneration&&this.isConnected&&this.selectedNodeId===id&&this.isVisibleNode(id)&&await this.activateEntity(id)}waitForActivationFrame(generation){this.cancelActivationFrame();const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;return!ownerWindow||!this.isConnected||generation!==this.activationGeneration?Promise.resolve(!1):new Promise(resolve=>{let settled=!1;const settle=ready=>{settled||(settled=!0,resolve(ready))};let handle;const onPageHide=()=>{this.activationFrameOwner===ownerWindow&&this.activationFrameDocument===ownerDocument&&this.activationFrameResolve===settle&&this.cancelActivationFrame()};try{handle=ownerWindow.requestAnimationFrame(()=>{const current=this.activationFrameId===handle&&this.activationFrameOwner===ownerWindow&&this.activationFrameDocument===ownerDocument&&this.activationFrameResolve===settle&&generation===this.activationGeneration&&this.isConnected&&this.ownerDocument===ownerDocument;current&&this.clearActivationFrameRecord(),settle(current)})}catch{settle(!1);return}this.activationFrameId=handle,this.activationFrameOwner=ownerWindow,this.activationFrameDocument=ownerDocument,this.activationFrameResolve=settle,this.activationFramePageHide=onPageHide,ownerWindow.addEventListener("pagehide",onPageHide,{once:!0})})}clearActivationFrameRecord(){this.activationFramePageHide&&this.activationFrameOwner?.removeEventListener("pagehide",this.activationFramePageHide),this.activationFrameId=void 0,this.activationFrameOwner=void 0,this.activationFrameDocument=void 0,this.activationFrameResolve=void 0,this.activationFramePageHide=void 0}cancelActivationFrame(){const handle=this.activationFrameId,ownerWindow=this.activationFrameOwner,settle=this.activationFrameResolve;this.clearActivationFrameRecord();try{handle!==void 0&&ownerWindow?.cancelAnimationFrame(handle)}finally{settle?.(!1)}}invalidateActivation(){return this.activationGeneration+=1,this.cancelActivationFrame(),this.activationGeneration}resumePresetActivation(){const id=this.selectedNodeId,graph=this.graphEl;if(!id||!graph||!this.isVisibleNode(id))return;const generation=this.invalidateActivation();this.activatePresetWhenGraphReady(id,graph,generation)}setInternalSelectedNodeId(value){Object.is(this.selectedNodeId,value)||(this.internalSelectionAssignment={value},this.selectedNodeId=value,this.emit("lr-selection-change",{selectedNodeId:value,selectedNodeIds:value?[value]:[],selectedEdgeIds:[]}))}disconnectedCallback(){this.invalidateActivation(),this.pendingNodeId=void 0,this.trackedNodeEl=void 0,this.hoveredNodeId=null,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.invalidateActivation(),this.announcements.adopted(),this.isConnected&&this.resumePresetActivation()}rebuildDerivedCollections(){const model=this.graphModel;this.nodeById=new Map(model.nodes.map(node=>[node.id,node])),this.communityLabelById=new Map(model.communities.map(community=>[community.id,community.label]));const linksByNodeId=new Map,degrees=new Map;for(const link of model.links)for(const id of new Set([link.source,link.target])){const adjacent=linksByNodeId.get(id);adjacent?adjacent.push(link):linksByNodeId.set(id,[link]),degrees.set(id,(degrees.get(id)??0)+1)}this.linksByNodeId=linksByNodeId,this.degreeByNodeId=degrees}isVisibleGraphNode(node){return node.type==null||!this.canonicalHiddenTypes.includes(node.type)}isVisibleNode(id){const node=this.nodeById.get(id);return!!node&&this.isVisibleGraphNode(node)}canActivateNode(id){const node=this.nodeById.get(id);return node?this.isVisibleGraphNode(node):!this.hasUpdated&&this.graphModel.nodes.length===0}nodeLabel(id){const node=this.nodeById.get(id);return node?.label||node?.accessibleLabel||id}degreeOf(id){return this.degreeByNodeId.get(id)??0}entityFor(id){const node=this.nodeById.get(id);if(!node)return;const details=this.entityDetails[id];return{id:node.id,label:node.label||node.accessibleLabel||node.id,type:node.type,communityId:node.communityId,description:details?.description,properties:details?.properties,degree:details?.degree??this.degreeOf(node.id)}}communityLabelFor(communityId){return communityId?this.communityLabelById.get(communityId)??communityId:""}neighborRowsFor(id){const rows=[];for(const link of this.linksByNodeId.get(id)??[])if(link.source===id){const node=this.entityFor(link.target);node&&this.isVisibleNode(link.target)&&rows.push({relation:link.label??"",direction:"out",node})}else if(link.target===id){const node=this.entityFor(link.source);node&&this.isVisibleNode(link.source)&&rows.push({relation:link.label??"",direction:"in",node})}return rows}searchableNamesOf(node){return[node.label,node.accessibleLabel,node.id].filter(name=>typeof name=="string"&&name!=="")}matchingNodes(){const query2=this.query??"",locale=this.effectiveLocale,model=this.graphModel,hidden=this.canonicalHiddenTypes,memo=this.matchesMemo;if(memo?.[0]===query2&&memo[1]===locale&&memo[2]===model&&memo[3]===hidden)return memo[4];const q=query2.trim().toLocaleLowerCase(locale),matches=q?model.nodes.filter(node=>this.isVisibleGraphNode(node)&&this.searchableNamesOf(node).some(name=>name.toLocaleLowerCase(locale).includes(q))):void 0;return this.matchesMemo=[query2,locale,model,hidden,matches],matches}searchResultAnnouncement(matches=this.matchingNodes()){return matches?matches.length===0?this.localize("viewerSearchNoMatches"):this.localize("viewerSearchMatchCount",void 0,{count:getNumberFormat(this.effectiveLocale).format(matches.length),pluralCount:matches.length}):""}neighborIdsOf(id){const ids=new Set;for(const link of this.linksByNodeId.get(id)??[])link.source===id?ids.add(link.target):link.target===id&&ids.add(link.source);return ids}linkKey(link){return graphLinkIdentity(link)}get computedDimmedNodeIds(){if(this.highlight==="none")return[];const matches=this.matchingNodes();if(matches){const matchIds=new Set(matches.map(n=>n.id));return this.graphModel.nodes.filter(n=>!matchIds.has(n.id)).map(n=>n.id)}const focusNodeId=this.selectedNodeId??(this.highlight==="hover"?this.hoveredNodeId:null);if(focusNodeId){const keep=this.neighborIdsOf(focusNodeId);return keep.add(focusNodeId),this.graphModel.nodes.filter(n=>!keep.has(n.id)).map(n=>n.id)}return[]}get computedDimmedLinkIds(){const dimmedNodes=new Set(this.computedDimmedNodeIds);return dimmedNodes.size===0?[]:this.graphModel.links.filter(l=>dimmedNodes.has(l.source)||dimmedNodes.has(l.target)).map(l=>this.linkKey(l))}togglePin(id){if(!isNonBlankIdentity(id))return;const pinnedNodeIds=this.canonicalPinnedNodeIds,wasPinned=pinnedNodeIds.includes(id),next=wasPinned?pinnedNodeIds.filter(existing=>existing!==id):[...pinnedNodeIds,id];this.pinnedNodeIds=next,this.pinLiveText=this.localize(wasPinned?"graphExplorerUnpinned":"graphExplorerPinned",void 0,{label:this.nodeLabel(id)}),this.announcements.announcePolite(this.pinLiveText),this.emit("lr-pin-change",{pinnedNodeIds:next})}requestPath(){const pinnedNodeIds=this.canonicalPinnedNodeIds;if(pinnedNodeIds.length!==2)return;const[sourceNodeId,targetNodeId]=pinnedNodeIds;this.emit("lr-path-request",{sourceNodeId,targetNodeId})}fit(options){this.graphEl?.fit(options)}resetView(){this.graphEl?.fit()}async focusNode(id,options){return this.isVisibleNode(id)?await this.graphEl?.focusNode(id,options)??!1:!1}async activateEntity(id){if(!this.canActivateNode(id))return;const generation=this.invalidateActivation();this.setInternalSelectedNodeId(id),this.trackedNodeEl=void 0;const graph=this.graphEl,focused=graph?await graph.focusNode(id):!1;if(generation!==this.activationGeneration||!this.isConnected||this.selectedNodeId!==id||!this.isVisibleNode(id)||!focused)return;const rect=graph?.getBoundingClientRect();rect&&this.openDetailAt(id,{x:rect.left+rect.width/2,y:rect.top+rect.height/2,width:0,height:0})}openDetailAt(id,rect){const popover=this.popoverEl;popover&&(popover.accessibleLabel=this.entityFor(id)?.label||"",popover.showAt(rect))}resolveDirectClickAnchor(event){if(this.renderer==="canvas")return this.trackedNodeEl=void 0,{x:event.clientX,y:event.clientY,width:0,height:0};const nodeEl=event.composedPath().find(el=>isElementNode(el)&&el.matches('[part="node"]'));if(!nodeEl)return this.trackedNodeEl=void 0,{x:event.clientX,y:event.clientY,width:0,height:0};this.trackedNodeEl=nodeEl;const rect=nodeEl.getBoundingClientRect();return{x:rect.left+rect.width/2,y:rect.top,width:rect.width,height:rect.height}}render(){const groupLabel=retrievalSemanticLabel(this,this.label==null?this.localize("graphExplorerLabel"):this.label),groupRole=retrievalSemanticRole(this,"group"),matches=this.matchingNodes(),detailsLimit=publicCollectionTruncation(this,"entityDetails"),model=this.graphModel,pinnedNodeIds=this.canonicalPinnedNodeIds,hiddenTypes=this.canonicalHiddenTypes,selectedEntity=this.selectedNodeId?this.entityFor(this.selectedNodeId)??null:null,isPinned=this.selectedNodeId!=null&&pinnedNodeIds.includes(this.selectedNodeId),dimmedDeps=[this.highlight,matches,this.selectedNodeId,this.hoveredNodeId,model],detailDeps=[this.selectedNodeId,model,hiddenTypes,this.entityDetails];return html`
1
+ import{__decorate}from"tslib";import{collectionSupport,publicCollectionTruncation}from"../../../internal/collection-snapshot.js";import{tag}from"../../../internal/prefix.js";import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{guard}from"lit/directives/guard.js";import{LyraElement}from"../../../internal/lyra-element.js";import{finiteRange}from"../../../internal/numbers.js";import{srOnly}from"../../../internal/a11y.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./knowledge-graph-explorer.styles.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{graphLengthConverter,graphLinkIdentity,normalizeGraphModel}from"../graph/graph-model.js";import{canonicalIdentityList,isNonBlankIdentity}from"../retrieval-identity.js";import"../graph/graph.class.js";import"../graph-legend/graph-legend.class.js";import"../entity-card/entity-card.class.js";import"../neighbor-list/neighbor-list.class.js";import"../path-strip/path-strip.class.js";import"../../overlays/overlay/popover.class.js";import"../../forms/input/input.class.js";import"../../overlays/chip/chip.class.js";import"../../forms/button/button.class.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{LYRA_DEFAULT_graphDataListLimit,LYRA_DEFAULT_graphExplorerFindPath,LYRA_DEFAULT_graphExplorerLabel,LYRA_DEFAULT_graphExplorerPin,LYRA_DEFAULT_graphExplorerPinned,LYRA_DEFAULT_graphExplorerPinnedHeading,LYRA_DEFAULT_graphExplorerSearchLimit,LYRA_DEFAULT_graphExplorerSearchPlaceholder,LYRA_DEFAULT_graphExplorerSearchResultsLabel,LYRA_DEFAULT_graphExplorerUnpin,LYRA_DEFAULT_graphExplorerUnpinned}from"../../../internal/default-strings/retrieval.generated.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}from"../../../internal/default-strings/shared.generated.js";const SEARCH_RESULT_LIMIT=50;function isElementNode(value){if(typeof value!="object"||value===null)return!1;const candidate=value;return candidate.nodeType===1&&typeof candidate.matches=="function"&&typeof candidate.getBoundingClientRect=="function"}class LyraKnowledgeGraphExplorer extends LyraElement{constructor(){super(...arguments),this.nodes=[],this.edges=[],this.nodeTypes=[],this.communities=[],this.entityDetails={},this.pinnedNodeIds=[],this.path=[],this.hiddenTypes=[],this.selectedNodeId=null,this.renderer="svg",this.fitTo="none",this.width=800,this.height=600,this.highlight="selection",this.query="",this.pinLiveText="",this.hoveredNodeId=null,this.activeResult=0,this.activationGeneration=0,this.nodeById=new Map,this.linksByNodeId=new Map,this.degreeByNodeId=new Map,this.communityLabelById=new Map,this.announcements=new AnnouncementSinkController(this,{eager:["polite"]}),this.onVisibilityChange=event=>{event.stopPropagation(),this.hiddenTypes=event.detail.hiddenTypes,this.emit("lr-hidden-types-change",{hiddenTypes:this.hiddenTypes})},this.onVisibilityChangeProposal=event=>{event.stopPropagation()},this.onSearchInput=event=>{event.stopPropagation();const value=event.detail.value;this.query!==value&&(this.query=value,this.emit("lr-search-change",{query:value,matchCount:this.matchingNodes()?.length??0,matchCountExact:!0,activeIndex:-1}))},this.onEntityActivate=event=>{event.stopPropagation(),this.activateEntity(event.detail.entityId)},this.onGraphNodeClick=event=>{const id=event.detail.nodeId;if(!this.canActivateNode(id))return;const generation=this.invalidateActivation();this.setInternalSelectedNodeId(id),this.pendingNodeId=id;const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;ownerWindow&&ownerWindow.queueMicrotask(()=>{generation===this.activationGeneration&&this.isConnected&&this.ownerDocument===ownerDocument&&this.pendingNodeId===id&&(this.pendingNodeId=void 0,this.selectedNodeId===id&&this.isVisibleNode(id)&&this.activateEntity(id))})},this.onGraphNativeClick=event=>{const id=this.pendingNodeId;id&&(this.pendingNodeId=void 0,this.openDetailAt(id,this.resolveDirectClickAnchor(event)))},this.onGraphViewportChange=()=>{const el=this.trackedNodeEl,popover=this.popoverEl;if(!el?.isConnected||!popover?.open)return;const rect=el.getBoundingClientRect();popover.showAt({x:rect.left+rect.width/2,y:rect.top,width:rect.width,height:rect.height})},this.onGraphNodeEnter=event=>{this.highlight==="hover"&&(this.hoveredNodeId=event.detail.nodeId)},this.onGraphNodeLeave=event=>{this.highlight==="hover"&&this.hoveredNodeId===event.detail.nodeId&&(this.hoveredNodeId=null)},this.onResultKeyDown=event=>{const buttons=[...this.renderRoot.querySelectorAll('[part="search-result"] button')],index=buttons.indexOf(event.target),next={ArrowDown:index+1,ArrowUp:index-1,Home:0,End:buttons.length-1}[event.key];index<0||next===void 0||(event.preventDefault(),this.activeResult=Math.max(0,Math.min(buttons.length-1,next)),buttons[this.activeResult].focus())},this.onPopoverHide=()=>{this.invalidateActivation(),this.trackedNodeEl=void 0,this.setInternalSelectedNodeId(null)}}static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,graphDataListLimit:LYRA_DEFAULT_graphDataListLimit,graphExplorerFindPath:LYRA_DEFAULT_graphExplorerFindPath,graphExplorerLabel:LYRA_DEFAULT_graphExplorerLabel,graphExplorerPin:LYRA_DEFAULT_graphExplorerPin,graphExplorerPinned:LYRA_DEFAULT_graphExplorerPinned,graphExplorerPinnedHeading:LYRA_DEFAULT_graphExplorerPinnedHeading,graphExplorerSearchLimit:LYRA_DEFAULT_graphExplorerSearchLimit,graphExplorerSearchPlaceholder:LYRA_DEFAULT_graphExplorerSearchPlaceholder,graphExplorerSearchResultsLabel:LYRA_DEFAULT_graphExplorerSearchResultsLabel,graphExplorerUnpin:LYRA_DEFAULT_graphExplorerUnpin,graphExplorerUnpinned:LYRA_DEFAULT_graphExplorerUnpinned,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["nodes","edges","nodeTypes","communities","entityDetails","pinnedNodeIds","path","hiddenTypes"])}static{this.styles=[LyraElement.styles,styles,srOnly]}static{this.immutableEventDetails=Object.freeze(["lr-selection-change","lr-pin-change","lr-hidden-types-change"])}get graphModel(){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 canonicalPinnedNodeIds(){return canonicalIdentityList(this.pinnedNodeIds)}get canonicalHiddenTypes(){return canonicalIdentityList(this.hiddenTypes)}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.resumePresetActivation()}willUpdate(changed){super.willUpdate(changed),(changed.has("nodes")||changed.has("edges")||changed.has("communities"))&&this.rebuildDerivedCollections(),this.hoveredNodeId&&!this.isVisibleNode(this.hoveredNodeId)&&(this.hoveredNodeId=null),(changed.has("nodes")||changed.has("hiddenTypes"))&&this.selectedNodeId&&!this.isVisibleNode(this.selectedNodeId)&&(this.invalidateActivation(),this.setInternalSelectedNodeId(null),this.popoverEl&&(this.popoverEl.open=!1)),this.hasUpdated&&(this.query??"").trim()&&(changed.has("query")||changed.has("nodes")||changed.has("hiddenTypes")||changed.has("locale")||changed.has("strings"))&&this.announcements.announcePolite(this.searchResultAnnouncement())}updated(changed){if(super.updated(changed),!changed.has("selectedNodeId"))return;const internallyAssigned=this.internalSelectionAssignment!==void 0&&Object.is(this.internalSelectionAssignment.value,this.selectedNodeId);if(this.internalSelectionAssignment=void 0,internallyAssigned)return;const generation=this.invalidateActivation(),id=this.selectedNodeId;if(!isNonBlankIdentity(id)){id!==null&&(this.selectedNodeId=null),this.popoverEl&&(this.popoverEl.open=!1);return}const graph=this.graphEl;graph&&this.isVisibleNode(id)&&this.activatePresetWhenGraphReady(id,graph,generation)}async activatePresetWhenGraphReady(id,graph,generation){for(await graph.updateComplete;generation===this.activationGeneration&&this.isConnected&&graph.isConnected&&this.selectedNodeId===id&&graph.shadowRoot?.querySelector(tag("skeleton"));)if(!await this.waitForActivationFrame(generation))return;generation===this.activationGeneration&&this.isConnected&&this.selectedNodeId===id&&this.isVisibleNode(id)&&await this.activateEntity(id)}waitForActivationFrame(generation){this.cancelActivationFrame();const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;return!ownerWindow||!this.isConnected||generation!==this.activationGeneration?Promise.resolve(!1):new Promise(resolve=>{let settled=!1;const settle=ready=>{settled||(settled=!0,resolve(ready))};let handle;const onPageHide=()=>{this.activationFrameOwner===ownerWindow&&this.activationFrameDocument===ownerDocument&&this.activationFrameResolve===settle&&this.cancelActivationFrame()};try{handle=ownerWindow.requestAnimationFrame(()=>{const current=this.activationFrameId===handle&&this.activationFrameOwner===ownerWindow&&this.activationFrameDocument===ownerDocument&&this.activationFrameResolve===settle&&generation===this.activationGeneration&&this.isConnected&&this.ownerDocument===ownerDocument;current&&this.clearActivationFrameRecord(),settle(current)})}catch{settle(!1);return}this.activationFrameId=handle,this.activationFrameOwner=ownerWindow,this.activationFrameDocument=ownerDocument,this.activationFrameResolve=settle,this.activationFramePageHide=onPageHide,ownerWindow.addEventListener("pagehide",onPageHide,{once:!0})})}clearActivationFrameRecord(){this.activationFramePageHide&&this.activationFrameOwner?.removeEventListener("pagehide",this.activationFramePageHide),this.activationFrameId=void 0,this.activationFrameOwner=void 0,this.activationFrameDocument=void 0,this.activationFrameResolve=void 0,this.activationFramePageHide=void 0}cancelActivationFrame(){const handle=this.activationFrameId,ownerWindow=this.activationFrameOwner,settle=this.activationFrameResolve;this.clearActivationFrameRecord();try{handle!==void 0&&ownerWindow?.cancelAnimationFrame(handle)}finally{settle?.(!1)}}invalidateActivation(){return this.activationGeneration+=1,this.cancelActivationFrame(),this.activationGeneration}resumePresetActivation(){const id=this.selectedNodeId,graph=this.graphEl;if(!id||!graph||!this.isVisibleNode(id))return;const generation=this.invalidateActivation();this.activatePresetWhenGraphReady(id,graph,generation)}setInternalSelectedNodeId(value){Object.is(this.selectedNodeId,value)||(this.internalSelectionAssignment={value},this.selectedNodeId=value,this.emit("lr-selection-change",{selectedNodeId:value,selectedNodeIds:value?[value]:[],selectedEdgeIds:[]}))}disconnectedCallback(){this.invalidateActivation(),this.pendingNodeId=void 0,this.trackedNodeEl=void 0,this.hoveredNodeId=null,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.invalidateActivation(),this.announcements.adopted(),this.isConnected&&this.resumePresetActivation()}rebuildDerivedCollections(){const model=this.graphModel;this.nodeById=new Map(model.nodes.map(node=>[node.id,node])),this.communityLabelById=new Map(model.communities.map(community=>[community.id,community.label]));const linksByNodeId=new Map,degrees=new Map;for(const link of model.links)for(const id of new Set([link.source,link.target])){const adjacent=linksByNodeId.get(id);adjacent?adjacent.push(link):linksByNodeId.set(id,[link]),degrees.set(id,(degrees.get(id)??0)+1)}this.linksByNodeId=linksByNodeId,this.degreeByNodeId=degrees}isVisibleGraphNode(node){return node.type==null||!this.canonicalHiddenTypes.includes(node.type)}isVisibleNode(id){const node=this.nodeById.get(id);return!!node&&this.isVisibleGraphNode(node)}canActivateNode(id){const node=this.nodeById.get(id);return node?this.isVisibleGraphNode(node):!this.hasUpdated&&this.graphModel.nodes.length===0}nodeLabel(id){const node=this.nodeById.get(id);return node?.label||node?.accessibleLabel||id}degreeOf(id){return this.degreeByNodeId.get(id)??0}entityFor(id){const node=this.nodeById.get(id);if(!node)return;const details=this.entityDetails[id];return{id:node.id,label:node.label||node.accessibleLabel||node.id,type:node.type,communityId:node.communityId,description:details?.description,properties:details?.properties,degree:details?.degree??this.degreeOf(node.id)}}communityLabelFor(communityId){return communityId?this.communityLabelById.get(communityId)??communityId:""}neighborRowsFor(id){const rows=[];for(const link of this.linksByNodeId.get(id)??[])if(link.source===id){const node=this.entityFor(link.target);node&&this.isVisibleNode(link.target)&&rows.push({relation:link.label??"",direction:"out",node})}else if(link.target===id){const node=this.entityFor(link.source);node&&this.isVisibleNode(link.source)&&rows.push({relation:link.label??"",direction:"in",node})}return rows}searchableNamesOf(node){return[node.label,node.accessibleLabel,node.id].filter(name=>typeof name=="string"&&name!=="")}matchingNodes(){const query2=this.query??"",locale=this.effectiveLocale,model=this.graphModel,hidden=this.canonicalHiddenTypes,memo=this.matchesMemo;if(memo?.[0]===query2&&memo[1]===locale&&memo[2]===model&&memo[3]===hidden)return memo[4];const q=query2.trim().toLocaleLowerCase(locale);let matches;if(q){const hiddenTypes=new Set(hidden);matches=model.nodes.filter(node=>(node.type==null||!hiddenTypes.has(node.type))&&this.searchableNamesOf(node).some(name=>name.toLocaleLowerCase(locale).includes(q)))}return this.matchesMemo=[query2,locale,model,hidden,matches],matches}searchResultAnnouncement(matches=this.matchingNodes()){return matches?matches.length===0?this.localize("viewerSearchNoMatches"):this.localize("viewerSearchMatchCount",void 0,{count:getNumberFormat(this.effectiveLocale).format(matches.length),pluralCount:matches.length}):""}neighborIdsOf(id){const ids=new Set;for(const link of this.linksByNodeId.get(id)??[])link.source===id?ids.add(link.target):link.target===id&&ids.add(link.source);return ids}linkKey(link){return graphLinkIdentity(link)}get computedDimmedNodeIds(){if(this.highlight==="none")return[];const matches=this.matchingNodes();if(matches){const matchIds=new Set(matches.map(n=>n.id));return this.graphModel.nodes.filter(n=>!matchIds.has(n.id)).map(n=>n.id)}const focusNodeId=this.selectedNodeId??(this.highlight==="hover"?this.hoveredNodeId:null);if(focusNodeId){const keep=this.neighborIdsOf(focusNodeId);return keep.add(focusNodeId),this.graphModel.nodes.filter(n=>!keep.has(n.id)).map(n=>n.id)}return[]}get computedDimmedLinkIds(){const dimmedNodes=new Set(this.computedDimmedNodeIds);return dimmedNodes.size===0?[]:this.graphModel.links.filter(l=>dimmedNodes.has(l.source)||dimmedNodes.has(l.target)).map(l=>this.linkKey(l))}togglePin(id){if(!isNonBlankIdentity(id))return;const pinnedNodeIds=this.canonicalPinnedNodeIds,wasPinned=pinnedNodeIds.includes(id),next=wasPinned?pinnedNodeIds.filter(existing=>existing!==id):[...pinnedNodeIds,id];this.pinnedNodeIds=next,this.pinLiveText=this.localize(wasPinned?"graphExplorerUnpinned":"graphExplorerPinned",void 0,{label:this.nodeLabel(id)}),this.announcements.announcePolite(this.pinLiveText),this.emit("lr-pin-change",{pinnedNodeIds:next})}requestPath(){const pinnedNodeIds=this.canonicalPinnedNodeIds;if(pinnedNodeIds.length!==2)return;const[sourceNodeId,targetNodeId]=pinnedNodeIds;this.emit("lr-path-request",{sourceNodeId,targetNodeId})}fit(options){this.graphEl?.fit(options)}resetView(){this.graphEl?.fit()}async focusNode(id,options){return this.isVisibleNode(id)?await this.graphEl?.focusNode(id,options)??!1:!1}async activateEntity(id){if(!this.canActivateNode(id))return;const generation=this.invalidateActivation();this.setInternalSelectedNodeId(id),this.trackedNodeEl=void 0;const graph=this.graphEl,focused=graph?await graph.focusNode(id):!1;if(generation!==this.activationGeneration||!this.isConnected||this.selectedNodeId!==id||!this.isVisibleNode(id)||!focused)return;const rect=graph?.getBoundingClientRect();rect&&this.openDetailAt(id,{x:rect.left+rect.width/2,y:rect.top+rect.height/2,width:0,height:0})}openDetailAt(id,rect){const popover=this.popoverEl;popover&&(popover.accessibleLabel=this.entityFor(id)?.label||"",popover.showAt(rect))}resolveDirectClickAnchor(event){if(this.renderer==="canvas")return this.trackedNodeEl=void 0,{x:event.clientX,y:event.clientY,width:0,height:0};const nodeEl=event.composedPath().find(el=>isElementNode(el)&&el.matches('[part="node"]'));if(!nodeEl)return this.trackedNodeEl=void 0,{x:event.clientX,y:event.clientY,width:0,height:0};this.trackedNodeEl=nodeEl;const rect=nodeEl.getBoundingClientRect();return{x:rect.left+rect.width/2,y:rect.top,width:rect.width,height:rect.height}}render(){const groupLabel=retrievalSemanticLabel(this,this.label==null?this.localize("graphExplorerLabel"):this.label),groupRole=retrievalSemanticRole(this,"group"),matches=this.matchingNodes(),detailsLimit=publicCollectionTruncation(this,"entityDetails"),model=this.graphModel,pinnedNodeIds=this.canonicalPinnedNodeIds,hiddenTypes=this.canonicalHiddenTypes,selectedEntity=this.selectedNodeId?this.entityFor(this.selectedNodeId)??null:null,isPinned=this.selectedNodeId!=null&&pinnedNodeIds.includes(this.selectedNodeId),dimmedDeps=[this.highlight,matches,this.selectedNodeId,this.hoveredNodeId,model],detailDeps=[this.selectedNodeId,model,hiddenTypes,this.entityDetails];return html`
2
2
  <div
3
3
  part="base"
4
4
  role=${groupRole??nothing}
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{guard}from"lit/directives/guard.js";import{LyraElement}from"../../../internal/lyra-element.js";import{firstByRetrievalIdentity}from"../retrieval-identity.js";import{expandIcon}from"../../../internal/icons.js";import{finiteCount}from"../../../internal/numbers.js";import{getCollator,getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import"../../overlays/empty/empty.class.js";import{styles}from"./neighbor-list.styles.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{LYRA_DEFAULT_neighborExpand,LYRA_DEFAULT_neighborGroupHeader,LYRA_DEFAULT_neighborListEmpty,LYRA_DEFAULT_neighborListLabel,LYRA_DEFAULT_neighborRowLabel}from"../../../internal/default-strings/retrieval.generated.js";import{LYRA_DEFAULT_neighborDirectionBoth,LYRA_DEFAULT_neighborDirectionIn,LYRA_DEFAULT_neighborDirectionOut}from"../../../internal/default-strings/shared.generated.js";let virtualListRegistration;class LyraNeighborList extends LyraElement{constructor(){super(...arguments),this.rows=[],this.types=[],this.groupByRelation=!1,this.expandable=!1,this.virtualizeAt=100,this.sortedRowsCache=[],this.hasComputedRows=!1,this.processedSignature="",this.renderRow=item=>this.renderNeighborRow(item),this.virtualListKeyFunction=item=>item.node.id}static{this.defaultStrings={...super.defaultStrings,neighborDirectionBoth:LYRA_DEFAULT_neighborDirectionBoth,neighborDirectionIn:LYRA_DEFAULT_neighborDirectionIn,neighborDirectionOut:LYRA_DEFAULT_neighborDirectionOut,neighborExpand:LYRA_DEFAULT_neighborExpand,neighborGroupHeader:LYRA_DEFAULT_neighborGroupHeader,neighborListEmpty:LYRA_DEFAULT_neighborListEmpty,neighborListLabel:LYRA_DEFAULT_neighborListLabel,neighborRowLabel:LYRA_DEFAULT_neighborRowLabel}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["rows","types"])}static{this.styles=[LyraElement.styles,styles]}get effectiveVirtualizeAt(){return finiteCount(this.virtualizeAt,100)}willUpdate(changed){super.willUpdate(changed);const signature=`${this.effectiveLocale} ${this.groupByRelation}`;(!this.hasComputedRows||changed.has("rows")||changed.has("groupByRelation")||signature!==this.processedSignature)&&(this.hasComputedRows=!0,this.processedSignature=signature,this.sortedRowsCache=this.computeSortedRows(),this.groupsCache=this.computeGroups(this.sortedRowsCache)),this.sortedRowsCache.length>this.effectiveVirtualizeAt&&(virtualListRegistration??=import("../../layout/virtual-list/virtual-list.js").catch(()=>virtualListRegistration=void 0))}sortedRows(){return this.sortedRowsCache}computeSortedRows(){const rows=firstByRetrievalIdentity(this.rows,row=>row?.node?.id);return this.groupByRelation?rows.sort((a,b)=>getCollator(this.effectiveLocale).compare(a.relation,b.relation)):rows}groups(sorted){return sorted===this.sortedRowsCache?this.groupsCache:this.computeGroups(sorted)}computeGroups(sorted){if(!this.groupByRelation)return;const groups=[],counts=new Map;for(const row of sorted)counts.set(row.relation,(counts.get(row.relation)??0)+1);const numberFormat=getNumberFormat(this.effectiveLocale);let lastRelation;return sorted.forEach((row,i)=>{if(row.relation!==lastRelation){const count=numberFormat.format(counts.get(row.relation)??0);groups.push({key:row.relation,label:this.localize("neighborGroupHeader",void 0,{relation:row.relation,count}),startIndex:i}),lastRelation=row.relation}}),groups}directionGlyph(direction){return direction==="both"?"↔":direction==="out"?"→":"←"}directionText(direction){return this.localize(direction==="in"?"neighborDirectionIn":direction==="out"?"neighborDirectionOut":"neighborDirectionBoth")}renderNeighborRow(row){const nodeLabel=row.node.label||row.node.id,directionText=this.directionText(row.direction),accessibleName=this.localize("neighborRowLabel",void 0,{label:nodeLabel,relation:row.relation,direction:directionText}),nodeType=typeof row.node.type=="string"&&row.node.type.trim()!==""?row.node.type:void 0;this.typeLabels?.[0]!==this.types&&(this.typeLabels=[this.types,new Map(firstByRetrievalIdentity(this.types,type=>type?.id).map(type=>[type.id,type.label]))]);const meta=[nodeType&&(this.typeLabels[1].get(nodeType)??nodeType),row.node.degree!=null?getNumberFormat(this.effectiveLocale).format(finiteCount(row.node.degree)):void 0].filter(v=>typeof v=="string"&&v!==""),metaText=getListFormat(this.effectiveLocale,{style:"short",type:"unit"}).format(meta);return html`
1
+ import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{guard}from"lit/directives/guard.js";import{LyraElement}from"../../../internal/lyra-element.js";import{firstByRetrievalIdentity}from"../retrieval-identity.js";import{expandIcon}from"../../../internal/icons.js";import{finiteCount}from"../../../internal/numbers.js";import{getCollator,getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import"../../overlays/empty/empty.class.js";import{styles}from"./neighbor-list.styles.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{LYRA_DEFAULT_neighborExpand,LYRA_DEFAULT_neighborGroupHeader,LYRA_DEFAULT_neighborListEmpty,LYRA_DEFAULT_neighborListLabel,LYRA_DEFAULT_neighborRowLabel}from"../../../internal/default-strings/retrieval.generated.js";import{LYRA_DEFAULT_neighborDirectionBoth,LYRA_DEFAULT_neighborDirectionIn,LYRA_DEFAULT_neighborDirectionOut}from"../../../internal/default-strings/shared.generated.js";let virtualListRegistration;class LyraNeighborList extends LyraElement{constructor(){super(...arguments),this.rows=[],this.types=[],this.groupByRelation=!1,this.expandable=!1,this.virtualizeAt=100,this.sortedRowsCache=[],this.hasComputedRows=!1,this.processedSignature="",this.renderRow=item=>this.renderNeighborRow(item),this.virtualListKeyFunction=item=>item.node.id}static{this.defaultStrings={...super.defaultStrings,neighborDirectionBoth:LYRA_DEFAULT_neighborDirectionBoth,neighborDirectionIn:LYRA_DEFAULT_neighborDirectionIn,neighborDirectionOut:LYRA_DEFAULT_neighborDirectionOut,neighborExpand:LYRA_DEFAULT_neighborExpand,neighborGroupHeader:LYRA_DEFAULT_neighborGroupHeader,neighborListEmpty:LYRA_DEFAULT_neighborListEmpty,neighborListLabel:LYRA_DEFAULT_neighborListLabel,neighborRowLabel:LYRA_DEFAULT_neighborRowLabel}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["rows","types"])}static{this.styles=[LyraElement.styles,styles]}get effectiveVirtualizeAt(){return finiteCount(this.virtualizeAt,100)}willUpdate(changed){super.willUpdate(changed);const signature=`${this.effectiveLocale} ${this.groupByRelation}`;(!this.hasComputedRows||changed.has("rows")||changed.has("groupByRelation")||signature!==this.processedSignature)&&(this.hasComputedRows=!0,this.processedSignature=signature,this.sortedRowsCache=this.computeSortedRows(),this.groupsCache=this.computeGroups(this.sortedRowsCache)),this.sortedRowsCache.length>this.effectiveVirtualizeAt&&(virtualListRegistration??=import("../../layout/virtual-list/virtual-list.js").catch(()=>virtualListRegistration=void 0))}sortedRows(){return this.sortedRowsCache}computeSortedRows(){const rows=firstByRetrievalIdentity(this.rows,row=>row?.node?.id);if(!this.groupByRelation)return rows;const compare=getCollator(this.effectiveLocale).compare;return rows.sort((a,b)=>compare(a.relation,b.relation))}groups(sorted){return sorted===this.sortedRowsCache?this.groupsCache:this.computeGroups(sorted)}computeGroups(sorted){if(!this.groupByRelation)return;const groups=[],counts=new Map;for(const row of sorted)counts.set(row.relation,(counts.get(row.relation)??0)+1);const numberFormat=getNumberFormat(this.effectiveLocale);let lastRelation;return sorted.forEach((row,i)=>{if(row.relation!==lastRelation){const count=numberFormat.format(counts.get(row.relation)??0);groups.push({key:row.relation,label:this.localize("neighborGroupHeader",void 0,{relation:row.relation,count}),startIndex:i}),lastRelation=row.relation}}),groups}directionGlyph(direction){return direction==="both"?"↔":direction==="out"?"→":"←"}directionText(direction){return this.localize(direction==="in"?"neighborDirectionIn":direction==="out"?"neighborDirectionOut":"neighborDirectionBoth")}renderNeighborRow(row){const nodeLabel=row.node.label||row.node.id,directionText=this.directionText(row.direction),accessibleName=this.localize("neighborRowLabel",void 0,{label:nodeLabel,relation:row.relation,direction:directionText}),nodeType=typeof row.node.type=="string"&&row.node.type.trim()!==""?row.node.type:void 0;this.typeLabels?.[0]!==this.types&&(this.typeLabels=[this.types,new Map(firstByRetrievalIdentity(this.types,type=>type?.id).map(type=>[type.id,type.label]))]);const meta=[nodeType&&(this.typeLabels[1].get(nodeType)??nodeType),row.node.degree!=null?getNumberFormat(this.effectiveLocale).format(finiteCount(row.node.degree)):void 0].filter(v=>typeof v=="string"&&v!==""),metaText=getListFormat(this.effectiveLocale,{style:"short",type:"unit"}).format(meta);return html`
2
2
  <button
3
3
  part="node-label"
4
4
  type="button"
@@ -186,4 +186,4 @@ announce:boolean;
186
186
  * says exactly what this region is. An explicit empty string clears the fallback. A non-empty
187
187
  * host `aria-label` makes the host the sole overall owner; an explicitly empty host label stays
188
188
  * empty on the region. */
189
- label?:string;private expandedChunkIds;private pendingFocusTarget;private previousProcessedChunkIds;private focusRestoreGeneration;private isMounting;private initialStateAnnounced;private connectionGeneration;private errorAnnouncementSink?;private emptyAnnouncementSink?;private readonly retrievalChunkKey;private wasEmptyPresented;private processedChunksCache?;private processedGroupingLocaleSignature;connectedCallback():void;disconnectedCallback():void;private deepActiveElement;private chunkAnchor;private renderedChunkIds;protected willUpdate(changed:PropertyValues<this>):void;protected updated(changed:PropertyValues<this>):void;private announcePresentedState;private restoreControlledFocus;private get effectiveVirtualizeAt();private canonicalChunks;private normalizedSelectedChunkIds;private get processedChunks();private computeProcessedChunks;private orderedGroupKeys;private bucketed;private stopOwnedEvent;private reportSelection;private toggleSelect;private stopRowToggle;private onChunkToggle;private readonly rowChunks;private rowChunksFor;private renderMetadata;private renderRow;private renderLoadMoreFooter;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-retrieval-results':LyraRetrievalResults;}}
189
+ label?:string;private expandedChunkIds;private pendingFocusTarget;private previousProcessedChunkIds;private focusRestoreGeneration;private isMounting;private initialStateAnnounced;private connectionGeneration;private errorAnnouncementSink?;private emptyAnnouncementSink?;private readonly retrievalChunkKey;private wasEmptyPresented;private processedChunksCache?;private processedGroupingLocaleSignature;connectedCallback():void;disconnectedCallback():void;private deepActiveElement;private chunkAnchor;private renderedChunkIds;protected willUpdate(changed:PropertyValues<this>):void;protected updated(changed:PropertyValues<this>):void;private announcePresentedState;private restoreControlledFocus;private get effectiveVirtualizeAt();private canonicalChunks;private normalizedSelectedChunkIds;private get processedChunks();private computeProcessedChunks;private orderedGroupKeys;private bucketed;private stopOwnedEvent;private reportSelection;private toggleSelect;private stopRowToggle;private onChunkToggle;private readonly rowChunks;private rowChunksFor;private renderMetadata;private selectedMembership?;private isChunkSelected;private renderRow;private renderLoadMoreFooter;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-retrieval-results':LyraRetrievalResults;}}