@kineviz/gl 0.7.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,394 @@
1
+ import{D as Ol,F as Ll,H as Vl,d as Rl,e as Cl,f as wl,g as Tl,h as Ml,i as Il,j as Pl,k as Al,l as _l,m as Dl,n as Nl,o as kl,p as Gl,q as Hl,r as Fl,s as zl,t as Bl}from"./chunk-EHGKWZTS.mjs";import{$ as Jo,A as Zn,Aa as Tu,Ba as Mu,Ca as Iu,D as Oi,Da as Pu,E as nu,Ea as Au,F as iu,Fa as _u,Ga as yl,Ha as Du,I as Li,Ka as Nu,La as ku,M as Jt,N as Vi,Na as vl,O as ou,Oa as Ui,P as su,Q as Xo,Qa as bl,Ra as Sl,S as au,Sa as xl,T as du,Ta as El,Ua as Nr,W as O,X as lu,Y as hl,Z as cu,_ as Qo,a as dl,aa as uu,b as dt,ca as hu,d as _r,da as pu,e as pn,ea as gu,f as zi,fa as fu,g as gn,ga as mu,ha as es,i as Bi,ia as ts,j as Dr,ja as yu,ka as pl,la as vu,ma as bu,na as gl,o as fn,oa as fl,p as Kr,pa as Su,q as ll,qa as rs,sa as xu,ta as Eu,ua as Ru,v as cl,w as Yo,wa as ml,x as ul,ya as Cu,za as wu}from"./chunk-67FBXXN6.mjs";import*as Gu from"three";Gu.ColorManagement.enabled=!1;var Fu=["coverage","polygon","algorithms","io","skills"],zu=new Map,Bu=new Map,Ou=new Set;function vg(...a){for(let e of a){e.requires&&vg(...e.requires);for(let[t,r]of Object.entries(e.slots??{}))zu.set(t,r);for(let[t,r]of Object.entries(e.namespaces??{}))Bu.set(t,r);Ou.add(e.name)}}function gy(){return[...Ou]}function Ct(a){return zu.get(a)}function Ul(a){return Bu.get(a)}var bg={flatMap:"maps",globeMap:"maps",geoEgoRing:"geoEgoRing",egoCollapse:"geoEgoRing",minimap:"minimap",toolbar:"toolbar",legend:"legend",cards:"nodeCards",nodeInfo:"nodeInfo",quickCreate:"quickCreate",contextMenu:"contextMenu",coverage:"coverage",polygon:"polygons",algorithms:"algorithms",io:"io",skills:"skills"};function Wl(a){let e=bg[a];return`import { ${e} } from "@kineviz/gl/builtins" and call installBuiltins(${e}), or import from "@kineviz/gl", which installs every built-in`}var Hu=new Set;function Yn(a,e){Hu.has(a)||(Hu.add(a),console.warn(`[kineviz.gl] ${e} is not installed, so nothing is drawn for it: ${Wl(a)}.`))}var jl=class Wi{constructor(){this.textureSize=1,this._nodeIdToIndex=new Map,this.nodeIndexToId=[],this._edgeIdToIndex=new Map,this.edgeIndexToId=[],this.edgeSourceIndices=new Uint32Array(0),this.edgeTargetIndices=new Uint32Array(0),this._adj=null}get nodeIdToIndex(){let e=this._nodeIdToIndex;if(e===null){e=new Map;let t=this.nodeIndexToId;for(let r=0;r<t.length;r++)e.set(t[r],r);this._nodeIdToIndex=e}return e}set nodeIdToIndex(e){this._nodeIdToIndex=e}get edgeIdToIndex(){let e=this._edgeIdToIndex;if(e===null){e=new Map;let t=this.edgeIndexToId;for(let r=0;r<t.length;r++)e.set(t[r],r);this._edgeIdToIndex=e}return e}set edgeIdToIndex(e){this._edgeIdToIndex=e}buildFromGraphData(e){this.clear(),this.textureSize=this.calculateTextureSize(e.nodes.length);let t=e.nodes,r=new Array(t.length);for(let l=0;l<t.length;l++)r[l]=t[l].id;this.nodeIndexToId=r,this._nodeIdToIndex=null;let n=e.edges,i=n.length>0?this.nodeIdToIndex:null,o=new Array(n.length),s=new Uint32Array(n.length),d=new Uint32Array(n.length);for(let l=0;l<n.length;l++){let u=n[l];o[l]=u.id;let c=i.get(u.source),h=i.get(u.target);c!==void 0?s[l]=c:console.warn(`Edge ${u.id}: source node ${u.source} not found`),h!==void 0?d[l]=h:console.warn(`Edge ${u.id}: target node ${u.target} not found`)}this.edgeIndexToId=o,this.edgeSourceIndices=s,this.edgeTargetIndices=d,this._edgeIdToIndex=null}clear(){this._nodeIdToIndex=new Map,this.nodeIndexToId=[],this._edgeIdToIndex=new Map,this.edgeIndexToId=[],this.edgeSourceIndices=new Uint32Array(0),this.edgeTargetIndices=new Uint32Array(0),this.textureSize=1,this._adj=null}calculateTextureSize(e){if(e===0)return 1;let t=Math.ceil(Math.sqrt(e));return Math.pow(2,Math.ceil(Math.log2(t)))}indexToTexCoord(e){let t=(e%this.textureSize+.5)/this.textureSize,r=(Math.floor(e/this.textureSize)+.5)/this.textureSize;return[t,r]}getNodeIndex(e){return this.nodeIdToIndex.get(e)}getNodeId(e){return this.nodeIndexToId[e]}getEdgeIndex(e){return this.edgeIdToIndex.get(e)}getEdgeId(e){return this.edgeIndexToId[e]}getEdgeEndpoints(e){if(!(e<0||e>=this.edgeIndexToId.length))return{source:this.edgeSourceIndices[e],target:this.edgeTargetIndices[e]}}get nodeCount(){return this.nodeIndexToId.length}get edgeCount(){return this.edgeIndexToId.length}hasNode(e){return this.nodeIdToIndex.has(e)}hasEdge(e){return this.edgeIdToIndex.has(e)}addNode(e){if(this.nodeIdToIndex.has(e))return this.nodeIdToIndex.get(e);let t=this.nodeIndexToId.length;this.nodeIdToIndex.set(e,t),this.nodeIndexToId.push(e),this._adj?.push([]);let r=this.calculateTextureSize(this.nodeIndexToId.length);return r>this.textureSize&&(this.textureSize=r),t}addEdge(e,t,r){if(this.edgeIdToIndex.has(e))return this.edgeIdToIndex.get(e);let n=this.edgeIndexToId.length;if(this.edgeIdToIndex.set(e,n),this.edgeIndexToId.push(e),n>=this.edgeSourceIndices.length){let i=Math.max(8,this.edgeSourceIndices.length*2,n+1),o=new Uint32Array(i),s=new Uint32Array(i);o.set(this.edgeSourceIndices),s.set(this.edgeTargetIndices),this.edgeSourceIndices=o,this.edgeTargetIndices=s}return this.edgeSourceIndices[n]=this.nodeIdToIndex.get(t)??0,this.edgeTargetIndices[n]=this.nodeIdToIndex.get(r)??0,this._adj&&this.adjLink(n),n}ensureAdj(){if(this._adj)return this._adj;let e=new Array(this.nodeIndexToId.length);for(let t=0;t<e.length;t++)e[t]=[];this._adj=e;for(let t=0;t<this.edgeIndexToId.length;t++)this.adjLink(t);return e}adjLink(e){let t=this._adj,r=this.edgeSourceIndices[e],n=this.edgeTargetIndices[e];t[r]?.push(e),n!==r&&t[n]?.push(e)}static dropFrom(e,t){if(!e)return;let r=e.indexOf(t);if(r<0)return;let n=e.pop();r<e.length&&(e[r]=n)}static replaceIn(e,t,r){if(!e)return;let n=e.indexOf(t);n>=0&&(e[n]=r)}edgesOfNode(e){return this.ensureAdj()[e]??[]}degree(e){return this.ensureAdj()[e]?.length??0}swapRemoveEdge(e){let t=this.edgeIdToIndex.get(e);if(t===void 0)return;let r=this.ensureAdj(),n=this.edgeIndexToId.length-1,i=this.edgeSourceIndices[t],o=this.edgeTargetIndices[t];Wi.dropFrom(r[i],t),o!==i&&Wi.dropFrom(r[o],t);let s;if(t!==n){s=this.edgeIndexToId[n];let d=this.edgeSourceIndices[n],l=this.edgeTargetIndices[n];Wi.replaceIn(r[d],n,t),l!==d&&Wi.replaceIn(r[l],n,t),this.edgeIndexToId[t]=s,this.edgeIdToIndex.set(s,t),this.edgeSourceIndices[t]=d,this.edgeTargetIndices[t]=l}return this.edgeIndexToId.pop(),this.edgeIdToIndex.delete(e),{id:e,slot:t,last:n,movedId:s}}swapRemoveNode(e){let t=this.nodeIdToIndex.get(e);if(t===void 0)return;let r=this.ensureAdj();if(r[t].length>0)throw new Error(`[IndexManager] swapRemoveNode("${e}"): node still has ${r[t].length} incident edge(s)`);let n=this.nodeIndexToId.length-1,i;if(t!==n){i=this.nodeIndexToId[n];let o=r[n];for(let s of o)this.edgeSourceIndices[s]===n&&(this.edgeSourceIndices[s]=t),this.edgeTargetIndices[s]===n&&(this.edgeTargetIndices[s]=t);r[t]=o,this.nodeIndexToId[t]=i,this.nodeIdToIndex.set(i,t)}return r.pop(),this.nodeIndexToId.pop(),this.nodeIdToIndex.delete(e),this.textureSize=this.calculateTextureSize(this.nodeIndexToId.length),{id:e,slot:t,last:n,movedId:i}}},ql=class{constructor(a,e){this.data=a,this.index=e}updateReferences(a,e){this.data=a,this.index=e}getNode(a){let e=this.index.nodeIdToIndex.get(a);if(e!==void 0)return this.data.nodes[e]}getEdge(a){let e=this.index.edgeIdToIndex.get(a);if(e!==void 0)return this.data.edges[e]}getDegree(a){let e=this.index.nodeIdToIndex.get(a);if(e===void 0)return 0;let t=0,r=this.index.edgeSourceIndices,n=this.index.edgeTargetIndices;for(let i=0;i<this.data.edges.length;i++)(r[i]===e||n[i]===e)&&t++;return t}getInDegree(a){let e=this.index.nodeIdToIndex.get(a);if(e===void 0)return 0;let t=0,r=this.index.edgeTargetIndices;for(let n=0;n<this.data.edges.length;n++)r[n]===e&&t++;return t}getOutDegree(a){let e=this.index.nodeIdToIndex.get(a);if(e===void 0)return 0;let t=0,r=this.index.edgeSourceIndices;for(let n=0;n<this.data.edges.length;n++)r[n]===e&&t++;return t}getNeighbors(a){let e=this.index.nodeIdToIndex.get(a);if(e===void 0)return[];let t=[],r=this.index.edgeSourceIndices,n=this.index.edgeTargetIndices;for(let i=0;i<this.data.edges.length;i++){let o=r[i],s=n[i];o===e?t.push({nodeId:this.index.nodeIndexToId[s],edgeId:this.index.edgeIndexToId[i],direction:"out"}):s===e&&t.push({nodeId:this.index.nodeIndexToId[o],edgeId:this.index.edgeIndexToId[i],direction:"in"})}return t}getNeighborIds(a){let e=this.getNeighbors(a);return Array.from(new Set(e.map(t=>t.nodeId)))}getEdgesBetween(a,e){let t=this.index.nodeIdToIndex.get(a),r=this.index.nodeIdToIndex.get(e);if(t===void 0||r===void 0)return[];let n=[],i=this.index.edgeSourceIndices,o=this.index.edgeTargetIndices;for(let s=0;s<this.data.edges.length;s++){let d=i[s],l=o[s];(d===t&&l===r||d===r&&l===t)&&n.push(this.index.edgeIndexToId[s])}return n}getConnectedEdges(a){let e=this.index.nodeIdToIndex.get(a);if(e===void 0)return[];let t=[],r=this.index.edgeSourceIndices,n=this.index.edgeTargetIndices;for(let i=0;i<this.data.edges.length;i++)(r[i]===e||n[i]===e)&&t.push(this.index.edgeIndexToId[i]);return t}getCategories(){let a=new Set;for(let e of this.data.nodes)a.add(e.category);return Array.from(a)}getRelationshipTypes(){let a=new Set;for(let e of this.data.edges)a.add(e.relationship);return Array.from(a)}getNodesByCategory(a){return this.data.nodes.filter(e=>e.category===a)}getEdgesByRelationship(a){return this.data.edges.filter(e=>e.relationship===a)}findNodes(a){return this.data.nodes.filter(a)}findEdges(a){return this.data.edges.filter(a)}getNodeProperty(a,e){return this.getNode(a)?.properties[e]}getEdgeProperty(a,e){return this.getEdge(a)?.properties[e]}inferSchema(){return{categories:this.inferCategorySchemas(),relationships:this.inferRelationshipSchemas()}}inferCategorySchemas(){let a=new Map;for(let t of this.data.nodes){let r=a.get(t.category);r||(r=new Map,a.set(t.category,r));for(let[n,i]of Object.entries(t.properties)){if(i===null)continue;let o=r.get(n);o||(o=new Set,r.set(n,o)),o.add(typeof i)}}let e=[];for(let[t,r]of a){let n=[];for(let[i,o]of r)n.push({key:i,type:o.has("string")?"string":o.has("number")?"number":"boolean"});e.push({name:t,properties:n})}return e.sort((t,r)=>t.name.localeCompare(r.name))}inferRelationshipSchemas(){let a=new Map;for(let t of this.data.edges){let r=a.get(t.relationship);r||(r=new Map,a.set(t.relationship,r));for(let[n,i]of Object.entries(t.properties)){if(i===null)continue;let o=r.get(n);o||(o=new Set,r.set(n,o)),o.add(typeof i)}}let e=[];for(let[t,r]of a){let n=[];for(let[i,o]of r)n.push({key:i,type:o.has("string")?"string":o.has("number")?"number":"boolean"});e.push({name:t,properties:n})}return e.sort((t,r)=>t.name.localeCompare(r.name))}},my=class{constructor(){this.handlers=new Map}on(a,e){return this.handlers.has(a)||this.handlers.set(a,new Set),this.handlers.get(a).add(e),()=>this.off(a,e)}once(a,e){let t=r=>{this.off(a,t),e(r)};return this.on(a,t)}off(a,e){this.handlers.get(a)?.delete(e)}emit(a,e){let t=this.handlers.get(a);if(t)for(let r of t)r(e)}removeAllListeners(a){a?this.handlers.delete(a):this.handlers.clear()}};var Be=(a,e,t)=>({t:"col",kind:a,attr:e,domain:t}),Kl=a=>({t:"capacity",kind:a}),ji=a=>({t:"bump",domains:a}),Sg={structure:[Kl("node"),Kl("edge")],edgeStructure:[Kl("edge")],nodeColors:[Be("node","color")],nodeSizes:[Be("node","size")],nodeOpacities:[Be("node","opacity")],nodeIcons:[Be("node","icon"),Be("node","iconUV")],nodeImages:[Be("node","imageUV")],nodeSelection:[Be("node","flags",O.Selection)],nodeHighlight:[Be("node","flags",O.Selection)],nodeHover:[Be("node","flags",O.Hover)],nodePinned:[Be("node","flags",O.Pin)],nodeHidden:[Be("node","flags",O.Visibility)],nodeRingColors:[Be("node","ringColor")],nodeCollection:[Be("node","collect")],nodeLabels:[ji(O.Labels)],nodeSuppressFill:[Be("node","suppressFill")],nodeShapes:[Be("node","shape")],edgeColors:[Be("edge","color")],edgeWidths:[Be("edge","width")],edgeOpacities:[Be("edge","opacity")],edgeSelection:[Be("edge","flags",O.Selection)],edgeHighlight:[Be("edge","flags",O.Selection)],edgeDashed:[Be("edge","shape")],edgeShapes:[Be("edge","shape")],nodeRipple:[Be("node","effects")],nodeBreathe:[Be("node","effects")],nodeHalo:[Be("node","effects")],badges:[ji(O.Decorations)],tags:[ji(O.Decorations)],collect:[ji(O.Decorations)],groups:[ji(O.Decorations)],edgeFlow:[Be("edge","flow")],edgeGlow:[Be("edge","glow")],edgeTubeGlow:[Be("edge","tubeGlow")]};function $l(a,e,t){let r=Sg[e];if(r)for(let n of r)n.t==="col"?t===void 0?a.touchAll(n.kind,n.attr,n.domain):a.touch(n.kind,n.attr,t,n.domain):n.t==="capacity"?a.recordCapacityChange(n.kind):a.bump(n.domains)}var ns=class{constructor(){this._dirtyFlags=new Set;this._changes=null}attachChangeLog(e){this._changes=e}markDirty(e,t){this._dirtyFlags.add(e),this._changes&&$l(this._changes,e,t)}markDirtyBatch(e){let t=this._changes;if(t){t.batch(()=>{for(let r of e)this._dirtyFlags.add(r),$l(t,r)});return}for(let r of e)this._dirtyFlags.add(r)}consumeDirty(){let e=new Set(this._dirtyFlags);return this._dirtyFlags.clear(),e}isDirty(){return this._dirtyFlags.size>0}isDirtyFlag(e){return this._dirtyFlags.has(e)}hasDirty(e){return this._dirtyFlags.has(e)}clear(){this._dirtyFlags.clear()}get currentDirtyFlags(){return this._dirtyFlags}},xg={structure:["*"],edgeStructure:["*"],nodeColors:["nodeColor"],nodeSizes:["nodeSize"],nodeOpacities:["nodeOpacity"],nodeIcons:["nodeIcon"],nodeImages:["nodeImage"],nodeSelection:["nodeSelected"],nodeHighlight:["nodeHighlighted"],nodeHover:["nodeHovered"],nodePinned:["nodePinned"],nodeHidden:["nodeHidden"],nodeRingColors:["nodeRingColor"],nodeCollection:["nodeCollection"],nodeLabels:[],nodeSuppressFill:["nodeSuppressFill"],nodeShapes:["nodeShape"],edgeColors:["edgeColor"],edgeWidths:["edgeWidth"],edgeOpacities:["edgeOpacity"],edgeSelection:["edgeSelected"],edgeHighlight:["edgeHighlighted"],edgeDashed:["edgeDashed"],edgeShapes:["edgeShape"],nodeRipple:["nodeRipple"],nodeBreathe:["nodeBreathe"],badges:[],tags:[],collect:[],edgeFlow:["edgeFlow"],edgeGlow:["edgeGlow"],edgeTubeGlow:["edgeTubeGlow"],nodeHalo:["nodeHalo"],groups:[]};function wy(a){return a.has("structure")}function Ty(a){let e=new Set;return Array.from(a).forEach(t=>{let r=xg[t];r&&r.forEach(n=>{e.add(n)})}),e}var Lu=["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5","#FF6B6B","#4ECDC4","#45B7D1","#96CEB4","#FFEAA7","#DDA0DD","#98D8C8","#F7DC6F"],Eg=["#74b9ff","#a29bfe","#0984e3","#6c5ce7","#ff7675","#fd79a8","#fdcb6e","#e17055","#e84393","#003f5c","#2f4b7c","#665191","#a05195","#d45087","#f95d6a","#ff7c43","#ffa600"],qi=class a{constructor(e){this.assignments=new Map;this.palette=e??Lu}static forNodes(){return new a(Lu)}static forEdges(){return new a(Eg)}getColor(e){let t=this.assignments.get(e);if(t)return t;let r=new Set(this.assignments.values());for(let i of this.palette)if(!r.has(i.toLowerCase()))return this.assignments.set(e,i),i;let n=this.palette[this.assignments.size%this.palette.length];return this.assignments.set(e,n),n}setColor(e,t){this.assignments.set(e,t)}releaseColor(e){this.assignments.delete(e)}hasColor(e){return this.assignments.has(e)}getAssignments(){return this.assignments}loadAssignments(e){for(let[t,r]of e)this.assignments.set(t,r)}reset(){this.assignments.clear()}};var Zl={circle:0,rect:1,roundRect:2,diamond:3,triangle:4,hexagon:5,star:6,ring:7},Rg=Object.keys(Zl);function Ki(a){return typeof a=="number"?Number.isInteger(a)&&a>=0&&a<Rg.length?a:-1:a in Zl?Zl[a]:-1}var Cg=1024,wg=8191;function Vu(a,e){let t=Math.min(Math.max(Math.round((e>0?e:1)*Cg),1),wg);return Math.round(a)+16*t}function Tg(a){let e=a.sizeMapping;if(e&&!e.domain)return!0;let t=a.colorMapping;return!!(t&&(t.type==="sequential"||t.type==="diverging")&&!t.domain)}function Mg(a){let e=a.widthMapping;if(e&&!e.domain)return!0;let t=a.colorMapping;return!!(t&&(t.type==="sequential"||t.type==="diverging")&&!t.domain)}var is=class{constructor(e){this._categoryConfigs=new Map;this._relationshipConfigs=new Map;this._configSources=new Map;this.categoryColors=qi.forNodes();this.relationshipColors=qi.forEdges();this.store=e}setCategoryConfig(e,t="user"){t==="ontology"&&this._configSources.get(e.category)==="user"||(!e.defaultColor&&!e.colorMapping?e={...e,defaultColor:this.categoryColors.getColor(e.category)}:e.defaultColor&&this.categoryColors.setColor(e.category,e.defaultColor),Ig(e),this._categoryConfigs.set(e.category,e),this._configSources.set(e.category,t),this.store.markNodeLabelsDirty())}removeCategoryConfig(e){this._categoryConfigs.delete(e),this._configSources.delete(e),this.categoryColors.releaseColor(e),this.store.markNodeLabelsDirty()}getCategoryConfig(e){return this._categoryConfigs.get(e)}get categoryConfigs(){return this._categoryConfigs}setRelationshipConfig(e,t="user"){t==="ontology"&&this._configSources.get(e.relationship)==="user"||(!e.defaultColor&&!e.colorMapping?e={...e,defaultColor:this.relationshipColors.getColor(e.relationship)}:e.defaultColor&&this.relationshipColors.setColor(e.relationship,e.defaultColor),this._relationshipConfigs.set(e.relationship,e),this._configSources.set(e.relationship,t))}removeRelationshipConfig(e){this._relationshipConfigs.delete(e),this._configSources.delete(e),this.relationshipColors.releaseColor(e)}getRelationshipConfig(e){return this._relationshipConfigs.get(e)}get relationshipConfigs(){return this._relationshipConfigs}clearAll(){this._categoryConfigs.clear(),this._relationshipConfigs.clear(),this._configSources.clear(),this.categoryColors.reset(),this.relationshipColors.reset(),this.store.markNodeLabelsDirty()}clearConfigOverride(e){this._configSources.delete(e)}apply(e){this.store.runAsMapper(()=>this.applyScoped(e))}applyScoped(e){if(!e||e.nodes?.length){let t=null;if(e){t=new Map;for(let r of e.nodes){let n=t.get(r.category);n?n.push(r):t.set(r.category,[r])}}for(let r of this._categoryConfigs.values()){let n=t?.get(r.category);if(t&&!n)continue;let i=()=>this.store.queries.getNodesByCategory(r.category),o=n&&!Tg(r)&&!e?.fullCategories?.has(r.category)?n:i();o.length!==0&&(this.applySizeMapping(r,o),this.applyColorMapping(r,o),this.applyIconMapping(r,o),this.applyShapeMapping(r,o),this.applyImageUrlMapping(r,o))}}if(!e||e.edges?.length){let t=null;if(e){t=new Map;for(let r of e.edges){let n=t.get(r.relationship);n?n.push(r):t.set(r.relationship,[r])}}for(let r of this._relationshipConfigs.values()){let n=t?.get(r.relationship);if(t&&!n)continue;let i=n&&!Mg(r)&&!e?.fullRelationships?.has(r.relationship)?n:this.store.queries.getEdgesByRelationship(r.relationship);i.length!==0&&(this.applyEdgeWidthMapping(r,i),this.applyEdgeColorMapping(r,i))}}}applySizeMapping(e,t){let r=e.sizeMapping;if(!r&&e.defaultSize==null)return;if(!r){for(let o of t)this.store.setNodeSize(o.id,e.defaultSize);return}let n=r.domain??Ui(t,r.property),i=vl(r.scale);for(let o of t){let s=Number(o.properties[r.property]),d=isNaN(s)?r.defaultSize??e.defaultSize??10:i(s,n,r.range);this.store.setNodeSize(o.id,d)}}applyColorMapping(e,t){let r=e.colorMapping;if(!(!r&&!e.defaultColor)){if(!r){let n=Nr(e.defaultColor);for(let i of t)this.store.setNodeColor(i.id,n);return}if(r.type==="ordinal"){let n={};for(let[o,s]of Object.entries(r.colorMap))n[o]=Nr(s);let i=r.defaultColor?Nr(r.defaultColor):[.6,.6,.6];for(let o of t){let s=String(o.properties[r.property]??"");this.store.setNodeColor(o.id,xl(s,n,i))}}else if(r.type==="threshold"){let n=r.colors.map(Nr);for(let i of t){let o=Number(i.properties[r.property]),s=isNaN(o)?n[0]??[.5,.5,.5]:El(o,r.thresholds,n);this.store.setNodeColor(i.id,s)}}else{let n=r.domain??Ui(t,r.property);for(let i of t){let o=Number(i.properties[r.property]);if(isNaN(o))continue;let s=r.type==="diverging"?Sl(o,n,r.midpoint??0,r.scheme):bl(o,n,r.scheme);this.store.setNodeColor(i.id,s)}}}}applyIconMapping(e,t){let r=e.iconMapping;if(!(!r&&!e.defaultIcon))for(let n of t){let i=null;if(r){if(r.iconNameProperty){let o=n.properties[r.iconNameProperty];i=o!=null?String(o):r.defaultIcon??e.defaultIcon??null}else if(r.property&&r.iconMap){let o=String(n.properties[r.property]??"");i=r.iconMap[o]??r.defaultIcon??e.defaultIcon??null}}else i=e.defaultIcon??null;this.store.setNodeIcon(n.id,i)}}applyShapeMapping(e,t){let r=e.shapeMapping;if(!r&&e.defaultShape==null&&e.defaultAspect==null)return;let n=e.defaultAspect;for(let i of t){let o=e.defaultShape;if(r){let s=i.properties[r.property];o=(s!=null?r.shapeMap[String(s)]:void 0)??r.defaultShape??e.defaultShape}this.store.setNodeShape(i.id,o??this.store.nodeState.shapeIds[this.store.index.getNodeIndex(i.id)??0],n)}}applyImageUrlMapping(e,t){let r=e.imageUrlMapping;if(r)for(let n of t){let i=n.properties[r.property];if(!i&&!r.fallbackUrl)continue;let o=i?r.urlTemplate?r.urlTemplate.replace(/\{value\}/g,String(i)):String(i):r.fallbackUrl;this.store.setNodeImageUrl(n.id,o)}}applyEdgeWidthMapping(e,t){let r=e.widthMapping;if(!r&&e.defaultWidth==null)return;if(!r){for(let o of t)this.store.setEdgeWidth(o.id,e.defaultWidth);return}let n=r.domain??Ui(t,r.property),i=vl(r.scale);for(let o of t){let s=Number(o.properties[r.property]),d=isNaN(s)?r.defaultWidth??e.defaultWidth??1:i(s,n,r.range);this.store.setEdgeWidth(o.id,d)}}applyEdgeColorMapping(e,t){let r=e.colorMapping;if(!(!r&&!e.defaultColor)){if(!r){let n=Nr(e.defaultColor);for(let i of t)this.store.setEdgeColor(i.id,n);return}if(r.type==="ordinal"){let n={};for(let[o,s]of Object.entries(r.colorMap))n[o]=Nr(s);let i=r.defaultColor?Nr(r.defaultColor):[.6,.6,.6];for(let o of t){let s=String(o.properties[r.property]??"");this.store.setEdgeColor(o.id,xl(s,n,i))}}else if(r.type==="threshold"){let n=r.colors.map(Nr);for(let i of t){let o=Number(i.properties[r.property]),s=isNaN(o)?n[0]??[.5,.5,.5]:El(o,r.thresholds,n);this.store.setEdgeColor(i.id,s)}}else{let n=r.domain??Ui(t,r.property);for(let i of t){let o=Number(i.properties[r.property]);if(isNaN(o))continue;let s=r.type==="diverging"?Sl(o,n,r.midpoint??0,r.scheme):bl(o,n,r.scheme);this.store.setEdgeColor(i.id,s)}}}}};function Ig(a){let e=(r,n)=>{if(r!==void 0&&Ki(r)<0)throw new Error(`CategoryConfig "${a.category}": unknown shape "${String(r)}" in ${n}`)};e(a.defaultShape,"defaultShape");let t=a.shapeMapping;if(t){e(t.defaultShape,"shapeMapping.defaultShape");for(let[r,n]of Object.entries(t.shapeMap))e(n,`shapeMapping.shapeMap["${r}"]`)}if(a.defaultAspect!==void 0&&!(a.defaultAspect>0&&Number.isFinite(a.defaultAspect)))throw new Error(`CategoryConfig "${a.category}": defaultAspect must be a positive number`)}var Hy=14;var $i=Object.freeze({"top-left":[-14,-14],top:[0,-14],"top-right":[14,-14],left:[-14,0],right:[14,0],"bottom-left":[-14,14],bottom:[0,14],"bottom-right":[14,14]}),os=2.5;function ss(a,e,t,r,n=0){let[i,o]=$i[a],s=Math.sign(i),d=Math.sign(o),l=s!==0&&d!==0?e*Math.SQRT1_2:e,u=Math.max(0,l);return[s===0?0:s*(u+t[0]*r+n),d===0?0:d*(u+t[1]*r+n)]}var as=4;function Pg(a){return a<1e3?`+${a}`:`${Math.min(99,Math.floor(a/1e3))}k+`}function Ag(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`grp-${crypto.randomUUID()}`:`grp-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function wt(a){return a._groups||(a._groups=new Map),a._nodeToGroup||(a._nodeToGroup=new Map),{groups:a._groups,nodeToGroup:a._nodeToGroup}}var ds=class{constructor(e){this._dragMode="node";this._savedHiddenFlags=new Map;this._savedEdgeOpacities=new Map;this.aggregatedEdgeColor="#888888";this.aggregatedEdgeWidthCap=10;this.store=e,wt(e),e._groupManager=this}setDragMode(e){this._dragMode=e}getDragMode(){return this._dragMode}createGroup(e,t){let{groups:r,nodeToGroup:n}=wt(this.store),i=Ag(),o=new Set;for(let d of e){let l=n.get(d);l!==void 0&&l!==i&&r.get(l)?.memberNodeIds.delete(d),o.add(d),n.set(d,i)}let s={id:i,spec:t,memberNodeIds:o,collapsed:!1,anchorNodeId:null,savedAnchorColor:null,savedAnchorLabel:null,center:{x:0,y:0,z:0},radius:0,boundingBox:{minX:0,maxX:0,minY:0,maxY:0,minZ:0,maxZ:0}};return r.set(i,s),this.store.updateStrategy.markDirty("groups"),this.store.notifyChange(),i}createGroupsByAttribute(e){let t=new Map,r=new Map;for(let n of this.store.data.nodes){let i;if(e==="category")i=n.category;else{let o=n.properties?.[e];i=o!=null?String(o):void 0}i!==void 0&&(r.has(i)||r.set(i,[]),r.get(i).push(n.id))}for(let[n,i]of r){let o=this.getNodeColorHex(i[0]),s=this.createGroup(i,{name:n,color:o});t.set(n,s)}return t}createGroupsByFunction(e,t){let r=new Map,n=new Map;for(let i of this.store.data.nodes){let o=e(i);o!=null&&(n.has(o)||n.set(o,[]),n.get(o).push(i.id))}for(let[i,o]of n){let s=t?t(i,o):{},d=s.color??this.getNodeColorHex(o[0]),l=this.createGroup(o,{name:i,color:d,...s});r.set(i,l)}return r}createGroupsFromClusters(e){let t=new Map;for(let[r,n]of e){let i=this.createGroup(n,{name:r});t.set(r,i)}return t}dissolveGroup(e){let{groups:t,nodeToGroup:r}=wt(this.store),n=t.get(e);if(n){for(let i of n.memberNodeIds)r.get(i)===e&&r.delete(i);t.delete(e),this._savedHiddenFlags.delete(e),this._savedEdgeOpacities.delete(e),this.store.updateStrategy.markDirty("groups"),this.store.notifyChange()}}addNodesToGroup(e,t){let{groups:r,nodeToGroup:n}=wt(this.store),i=r.get(e);if(!i){console.warn(`[GroupManager] addNodesToGroup: unknown groupId ${e}`);return}for(let o of t){let s=n.get(o);s!==void 0&&s!==e&&r.get(s)?.memberNodeIds.delete(o),i.memberNodeIds.add(o),n.set(o,e)}i.collapsed&&i.anchorNodeId&&this.syncCountBadge(i,i.anchorNodeId),this.store.updateStrategy.markDirty("groups"),this.store.notifyChange()}removeNodesFromGroup(e,t){let{groups:r,nodeToGroup:n}=wt(this.store),i=r.get(e);if(i){for(let o of t)i.memberNodeIds.delete(o),n.get(o)===e&&n.delete(o);i.memberNodeIds.size===0?r.delete(e):i.collapsed&&i.anchorNodeId&&this.syncCountBadge(i,i.anchorNodeId),this.store.updateStrategy.markDirty("groups"),this.store.notifyChange()}}recomputeGroupGeometry(e){let{groups:t}=wt(this.store),r=t.get(e);if(!r||r.memberNodeIds.size===0)return;let n=this.store.positionProvider?.getPositions();if(!n)return;let i=1/0,o=-1/0,s=1/0,d=-1/0,l=1/0,u=-1/0,c=0,h=0,p=0,f=0;for(let x of r.memberNodeIds){let w=this.store.index.getNodeIndex(x);if(w===void 0)continue;let T=n[w*3],I=n[w*3+1],R=n[w*3+2];c+=T,h+=I,p+=R,T<i&&(i=T),T>o&&(o=T),I<s&&(s=I),I>d&&(d=I),R<l&&(l=R),R>u&&(u=R),f++}if(f===0)return;let m=c/f,g=h/f,y=p/f;r.center={x:m,y:g,z:y};let v=0;for(let x of r.memberNodeIds){let w=this.store.index.getNodeIndex(x);if(w===void 0)continue;let T=n[w*3]-m,I=n[w*3+1]-g,R=n[w*3+2]-y,S=Math.sqrt(T*T+I*I+R*R);S>v&&(v=S)}let b=r.spec.padding??1;r.radius=v+b,r.boundingBox={minX:i,maxX:o,minY:s,maxY:d,minZ:l,maxZ:u}}recomputeAllGeometry(){let{groups:e}=wt(this.store);for(let t of e.keys())this.recomputeGroupGeometry(t)}getNodeColorHex(e){let t=this.store.index.getNodeIndex(e);if(t===void 0||!this.store.nodeState)return;let r=this.store.nodeState.colors,n=Math.round(r[t*3]*255),i=Math.round(r[t*3+1]*255),o=Math.round(r[t*3+2]*255);return`#${n.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`}collapseGroup(e){let{groups:t}=wt(this.store),r=t.get(e);if(!r||r.collapsed)return;this.ensureAggregatedRelationshipConfig();let n=this.resolveAnchor(r),i=r.memberNodeIds,o=this.store.nodeState,s=this.store.edgeState;if(!o)return;let d=new Map;for(let u of i){if(u===n)continue;let c=this.store.index.getNodeIndex(u);c!==void 0&&(d.set(u,o.hidden[c]),o.hidden[c]=1)}this._savedHiddenFlags.set(e,d);let l=new Map;if(s)for(let u of this.store.data.edges){let c=i.has(u.source),h=i.has(u.target);if(!c&&!h)continue;let p=this.store.index.getEdgeIndex(u.id);if(p===void 0)continue;let f=c&&h,m=!1;if(f)m=!0;else{let g=c?u.target:u.source,y=this.store._nodeToGroup?.get(g);y===void 0?m=!0:m=!!t.get(y)?.collapsed}m&&(l.set(u.id,s.opacities[p]),s.opacities[p]=0)}this._savedEdgeOpacities.set(e,l),this.applyAnchorVisuals(r,n),this.store.setNodeCollect(n,!0),r.collapsed=!0,r.anchorNodeId=n,this.recomputeGroupGeometry(e),this.computeAggregatedEdges(),this.keepAnchorOwnEdges(e),this.ensureAggregatedEdgeRender(e),this.store.updateStrategy.markDirty("groups"),this.store.updateStrategy.markDirty("nodeHidden"),this.store.updateStrategy.markDirty("nodeColors"),this.store.updateStrategy.markDirty("nodeCollection"),this.store.updateStrategy.markDirty("edgeOpacities"),this.store.notifyChange()}expandGroup(e){let{groups:t}=wt(this.store),r=t.get(e);if(!r||!r.collapsed)return;let n=r.anchorNodeId,i=this.store.nodeState,o=this.store.edgeState;n!==null&&(this.store.setNodeCollect(n,!1),this.restoreAnchorVisuals(r,n));let s=this._savedHiddenFlags.get(e);if(s&&i)for(let[l,u]of s){let c=this.store.index.getNodeIndex(l);c!==void 0&&(i.hidden[c]=u)}this._savedHiddenFlags.delete(e);let d=this._savedEdgeOpacities.get(e);if(d&&o)for(let[l,u]of d){let c=this.store.index.getEdgeIndex(l);c!==void 0&&(o.opacities[c]=u)}this._savedEdgeOpacities.delete(e),r.collapsed=!1,r.anchorNodeId=null,this.clearAggregatedEdgeRender(e),this.store._aggregatedEdges=null,this.store.updateStrategy.markDirty("groups"),this.store.updateStrategy.markDirty("nodeHidden"),this.store.updateStrategy.markDirty("nodeColors"),this.store.updateStrategy.markDirty("nodeCollection"),this.store.updateStrategy.markDirty("edgeOpacities"),this.store.notifyChange()}onNodesAffected(e){let{groups:t}=wt(this.store),r=new Set;for(let[n,i]of t){if(i.memberNodeIds.size===0){r.add(n);continue}i.collapsed&&i.anchorNodeId!==null&&(i.memberNodeIds.has(i.anchorNodeId)||r.add(n))}for(let n of r){let i=t.get(n);if(i){if(i.memberNodeIds.size===0){this.dissolveGroup(n);continue}if(i.collapsed){let o=i.anchorNodeId,s=this.resolveAnchor(i),d=this._savedHiddenFlags.get(n);d?.delete(o),d?.delete(s),i.anchorNodeId=s;let l=this.store.index.getNodeIndex(s);l!==void 0&&this.store.nodeState&&(this.store.nodeState.hidden[l]=0),i.savedAnchorColor=null,i.savedAnchorLabel=null,this.applyAnchorVisuals(i,s),this.store.setNodeCollect(s,!0),this.store.updateStrategy.markDirty("nodeHidden"),this.store.updateStrategy.markDirty("nodeColors"),this.store.updateStrategy.markDirty("nodeCollection"),this.computeAggregatedEdges(),this.clearAggregatedEdgeRender(n),this.ensureAggregatedEdgeRender(n),this.store.notifyChange()}}}}switchAnchor(e,t){let{groups:r}=wt(this.store),n=r.get(e);if(!n||!n.collapsed||!n.memberNodeIds.has(t)||n.anchorNodeId===t)return;let i=n.anchorNodeId,o=this.store.nodeState;if(!o)return;this.store.setNodeCollect(i,!1),this.restoreAnchorVisuals(n,i);let s=this.store.index.getNodeIndex(i),d=this.store.index.getNodeIndex(t);s!==void 0&&(o.hidden[s]=1),d!==void 0&&(o.hidden[d]=0);let l=this._savedHiddenFlags.get(e);l&&(l.set(i,0),l.delete(t)),this.applyAnchorVisuals(n,t),this.store.setNodeCollect(t,!0),n.anchorNodeId=t,this.computeAggregatedEdges(),this.clearAggregatedEdgeRender(e),this.ensureAggregatedEdgeRender(e),this.store.updateStrategy.markDirty("groups"),this.store.updateStrategy.markDirty("nodeHidden"),this.store.updateStrategy.markDirty("nodeColors"),this.store.updateStrategy.markDirty("nodeCollection"),this.store.notifyChange()}computeAggregatedEdges(){let{groups:e,nodeToGroup:t}=wt(this.store),r=this.store.data.edges,n=new Map;for(let o of r){if(o.properties?._isAggregated===!0)continue;let s=t.get(o.source),d=t.get(o.target),l=s?e.get(s):void 0,u=d?e.get(d):void 0,c=l?.collapsed===!0,h=u?.collapsed===!0;if(!c&&!h||s&&s===d)continue;let p,f;c&&h?(p=s,f={kind:"group",groupId:d}):c?(p=s,d&&u?f={kind:"group",groupId:d}:f={kind:"node",nodeId:o.target}):(p=d,s&&l?f={kind:"group",groupId:s}:f={kind:"node",nodeId:o.source});let m=f.kind==="group"?`group:${f.groupId}`:`node:${f.nodeId}`,g=`${p}\u2192${m}`,y=n.get(g);y||(y={sourceGroupId:p,target:f,edgeIds:[]},n.set(g,y)),y.edgeIds.push(o.id)}let i=[];for(let o of n.values())i.push({sourceGroupId:o.sourceGroupId,target:o.target,originalEdgeIds:o.edgeIds,weight:o.edgeIds.length});this.store._aggregatedEdges=i.length>0?i:null}keepAnchorOwnEdges(e){let t=this.store._groups?.get(e),r=t?.anchorNodeId,n=this.store._aggregatedEdges;if(!t||t.spec.kind!=="collect"||!r||!n)return;let i=this._savedEdgeOpacities.get(e),o=this.store.edgeState,s=new Map(this.store.data.edges.map(l=>[l.id,l])),d=n.filter(l=>{if(l.originalEdgeIds.length!==1||l.sourceGroupId!==e||l.target.kind!=="node")return!0;let u=s.get(l.originalEdgeIds[0]);if(!u||u.source!==r&&u.target!==r)return!0;let c=this.store.index.getEdgeIndex(u.id);return o&&c!==void 0&&i?.has(u.id)&&(o.opacities[c]=i.get(u.id),i.delete(u.id)),!1});this.store._aggregatedEdges=d.length>0?d:null}parseHexColor(e){let t=e.replace("#",""),r=parseInt(t.slice(0,2),16)/255,n=parseInt(t.slice(2,4),16)/255,i=parseInt(t.slice(4,6),16)/255;return[r,n,i]}aggregatedWidth(e){return 1*Math.min(this.aggregatedEdgeWidthCap,1+Math.log(Math.max(1,e)))}ensureAggregatedEdgeRender(e){let{groups:t}=wt(this.store),n=(this.store._aggregatedEdges??[]).filter(s=>s.sourceGroupId===e?!0:s.target.kind==="group"&&s.target.groupId===e);if(n.length===0)return;let i=[];for(let s of n){let l=t.get(s.sourceGroupId)?.anchorNodeId;if(!l)continue;let u,c;if(s.target.kind==="group"){let p=t.get(s.target.groupId);if(!p?.collapsed||!p.anchorNodeId)continue;u=p.anchorNodeId,c=`group:${s.target.groupId}`}else u=s.target.nodeId,c=`node:${s.target.nodeId}`;let h=`__group_agg_${s.sourceGroupId}__${s.target.kind==="group"?s.target.groupId:s.target.nodeId}`;this.store.index.getEdgeIndex(h)===void 0&&i.push({id:h,source:l,target:u,relationship:"__group_aggregated",properties:{_isAggregated:!0,_aggregatedGroupId:s.sourceGroupId,_aggregatedTargetKey:c,_weight:s.weight,_originalEdgeIds:[...s.originalEdgeIds]}})}if(i.length===0)return;this.store.addEdges(i,{silent:!0});let o=this.store.edgeState;if(o){let[s,d,l]=this.parseHexColor(this.aggregatedEdgeColor);for(let u of i){let c=this.store.index.getEdgeIndex(u.id);c!==void 0&&(o.widths[c]=this.aggregatedWidth(u.properties._weight),o.opacities[c]=1,o.colors[3*c]=s,o.colors[3*c+1]=d,o.colors[3*c+2]=l)}}this.store.updateStrategy.markDirty("edgeWidths"),this.store.updateStrategy.markDirty("edgeOpacities"),this.store.updateStrategy.markDirty("edgeColors")}clearAggregatedEdgeRender(e){let t=[];for(let r of this.store.data.edges)r.properties?._isAggregated===!0&&r.properties?._aggregatedGroupId===e&&t.push(r.id);t.length>0&&this.store.deleteEdges(t,{silent:!0})}ensureAggregatedRelationshipConfig(){let e=this.store.visualMapper;e.getRelationshipConfig("__group_aggregated")||e.setRelationshipConfig({relationship:"__group_aggregated",defaultColor:"#888888"},"ontology")}applyAnchorVisuals(e,t){let r=this.store.index.getNodeIndex(t);if(r===void 0)return;let n=this.store.nodeState;if(!n)return;e.savedAnchorColor=[n.colors[3*r],n.colors[3*r+1],n.colors[3*r+2]];let i=this.store.data.nodes.find(o=>o.id===t);if(e.savedAnchorLabel=i?.caption??null,e.spec.color){let[o,s,d]=this.parseHexColor(e.spec.color);n.colors[3*r]=o,n.colors[3*r+1]=s,n.colors[3*r+2]=d}i&&e.spec.kind!=="collect"&&(i.caption=e.spec.name,this.store.markNodeLabelsDirty()),e.savedAnchorBadge=this.store.getNodeBadge(t),e.countBadgeText=null,this.syncCountBadge(e,t)}syncCountBadge(e,t){let r=e.memberNodeIds.size-(e.memberNodeIds.has(t)?1:0),n=this.store.getNodeBadge(t),i=e.countBadgeText!=null&&n?.text===e.countBadgeText;if(n&&!i&&e.countBadgeText!=null)return;if(r<=0){i&&this.store.setNodeBadge(t,e.savedAnchorBadge??null),e.countBadgeText=null;return}let o=Pg(r);this.store.setNodeBadge(t,{text:o,anchor:"top-right",bg:"#f5a524",fg:"#1a1206"}),e.countBadgeText=o}restoreAnchorVisuals(e,t){let r=this.store.index.getNodeIndex(t);if(r===void 0)return;let n=this.store.nodeState;n&&e.savedAnchorColor&&(n.colors[3*r]=e.savedAnchorColor[0],n.colors[3*r+1]=e.savedAnchorColor[1],n.colors[3*r+2]=e.savedAnchorColor[2]);let i=this.store.data.nodes.find(o=>o.id===t);i&&(e.savedAnchorLabel===null?delete i.caption:i.caption=e.savedAnchorLabel,this.store.markNodeLabelsDirty()),e.countBadgeText!=null&&this.store.getNodeBadge(t)?.text===e.countBadgeText&&this.store.setNodeBadge(t,e.savedAnchorBadge??null),e.savedAnchorColor=null,e.savedAnchorLabel=null,e.savedAnchorBadge=null,e.countBadgeText=null}applyAnchorVisualsForTest(e,t){this.applyAnchorVisuals(e,t)}restoreAnchorVisualsForTest(e,t){this.restoreAnchorVisuals(e,t)}resolveAnchor(e){if(e.spec.anchorNodeId!==void 0&&e.memberNodeIds.has(e.spec.anchorNodeId)&&this.store.index.getNodeIndex(e.spec.anchorNodeId)!==void 0)return e.spec.anchorNodeId;if(e.memberNodeIds.size===1)return[...e.memberNodeIds][0];let t=this.store.positionProvider?.getPositions();if(t){let r=this.pickCentroidMember(e.memberNodeIds,t);if(r)return r}for(let r of e.memberNodeIds)if(this.store.index.getNodeIndex(r)!==void 0)return r;throw new Error(`[GroupManager] group ${e.id} has no valid member to anchor`)}pickCentroidMember(e,t){let r=0,n=0,i=0,o=0;for(let l of e){let u=this.store.index.getNodeIndex(l);if(u===void 0)continue;let c=t[3*u],h=t[3*u+1],p=t[3*u+2];Number.isFinite(c+h+p)&&(r+=c,n+=h,i+=p,o++)}if(o===0)return null;r/=o,n/=o,i/=o;let s=null,d=1/0;for(let l of e){let u=this.store.index.getNodeIndex(l);if(u===void 0)continue;let c=t[3*u],h=t[3*u+1],p=t[3*u+2];if(!Number.isFinite(c+h+p))continue;let f=(c-r)**2+(h-n)**2+(p-i)**2;f<d&&(s=l,d=f)}return s}resolveAnchorForTest(e){let t=this.store._groups.get(e);return this.resolveAnchor(t)}snapshotGroupState(){let{groups:e,nodeToGroup:t}=wt(this.store),r=this.store._aggregatedEdges,n=new Map;for(let[i,o]of e)n.set(i,{...o,memberNodeIds:new Set(o.memberNodeIds),center:{...o.center},boundingBox:{...o.boundingBox}});return{groups:n,nodeToGroup:new Map(t),aggregatedEdges:r?r.map(i=>({...i,originalEdgeIds:[...i.originalEdgeIds],target:{...i.target}})):null}}restoreGroupState(e){wt(this.store),this.store._groups=new Map;for(let[t,r]of e.groups)this.store._groups.set(t,{...r,memberNodeIds:new Set(r.memberNodeIds),center:{...r.center},boundingBox:{...r.boundingBox}});this.store._nodeToGroup=new Map(e.nodeToGroup),this.store._aggregatedEdges=e.aggregatedEdges?e.aggregatedEdges.map(t=>({...t,originalEdgeIds:[...t.originalEdgeIds],target:{...t.target}})):null,this.store.updateStrategy.markDirty("groups"),this.store.notifyChange()}};var ls=class{constructor(e,t){this._permanentlyDeleted=new Set;this.onCollectionChange=null;this.store=e,this.gm=t}isCollection(e){let t=this.findCollectGroupByAnchor(e);return!!t&&t.collapsed&&t.anchorNodeId===e}isCollected(e){let t=this.store._nodeToGroup?.get(e);if(!t)return!1;let r=this.store._groups?.get(t);return!!r&&r.spec.kind==="collect"&&r.collapsed&&r.anchorNodeId!==e}isPermanentlyDeleted(e){return this._permanentlyDeleted.has(e)}get collections(){let e=new Map;for(let t of this.store._groups?.values()??[])if(t.spec.kind==="collect"&&t.collapsed&&t.anchorNodeId){let r=[...t.memberNodeIds].filter(n=>n!==t.anchorNodeId);e.set(t.anchorNodeId,{parentId:t.anchorNodeId,childNodeIds:r,savedState:new Map,savedEdges:[]})}return e}get collectionCount(){let e=0;for(let t of this.store._groups?.values()??[])t.spec.kind==="collect"&&t.collapsed&&e++;return e}collect(e,t){if(t.length===0||this.isCollection(e)||this._permanentlyDeleted.has(e))return;let n=this.store.data.nodes.find(o=>o.id===e)?.labels?.[0]??e,i=this.gm.createGroup([e,...t],{name:n,anchorNodeId:e,kind:"collect"});this.gm.collapseGroup(i),this.onCollectionChange?.("collect",e)}explode(e){let t=this.findCollectGroupByAnchor(e);t&&(this.gm.expandGroup(t.id),this.gm.dissolveGroup(t.id),this.onCollectionChange?.("explode",e))}explodeAll(){let e=[];for(let t of this.store._groups?.values()??[])t.spec.kind==="collect"&&t.collapsed&&t.anchorNodeId&&e.push(t.anchorNodeId);for(let t of e)this.explode(t)}deleteCollection(e){let t=this.findCollectGroupByAnchor(e);if(!t)return;let r=[...t.memberNodeIds];for(let n of r)this._permanentlyDeleted.add(n);this.gm.dissolveGroup(t.id),this.store.deleteNodes(r),this.onCollectionChange?.("delete",e)}collectLeaves(){let e=this.store.data,t=this.store.queries,r=new Map;for(let n of e.nodes){if(this.isCollected(n.id)||this.isCollection(n.id)||this._permanentlyDeleted.has(n.id))continue;let o=t.getNeighbors(n.id).filter(s=>!this.isCollected(s.nodeId)&&!this._permanentlyDeleted.has(s.nodeId));if(o.length===1){let s=o[0].nodeId;r.has(s)||r.set(s,[]),r.get(s).push(n.id)}}for(let[n,i]of r)i.length>=2&&this.collect(n,i)}onNodesDeleted(e){for(let t of e)this._permanentlyDeleted.add(t)}findCollectGroupByAnchor(e){let t=this.store._nodeToGroup?.get(e);if(!t)return;let r=this.store._groups?.get(t);if(!(!r||r.spec.kind!=="collect")&&r.anchorNodeId===e)return r}};var Uu={straight:0,curve:1,radial:2,orthogonal:3,routed:4,family:5},_g=/^[a-z][a-zA-Z0-9-]*$/,Dg=/^[a-z][a-z0-9-]*:[A-Za-z][A-Za-z0-9_-]*$/,Zi=class{constructor(e){this.category=e;this.entries=new Map}registerBuiltin(e,t){if(!_g.test(e))throw new Error(`[${this.category}] invalid built-in name "${e}"`);this.entries.set(e,{name:e,builtin:!0,description:t})}register(e,t){if(!Dg.test(e))throw new Error(`[${this.category}] invalid type name "${e}": extension types must be named "<pack>:<name>"`);let r=this.entries.get(t.fallback);if(!r||!r.builtin)throw new Error(`[${this.category}] "${e}": fallback "${t.fallback}" is not a built-in ${this.category} type`);if(this.entries.get(e)&&!t.replace)throw new Error(`[${this.category}] type "${e}" is already registered`);let i={name:e,builtin:!1,description:t.description,fallback:t.fallback};return this.entries.set(e,i),()=>{this.entries.get(e)===i&&this.entries.delete(e)}}has(e){return this.entries.has(e)}get(e){return this.entries.get(e)}list(){let e=[...this.entries.values()];return[...e.filter(t=>t.builtin),...e.filter(t=>!t.builtin)]}resolveBuiltin(e){let t=this.entries.get(e);if(t)return t.builtin?t.name:t.fallback}},cs=class{constructor(){this.nodes=new Zi("node");this.edges=new Zi("edge");this.arrows=new Zi("arrow");this.layouts=Ol();this.nodes.registerBuiltin("circle","Round billboard node.");for(let e of Object.keys(Uu))this.edges.registerBuiltin(e);this.arrows.registerBuiltin("cone","Cone arrow head.")}resolveEdgeShapeId(e){let t=this.edges.resolveBuiltin(e);return t===void 0?0:Uu[t]??0}};var Wu=!1,ju=class{constructor(e){this.mode="gpu";this._positionTexture=null;this._textureSize=512;this._spaceSize=1;this._needsUpdate=!1;e&&(this._positionTexture=e.positionTexture??null,this._textureSize=e.textureSize??512,this._spaceSize=e.spaceSize??1)}getPositionTexture(){return this._positionTexture}getTextureSize(){return this._textureSize}getSpaceSize(){return this._spaceSize}getPositions(){return null}get needsUpdate(){return this._needsUpdate}clearNeedsUpdate(){this._needsUpdate=!1}setPositionTexture(e,t){this._positionTexture=e,this._textureSize=t,this._needsUpdate=!0}setSpaceSize(e){this._spaceSize=e,this._needsUpdate=!0}},Yi=class a{constructor(e,t){this.mode="gpu";this._positions=null;this._nodeIdToIndex=new Map;this._bridge=null;this._syncedEpoch=-1;this._mirrorStale=!0;this.layoutController=e,this._bridge=t?.bridge??null,!this._bridge&&!Wu&&(Wu=!0,console.warn("[GPULayoutProviderAdapter] constructed without a StoreIndexBridge \u2014 falling back to the legacy private id\u2192index map (spec C5).")),this._initPositionArray()}_indexOf(e){return this._bridge?this._bridge.getNodeIndex(e):this._nodeIdToIndex.get(e)}_epochStale(){return this._bridge!==null&&this._bridge.structureEpoch!==this._syncedEpoch}_stampEpoch(){this._bridge&&(this._syncedEpoch=this._bridge.structureEpoch)}_initPositionArray(){this._stampEpoch();let e=this.layoutController.graph?.layoutNodes;!e||e.length===0||(this._positions=new Float32Array(e.length*3),this._nodeIdToIndex.clear(),e.forEach((t,r)=>{this._nodeIdToIndex.set(t.id,r),this._positions[r*3]=t.position.x,this._positions[r*3+1]=t.position.y,this._positions[r*3+2]=t.position.z}))}_inTransitionWindow(){if(!this._bridge)return!1;let e=this.layoutController.graph?.layoutNodes;return e!=null&&e.length!==this._bridge.getNodeCount()}syncFromLayout(){if(this._inTransitionWindow())return;let e=this.layoutController.graph?.layoutNodes;if(!e||!this._positions||this._epochStale()||e.length*3>this._positions.length){this._initPositionArray();return}!this._bridge&&this._nodeIdToIndex.size!==e.length&&(this._nodeIdToIndex.clear(),e.forEach((t,r)=>{this._nodeIdToIndex.set(t.id,r)})),e.forEach((t,r)=>{this._positions[r*3]=t.position.x,this._positions[r*3+1]=t.position.y,this._positions[r*3+2]=t.position.z})}getPositionTexture(){return this.layoutController.getPositionTexture()}getTextureSize(){return this.layoutController.getTextureSize()}getSpaceSize(){return this.layoutController.getSpaceSize()}invalidateMirror(){this._mirrorStale=!0}onStructureResynced(){this._initPositionArray(),this._mirrorStale=!0}getPositions(){if(this._inTransitionWindow())return this._positions;let e=this._mirrorStale||this.layoutController.graph?.renderNeedsUpdate===!0;return e&&this.layoutController.readBackPositions&&this.layoutController.readBackPositions(),(e||this._epochStale()||!this._positions)&&(this.syncFromLayout(),e&&(this._mirrorStale=!1)),this._positions}getCpuMirrorPositions(){return this._positions}updatePosition(e,t,r,n=0){let i=(e+1)*3;if(!this._positions)this._positions=new Float32Array(i);else if(this._positions.length<i){let s=new Float32Array(i);s.set(this._positions),this._positions=s}this._positions[e*3]=t,this._positions[e*3+1]=r,this._positions[e*3+2]=n;let o=this.layoutController.graph?.layoutNodes;if(o&&e<o.length){let s=o[e];s.position.x=t,s.position.y=r,s.position.z=n,s.pinned=!0,this.layoutController.pinNodes&&this.layoutController.pinNodes([s])}this.layoutController.graph.renderNeedsUpdate=!0}markNeedsUpdate(){this.layoutController.graph.renderNeedsUpdate=!0}get needsUpdate(){return this.layoutController.graph.renderNeedsUpdate}clearNeedsUpdate(){this.layoutController.graph.renderNeedsUpdate=!1}_uploadSubset(e){let t=this.layoutController.graph?.layoutNodes;if(!t||!this.layoutController.pinNodes){this.layoutController.graph.renderNeedsUpdate=!0;return}if(this._bridge&&t.length!==this._bridge.getNodeCount()){this.layoutController.graph.renderNeedsUpdate=!0;return}let r=new Set,n=[];for(let i of e){let o=this._indexOf(i);if(o===void 0)continue;let s=this._positions[o*3],d=this._positions[o*3+1],l=this._positions[o*3+2],u=t[o];u&&(u.position.x=s,u.position.y=d,u.position.z=l,u.pinned&&r.add(i)),n.push({id:i,position:{x:s,y:d,z:l},pinned:!0})}if(n.length===0){this.layoutController.graph.renderNeedsUpdate=!0;return}if(this.layoutController.pinNodes(n),this.layoutController.unpinNodes){let i=[];for(let o of n)r.has(o.id)||i.push(o.id);i.length>0&&this.layoutController.unpinNodes(i)}this.layoutController.graph.renderNeedsUpdate=!0}updatePositions(e){if(this._epochStale()&&this.syncFromLayout(),!(!this._positions||e.length===0)){if(!this.layoutController.pinNodes){this.layoutController.graph.renderNeedsUpdate=!0;return}this._uploadSubset(e)}}writePositions(e){if(e.size===0)return[];if(this._epochStale()&&this.syncFromLayout(),this._positions||this._initPositionArray(),!this._positions)return[];let t=this.layoutController.graph?.layoutNodes,r=!this._bridge||t!=null&&t.length===this._bridge.getNodeCount(),n=[];for(let[i,o]of e){let s=this._indexOf(i);if(s===void 0)continue;let d=(s+1)*3;if(this._positions.length<d){let l=new Float32Array(d);l.set(this._positions),this._positions=l}this._positions[s*3]=o[0],this._positions[s*3+1]=o[1],this._positions[s*3+2]=o[2],n.push(i)}return n.length>0&&r&&this._uploadSubset(n),this.layoutController.graph.renderNeedsUpdate=!0,n}setAllPositions(e,t){if(this._epochStale()&&this.syncFromLayout(),!this._positions)return;if(e instanceof Float32Array)e!==this._positions&&e.length===this._positions.length&&this._positions.set(e);else{let s=Math.min(e.length,this._positions.length);for(let d=0;d<s;d++)this._positions[d]=e[d]}let r=this.layoutController.graph?.layoutNodes;if(!r||!this.layoutController.pinNodes){this.layoutController.graph.renderNeedsUpdate=!0;return}let n=new Set;for(let s=0;s<r.length;s++){let d=r[s];d&&d.pinned&&n.add(d.id)}let i=[];for(let s=0;s<r.length;s++){let d=r[s];if(!d)continue;let l=this._positions[s*3],u=this._positions[s*3+1],c=this._positions[s*3+2];d.position.x=l,d.position.y=u,d.position.z=c,i.push({id:d.id,position:{x:l,y:u,z:c},pinned:!0})}if(this.layoutController.pinNodes(i),!(t?.pin??!1)&&this.layoutController.unpinNodes){let s=[];for(let d of i)n.has(d.id)||s.push(d.id);s.length>0&&this.layoutController.unpinNodes(s)}this.layoutController.graph.renderNeedsUpdate=!0}static fromGPUForceLayoutController(e){return new a(e)}},mn=class{constructor(e){this.mode="cpu";this._spaceSize=1;this._needsUpdate=!1;this._indexBridge=null;this._positions=new Float32Array(e*3)}getPositionTexture(){return null}getTextureSize(){return 0}getSpaceSize(){return this._spaceSize}getPositions(){return this._positions}get needsUpdate(){return this._needsUpdate}clearNeedsUpdate(){this._needsUpdate=!1}setPosition(e,t,r,n){let i=e*3;this._positions[i]=t,this._positions[i+1]=r,this._positions[i+2]=n,this._needsUpdate=!0}updatePosition(e,t,r,n=0){this.setPosition(e,t,r,n)}getPosition(e){let t=e*3;return{x:this._positions[t],y:this._positions[t+1],z:this._positions[t+2]}}updatePositions(e){this._needsUpdate=!0}setAllPositions(e){e instanceof Float32Array?this._positions=e:this._positions.set(e),this._needsUpdate=!0}resize(e){let t=new Float32Array(e*3);t.set(this._positions.subarray(0,Math.min(this._positions.length,e*3))),this._positions=t,this._needsUpdate=!0}remapPositions(e){let t=new Float32Array(e.length*3);for(let r=0;r<e.length;r++){let n=e[r];t[r*3]=this._positions[n*3],t[r*3+1]=this._positions[n*3+1],t[r*3+2]=this._positions[n*3+2]}this._positions=t,this._needsUpdate=!0}markNeedsUpdate(){this._needsUpdate=!0}setSpaceSize(e){this._spaceSize=e}setIndexBridge(e){this._indexBridge=e}writePositions(e){if(!this._indexBridge)return[];let t=this.getPositions();if(!t)return[];let r=[];for(let[n,i]of e){let o=this._indexBridge.getNodeIndex(n);o===void 0||o*3+2>=t.length||(t[o*3]=i[0],t[o*3+1]=i[1],t[o*3+2]=i[2],r.push(n))}return r.length>0&&this.markNeedsUpdate(),r}},us=class{constructor(e){this.mode="cpu";this._indexBridge=null;this.layoutController=e}getPositionTexture(){return null}getTextureSize(){return 0}getSpaceSize(){return this.layoutController.getSpaceSize()}getPositions(){return this.layoutController.sharedArray}updatePosition(e,t,r,n=0){let i=this.layoutController.sharedArray;i&&(i[e*3]=t,i[e*3+1]=r,i[e*3+2]=n);let o=this.layoutController.graph?.layoutNodes;if(o&&e<o.length){let s=o[e];s.position.x=t,s.position.y=r,s.position.z=n,s.pinned=!0,this.layoutController.pinNodes&&this.layoutController.pinNodes([s])}this.layoutController.graph.renderNeedsUpdate=!0}markNeedsUpdate(){this.layoutController.graph.renderNeedsUpdate=!0}updatePositions(e){this.layoutController.graph.renderNeedsUpdate=!0}get needsUpdate(){return this.layoutController.graph.renderNeedsUpdate}clearNeedsUpdate(){this.layoutController.graph.renderNeedsUpdate=!1}setIndexBridge(e){this._indexBridge=e}writePositions(e){if(!this._indexBridge)return[];let t=this.getPositions();if(!t)return[];let r=this.layoutController.graph?.layoutNodes,n=[];for(let[i,o]of e){let s=this._indexBridge.getNodeIndex(i);if(!(s===void 0||s*3+2>=t.length)){if(t[s*3]=o[0],t[s*3+1]=o[1],t[s*3+2]=o[2],r){let d=s<r.length?r[s]:void 0;d&&(d.position.x=o[0],d.position.y=o[1],d.position.z=o[2])}n.push(i)}}return n.length>0&&this.markNeedsUpdate(),n}},Xn=class{constructor(e){this.mode="cpu";this._spaceSize=1;this._needsUpdate=!0;this._indexBridge=null;e instanceof Float32Array?this._positions=e:(this._positions=new Float32Array(e.length*3),e.forEach((t,r)=>{this._positions[r*3]=t.x,this._positions[r*3+1]=t.y,this._positions[r*3+2]=t.z??0}))}getPositionTexture(){return null}getTextureSize(){return 0}getSpaceSize(){return this._spaceSize}getPositions(){return this._positions}get needsUpdate(){return this._needsUpdate}clearNeedsUpdate(){this._needsUpdate=!1}updatePosition(e,t,r,n=0){let i=e*3;this._positions[i]=t,this._positions[i+1]=r,this._positions[i+2]=n,this._needsUpdate=!0}updatePositions(e){this._needsUpdate=!0}remapPositions(e){let t=new Float32Array(e.length*3);for(let r=0;r<e.length;r++){let n=e[r];t[r*3]=this._positions[n*3],t[r*3+1]=this._positions[n*3+1],t[r*3+2]=this._positions[n*3+2]}this._positions=t,this._needsUpdate=!0}setIndexBridge(e){this._indexBridge=e}writePositions(e){if(!this._indexBridge)return[];let t=this.getPositions();if(!t)return[];let r=[];for(let[n,i]of e){let o=this._indexBridge.getNodeIndex(n);o===void 0||o*3+2>=t.length||(t[o*3]=i[0],t[o*3+1]=i[1],t[o*3+2]=i[2],r.push(n))}return r.length>0&&(this._needsUpdate=!0),r}};var Wt={color:1,size:2,opacity:4,shape:8,icon:16},hs=31;var yn=class{constructor(){this.state=0;this.buf=new Uint32Array(16);this.len=0;this.lo=1/0;this.hi=-1}get isEmpty(){return this.state===0}add(e,t){if(this.state!==3&&(e<this.lo&&(this.lo=e),e>this.hi&&(this.hi=e),this.state!==2)){if(this.state=1,this.len===this.buf.length){if(this.len>=t&&(this.fold(t),this.state===2))return;let r=new Uint32Array(this.buf.length*2);r.set(this.buf),this.buf=r}this.buf[this.len++]=e}}addRange(e,t){t<=e||this.state===3||(e<this.lo&&(this.lo=e),t-1>this.hi&&(this.hi=t-1),this.state=2,this.len=0)}addAll(){this.state=3,this.len=0}fold(e){let t=this.buf.subarray(0,this.len);t.sort();let r=0;for(let n=0;n<this.len;n++)(n===0||t[n]!==t[n-1])&&(t[r++]=t[n]);this.len=r,this.len>=e&&(this.state=2,this.len=0)}freeze(e){if(this.state===0||e<=0)return null;if(this.state===3)return new Qn("all",e,null,0,0);if(this.state===2){let i=this.lo,o=Math.min(this.hi+1,e);return i>=o?null:(o-i)*2>e?new Qn("all",e,null,0,0):new Qn("range",o-i,null,i,o)}let t=this.buf.subarray(0,this.len);t.sort();let r=new Uint32Array(this.len),n=0;for(let i=0;i<this.len;i++){let o=t[i];if(o>=e)break;(n===0||r[n-1]!==o)&&(r[n++]=o)}return n===0?null:new Qn("sparse",n,n===r.length?r:r.slice(0,n),0,0)}},Qn=class{constructor(e,t,r,n,i){this.kind=e;this.size=t;this.slots=r;this.lo=n;this.hi=i}forEach(e){if(this.kind==="sparse")for(let t=0;t<this.slots.length;t++)e(this.slots[t]);else{let t=this.kind==="all"?0:this.lo,r=this.kind==="all"?this.size:this.hi;for(let n=t;n<r;n++)e(n)}}ranges(e=0){if(this.kind==="all")return[{start:0,end:this.size}];if(this.kind==="range")return[{start:this.lo,end:this.hi}];let t=[],r=this.slots,n=r[0],i=n+1;for(let o=1;o<r.length;o++){let s=r[o];s-i<=e||(t.push({start:n,end:i}),n=s),i=s+1}return t.push({start:n,end:i}),t}};var Ng=4096,pr=class{constructor(){this.ops=[];this.attrs=new Map;this.data=new Map;this.capacityChanged=!1}},Yl=class{constructor(e,t){this.log=e;this.needsFull=!0;this.pendingDomains=0;this.node=new pr;this.edge=new pr;this.disposed=!1;this.name=t.name,this.interest=t.domains??O.All,this.captureBefore=t.captureBefore??!1,this.maxOps=t.maxOps??Ng,this.maxSparse=t.maxSparse}hasPending(){return!this.disposed&&(this.needsFull||this.pendingDomains!==0)}dispose(){this.disposed||(this.disposed=!0,this.log._removeReader(this))}pend(e){return e==="node"?this.node:this.edge}sparseLimit(e){return this.maxSparse??Math.max(256,this.log.count(e)>>4)}overflow(){this.needsFull=!0,this.node=new pr,this.edge=new pr}acc(e,t){let r=e.attrs.get(t);return r||e.attrs.set(t,r=new yn),r}onTouch(e,t,r,n){this.pendingDomains|=n&this.interest,!this.needsFull&&this.acc(this.pend(e),t).add(r,this.sparseLimit(e))}onTouchRange(e,t,r,n,i){this.pendingDomains|=i&this.interest,!this.needsFull&&this.acc(this.pend(e),t).addRange(r,n)}onTouchAll(e,t,r){this.pendingDomains|=r&this.interest,!this.needsFull&&this.acc(this.pend(e),t).addAll()}touchWholeSlot(e,t){let r=this.pend(e),n=this.sparseLimit(e);for(let i of cu(e)){let o=hl(e,i);o&this.interest&&(this.acc(r,i).add(t,n),this.pendingDomains|=o&this.interest)}}onAdd(e,t,r){if(this.pendingDomains|=O.Structure&this.interest,this.needsFull||!(this.interest&O.Structure)){this.needsFull||this.touchWholeSlot(e,r);return}let n=this.pend(e);n.ops.push({op:"add",id:t,slot:r}),this.touchWholeSlot(e,r),n.ops.length>this.maxOps&&this.overflow()}onRemove(e,t,r,n,i){if(this.pendingDomains|=O.Structure&this.interest,this.needsFull)return;let o=this.pend(e);if(this.interest&O.Structure&&(o.ops.push(i===void 0?{op:"remove",id:t,slot:r,last:n}:{op:"remove",id:t,slot:r,last:n,movedId:i}),o.ops.length>this.maxOps))return this.overflow();if(o.data.delete(t),i!==void 0){let s=o.data.get(i);s&&(s.slot=r),this.touchWholeSlot(e,r)}}onData(e,t,r,n,i){if(this.pendingDomains|=O.Data&this.interest,this.needsFull||!(this.interest&O.Data))return;let o=this.pend(e),s=o.data.get(t);s||o.data.set(t,s={slot:r,keys:new Set}),s.slot=r;for(let d of n)s.keys.add(d);if(this.captureBefore&&i){let d=s.before??(s.before={});for(let l of Object.keys(i))l in d||(d[l]=i[l])}o.data.size>this.maxOps&&this.overflow()}onCapacity(e){this.pendingDomains|=O.Structure&this.interest,!this.needsFull&&(this.pend(e).capacityChanged=!0)}onBump(e){this.pendingDomains|=e&this.interest}read(){if(this.disposed||!this.needsFull&&this.pendingDomains===0)return null;let e=this.log.seq,t=this.log.count("node"),r=this.log.count("edge");if(this.needsFull)return this.needsFull=!1,this.pendingDomains=0,this.node=new pr,this.edge=new pr,{seq:e,full:!0,domains:this.interest,nodes:qu(t),edges:qu(r)};let n=this.pendingDomains,i=this.node,o=this.edge;return this.pendingDomains=0,this.node=new pr,this.edge=new pr,{seq:e,full:!1,domains:n,nodes:Ku(i,t),edges:Ku(o,r)}}};function qu(a){return{count:a,capacityChanged:!1,ops:[],attrs:new Map,data:[]}}function Ku(a,e){let t=new Map;for(let[n,i]of a.attrs){let o=i.freeze(e);o&&t.set(n,o)}let r=[];for(let[n,i]of a.data)r.push(i.before?{id:n,slot:i.slot,keys:i.keys,before:i.before}:{id:n,slot:i.slot,keys:i.keys});return{count:e,capacityChanged:a.capacityChanged,ops:a.ops,attrs:t,data:r}}var ps=class{constructor(e){this.opts=e;this.readers=[];this._seq=0;this.domainSeq=new Array(lu).fill(0);this.depth=0;this.batchDomains=0;this.subs=new Set;this.notifyMask=0;this.notifyScheduled=!1}count(e){return this.opts.getCount(e)}get seq(){return this._seq}get readerCount(){return this.readers.length}get wantsBefore(){for(let e of this.readers)if(e.captureBefore)return!0;return!1}createReader(e){let t=new Yl(this,e);return this.readers.push(t),t}_removeReader(e){let t=this.readers.indexOf(e);t>=0&&this.readers.splice(t,1)}versionOf(e){let t=0;for(let r=e&O.All;r!==0;r&=r-1){let n=this.domainSeq[31-Math.clz32(r&-r)];n>t&&(t=n)}return t}subscribe(e,t){let r={mask:e,fn:t};return this.subs.add(r),()=>this.subs.delete(r)}batch(e){this.depth++;try{return e()}finally{--this.depth===0&&this.commit()}}mark(e){this.batchDomains|=e,this.depth===0&&this.commit()}commit(){let e=this.batchDomains;if(e===0)return;this.batchDomains=0;let t=++this._seq;for(let r=e;r!==0;r&=r-1)this.domainSeq[31-Math.clz32(r&-r)]=t;this.notifyMask|=e,!(this.notifyScheduled||this.subs.size===0)&&(this.notifyScheduled=!0,queueMicrotask(()=>{this.notifyScheduled=!1;let r=this.notifyMask;this.notifyMask=0;for(let n of[...this.subs])if(n.mask&r)try{n.fn()}catch(i){console.error("[ChangeLog] subscriber threw:",i)}}))}maskOf(e,t,r){let n=hl(e,t);if(n===void 0)throw new Error(`[ChangeLog] unknown ${e} attribute "${t}"`);return r===void 0?n:r&n}touch(e,t,r,n){let i=this.maskOf(e,t,n);for(let o of this.readers)o.interest&i&&o.onTouch(e,t,r,i);this.mark(i)}touchRange(e,t,r,n,i){let o=this.maskOf(e,t,i);for(let s of this.readers)s.interest&o&&s.onTouchRange(e,t,r,n,o);this.mark(o)}touchAll(e,t,r){let n=this.maskOf(e,t,r);for(let i of this.readers)i.interest&n&&i.onTouchAll(e,t,n);this.mark(n)}recordAdd(e,t,r){for(let n of this.readers)n.onAdd(e,t,r);this.mark(O.Structure)}recordRemove(e,t,r,n,i){if(i===void 0!=(r===n))throw new Error(`[ChangeLog] recordRemove(${t}): movedId must be given exactly when slot (${r}) !== last (${n})`);for(let o of this.readers)o.onRemove(e,t,r,n,i);this.mark(O.Structure)}recordData(e,t,r,n,i){for(let o of this.readers)o.onData(e,t,r,n,i);this.mark(O.Data)}recordCapacityChange(e){for(let t of this.readers)t.onCapacity(e);this.mark(O.Structure)}bump(e){for(let t of this.readers)t.interest&e&&t.onBump(e);this.mark(e)}};var gr=[{name:"colors",stride:3,default:0,initValues:[.6,.6,.6]},{name:"sizes",stride:1,default:10},{name:"effectiveSizes",stride:1,default:10},{name:"opacities",stride:1,default:1},{name:"icons",stride:1,default:-1},{name:"imageIndices",stride:1,default:-1},{name:"selected",stride:1,default:0},{name:"highlighted",stride:1,default:0},{name:"hovered",stride:1,default:0},{name:"pinned",stride:1,default:0},{name:"hidden",stride:1,default:0},{name:"collection",stride:1,default:0},{name:"iconUVs",stride:4,default:-1},{name:"imageUVs",stride:4,default:-1},{name:"ringColors",stride:3,default:0,optional:!0},{name:"ripple",stride:1,default:0},{name:"breathe",stride:1,default:0},{name:"halo",stride:1,default:0},{name:"suppressFill",stride:1,default:0},{name:"shapeIds",stride:1,default:0},{name:"aspects",stride:1,default:1},{name:"overrides",stride:1,default:0}],kt=[{name:"colors",stride:3,default:0,initValues:[.5,.5,.5]},{name:"widths",stride:1,default:1},{name:"opacities",stride:1,default:.8},{name:"selected",stride:1,default:0},{name:"highlighted",stride:1,default:0},{name:"dashed",stride:1,default:0},{name:"shapes",stride:1,default:-1},{name:"bends",stride:1,default:NaN},{name:"flow",stride:1,default:0},{name:"glow",stride:1,default:0},{name:"tubeGlow",stride:1,default:0}];function Xi(a,e){let t={};for(let r of a){if(r.optional)continue;let n=new Float32Array(e*r.stride);r.default!==0&&n.fill(r.default),t[r.name]=n}return t}function vn(a,e,t,r,n){for(let i of e){let o=a[i.name];if(!o)continue;let s=i.stride;if(i.initValues)for(let d=t;d<t+r;d++){let l=d*s;for(let u=0;u<s;u++)o[l+u]=i.initValues[u]}else{let d=n?.[i.name]??i.default;d!==0&&o.fill(d,t*s,(t+r)*s)}}}function Xl(a,e,t,r){if(t!==r)for(let n of e){let i=a[n.name];if(!i)continue;let o=n.stride;i.copyWithin(r*o,t*o,(t+1)*o)}}function Ql(a,e,t){for(let r of e){let n=a[r.name];n&&n.fill(r.default,t*r.stride,(t+1)*r.stride)}}function Jl(a,e,t,r,n){let i={};for(let o of e){let s=a[o.name];if(!s){if(o.optional)continue;let u=new Float32Array(n*o.stride);o.default!==0&&u.fill(o.default),i[o.name]=u;continue}let d=o.stride,l=new Float32Array(n*d);o.default!==0&&l.fill(o.default);for(let u=0;u<r;u++){let c=t[u];if(c===void 0)continue;let h=c*d,p=u*d;for(let f=0;f<d;f++)l[p+f]=s[h+f]}i[o.name]=l}return i}function ec(a,e,t,r){let n={};for(let i of e){let o=a[i.name];if(!o){if(i.optional)continue;let l=new Float32Array(t*i.stride);i.default!==0&&l.fill(i.default),n[i.name]=l;continue}let s=r?.[i.name]??i.default,d=new Float32Array(t*i.stride);d.set(o),s!==0&&d.fill(s,o.length),n[i.name]=d}return n}function gs(a,e,t){let r={};for(let n of e){let i=a[n.name];if(!i){if(n.optional)continue;continue}let o=t*n.stride,s=new Float32Array(o);s.set(i.subarray(0,Math.min(i.length,o))),r[n.name]=s}return r}var $u=1.5;function kg(a,e){if(a.size!==e.size)return!1;for(let[t,r]of a){let n=e.get(t);if(!n||n.x!==r.x||n.y!==r.y||(n.unit??"node")!==(r.unit??"node"))return!1}return!0}var fs=class{constructor(){this.registry=new cs;this._version=0;this._iconVersion=0;this._labelVersion=0;this._labelExtentOwners=new Map;this._labelExtentMerged=null;this._versionChangedSubs=new Set;this._iconVersionChangedSubs=new Set;this._versionNotifyPending=!1;this._iconVersionNotifyPending=!1;this._data={nodes:[],edges:[]};this._index=new jl;this._nodeState=null;this._edgeState=null;this._nodeCapacity=0;this._edgeCapacity=0;this._positionProvider=null;this._structureEpoch=0;this._updateStrategy=new ns;this.changes=new ps({getCount:e=>e==="node"?this.data.nodes.length:this.data.edges.length});this._visibilityFilter=null;this.onStructureChange=null;this._eventBus=null;this._layoutRuntime=null;this._configuredSchema=null;this._iconNames=new Map;this._imageUrls=new Map;this._badges=null;this._tagSpecs=null;this._nodeToTag=null;this._tagToNodes=null;this._collect=null;this._groups=null;this._nodeToGroup=null;this._aggregatedEdges=null;this._groupManager=null;this._algorithmPropertyKeys=new Set;this._defaultNodeSize=Math.pow(10,.2);this._globalNodeSizeScale=1;this._edgeArrowVisible=!0;this._edgeScale=1;this._defaultEdgeShape=-1;this._edgeCornerRadius=.35;this._edgeAnchors=new Map;this._edgeRoutes=new Map;this._edgeRouteVersion=0;this._edgeRoutingAxis=-1;this.rippleColor=[0,.9,1];this.rippleSpeed=.5;this.rippleRings=3;this._ontologyRegistry=null;this._lastTransactionVersion=-1;this._categoryIndex=null;this._onSelectionChanged=null;this._selectionChangedSubs=new Set;this._mapperDepth=0;this._updateStrategy.attachChangeLog(this.changes),this._queries=new ql(this._data,this._index),this._visualMapper=new is(this)}get structureEpoch(){return this._structureEpoch}setEventBus(e){this._eventBus=e}setLayoutRuntime(e){this._layoutRuntime=e}get version(){return this._version}isResolvedByTransaction(){return this._lastTransactionVersion===this._version}markTransactionResolved(){this._lastTransactionVersion=this._version}invalidateTransactionVersion(){this._lastTransactionVersion=-1}get iconVersion(){return this._iconVersion}get labelVersion(){return this._labelVersion}markNodeLabelsDirty(){this._updateStrategy.markDirty("nodeLabels"),this._labelVersion++}batch(e){return this.changes.batch(e)}notifyChange(){this._bumpVersion(O.All)}subscribeVersionChanged(e){return this._versionChangedSubs.add(e),()=>{this._versionChangedSubs.delete(e)}}subscribeIconVersionChanged(e){return this._iconVersionChangedSubs.add(e),()=>{this._iconVersionChangedSubs.delete(e)}}_bumpVersion(e){this._version++,this.changes.bump(e),!this._versionNotifyPending&&(this._versionNotifyPending=!0,queueMicrotask(()=>{this._versionNotifyPending=!1;for(let t of this._versionChangedSubs)try{t()}catch(r){console.error("[GraphStore] versionChanged subscriber threw:",r)}}))}_bumpIconVersion(){this._iconVersion++,this.changes.bump(O.Icons),!this._iconVersionNotifyPending&&(this._iconVersionNotifyPending=!0,queueMicrotask(()=>{this._iconVersionNotifyPending=!1;for(let e of this._iconVersionChangedSubs)try{e()}catch(t){console.error("[GraphStore] iconVersionChanged subscriber threw:",t)}}))}get data(){return this._data}get index(){return this._index}get nodeState(){return this._nodeState}get edgeState(){return this._edgeState}get positionProvider(){return this._positionProvider}get updateStrategy(){return this._updateStrategy}get queries(){return this._queries}get defaultNodeSize(){return this._defaultNodeSize}set defaultNodeSize(e){this._defaultNodeSize=e}get edgeArrowVisible(){return this._edgeArrowVisible}set edgeArrowVisible(e){this._edgeArrowVisible=e}get edgeScale(){return this._edgeScale}set edgeScale(e){this._edgeScale=e}get edgeCornerRadius(){return this._edgeCornerRadius}set edgeCornerRadius(e){this._edgeCornerRadius=e}get edgeRoutingAxis(){return this._edgeRoutingAxis}set edgeRoutingAxis(e){this._edgeRoutingAxis=e}get defaultEdgeShape(){return this._defaultEdgeShape}set defaultEdgeShape(e){this._defaultEdgeShape=e}get visualMapper(){return this._visualMapper}get nodeCount(){return this._data.nodes.length}get edgeCount(){return this._data.edges.length}get nodeCapacity(){return this._nodeCapacity}get edgeCapacity(){return this._edgeCapacity}getSchema(){let e=this._queries.inferSchema();if(!this._configuredSchema)return e;let t=new Map(this._configuredSchema.categories.map(o=>[o.name,o])),r=new Map(this._configuredSchema.relationships.map(o=>[o.name,o])),n=e.categories.map(o=>t.get(o.name)||o);for(let o of this._configuredSchema.categories)n.find(s=>s.name===o.name)||n.push(o);let i=e.relationships.map(o=>r.get(o.name)||o);for(let o of this._configuredSchema.relationships)i.find(s=>s.name===o.name)||i.push(o);return{categories:n,relationships:i}}setSchema(e){this._configuredSchema=e}setOntologyRegistry(e){this._ontologyRegistry=e,this._reproject()}get ontology(){return this._ontologyRegistry?.resolved??null}get ontologyRegistry(){return this._ontologyRegistry}_reproject(){if(!this._ontologyRegistry)return;let{schema:e,categoryConfigs:t,relationshipConfigs:r}=this._ontologyRegistry.project();this.setSchema(e);let n=new Set(t.map(s=>s.category)),i=new Set(r.map(s=>s.relationship));for(let s of t)this._visualMapper.setCategoryConfig(s,"ontology");for(let s of r)this._visualMapper.setRelationshipConfig(s,"ontology");let o=this._ontologyRegistry.resolved;for(let s of o.entityTypes.keys())!n.has(s)&&!this._visualMapper.getCategoryConfig(s)&&this._visualMapper.setCategoryConfig({category:s},"ontology");for(let s of o.linkTypes.keys())!i.has(s)&&!this._visualMapper.getRelationshipConfig(s)&&this._visualMapper.setRelationshipConfig({relationship:s},"ontology");this._visualMapper.apply()}setData(e){this._replaceData(e,Math.ceil(e.nodes.length*1.5)||1)}setDataFromArrays(e){let t=e.dimensions??3;if(t!==2&&t!==3)throw new Error(`setDataFromArrays: dimensions must be 2 or 3, got ${t}`);let r=e.positions;if(!r||r.length%t!==0)throw new Error(`setDataFromArrays: positions length ${r?.length} is not a multiple of ${t}`);let n=r.length/t,{ids:i,category:o,colors:s,sizes:d}=e,l=(m,g,y)=>{if(g&&g.length!==n*y)throw new Error(`setDataFromArrays: ${m} length ${g.length}, expected ${n*y} for ${n} nodes`)};l("ids",i,1),l("category",typeof o=="string"?void 0:o,1),l("colors",s,3),l("sizes",d,1);let u=e.shape===void 0?0:Ki(e.shape);if(u<0)throw new Error(`setDataFromArrays: unknown shape "${String(e.shape)}"`);let c=new Array(n),h=typeof o=="string"?o:"node",p=typeof o=="string"?null:o??null;for(let m=0;m<n;m++)c[m]={id:i?i[m]:String(m),category:p?p[m]:h,properties:{}};let f;if(t===3&&r instanceof Float32Array)f=r;else{f=new Float32Array(n*3);for(let m=0;m<n;m++)f[m*3]=r[m*t],f[m*3+1]=r[m*t+1],t===3&&(f[m*3+2]=r[m*3+2])}this.batch(()=>{this._replaceData({nodes:c,edges:[]},n||1);let m=this._nodeState;if(s){let y=s instanceof Uint8Array||s instanceof Uint8ClampedArray?.00392156862745098:1;if(y===1&&s instanceof Float32Array)m.colors.set(s);else for(let v=0;v<n*3;v++)m.colors[v]=s[v]*y;this._updateStrategy.markDirty("nodeColors")}if(d){for(let y=0;y<n;y++)m.sizes[y]=d[y];this.refreshEffectiveSizes(),this._updateStrategy.markDirty("nodeSizes")}u>0&&(m.shapeIds.fill(u,0,n),this._updateStrategy.markDirty("nodeShapes"));let g=(s?Wt.color:0)|(d?Wt.size:0)|(e.shape!==void 0?Wt.shape:0);g&&m.overrides.fill(g,0,n),(s||d||e.shape!==void 0)&&this._bumpVersion(O.Style),this.setPositionProvider(new Xn(f))})}_replaceData(e,t){this._data=e,this._edgeAnchors.clear(),this._edgeRoutes.size>0&&(this._edgeRoutes.clear(),this._edgeRouteVersion++),this._index.buildFromGraphData(e),this._structureEpoch++,this._queries.updateReferences(e,this._index),this.initRenderState(t),this._visibilityFilter=null,this._bumpVersion(O.All),this._bumpIconVersion(),this._updateStrategy.markDirty("structure"),this._ontologyRegistry?this._ontologyRegistry.setInferred(e.nodes,e.edges)?this._reproject():(this._visualMapper.categoryConfigs.size>0||this._visualMapper.relationshipConfigs.size>0)&&this._visualMapper.apply():(this._visualMapper.categoryConfigs.size>0||this._visualMapper.relationshipConfigs.size>0)&&this._visualMapper.apply(),this._eventBus?.emit("graph:dataReset",{nodeCount:e.nodes.length,edgeCount:e.edges.length}),this.onStructureChange?.()}addNodes(e,t){if(e.length===0)return[];this._nodeState||this.initRenderState();let r=[];for(let i of e)this._index.hasNode(i.id)||r.push(i);if(r.length===0)return[];let n=this._data.nodes.length;this._data.nodes.push(...r);for(let i of r)this._index.addNode(i.id);if(this._structureEpoch++,this.changes.batch(()=>{for(let i=0;i<r.length;i++)this.changes.recordAdd("node",r[i].id,n+i)}),this.ensureNodeCapacity(this._data.nodes.length),this.initNewNodesRenderState(n,r.length),!t?.silent){this._bumpVersion(O.Structure),this._bumpIconVersion(),this._updateStrategy.markDirty("structure");let i=new Set;for(let o of r)this._visualMapper.getCategoryConfig(o.category)||(this._visualMapper.setCategoryConfig({category:o.category},"ontology"),i.add(o.category));this._visualMapper.apply({nodes:r,fullCategories:i}),this.onStructureChange?.()}return r}addEdges(e,t){if(e.length===0)return[];this._edgeState||this.initRenderState();let r=[];for(let i of e)this._index.hasEdge(i.id)||r.push(i);if(r.length===0)return[];let n=this._data.edges.length;this._data.edges.push(...r);for(let i of r)this._index.addEdge(i.id,i.source,i.target);if(this.changes.batch(()=>{for(let i=0;i<r.length;i++)this.changes.recordAdd("edge",r[i].id,n+i)}),this.ensureEdgeCapacity(this._data.edges.length),this.initNewEdgesRenderState(n,r.length),!t?.silent){this._bumpVersion(O.Structure),this._updateStrategy.markDirty("structure");let i=new Set;for(let o of r)this._visualMapper.getRelationshipConfig(o.relationship)||(this._visualMapper.setRelationshipConfig({relationship:o.relationship},"ontology"),i.add(o.relationship));this._visualMapper.apply({edges:r,fullRelationships:i}),this.onStructureChange?.()}return r}deleteNodes(e,t){if(e.length===0||!this._nodeState)return;let r=new Set;for(let l of e)this._index.hasNode(l)&&r.add(l);if(r.size===0)return;this._onBeforeRebuild?.();for(let l of r){this._badges?.delete(l),this._collect?.delete(l);let u=this._nodeToTag?.get(l);u!==void 0&&(this._nodeToTag.delete(l),this._tagToNodes?.get(u)?.delete(l))}if(this._nodeToGroup){for(let l of r){let u=this._nodeToGroup.get(l);if(u){this._nodeToGroup.delete(l);let c=this._groups?.get(u);c&&c.memberNodeIds.delete(l)}}this._groupManager?.onNodesAffected([...r])}let n=this._positionProvider,i=n?n.getPositions():null,o=this._data.nodes,s=this._nodeState,d=new Map;if(this.changes.batch(()=>{let l=new Set;for(let u of r){let c=this._index.getNodeIndex(u);for(let h of this._index.edgesOfNode(c))l.add(this._index.getEdgeId(h))}l.size>0&&this.deleteEdges([...l],{silent:!0});for(let u of r){let c=this._index.swapRemoveNode(u);if(c){if(d.delete(u),c.slot!==c.last){let h=c.movedId;d.has(h)||d.set(h,c.last),o[c.slot]=o[c.last],Xl(s,gr,c.last,c.slot)}o.pop(),Ql(s,gr,c.last),this.changes.recordRemove("node",c.id,c.slot,c.last,c.movedId)}}}),this._structureEpoch++,o.length*4<this._nodeCapacity&&this._nodeCapacity>64){let l=Math.ceil(o.length*1.5)||1;this._nodeState=gs(s,gr,l),this._nodeCapacity=l,this.changes.recordCapacityChange("node")}if(t?.silent||(this._visibilityFilter=null,this._bumpVersion(O.Structure),this._bumpIconVersion(),this._updateStrategy.markDirty("structure"),this.onStructureChange?.()),n&&i&&d.size>0){let l=new Map;for(let[c,h]of d)l.set(c,[i[h*3],i[h*3+1],i[h*3+2]]);let u=!1;if(typeof n.writePositions=="function"&&(u=n.writePositions(l).length>0),!u){let c=n.getPositions();if(c)for(let[h,p]of l){let f=this._index.getNodeIndex(h);f!==void 0&&(c[f*3]=p[0],c[f*3+1]=p[1],c[f*3+2]=p[2])}}}}deleteEdges(e,t){if(e.length===0)return;let r=this._data.edges,n=this._edgeState,i=0;if(this.changes.batch(()=>{for(let o of e){let s=this._index.swapRemoveEdge(o);s&&(i++,this._edgeAnchors.delete(s.id),this._edgeRoutes.delete(s.id)&&this._edgeRouteVersion++,s.slot!==s.last&&(r[s.slot]=r[s.last],n&&Xl(n,kt,s.last,s.slot)),r.pop(),n&&Ql(n,kt,s.last),this.changes.recordRemove("edge",s.id,s.slot,s.last,s.movedId))}}),i!==0){if(this._edgeState&&r.length*4<this._edgeCapacity&&this._edgeCapacity>64){let o=Math.ceil(r.length*1.5)||1;this._edgeState=gs(this._edgeState,kt,o),this._edgeCapacity=o,this.changes.recordCapacityChange("edge")}t?.silent||(this._visibilityFilter=null,this._bumpVersion(O.Structure),this._updateStrategy.markDirty("edgeStructure"),this.onStructureChange?.())}}removeNodes(e,t){this.deleteNodes(e,t)}removeEdges(e,t){this.deleteEdges(e,t)}applyDelta(e){return this.changes.batch(()=>this._applyDelta(e))}_applyDelta(e){let t={addedNodes:[],updatedNodes:[],removedNodeIds:[],addedEdges:[],updatedEdges:[],removedEdgeIds:[],positionPatches:[],pinPatches:[]},r=!1,n=[],i=[],o=new Set,s=new Set;if(e.removedEdgeIds&&e.removedEdgeIds.length>0){let c=e.removedEdgeIds.filter(h=>this._index.hasEdge(h));this.deleteEdges(e.removedEdgeIds,{silent:!0}),t.removedEdgeIds=c,t.removedEdgeIds.length>0&&(r=!0)}if(e.removedNodeIds&&e.removedNodeIds.length>0){let c=this._nodeState?e.removedNodeIds.filter(f=>this._index.hasNode(f)):[],h=[];if(c.length>0){let f=new Set,m=new Set(t.removedEdgeIds);for(let g of c)for(let y of this._index.edgesOfNode(this._index.getNodeIndex(g)))f.has(y)||(f.add(y),m.has(this._index.getEdgeId(y))||h.push(y));h.sort((g,y)=>g-y)}let p=h.map(f=>this._index.getEdgeId(f));this.deleteNodes(e.removedNodeIds,{silent:!0}),t.removedNodeIds=c;for(let f of p)t.removedEdgeIds.push(f);t.removedNodeIds.length>0&&(r=!0)}if(e.addedNodes&&e.addedNodes.length>0){this.addNodes(e.addedNodes,{silent:!0});for(let c of e.addedNodes)this._visualMapper.getCategoryConfig(c.category)||(this._visualMapper.setCategoryConfig({category:c.category},"ontology"),o.add(c.category));t.addedNodes=e.addedNodes.slice(),r=!0}if(e.addedEdges&&e.addedEdges.length>0){this.addEdges(e.addedEdges,{silent:!0});for(let c of e.addedEdges)this._visualMapper.getRelationshipConfig(c.relationship)||(this._visualMapper.setRelationshipConfig({relationship:c.relationship},"ontology"),s.add(c.relationship));t.addedEdges=e.addedEdges.slice(),r=!0}if(e.updatedNodes&&e.updatedNodes.length>0){for(let c of e.updatedNodes){let h=this._nodeById(c.id);if(h&&c.next){let p=[];c.next.category!==void 0&&(h.category=c.next.category,p.push("$category")),c.next.labels!==void 0&&(h.labels=c.next.labels,p.push("$labels")),c.next.tags!==void 0&&(h.tags=c.next.tags,p.push("$tags")),c.next.properties!==void 0&&(p.push(...Object.keys(c.next.properties)),h.properties={...h.properties,...c.next.properties},this.markNodeLabelsDirty()),p.length>0&&this.changes.recordData("node",h.id,this._index.getNodeIndex(h.id),p),t.updatedNodes.push({...h}),n.push(h)}}r=!0}if(e.updatedEdges&&e.updatedEdges.length>0){for(let c of e.updatedEdges){let h=this._edgeById(c.id);if(h&&c.next){let p=[];c.next.relationship!==void 0&&(h.relationship=c.next.relationship,p.push("$category")),c.next.properties!==void 0&&(p.push(...Object.keys(c.next.properties)),h.properties={...h.properties,...c.next.properties}),p.length>0&&this.changes.recordData("edge",h.id,this._index.getEdgeIndex(h.id),p),t.updatedEdges.push({...h}),i.push(h)}}r=!0}if(e.positionPatches&&e.positionPatches.length>0){t.positionPatches=e.positionPatches.slice();let c=this._layoutRuntime;if(c?.setNodePosition)for(let h of e.positionPatches)c.setNodePosition(h.id,h.position)}if(e.pinPatches&&e.pinPatches.length>0){t.pinPatches=e.pinPatches.slice();let c=[],h=[],p=this._layoutRuntime;for(let f of e.pinPatches)f.pinned&&f.position&&p?.setNodePosition&&p.setNodePosition(f.id,f.position),(f.pinned?c:h).push(f.id);c.length>0&&this.pinNodes(c),h.length>0&&this.unpinNodes(h)}let d=!!(e.removedNodeIds?.length||e.addedNodes?.length),l=!d&&!!(e.removedEdgeIds?.length||e.addedEdges?.length),u=!!(e.addedNodes?.length||e.addedEdges?.length||e.updatedNodes?.length||e.updatedEdges?.length);return r&&(this._visibilityFilter=null,this._bumpVersion(O.All),d?(this._bumpIconVersion(),this._updateStrategy.markDirty("structure")):l&&this._updateStrategy.markDirty("edgeStructure"),u&&(this._visualMapper.categoryConfigs.size>0||this._visualMapper.relationshipConfigs.size>0)&&this._visualMapper.apply({nodes:[...e.addedNodes??[],...n],edges:[...e.addedEdges??[],...i],fullCategories:o,fullRelationships:s}),d&&this.onStructureChange?.()),this._eventBus?.emit("graph:deltaApplied",{delta:e,result:t}),this._layoutRuntime?.applyGraphDelta?.(e),t}nodesOfCategory(e){let t=this._data.nodes,r=this.nodeSlotsOfCategory(e),n=new Array(r.length);for(let i=0;i<r.length;i++)n[i]=t[r[i]];return n}nodeSlotsOfCategory(e){let t=this._data.nodes,r=this.changes.versionOf(O.Structure|O.Data),n=this._categoryIndex;if(!n||n.version!==r||n.nodes!==t||n.count!==t.length){let s=new Map;for(let d=0;d<t.length;d++){let l=t[d].category,u=s.get(l);u||s.set(l,u=[]),u.push(d)}n={version:r,nodes:t,count:t.length,groups:s},this._categoryIndex=n}let i=n.groups.get(e);if(!i)return[];let o=[];for(let s=0;s<i.length;s++)t[i[s]].category===e&&o.push(i[s]);return o}_nodeById(e){let t=this._index.getNodeIndex(e);return t===void 0?void 0:this._data.nodes[t]}_edgeById(e){let t=this._index.getEdgeIndex(e);return t===void 0?void 0:this._data.edges[t]}hideNodes(e){if(this._nodeState){for(let t of e){let r=this._index.getNodeIndex(t);r!==void 0&&(this._nodeState.hidden[r]=1)}this._updateStrategy.markDirty("nodeHidden"),this._bumpVersion(O.Visibility)}}showNodes(e){if(this._nodeState){for(let t of e){let r=this._index.getNodeIndex(t);r!==void 0&&(this._nodeState.hidden[r]=0)}this._updateStrategy.markDirty("nodeHidden"),this._bumpVersion(O.Visibility)}}showAllNodes(){this._nodeState&&(this._nodeState.hidden.fill(0),this._updateStrategy.markDirty("nodeHidden"),this._bumpVersion(O.Visibility))}setPositionProvider(e){this._positionProvider=e,this._bumpVersion(O.Position)}setPositions(e){if(e.size===0)return;let t=this._positionProvider;if(!t)return;if(typeof t.writePositions=="function"&&t.writePositions(e).length>0){this._bumpVersion(O.Position);return}let r=t.getPositions();if(!r)return;let n=[];for(let[i,o]of e){let s=this._index.getNodeIndex(i);s!==void 0&&(r[s*3]=o[0],r[s*3+1]=o[1],r[s*3+2]=o[2],n.push(i))}n.length!==0&&(typeof t.updatePositions=="function"&&t.updatePositions(n),this._bumpVersion(O.Position))}getAllPositions(){let e=new Map,t=this._positionProvider;if(!t)return e;let r=t.getPositions();if(!r)return e;for(let n of this._data.nodes){let i=this._index.nodeIdToIndex.get(n.id);i!==void 0&&e.set(n.id,[r[i*3],r[i*3+1],r[i*3+2]])}return e}selectNodes(e){if(!this._nodeState)return;let t=this._nodeState.selected,r=[];for(let n=0;n<t.length;n++)t[n]>0&&r.push(n);t.fill(0);for(let n of e){let i=this._index.getNodeIndex(n);i!==void 0&&t[i]===0&&(t[i]=1,r.push(i))}this._updateStrategy.markDirty("nodeSelection"),this._bumpVersion(O.Selection),this._notifySelectionChanged(r)}subscribeSelectionChanged(e){return this._selectionChangedSubs.add(e),()=>{this._selectionChangedSubs.delete(e)}}_notifySelectionChanged(e){this._onSelectionChanged?.(e);for(let t of this._selectionChangedSubs)try{t(e)}catch(r){console.error("[GraphStore] selection sub threw:",r)}}toggleNodeSelection(e){if(!this._nodeState)return;let t=this._index.getNodeIndex(e);t!==void 0&&(this._nodeState.selected[t]=this._nodeState.selected[t]>0?0:1,this._updateStrategy.markDirty("nodeSelection"),this._bumpVersion(O.Selection),this._notifySelectionChanged([t]))}addToSelection(e){if(!this._nodeState)return;let t=[];for(let r of e){let n=this._index.getNodeIndex(r);n!==void 0&&this._nodeState.selected[n]===0&&(this._nodeState.selected[n]=1,t.push(n))}this._updateStrategy.markDirty("nodeSelection"),this._bumpVersion(O.Selection),this._notifySelectionChanged(t)}removeFromSelection(e){if(!this._nodeState)return;let t=[];for(let r of e){let n=this._index.getNodeIndex(r);n!==void 0&&this._nodeState.selected[n]>0&&(this._nodeState.selected[n]=0,t.push(n))}this._updateStrategy.markDirty("nodeSelection"),this._bumpVersion(O.Selection),this._notifySelectionChanged(t)}clearSelection(){let e=[];if(this._nodeState){let t=this._nodeState.selected;for(let r=0;r<t.length;r++)t[r]>0&&e.push(r);t.fill(0),this._updateStrategy.markDirty("nodeSelection")}this._edgeState&&(this._edgeState.selected.fill(0),this._updateStrategy.markDirty("edgeSelection")),this._bumpVersion(O.Selection),this._notifySelectionChanged(e)}getSelectedNodeIds(){if(!this._nodeState)return[];let e=[];for(let t=0;t<this._nodeState.selected.length;t++)if(this._nodeState.selected[t]>0){let r=this._index.getNodeId(t);r&&e.push(r)}return e}selectEdges(e){if(this._edgeState){this._edgeState.selected.fill(0);for(let t of e){let r=this._index.getEdgeIndex(t);r!==void 0&&(this._edgeState.selected[r]=1)}this._updateStrategy.markDirty("edgeSelection"),this._bumpVersion(O.Selection),this._notifySelectionChanged([])}}getSelectedEdgeIds(){if(!this._edgeState)return[];let e=[];for(let t=0;t<this._edgeState.selected.length;t++)if(this._edgeState.selected[t]>0){let r=this._index.getEdgeId(t);r&&e.push(r)}return e}highlightNodes(e){if(this._nodeState){this._nodeState.highlighted.fill(0);for(let t of e){let r=this._index.getNodeIndex(t);r!==void 0&&(this._nodeState.highlighted[r]=1)}this._updateStrategy.markDirty("nodeHighlight"),this._bumpVersion(O.Selection)}}clearHighlight(){this._nodeState&&(this._nodeState.highlighted.fill(0),this._updateStrategy.markDirty("nodeHighlight"),this._bumpVersion(O.Selection))}getAllHighlightedIds(){let e=this._nodeState;if(!e)return[];let t=[];for(let r=0;r<this._data.nodes.length;r++)if(e.highlighted[r]===1){let n=this._index.getNodeId(r);n&&t.push(n)}return t}setHoveredNode(e){if(this._nodeState){if(this._nodeState.hovered.fill(0),e){let t=this._index.getNodeIndex(e);t!==void 0&&(this._nodeState.hovered[t]=1)}this._updateStrategy.markDirty("nodeHover"),this._bumpVersion(O.Hover)}}pinNodes(e){if(this._nodeState&&e.length!==0){for(let t of e){let r=this._index.getNodeIndex(t);r!==void 0&&(this._nodeState.pinned[r]=1)}this._updateStrategy.markDirty("nodePinned"),this._bumpVersion(O.Pin),this._layoutRuntime&&this._layoutRuntime.pinNodes(e)}}unpinNodes(e){if(this._nodeState&&e.length!==0){for(let t of e){let r=this._index.getNodeIndex(t);r!==void 0&&(this._nodeState.pinned[r]=0)}this._updateStrategy.markDirty("nodePinned"),this._bumpVersion(O.Pin),this._layoutRuntime&&this._layoutRuntime.unpinNodes(e)}}updateLayoutSettings(e){this._layoutRuntime?.updateSettings?.(e)}isPinned(e){if(!this._nodeState)return!1;let t=typeof e=="number"?e:this._index.getNodeIndex(e);return t===void 0||t<0||t>=this._nodeState.pinned.length?!1:this._nodeState.pinned[t]>0}getPinnedNodeIds(){if(!this._nodeState)return[];let e=[],t=this._nodeState.pinned;for(let r=0;r<t.length;r++)if(t[r]>0){let n=this._index.getNodeId(r);n&&e.push(n)}return e}setNodeFillSuppressed(e,t){let r=this.nodeState;if(!r)return;let n=t?1:0,i=!1;for(let o of e){let s=this.index.getNodeIndex(o);s!==void 0&&s>=0&&s<r.suppressFill.length&&r.suppressFill[s]!==n&&(r.suppressFill[s]=n,i=!0)}i&&(this.updateStrategy.markDirty("nodeSuppressFill"),this._bumpVersion(O.Style))}setNodeLabelExtents(e,t){let r=this._labelExtentOwners.get(e),n=t&&t.size>0?t:null;!r&&!n||r&&n&&kg(r,n)||(n?this._labelExtentOwners.set(e,new Map(n)):this._labelExtentOwners.delete(e),this._labelExtentMerged=null,this.markNodeLabelsDirty())}getNodeLabelExtent(e){if(this._labelExtentOwners.size!==0){if(!this._labelExtentMerged){let t=new Map;for(let r of this._labelExtentOwners.values())for(let[n,i]of r){let o=t.get(n)??{nx:0,ny:0,wx:0,wy:0};i.unit==="world"?(o.wx=Math.max(o.wx,i.x),o.wy=Math.max(o.wy,i.y)):(o.nx=Math.max(o.nx,i.x),o.ny=Math.max(o.ny,i.y)),t.set(n,o)}this._labelExtentMerged=t}return this._labelExtentMerged.get(e)}}_claimOverride(e,t){let r=this._nodeState.overrides,n=r[e]|0;return this._mapperDepth>0?(n&t)===0:(r[e]=n|t,!0)}runAsMapper(e){this._mapperDepth++;try{return e()}finally{this._mapperDepth--}}getNodeOverrides(e){let t=this._index.getNodeIndex(e);return t===void 0||!this._nodeState?0:this._nodeState.overrides[t]|0}setNodeOverrides(e,t){let r=this._index.getNodeIndex(e);r===void 0||!this._nodeState||(this._nodeState.overrides[r]=t&hs)}clearNodeOverrides(e,t){let r=this._nodeState;if(!r)return;let n=t?t.reduce((o,s)=>o|Wt[s],0):hs,i=[];for(let o of Array.isArray(e)?e:[e]){let s=this._index.getNodeIndex(o);s!==void 0&&(r.overrides[s]=(r.overrides[s]|0)&~n,i.push(this._data.nodes[s]))}i.length&&this._visualMapper.apply({nodes:i})}setNodeShape(e,t,r){let n=this._nodeState;if(!n)return;let i=Ki(t);if(i<0)throw new Error(`setNodeShape: unknown shape "${String(t)}"`);if(r!==void 0&&!(r>0&&Number.isFinite(r)))throw new Error(`setNodeShape: aspect must be a positive number, got ${r}`);let o=!1;for(let s of Array.isArray(e)?e:[e]){let d=this._index.getNodeIndex(s);d!==void 0&&this._claimOverride(d,Wt.shape)&&(n.shapeIds[d]!==i||r!==void 0&&n.aspects[d]!==r)&&(n.shapeIds[d]=i,r!==void 0&&(n.aspects[d]=r),this._updateStrategy.markDirty("nodeShapes",d),o=!0)}o&&this._bumpVersion(O.Style)}getHiddenNodeIds(){if(!this._nodeState)return[];let e=[],t=this._nodeState.hidden;for(let r=0;r<t.length;r++)if(t[r]===1){let n=this._index.getNodeId(r);n&&e.push(n)}return e}listPinned(){return this.getPinnedNodeIds()}hasCollectData(){return!!this._collect&&this._collect.size>0}getNodeCollect(e){return!!this._collect?.has(e)}setNodeCollect(e,t){if(this._index.getNodeIndex(e)===void 0){console.warn(`[render-engine] setNodeCollect: unknown nodeId ${e}`);return}if(!!this._collect?.has(e)!==t){if(t?(this._collect||(this._collect=new Set),this._collect.add(e)):this._collect?.delete(e),this._nodeState){let n=this._index.getNodeIndex(e);this._nodeState.collection[n]=t?1:0}this._updateStrategy.markDirty("collect"),this._bumpVersion(O.Decorations)}}replaceNodeProperties(e,t){let r=this._nodeById(e);if(!r)return;let n=new Set([...Object.keys(r.properties??{}),...Object.keys(t)]);r.properties={...t},this.changes.recordData("node",e,this._index.getNodeIndex(e),n),this.markNodeLabelsDirty(),this._bumpVersion(O.Data|O.Labels)}setNodeColor(e,t){if(!this._nodeState)return;let r=this._index.getNodeIndex(e);if(r===void 0||!this._claimOverride(r,Wt.color))return;let n=this.parseColor(t),i=r*3;this._nodeState.colors[i]=n[0],this._nodeState.colors[i+1]=n[1],this._nodeState.colors[i+2]=n[2],this._updateStrategy.markDirty("nodeColors",r),this._bumpVersion(O.Style)}setNodeColorAtSlots(e,t){let r=this._nodeState;if(!r||e.length===0)return;let[n,i,o]=this.parseColor(t),s=this._data.nodes.length;for(let d=0;d<e.length;d++){let l=e[d];l<0||l>=s||!this._claimOverride(l,Wt.color)||(r.colors[l*3]=n,r.colors[l*3+1]=i,r.colors[l*3+2]=o)}this._updateStrategy.markDirty("nodeColors"),this._bumpVersion(O.Style)}restoreNodeColorsAtSlots(e,t,r){let n=this._nodeState;if(!n||e.length===0)return;let i=this._data.nodes.length;for(let o=0;o<e.length;o++){let s=e[o];s<0||s>=i||(n.colors[s*3]=t[o*3],n.colors[s*3+1]=t[o*3+1],n.colors[s*3+2]=t[o*3+2],n.overrides[s]=r[o]&hs)}this._updateStrategy.markDirty("nodeColors"),this._bumpVersion(O.Style)}updateNodeColors(e){if(this._nodeState){for(let{id:t,color:r}of e){let n=this._index.getNodeIndex(t);if(n!==void 0&&this._claimOverride(n,Wt.color)){let i=this.parseColor(r),o=n*3;this._nodeState.colors[o]=i[0],this._nodeState.colors[o+1]=i[1],this._nodeState.colors[o+2]=i[2]}}this._updateStrategy.markDirty("nodeColors"),this._bumpVersion(O.Style)}}setEdgeColor(e,t){if(!this._edgeState)return;let r=this._index.getEdgeIndex(e);if(r===void 0)return;let n=this.parseColor(t),i=r*3;this._edgeState.colors[i]=n[0],this._edgeState.colors[i+1]=n[1],this._edgeState.colors[i+2]=n[2],this._updateStrategy.markDirty("edgeColors"),this._bumpVersion(O.Style)}setNodeSize(e,t){if(!this._nodeState)return;let r=this._index.getNodeIndex(e);r!==void 0&&this._claimOverride(r,Wt.size)&&(this._nodeState.sizes[r]=t,this._updateStrategy.markDirty("nodeSizes",r),this._bumpVersion(O.Style))}updateNodeSizes(e){if(this._nodeState){for(let{id:t,size:r}of e){let n=this._index.getNodeIndex(t);n!==void 0&&this._claimOverride(n,Wt.size)&&(this._nodeState.sizes[n]=r)}this._updateStrategy.markDirty("nodeSizes"),this._bumpVersion(O.Style)}}setGlobalNodeSizeScale(e){this._globalNodeSizeScale=e,this.refreshEffectiveSizes()}get globalNodeSizeScale(){return this._globalNodeSizeScale}refreshEffectiveSizeAt(e){let t=this._nodeState;!t||e<0||e>=this._data.nodes.length||(t.effectiveSizes[e]=t.sizes[e]*this._globalNodeSizeScale*$u)}refreshEffectiveSizes(){if(!this._nodeState)return;let e=this._nodeState.sizes,t=this._nodeState.effectiveSizes,r=this._globalNodeSizeScale,n=this._data.nodes.length,i=!1;for(let o=0;o<n;o++){let s=Math.fround(e[o]*r*$u);t[o]!==s&&(t[o]=s,i=!0)}i&&(this._updateStrategy.markDirty("nodeSizes"),this._bumpVersion(O.Style))}setNodeIcon(e,t){if(!this._nodeState)return;let r=this._index.getNodeIndex(e);r!==void 0&&this._claimOverride(r,Wt.icon)&&(typeof t=="string"&&t?this._iconNames.set(e,t):typeof t=="number"?(this._nodeState.icons[r]=t,this._iconNames.delete(e)):(this._iconNames.delete(e),this._nodeState.icons[r]=-1),this._updateStrategy.markDirty("nodeIcons",r),this._bumpIconVersion(),this._bumpVersion(O.Icons))}getNodeIconName(e){return this._iconNames.get(e)}get iconNames(){return this._iconNames}setEdgeWidth(e,t){if(!this._edgeState)return;let r=this._index.getEdgeIndex(e);r!==void 0&&(this._edgeState.widths[r]=t,this._updateStrategy.markDirty("edgeWidths"),this._bumpVersion(O.Style))}setEdgeShape(e,t){if(!this._edgeState)return;let r=this._index.getEdgeIndex(e);r!==void 0&&(this._edgeState.shapes[r]=this.registry.resolveEdgeShapeId(t),this._updateStrategy.markDirty("edgeShapes"),this._bumpVersion(O.Style))}setEdgeBend(e,t){if(!this._edgeState)return;let r=this._index.getEdgeIndex(e);r!==void 0&&(this._edgeState.bends[r]=t,this._updateStrategy.markDirty("edgeShapes"),this._bumpVersion(O.Style))}setEdgeAnchor(e,t){this._index.getEdgeIndex(e)!==void 0&&(t===null?this._edgeAnchors.delete(e):this._edgeAnchors.set(e,t),this._updateStrategy.markDirty("edgeShapes"),this._bumpVersion(O.Style))}edgeAnchor(e){return this._edgeAnchors.get(e)}get hasEdgeAnchors(){return this._edgeAnchors.size>0}setEdgeRouteEncoded(e,t){if(this._index.getEdgeIndex(e)!==void 0){if(t===null){if(!this._edgeRoutes.delete(e))return}else this._edgeRoutes.set(e,t);this._edgeRouteVersion++,this._updateStrategy.markDirty("edgeShapes"),this._bumpVersion(O.Style)}}edgeRoute(e){return this._edgeRoutes.get(e)}get edgeRoutes(){return this._edgeRoutes}get edgeRouteVersion(){return this._edgeRouteVersion}setEdgeDashed(e,t){if(!this._edgeState)return;let r=this._index.getEdgeIndex(e);r!==void 0&&(this._edgeState.dashed[r]=t?1:0,this._updateStrategy.markDirty("edgeDashed"),this._bumpVersion(O.Style))}setNodeImage(e,t){if(!this._nodeState)return;let r=this._index.getNodeIndex(e);r!==void 0&&(this._nodeState.imageIndices[r]=t,this._updateStrategy.markDirty("nodeImages"),this._bumpVersion(O.Icons))}setNodeImageUrl(e,t){t?this._imageUrls.set(e,t):this._imageUrls.delete(e),this._updateStrategy.markDirty("nodeImages"),this._bumpVersion(O.Icons)}getNodeImageUrl(e){return this._imageUrls.get(e)}get imageUrls(){return this._imageUrls}hasGroupData(){return this._groups!==null&&this._groups.size>0}getGroupForNode(e){let t=this._nodeToGroup?.get(e);return t?this._groups?.get(t):void 0}getGroupMembers(e){let t=this._groups?.get(e);return t?Array.from(t.memberNodeIds):[]}listGroups(){return this._groups?Array.from(this._groups.values()):[]}get groups(){return this._groups}getGroupById(e){return this._groups?.get(e)}getAggregatedEdges(){return this._aggregatedEdges??[]}getGroupManager(){return this._groupManager||(this._groupManager=new ds(this)),this._groupManager}getCollectionManager(){return this._collectionManager||(this._collectionManager=new ls(this,this.getGroupManager())),this._collectionManager}hasAlgorithmProperty(e){return this._algorithmPropertyKeys.has(e)}addAlgorithmProperty(e){this._algorithmPropertyKeys.add(e)}removeAlgorithmProperty(e){this._algorithmPropertyKeys.delete(e)}hasBadgeData(){return!!this._badges&&this._badges.size>0}getNodeBadge(e){return this._badges?.get(e)??null}setNodeBadge(e,t){if(this._index.getNodeIndex(e)===void 0){console.warn(`[render-engine] setNodeBadge: unknown nodeId ${e}`);return}if(t===null)this._badges?.delete(e);else{let r=t;r.text&&r.text.length>as&&(console.warn(`[render-engine] setNodeBadge: text length ${r.text.length} > ${as}; truncating`),r={...r,text:r.text.slice(0,as)}),this._badges||(this._badges=new Map),this._badges.set(e,r)}this._updateStrategy.markDirty("badges"),this._bumpVersion(O.Decorations)}clearAllBadges(){this._badges&&this._badges.clear(),this._updateStrategy.markDirty("badges"),this._bumpVersion(O.Decorations)}listBadges(){return this._badges?Array.from(this._badges,([e,t])=>({nodeId:e,spec:t})):[]}hasTagData(){return!!this._tagSpecs&&this._tagSpecs.size>0}createTag(e){this._tagSpecs||(this._tagSpecs=new Map),this._tagToNodes||(this._tagToNodes=new Map);let t=this._generateTagId();return this._tagSpecs.set(t,e),this._tagToNodes.set(t,new Set),this._updateStrategy.markDirty("tags"),this._bumpVersion(O.Decorations),t}getTagSpec(e){return this._tagSpecs?.get(e)??null}getTagNodeIds(e){let t=this._tagToNodes?.get(e);return t?Array.from(t):[]}updateTag(e,t){let r=this._tagSpecs?.get(e);if(!r){console.warn(`[render-engine] updateTag: unknown tagId ${e}`);return}this._tagSpecs.set(e,{...r,...t}),this._updateStrategy.markDirty("tags"),this._bumpVersion(O.Decorations)}deleteTag(e){if(!this._tagSpecs?.has(e))return;let t=this._tagToNodes.get(e);for(let r of t)this._nodeToTag?.delete(r);this._tagSpecs.delete(e),this._tagToNodes.delete(e),this._updateStrategy.markDirty("tags"),this._bumpVersion(O.Decorations)}assignTag(e,t){if(!this._tagSpecs?.has(e)){console.warn(`[render-engine] assignTag: unknown tagId ${e}`);return}this._nodeToTag||(this._nodeToTag=new Map);let r=this._tagToNodes.get(e),n=!1;for(let i of t){if(this._index.getNodeIndex(i)===void 0){console.warn(`[render-engine] assignTag: unknown nodeId ${i}`);continue}let o=this._nodeToTag.get(i);o!==e&&(o!==void 0&&this._tagToNodes.get(o)?.delete(i),this._nodeToTag.set(i,e),r.add(i),n=!0)}n&&(this._updateStrategy.markDirty("tags"),this._bumpVersion(O.Decorations))}unassignTag(e,t){let r=this._tagToNodes?.get(e);if(!r)return;let n=!1;for(let i of t)this._nodeToTag?.get(i)===e&&(this._nodeToTag.delete(i),r.delete(i),n=!0);n&&(this._updateStrategy.markDirty("tags"),this._bumpVersion(O.Decorations))}getNodeTag(e){let t=this._nodeToTag?.get(e);if(!t)return null;let r=this._tagSpecs?.get(t);return r?{id:t,spec:r}:null}clearAllTags(){this._tagSpecs?.clear(),this._nodeToTag?.clear(),this._tagToNodes?.clear(),this._updateStrategy.markDirty("tags"),this._bumpVersion(O.Decorations)}listTags(){if(!this._tagSpecs)return[];let e=[];for(let[t,r]of this._tagSpecs)e.push({id:t,spec:r,nodeIds:Array.from(this._tagToNodes?.get(t)??[])});return e}_restoreTag(e,t,r){this._tagSpecs||(this._tagSpecs=new Map),this._tagToNodes||(this._tagToNodes=new Map),this._nodeToTag||(this._nodeToTag=new Map),this._tagSpecs.set(e,t),this._tagToNodes.set(e,new Set),this._updateStrategy.markDirty("tags"),this._bumpVersion(O.Decorations),r.length>0&&this.assignTag(e,r)}_snapshotDecorationsForUndo(){return{badges:new Map(this._badges??[]),tagSpecs:new Map(this._tagSpecs??[]),nodeToTag:new Map(this._nodeToTag??[]),tagToNodes:new Map(Array.from(this._tagToNodes??new Map,([e,t])=>[e,new Set(t)])),collect:new Set(this._collect??[]),groups:this._groupManager?.snapshotGroupState().groups??new Map,nodeToGroup:new Map(this._nodeToGroup??[])}}_restoreDecorationsFromSnapshot(e){if(this._badges=new Map(e.badges),this._tagSpecs=new Map(e.tagSpecs),this._nodeToTag=new Map(e.nodeToTag),this._tagToNodes=new Map(Array.from(e.tagToNodes,([t,r])=>[t,new Set(r)])),this._collect=new Set(e.collect),this._nodeState){this._nodeState.collection.fill(0);for(let t of this._collect){let r=this._index.getNodeIndex(t);r!==void 0&&(this._nodeState.collection[r]=1)}this._updateStrategy.markDirty("nodeCollection")}this._updateStrategy.markDirty("badges"),this._updateStrategy.markDirty("tags"),this._updateStrategy.markDirty("collect"),e.groups.size>0?(this._groups=new Map(Array.from(e.groups.entries()).map(([t,r])=>[t,{...r,memberNodeIds:new Set(r.memberNodeIds)}])),this._nodeToGroup=new Map(e.nodeToGroup),this._updateStrategy.markDirty("groups")):(this._groups=null,this._nodeToGroup=null),this._bumpVersion(O.Decorations)}_generateTagId(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`tag-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}setVisibleNodes(e){e===null?this._visibilityFilter=null:this._visibilityFilter=new Set(e.map(t=>this._index.getNodeIndex(t)).filter(t=>t!==void 0)),this._bumpVersion(O.Visibility)}isNodeVisible(e){if(this._visibilityFilter===null)return!0;let t=this._index.getNodeIndex(e);return t!==void 0&&this._visibilityFilter.has(t)}get visibleNodeCount(){return this._visibilityFilter?.size??this._data.nodes.length}getNodes(){return this._data.nodes}getEdges(){return this._data.edges}getDegree(e){return this._queries.getDegree(e)}isNodeHidden(e){if(!this._nodeState)return!1;let t=this._index.getNodeIndex(e);return t===void 0?!1:this._nodeState.hidden[t]===1}getIncidentEdgeIds(e){return this._queries.getConnectedEdges(e)}getDownstreamNeighborIds(e){let t=new Set(e);for(let r of e)for(let n of this._queries.getNeighbors(r))n.direction==="out"&&t.add(n.nodeId);return Array.from(t)}getUpstreamNeighborIds(e){let t=new Set(e);for(let r of e)for(let n of this._queries.getNeighbors(r))n.direction==="in"&&t.add(n.nodeId);return Array.from(t)}getNodesOnShortestPaths(e){let t=new Set(e),r=new Map,n=(o,s)=>{let d=r.get(o);d||(d=[],r.set(o,d)),d.push(s)};for(let o of this._data.edges)n(o.source,o.target),n(o.target,o.source);let i=(o,s)=>{if(o===s)return[o];let d=new Map,l=[o];for(d.set(o,o);l.length>0;){let u=l.shift();for(let c of r.get(u)??[])if(!d.has(c)){if(d.set(c,u),c===s){let h=[],p=c;for(;p!==o;)h.push(p),p=d.get(p);return h.push(o),h}l.push(c)}}return null};for(let o=0;o<e.length;o++)for(let s=o+1;s<e.length;s++){let d=i(e[o],e[s]);d&&d.forEach(l=>t.add(l))}return Array.from(t)}_rebuildNodeStateFromSurvivors(e){let t=this._nodeState;if(!t){this.initRenderState();return}let r=e.length,n=Math.ceil(r*1.5)||1;this._nodeState=Jl(t,gr,e,r,n),this._nodeCapacity=n}_rebuildEdgeState(e,t){let r=this._edgeState,n=e.length,i=Math.ceil(n*1.5)||1;if(!r){let d=Xi(kt,i);vn(d,kt,0,n),this._edgeState=d,this._edgeCapacity=i;return}let o=new Map;for(let d=0;d<t.length;d++)o.set(t[d].id,d);let s=e.map(d=>o.get(d.id));this._edgeState=Jl(r,kt,s,n,i),this._edgeCapacity=i}initRenderState(e=Math.ceil(this._data.nodes.length*1.5)||1){let t=this._data.nodes.length,r=this._data.edges.length,n=Math.ceil(r*1.5)||1;this._nodeCapacity=e,this._edgeCapacity=n;let i=this._nodeState===null&&this._edgeState===null,o=Xi(gr,e);vn(o,gr,0,t,{sizes:this._defaultNodeSize}),this._nodeState=o;let s=Xi(kt,n);vn(s,kt,0,r),this._edgeState=s,i&&this._eventBus?.emit("graph:renderStateAllocated",{nodeCount:t,edgeCount:r})}initEdgeRenderState(){let e=this._data.edges.length,t=Math.ceil(e*1.5)||1;this._edgeCapacity=t;let r=Xi(kt,t);vn(r,kt,0,e),this._edgeState=r}shrinkNodeBuffers(e){if(!this._nodeState)return;let t=Math.ceil(e*1.5)||1;this._nodeState=gs(this._nodeState,gr,t),this._nodeCapacity=t}initNewNodesRenderState(e,t){this._nodeState&&vn(this._nodeState,gr,e,t,{sizes:this._defaultNodeSize})}initNewEdgesRenderState(e,t){this._edgeState&&vn(this._edgeState,kt,e,t)}ensureNodeCapacity(e){if(!this._nodeState||e<=this._nodeCapacity)return;let t=Math.max(e*2,this._nodeCapacity*2);this._nodeCapacity=t,this._nodeState=ec(this._nodeState,gr,t,{sizes:this._defaultNodeSize}),this.changes.recordCapacityChange("node")}ensureEdgeCapacity(e){if(!this._edgeState||e<=this._edgeCapacity)return;let t=Math.max(e*2,this._edgeCapacity*2);this._edgeCapacity=t,this._edgeState=ec(this._edgeState,kt,t),this.changes.recordCapacityChange("edge")}parseColor(e){if(Array.isArray(e))return e;let t=e.replace("#",""),r=parseInt(t.substring(0,2),16)/255,n=parseInt(t.substring(2,4),16)/255,i=parseInt(t.substring(4,6),16)/255;return[r,n,i]}};var $r=class{constructor(){this.edgeGroups=new Map;this.edgeInfoCache=new Map;this.selfLoops=[];this.normalCount=0;this.baseCurvature=.15;this.slotOffset=null;this.pendingEdges=null;this.lastPlaneRotation=0}classify(e){this.slotOffset=null,this.pendingEdges=null,this.edgeGroups.clear(),this.edgeInfoCache.clear(),this.selfLoops=[],this.normalCount=0;for(let t of e){if(t.sourceId===t.targetId){this.selfLoops.push(t),this.edgeInfoCache.set(t.id,{type:"selfloop",index:this.selfLoops.length-1,total:1,isReverse:!1});continue}this.normalCount++;let r=this.getPairKey(t.sourceId,t.targetId),n=this.edgeGroups.get(r);n?n.push(t):this.edgeGroups.set(r,[t]),this.edgeInfoCache.set(t.id,{type:"single",index:0,total:1,isReverse:t.sourceId>t.targetId,key:r})}for(let t of this.edgeGroups.values()){let r=t.length;if(r!==1)for(let n=0;n<r;n++){let i=this.edgeInfoCache.get(t[n].id);i.type="multi",i.index=n,i.total=r}}}classifySlots(e,t,r,n){let i=e.length;for(let f=0;f<i;f++){let m=e[f];if(n[t[f]]!==m.source||n[r[f]]!==m.target){this.classify(e.map(g=>({id:g.id,sourceId:g.source,targetId:g.target})));return}}this.edgeGroups.clear(),this.edgeInfoCache.clear(),this.selfLoops=[],this.normalCount=0;let o=n.length,s=new Float32Array(i),d=new Int32Array(o+1);for(let f=0;f<i;f++){let m=t[f],g=r[f];if(m===g){let y=e[f];this.selfLoops.push({id:y.id,sourceId:y.source,targetId:y.target});continue}this.normalCount++,d[(m<g?m:g)+1]++}for(let f=0;f<o;f++)d[f+1]+=d[f];let l=new Int32Array(this.normalCount),u=d.slice(0,o);for(let f=0;f<i;f++){let m=t[f],g=r[f];m!==g&&(l[u[m<g?m:g]++]=f)}let c=new Int32Array(o).fill(-1),h=new Int32Array(o),p=new Int32Array(o);for(let f=0;f<o;f++){let m=d[f],g=d[f+1];if(g-m<2)continue;let y=!1;for(let v=m;v<g;v++){let b=l[v],x=t[b]===f?r[b]:t[b];c[x]!==f?(c[x]=f,h[x]=1,p[x]=0):(h[x]++,y=!0)}if(y)for(let v=m;v<g;v++){let b=l[v],x=t[b]===f?r[b]:t[b],w=h[x];if(w<2)continue;let T=p[x]++-(w-1)/2,I=e[b];s[b]=I.source>I.target?-T:T}}this.slotOffset=s,this.pendingEdges=e.slice()}readCurveAt(e,t,r=!1){let n=this.slotOffset;return n===null||e>=n.length?this.readCurve(t,r):(this.lastPlaneRotation=0,n[e]*this.baseCurvature)}materialize(){let e=this.pendingEdges;e!==null&&this.classify(e.map(t=>({id:t.id,sourceId:t.source,targetId:t.target})))}applyChanges(e,t,r,n){this.materialize();let i=new Set,o=new Set;for(let d of e){let l=this.edgeInfoCache.get(d);if(!l)continue;if(this.edgeInfoCache.delete(d),l.type==="selfloop"){let h=this.selfLoops.findIndex(p=>p.id===d);h>=0&&this.selfLoops.splice(h,1);continue}let u=l.key;if(this.normalCount--,u===void 0)continue;let c=this.edgeGroups.get(u);if(c){let h=c.findIndex(p=>p.id===d);h>=0&&c.splice(h,1),c.length===0&&this.edgeGroups.delete(u)}i.add(u)}for(let d of t){if(o.add(d.id),d.sourceId===d.targetId){this.selfLoops.push(d),this.edgeInfoCache.set(d.id,{type:"selfloop",index:this.selfLoops.length-1,total:1,isReverse:!1});continue}let l=this.getPairKey(d.sourceId,d.targetId),u=this.edgeGroups.get(l);u||this.edgeGroups.set(l,u=[]),u.push(d),this.edgeInfoCache.set(d.id,{type:"single",index:0,total:1,isReverse:d.sourceId>d.targetId,key:l}),this.normalCount++,i.add(l)}for(let d of r){o.add(d);let l=this.edgeInfoCache.get(d)?.key;l!==void 0&&i.add(l)}for(let d of i){let l=this.edgeGroups.get(d);if(!l)continue;l.sort((c,h)=>(n(c.id)??0)-(n(h.id)??0));let u=l.length;for(let c=0;c<u;c++){let h=l[c];this.edgeInfoCache.set(h.id,{type:u===1?"single":"multi",index:c,total:u,isReverse:h.sourceId>h.targetId,key:d}),o.add(h.id)}}let s=new Set(t.map(d=>d.id));for(let d of e)s.has(d)||o.delete(d);return o}getPairKey(e,t){return e<t?`${e}|${t}`:`${t}|${e}`}getEdgeInfo(e){return this.materialize(),this.edgeInfoCache.get(e)??null}computeCurvature(e){if(e.type==="single"||e.type==="selfloop"||e.total===1)return 0;let{index:t,total:r,isReverse:n}=e,i=(r-1)/2,s=(t-i)*this.baseCurvature;return n&&(s=-s),s}computePlaneRotation(e,t){return 0}readCurve(e,t=!1){this.materialize();let r=this.edgeInfoCache.get(e);return r?(this.lastPlaneRotation=this.computePlaneRotation(r,t),this.computeCurvature(r)):(this.lastPlaneRotation=0,0)}getCurveParams(e,t=!1){this.materialize();let r=this.edgeInfoCache.get(e);return r?{curvature:this.computeCurvature(r),planeRotation:this.computePlaneRotation(r,t)}:{curvature:0,planeRotation:0}}getSelfLoops(){return this.selfLoops}getNormalEdges(){this.materialize();let e=[];for(let t of this.edgeGroups.values())for(let r of t)e.push(r);return e}get selfLoopCount(){return this.selfLoops.length}get normalEdgeCount(){return this.normalCount}setBaseCurvature(e){this.baseCurvature=e}},tc=null;function Gg(){return tc||(tc=new $r),tc}import*as ze from"three";var Ji=class{constructor(e,t,r,n={}){this.geometry=null;this.material=null;this.mesh=null;this.positionProvider=null;this.cpuPositionTexture=null;this.scene=e,this.store=t,this.edgeClassifier=r,this.config={maxLoops:n.maxLoops??1e4,segments:n.segments??64,loopRadiusMult:n.loopRadiusMult??1,lineWidth:n.lineWidth??.5,centerOffsetMult:n.centerOffsetMult??1},this.resolution=new ze.Vector2(window.innerWidth||1,window.innerHeight||1)}init(){this.createGeometry(),this.createMaterial(),this.createMesh()}createGeometry(){this.geometry=new ze.InstancedBufferGeometry;let e=this.config.segments,t=[],r=[],n=[],i=[];for(let o=0;o<=e;o++){let s=o/e;t.push(0,0,0),r.push(s),n.push(-1),t.push(0,0,0),r.push(s),n.push(1)}for(let o=0;o<e;o++){let s=o*2;i.push(s,s+1,s+2),i.push(s+1,s+3,s+2)}this.geometry.setAttribute("position",new ze.Float32BufferAttribute(t,3)),this.geometry.setAttribute("loopProgress",new ze.Float32BufferAttribute(r,1)),this.geometry.setAttribute("side",new ze.Float32BufferAttribute(n,1)),this.geometry.setIndex(i),this.updateInstanceAttributes()}updateInstanceAttributes(){if(!this.geometry)return;let e=this.edgeClassifier.getSelfLoops(),t=e.length;if(t===0){let f=this.geometry;f.instanceCount=0,delete f._maxInstanceCount;return}let r=this.store.index,n=this.store.edgeState,i=new Float32Array(t),o=new Float32Array(t),s=new Float32Array(t*3),d=new Float32Array(t),l=new Float32Array(t),u=new Float32Array(t),c=this.store.nodeState;for(let f=0;f<t;f++){let m=e[f],g=r.nodeIdToIndex.get(m.sourceId)??0;i[f]=g,o[f]=c?.effectiveSizes[g]??10;let y=r.edgeIdToIndex.get(m.id);n&&y!==void 0?(s[f*3]=n.colors[y*3],s[f*3+1]=n.colors[y*3+1],s[f*3+2]=n.colors[y*3+2],d[f]=n.opacities[y],l[f]=n.widths?n.widths[y]:this.config.lineWidth,u[f]=n.selected[y]):(s[f*3]=.5,s[f*3+1]=.5,s[f*3+2]=.5,d[f]=.8,l[f]=this.config.lineWidth,u[f]=0)}let h=(f,m,g)=>{let y=this.geometry.getAttribute(f);y&&y.array.length===m.length?(y.set(m),y.needsUpdate=!0):this.geometry.setAttribute(f,new ze.InstancedBufferAttribute(m,g))};h("nodeIndex",i,1),h("nodeSize",o,1),h("loopColor",s,3),h("loopOpacity",d,1),h("loopWidth",l,1),h("loopSelected",u,1);let p=this.geometry;p.instanceCount=t,delete p._maxInstanceCount}createMaterial(){this.material=new ze.ShaderMaterial({vertexShader:yl,fragmentShader:Du,uniforms:{positionTexture:{value:null},textureSize:{value:512},spaceSize:{value:1},loopRadiusMult:{value:this.config.loopRadiusMult},centerOffsetMult:{value:this.config.centerOffsetMult},resolution:{value:this.resolution},lineWidthScale:{value:this.config.lineWidth*.008},nodeSizeScale:{value:1}},transparent:!0,depthWrite:!1,depthTest:!0,side:ze.DoubleSide})}createMesh(){!this.geometry||!this.material||(this.mesh=new ze.Mesh(this.geometry,this.material),this.mesh.frustumCulled=!1,this.mesh.name="SelfLoopCloud",this.scene.add(this.mesh))}update(){this.updateInstanceAttributes(),this.updatePositionUniforms()}setPositionProvider(e){this.positionProvider=e,this.updatePositionUniforms()}setSharedPositionTexture(e,t,r){this.material&&(this.material.uniforms.positionTexture.value=e,this.material.uniforms.textureSize.value=t,this.material.uniforms.spaceSize.value=r)}updatePositionUniforms(){let e=this.positionProvider;if(!e||!this.material)return;let t=null,r=512,n=1;if(e.mode==="gpu")t=e.getPositionTexture(),r=e.getTextureSize(),n=e.getSpaceSize();else{let i=e.getPositions();if(!i)return;let o=i.length/3;if(r=Math.max(2,Math.pow(2,Math.ceil(Math.log2(Math.sqrt(o))))),!this.cpuPositionTexture||this.cpuPositionTexture.image.width!==r){this.cpuPositionTexture&&this.cpuPositionTexture.dispose();let d=new Float32Array(r*r*4);this.cpuPositionTexture=new ze.DataTexture(d,r,r,ze.RGBAFormat,ze.FloatType),this.cpuPositionTexture.minFilter=ze.NearestFilter,this.cpuPositionTexture.magFilter=ze.NearestFilter}let s=this.cpuPositionTexture.image.data;for(let d=0;d<o;d++)s[d*4]=i[d*3],s[d*4+1]=i[d*3+1],s[d*4+2]=i[d*3+2],s[d*4+3]=1;this.cpuPositionTexture.needsUpdate=!0,t=this.cpuPositionTexture,n=e.getSpaceSize()}t&&(this.material.uniforms.positionTexture.value=t,this.material.uniforms.textureSize.value=r,this.material.uniforms.spaceSize.value=n)}setLineWidth(e){this.material&&(this.material.uniforms.lineWidthScale.value=e*.008)}setNodeSizeScale(e){this.store.setGlobalNodeSizeScale(e)}setResolution(e,t){this.resolution.set(e,t),this.material&&(this.material.uniforms.resolution.value=this.resolution)}getMesh(){return this.mesh}getSelfLoopCount(){return this.edgeClassifier.selfLoopCount}createPickingMesh(e){if(!this.geometry||this.edgeClassifier.selfLoopCount===0)return null;let t=this.edgeClassifier.getSelfLoops(),r=t.length,n=this.store.index,i=new Float32Array(r*3);for(let c=0;c<r;c++){let h=n.edgeIdToIndex.get(t[c].id)??0,[p,f,m]=e(h);i[c*3]=p,i[c*3+1]=f,i[c*3+2]=m}let o=this.geometry.clone();o.setAttribute("idColor",new ze.InstancedBufferAttribute(i,3));let s=yl.replace("attribute vec3 loopColor;",`attribute vec3 loopColor;
2
+ attribute vec3 idColor;`).replace("vColor = loopColor;","vColor = idColor;").replace("vOpacity = loopOpacity;","vOpacity = 1.0;"),d=`
3
+ precision highp float;
4
+ varying vec3 vColor;
5
+ varying float vOpacity;
6
+ void main() {
7
+ gl_FragColor = vec4(vColor, vOpacity);
8
+ if (gl_FragColor.a < 0.1) discard;
9
+ }
10
+ `,l=new ze.ShaderMaterial({vertexShader:s,fragmentShader:d,uniforms:{positionTexture:this.material.uniforms.positionTexture,textureSize:this.material.uniforms.textureSize,spaceSize:this.material.uniforms.spaceSize,loopRadiusMult:this.material.uniforms.loopRadiusMult,centerOffsetMult:this.material.uniforms.centerOffsetMult,resolution:this.material.uniforms.resolution,lineWidthScale:{value:this.material.uniforms.lineWidthScale.value*3},nodeSizeScale:this.material.uniforms.nodeSizeScale},transparent:!0,depthWrite:!1,depthTest:!1,side:ze.DoubleSide}),u=new ze.Mesh(o,l);return u.frustumCulled=!1,u}dispose(){this.mesh&&(this.scene.remove(this.mesh),this.mesh=null),this.geometry&&(this.geometry.dispose(),this.geometry=null),this.material&&(this.material.dispose(),this.material=null),this.cpuPositionTexture&&(this.cpuPositionTexture.dispose(),this.cpuPositionTexture=null)}};import*as De from"three";function Hg(a){return a<=0?0:a>=1?1:a<.5?4*a*a*a:1-Math.pow(-2*a+2,3)/2}function Fg(a){return a<=0?0:a>=1?1:a<.5?Math.cbrt(a/4):1-Math.cbrt((1-a)/4)}var Jn=524288,zg=Jn-1;function kr(a,e,t,r,n){let i;if(e<1)i=a;else{let u=Math.floor(n)%Jn-e;u<0&&(u+=Jn);let c=Math.min(u/Math.max(r,1),1),h=Hg(c);i=(1-a)*(1-h)+a*h}let o=t===1?i:1-i,s=Fg(o),d=(Math.floor(n-s*r)%Jn+Jn)%Jn;return d<1?1:Math.min(d,zg)}function Bg(a){let e=a.updateRanges;if(!e||e.length===0)return null;let t=1/0,r=-1/0;for(let n of e)n.count<=0||(n.start<t&&(t=n.start),n.start+n.count-1>r&&(r=n.start+n.count-1));return r<t?null:{offset:t,count:r-t+1}}function Zr(a,e,t){if(t<=0)return;let r=Bg(a);if(a.clearUpdateRanges(),r===null){a.addUpdateRange(e,t);return}let n=Math.min(r.offset,e),i=Math.max(r.offset+r.count-1,e+t-1);a.addUpdateRange(n,i-n+1)}function Zu(a){a.clearUpdateRanges()}function ms(a,e,t){a.clearUpdateRanges(),t>0&&a.addUpdateRange(e,t)}var Og=8,ei=class{constructor(){this.pending=new WeakSet;this.hooked=new WeakSet}hook(e){this.hooked.has(e)||(this.hooked.add(e),e.onUpload(()=>this.pending.delete(e)))}isFullPending(e){return this.pending.has(e)}markFull(e){this.hook(e),Zu(e),e.needsUpdate=!0,this.pending.add(e)}markSlots(e,t,r=Og){if(t.kind==="all")return this.markFull(e),e.array.length;if(this.hook(e),e.needsUpdate=!0,this.pending.has(e))return 0;let n=e.itemSize,i=0;for(let o of t.ranges(r)){let s=o.start*n,d=Math.min(o.end*n,e.array.length)-s;d<=0||(e.addUpdateRange(s,d),i+=d)}return i}};function eo(a){return typeof a=="number"&&Number.isFinite(a)&&a>=0?a:1.5}var Yu=64,Xu=new WeakMap;function Lg(a){let e=a.getContext?.();if(!e)return Yu;let t=Xu.get(e);if(t===void 0){let r=e.getParameter(e.ALIASED_POINT_SIZE_RANGE),n=r&&r.length>1?Number(r[1]):NaN;t=Number.isFinite(n)&&n>=1?n:Yu,Xu.set(e,t)}return t}function Qu(a,e){let t=a.uniforms;t.pixelRatio&&(t.pixelRatio.value=e.getPixelRatio()),t.maxPointSize&&(t.maxPointSize.value=Lg(e))}var Vg=O.Structure|O.Style|O.Icons|O.Selection|O.Hover|O.Visibility|O.Pin,Ug=[["color","nodeColor"],["size","nodeSize"],["opacity","nodeOpacity"],["icon","nodeIcon"],["iconUV","nodeIconUV"],["imageUV","nodeImageUV"],["ringColor","nodeRingColor"],["collect","aNodeCollect"]],ys=class{constructor(e,t,r={}){this.geometry=null;this.material=null;this.mesh=null;this.iconAtlas=null;this.avatarTexture=null;this.pinTexture=null;this.cpuPositionTexture=null;this.positionProvider=null;this.lastVersion=-1;this._lastConsumedDirtyFlags=null;this.lastNodeCapacity=0;this._unsubSelection=null;this._flagsSyncedVersion=-1;this.uploads=new ei;this.lastUploadedElements=0;this.hoverDimBits=new Uint8Array(0);this.hoverDimStarts=new Float32Array(0);this.scene=e,this.store=t,this.reader=t.changes.createReader({name:"GPUNodeRenderer",domains:Vg}),this.config={maxNodes:r.maxNodes??1e5,useCircle:r.useCircle??!0,iconColumns:r.iconColumns??4,iconMode:r.iconMode??1,iconDisplayMode:r.iconDisplayMode??0,hidePin:r.hidePin??!1,hideRing:r.hideRing??!1,lightMode:r.lightMode??!1,fixedSize:r.fixedSize??0,nodeSizeScale:r.nodeSizeScale??1,minPixelSize:eo(r.minPixelSize),primitive:r.primitive==="point"?"point":"quad"},this._unsubSelection=t.subscribeSelectionChanged(n=>{let i=this.geometry?.getAttribute("nodeFlags");if(!i||!this.store.nodeState)return;let o=i.array,s=this.store.nodeState,d=this.store.nodeCount;this.ensureHoverArrays(d);let l=this.hoverDimStarts,u=c=>(s.selected[c]>0?1:0)+(s.highlighted[c]>0?2:0)+(s.pinned[c]>0?4:0)+(s.hidden[c]>0?8:0)+(this.hoverDimBits[c]?16:0)+l[c]*32;if(n){let c=1/0,h=-1;for(let p of n)p<0||p>=d||(o[p]=u(p),p<c&&(c=p),p>h&&(h=p));if(h>=0){let p=h-c+1;p<d/4&&!this.uploads.isFullPending(i)?(Zr(i,c,p),i.needsUpdate=!0):this.uploads.markFull(i)}this._flagsSyncedVersion=this.store.version;return}for(let c=0;c<d;c++)o[c]=u(c);this.uploads.markFull(i),this._flagsSyncedVersion=this.store.version})}init(){this.createGeometry(),this.createMaterial(),this.createMesh()}ensureHoverArrays(e){if(this.hoverDimStarts.length>=e)return;let t=new Float32Array(e);t.set(this.hoverDimStarts),this.hoverDimStarts=t;let r=new Uint8Array(e);r.set(this.hoverDimBits),this.hoverDimBits=r}createGeometry(){let e=this.config.primitive==="point";this.geometry=e?new De.BufferGeometry:new De.InstancedBufferGeometry;let t=(s,d)=>e?new De.BufferAttribute(s,d):new De.InstancedBufferAttribute(s,d);this.reader.read(),this.store.refreshEffectiveSizes();let r=this.store.nodeCount||1,n=this.store.nodeCapacity||Math.ceil(r*1.5)||1;this.lastNodeCapacity=n;let i=this.store.nodeState;if(this.hoverDimBits.length!==this.store.nodeCount&&(this.hoverDimBits=new Uint8Array(this.store.nodeCount),this.hoverDimStarts=new Float32Array(this.store.nodeCount)),!e){let s=new Float32Array([-.5,-.5,.5,-.5,.5,.5,-.5,.5]);this.geometry.setAttribute("corner",new De.BufferAttribute(s,2));let d=new Float32Array([-.5,-.5,0,.5,-.5,0,.5,.5,0,-.5,.5,0]);this.geometry.setAttribute("position",new De.BufferAttribute(d,3)),this.geometry.setIndex(new De.BufferAttribute(new Uint16Array([0,1,2,0,2,3]),1))}let o=new Float32Array(n);for(let s=0;s<n;s++)o[s]=s;if(this.geometry.setAttribute("nodeIndex",t(o,1)),i){this.geometry.setAttribute("nodeColor",t(i.colors,3)),this.geometry.setAttribute("nodeSize",t(i.effectiveSizes,1)),this.geometry.setAttribute("nodeOpacity",t(i.opacities,1)),this.geometry.setAttribute("nodeIcon",t(i.icons,1));let s=i.ringColors||i.colors;this.geometry.setAttribute("nodeRingColor",t(s,3)),this.geometry.setAttribute("nodeIconUV",t(i.iconUVs,4)),this.geometry.setAttribute("nodeImageUV",t(i.imageUVs,4)),this.geometry.setAttribute("aNodeCollect",t(i.collection,1));let d=new Float32Array(n);this.geometry.setAttribute("nodeSuppressFill",t(d,1));let l=new Float32Array(n);for(let c=0;c<n;c++)l[c]=(i.selected[c]>0?1:0)+(i.highlighted[c]>0?2:0)+(i.pinned[c]>0?4:0)+(i.hidden[c]>0?8:0);this.geometry.setAttribute("nodeFlags",t(l,1));let u=new Float32Array(n*4);this.geometry.setAttribute("nodeEffects",t(u,4)),this.repackDerived(null,n)}else this.geometry.setAttribute("nodeColor",t(new Float32Array(n*3),3)),this.geometry.setAttribute("nodeSize",t(new Float32Array(n).fill(this.store.defaultNodeSize),1)),this.geometry.setAttribute("nodeOpacity",t(new Float32Array(n).fill(1),1)),this.geometry.setAttribute("nodeIcon",t(new Float32Array(n).fill(-1),1)),this.geometry.setAttribute("nodeRingColor",t(new Float32Array(n*3),3)),this.geometry.setAttribute("nodeIconUV",t(new Float32Array(n*4).fill(-1),4)),this.geometry.setAttribute("nodeImageUV",t(new Float32Array(n*4).fill(-1),4)),this.geometry.setAttribute("aNodeCollect",t(new Float32Array(n),1)),this.geometry.setAttribute("nodeSuppressFill",t(new Float32Array(n),1)),this.geometry.setAttribute("nodeFlags",t(new Float32Array(n),1)),this.geometry.setAttribute("nodeEffects",t(new Float32Array(n*4).map((s,d)=>d%4===3?1:0),4));this.geometry.setAttribute("toPosition",t(new Float32Array(n*3),3)),this.setDrawCount(this.store.nodeCount)}setDrawCount(e){let t=this.geometry;t&&(t instanceof De.InstancedBufferGeometry?t.instanceCount=e:t.setDrawRange(0,e))}createMaterial(){this.material=new De.ShaderMaterial({vertexShader:Cu,fragmentShader:wu,uniforms:{positionTexture:{value:null},textureSize:{value:512},spaceSize:{value:1},animate:{value:0},t:{value:0},iconAtlas:{value:null},iconColumn:{value:this.config.iconColumns},iconMode:{value:this.config.iconMode},iconSdfAtlas:{value:null},hasIconSdfAtlas:{value:0},iconDisplayMode:{value:this.config.iconDisplayMode},imageAtlas:{value:null},hasImageAtlas:{value:0},avatarTexture:{value:null},pinTexture:{value:null},hidePin:{value:this.config.hidePin?1:0},hideRing:{value:this.config.hideRing?1:0},useCircle:{value:this.config.useCircle?1:0},lightMode:{value:this.config.lightMode?1:0},time:{value:0},uRippleColor:{value:new De.Vector3(0,.9,1)},uRippleSpeed:{value:.5},uRippleRings:{value:3},fixedSize:{value:0},nodeSizeScale:{value:1},mapMode:{value:0},mapDamping:{value:1},mapMaxGrowth:{value:4},maxScreenFraction:{value:.5},pixelRatio:{value:window.devicePixelRatio||1},minPixelSize:{value:this.config.minPixelSize},maxPointSize:{value:64},sphereRadius:{value:0},resolution:{value:new De.Vector2(1,1)},u_hoverProgress:{value:0},u_hoverDimOpacity:{value:.15},u_hoverTime:{value:0},u_hoverDuration:{value:200}},transparent:!0,depthWrite:!1,depthTest:!0,blending:De.NormalBlending,fog:!0}),this.config.primitive==="point"&&(this.material.defines={KV_POINT_PRIMITIVE:""})}createMesh(){if(!this.geometry||!this.material)return;this.mesh=this.config.primitive==="point"?new De.Points(this.geometry,this.material):new De.Mesh(this.geometry,this.material),this.mesh.frustumCulled=!1;let e=this.material;this.mesh.onBeforeRender=t=>{Qu(e,t)},this.mesh.renderOrder=1,this.scene.add(this.mesh)}update(e){if(this._lastConsumedDirtyFlags=null,!this.geometry||!this.material)return;this.material.uniforms.time.value=performance.now()/1e3;let t=this.store.rippleColor;this.material.uniforms.uRippleColor.value.set(t[0],t[1],t[2]),this.material.uniforms.uRippleSpeed.value=this.store.rippleSpeed,this.material.uniforms.uRippleRings.value=this.store.rippleRings;let r=this.store;if(!r.nodeState)return;let i=r.version!==this.lastVersion,o=this.positionProvider?.needsUpdate??!1;if(!(!i&&!o&&!e)){if(i||e){this.lastVersion=r.version;let s=e??r.updateStrategy.consumeDirty();if(this._lastConsumedDirtyFlags=s,s.has("structure")){this.store.nodeCapacity!==this.lastNodeCapacity?(this.rebuildGeometry(),this.markAllAttributesDirty()):(this.setDrawCount(this.store.nodeCount),this.applyStructureChanges()),this.updatePositionUniforms(!0);return}this.reader.read(),this.updateDirtyAttributes(s)}this.updatePositionUniforms()}}getLastConsumedDirtyFlags(){return this._lastConsumedDirtyFlags}rebuildGeometry(){this.mesh&&(this.scene.remove(this.mesh),this.mesh=null),this.geometry&&(this.geometry.dispose(),this.geometry=null),this.createGeometry(),this.createMesh()}repackDerived(e,t){let r=this.geometry,n=this.store.nodeState;if(!r||!n)return;let i=r.getAttribute("nodeSuppressFill")?.array,o=r.getAttribute("nodeEffects")?.array;if(!i||!o)return;let s=t??this.store.nodeCount,d=l=>{i[l]=n.suppressFill[l]+2*n.shapeIds[l],o[l*4]=n.ripple?n.ripple[l]:0,o[l*4+1]=n.breathe?n.breathe[l]:0,o[l*4+2]=n.halo?n.halo[l]:0,o[l*4+3]=n.aspects[l]};if(!e||e.kind==="all")for(let l=0;l<s;l++)d(l);else e.forEach(l=>l<s&&d(l))}applyStructureChanges(){let e=this.geometry,t=this.store.nodeState;if(!e||!t)return;let r=this.reader.read();if(!r)return;if(r.full||r.nodes.capacityChanged&&this.store.nodeCapacity!==this.lastNodeCapacity){this.markAllAttributesDirty();return}this.moveHoverShadow(r);let n=this.store.nodeCount;this.ensureHoverArrays(n);let i=r.nodes.attrs.get("size");i&&(i.kind==="all"?this.store.refreshEffectiveSizes():i.forEach(h=>h<n&&this.store.refreshEffectiveSizeAt(h)));let o=0;for(let[h,p]of Ug){let f=r.nodes.attrs.get(h);if(!f)continue;let m=e.getAttribute(p);m&&(o+=this.uploads.markSlots(m,f))}let s=r.nodes.attrs.get("flags"),d=e.getAttribute("nodeFlags");if(s&&d){let h=d.array,p=this.hoverDimStarts,f=this.hoverDimBits,m=g=>{h[g]=(t.selected[g]>0?1:0)+(t.highlighted[g]>0?2:0)+(t.pinned[g]>0?4:0)+(t.hidden[g]>0?8:0)+(f[g]?16:0)+p[g]*32};if(s.kind==="all")for(let g=0;g<n;g++)m(g);else s.forEach(g=>g<n&&m(g));o+=this.uploads.markSlots(d,s)}let l=["shape","suppressFill","effects"].map(h=>r.nodes.attrs.get(h)).filter(h=>!!h),u=e.getAttribute("nodeEffects"),c=e.getAttribute("nodeSuppressFill");if(l.length&&u&&c)for(let h of l)this.repackDerived(h),o+=this.uploads.markSlots(u,h),o+=this.uploads.markSlots(c,h);this.lastUploadedElements=o}moveHoverShadow(e){let t=this.hoverDimBits,r=this.hoverDimStarts;for(let n of e.nodes.ops)n.op==="remove"&&(n.slot<t.length&&n.last<t.length&&(t[n.slot]=n.slot===n.last?0:t[n.last],r[n.slot]=n.slot===n.last?0:r[n.last]),n.last<t.length&&(t[n.last]=0,r[n.last]=0))}markAllAttributesDirty(){if(!this.geometry)return;this.store.refreshEffectiveSizes();let e=["nodeColor","nodeSize","nodeOpacity","nodeIcon","nodeRingColor","aNodeCollect","nodeIconUV","nodeImageUV","nodeFlags","nodeEffects","nodeSuppressFill"];this.repackDerived(null);for(let t of e){let r=this.geometry.getAttribute(t);r&&this.uploads.markFull(r)}}updateDirtyAttributes(e){if(!this.geometry)return;let t=this.store.version;e.has("nodeSizes")&&this.store.refreshEffectiveSizes();let r={structure:null,edgeStructure:null,nodeColors:"nodeColor",nodeSizes:"nodeSize",nodeOpacities:"nodeOpacity",nodeIcons:"nodeIcon",nodeImages:null,nodeSelection:null,nodeHighlight:null,nodeHover:null,nodePinned:null,nodeHidden:null,nodeRingColors:"nodeRingColor",nodeCollection:"aNodeCollect",nodeLabels:null,nodeSuppressFill:null,nodeShapes:null,nodeRipple:null,nodeBreathe:null,badges:null,tags:null,collect:null,edgeColors:null,edgeWidths:null,edgeOpacities:null,edgeSelection:null,edgeHighlight:null,edgeDashed:null,edgeShapes:null,edgeFlow:null,edgeGlow:null,edgeTubeGlow:null,nodeHalo:null,groups:null};Array.from(e).forEach(d=>{let l=r[d];if(l){let u=this.geometry.getAttribute(l);u&&this.uploads.markFull(u)}});let n=this.store.nodeState,i=e.has("nodeSelection")||e.has("nodeHighlight")||e.has("nodePinned")||e.has("nodeHidden"),s=!e.has("nodeHighlight")&&!e.has("nodePinned")&&!e.has("nodeHidden")&&this._flagsSyncedVersion===t;if(i&&!s){let d=this.geometry.getAttribute("nodeFlags");if(d&&n){let l=d.array,u=this.store.nodeCount;this.ensureHoverArrays(u);let c=this.hoverDimStarts;for(let h=0;h<u;h++)l[h]=(n.selected[h]>0?1:0)+(n.highlighted[h]>0?2:0)+(n.pinned[h]>0?4:0)+(n.hidden[h]>0?8:0)+(this.hoverDimBits[h]?16:0)+c[h]*32;this.uploads.markFull(d),d.needsUpdate=!0}}if(e.has("nodeShapes")||e.has("nodeSuppressFill")||e.has("nodeRipple")||e.has("nodeBreathe")||e.has("nodeHalo")){let d=this.geometry.getAttribute("nodeEffects"),l=this.geometry.getAttribute("nodeSuppressFill");d&&l&&n&&(this.repackDerived(null),this.uploads.markFull(d),this.uploads.markFull(l))}}updatePositionUniforms(e=!1){if(!this.material||!this.positionProvider)return;let t=this.positionProvider;if(t.mode==="gpu"){let r=t.getPositionTexture();r&&(this.material.uniforms.positionTexture.value=r,this.material.uniforms.textureSize.value=t.getTextureSize(),this.material.uniforms.spaceSize.value=t.getSpaceSize())}else{let r=t.getPositions();if(!r)return;let n=r.length/3,i=Math.max(2,Math.pow(2,Math.ceil(Math.log2(Math.sqrt(n))))),o=!1;if(!this.cpuPositionTexture||this.cpuPositionTexture.image.width!==i){this.cpuPositionTexture&&this.cpuPositionTexture.dispose();let s=new Float32Array(i*i*4);this.cpuPositionTexture=new De.DataTexture(s,i,i,De.RGBAFormat,De.FloatType),this.cpuPositionTexture.minFilter=De.NearestFilter,this.cpuPositionTexture.magFilter=De.NearestFilter,this.cpuPositionTexture.needsUpdate=!0,o=!0}if(e||o||t.needsUpdate){let s=this.cpuPositionTexture.image.data;for(let d=0;d<n;d++)s[d*4]=r[d*3],s[d*4+1]=r[d*3+1],s[d*4+2]=r[d*3+2],s[d*4+3]=1;this.cpuPositionTexture.needsUpdate=!0}this.material.uniforms.positionTexture.value=this.cpuPositionTexture,this.material.uniforms.textureSize.value=i,this.material.uniforms.spaceSize.value=t.getSpaceSize()}}setPositionProvider(e){e!==this.positionProvider&&(this.positionProvider=e,this.updatePositionUniforms(!0))}getCpuPositionTextureInfo(){if(!this.cpuPositionTexture||!this.positionProvider)return null;let e=this.positionProvider.getPositions();if(!e)return null;let t=e.length/3,r=Math.max(2,Math.pow(2,Math.ceil(Math.log2(Math.sqrt(t)))));return{texture:this.cpuPositionTexture,textureSize:r,spaceSize:this.positionProvider.getSpaceSize()}}forceUpdateAllAttributes(){if(!this.geometry)return;let e=["nodeColor","nodeSize","nodeOpacity","nodeIcon","nodeRingColor","aNodeCollect","nodeFlags","nodeEffects","nodeSuppressFill"];this.repackDerived(null);for(let t of e){let r=this.geometry.getAttribute(t);r&&this.uploads.markFull(r)}}setIconAtlas(e,t){this.iconAtlas=e,this.material&&(this.material.uniforms.iconAtlas.value=e,this.material.uniforms.iconColumn.value=t)}setIconSdfAtlas(e){this.material&&(this.material.uniforms.iconSdfAtlas.value=e,this.material.uniforms.hasIconSdfAtlas.value=e?1:0)}updateIconUVs(e){let t=this.geometry?.getAttribute("nodeIconUV");if(!t)return;let r=t.array,n=Math.min(r.length,e.length);r.set(e.subarray(0,n)),r.length>e.length&&r.fill(-1,e.length),t.needsUpdate=!0;let i=this.store.nodeState?.iconUVs;if(i){let o=Math.min(i.length,e.length);i.set(e.subarray(0,o)),i.length>e.length&&i.fill(-1,e.length)}}setImageAtlas(e){this.material&&(this.material.uniforms.imageAtlas.value=e,this.material.uniforms.hasImageAtlas.value=e?1:0)}updateImageUVs(e){let t=this.geometry?.getAttribute("nodeImageUV");if(!t)return;let r=t.array,n=Math.min(r.length,e.length);r.set(e.subarray(0,n)),r.length>e.length&&r.fill(-1,e.length),t.needsUpdate=!0;let i=this.store.nodeState?.imageUVs;if(i){let o=Math.min(i.length,e.length);i.set(e.subarray(0,o)),i.length>e.length&&i.fill(-1,e.length)}}setAvatarTexture(e){this.avatarTexture=e,this.material&&(this.material.uniforms.avatarTexture.value=e)}setPinTexture(e){this.pinTexture=e,this.material&&(this.material.uniforms.pinTexture.value=e)}setAnimationProgress(e,t=!0){this.material&&(this.material.uniforms.animate.value=t?1:0,this.material.uniforms.t.value=e)}setOptions(e){this.material&&(e.useCircle!==void 0&&(this.config.useCircle=e.useCircle,this.material.uniforms.useCircle.value=e.useCircle?1:0),e.iconMode!==void 0&&(this.config.iconMode=e.iconMode,this.material.uniforms.iconMode.value=e.iconMode),e.iconDisplayMode!==void 0&&(this.config.iconDisplayMode=e.iconDisplayMode,this.material.uniforms.iconDisplayMode.value=e.iconDisplayMode),e.hidePin!==void 0&&(this.config.hidePin=e.hidePin,this.material.uniforms.hidePin.value=e.hidePin?1:0),e.hideRing!==void 0&&(this.config.hideRing=e.hideRing,this.material.uniforms.hideRing.value=e.hideRing?1:0),e.lightMode!==void 0&&(this.config.lightMode=e.lightMode,this.material.uniforms.lightMode.value=e.lightMode?1:0),e.fixedSize!==void 0&&(this.config.fixedSize=e.fixedSize,this.material.uniforms.fixedSize.value=e.fixedSize),e.nodeSizeScale!==void 0&&(this.config.nodeSizeScale=e.nodeSizeScale,this.store.setGlobalNodeSizeScale(e.nodeSizeScale)))}setNodeSizeScale(e){this.config.nodeSizeScale=e,this.store.setGlobalNodeSizeScale(e)}setMinPixelSize(e){this.config.minPixelSize=eo(e),this.material&&(this.material.uniforms.minPixelSize.value=this.config.minPixelSize)}setMapMode(e,t,r){if(this.material){this.material.uniforms.mapMode.value=e?1:0,this.material.uniforms.mapDamping.value=r??.3;let n=e&&(t??0)>0;this.material.depthTest=n?!1:!e,this.material.uniforms.sphereRadius.value=n?t:0}}setMapMaxGrowth(e){if(!this.material)return;let t=e===1/0?-1:e;this.material.uniforms.mapMaxGrowth.value=t}setMaxScreenFraction(e){if(!this.material)return;let t=e===1/0?-1:e;this.material.uniforms.maxScreenFraction.value=t}setResolution(e,t){this.material&&this.material.uniforms.resolution.value.set(e,t)}getMesh(){return this.mesh}getGeometry(){return this.geometry}setHoverDimBit(e,t){if(e<0||e>=this.hoverDimBits.length)return;let r=this.hoverDimBits[e]?1:0;if(r===t)return;let n=performance.now(),i=this.material?.uniforms.u_hoverDuration?.value??500,o=kr(r,this.hoverDimStarts[e],t,i,n);if(this.hoverDimBits[e]=t,this.hoverDimStarts[e]=o,!this.geometry)return;let s=this.geometry.getAttribute("nodeFlags");if(!s)return;let d=s.array,l=d[e],u=l-Math.floor(l/32)*32,c=t?u<16?u+16:u:u>=16?u-16:u;d[e]=c+o*32,Zr(s,e,1),s.needsUpdate=!0}setHoverUniform(e,t){if(!this.material)return;let r=this.material.uniforms[e];r&&(r.value=t)}clearAllHoverDimBits(){if(!this.geometry)return;let e=this.geometry.getAttribute("nodeFlags");if(!e)return;let t=e.array,r=performance.now(),n=this.material?.uniforms.u_hoverDuration?.value??500;for(let i=0;i<t.length;i++){let o=t[i]-Math.floor(t[i]/32)*32;if(o>=16){let d=kr(1,this.hoverDimStarts[i],0,n,r);this.hoverDimBits[i]=0,this.hoverDimStarts[i]=d,t[i]=o-16+d*32}}ms(e,0,t.length),e.needsUpdate=!0}setHalo(e,t){let r=this.store.nodeState;!r||e<0||e>=r.halo.length||(r.halo[e]=t,this.store.updateStrategy.markDirty("nodeHalo"))}clearAllEmphasisHalo(){let e=this.store.nodeState;e&&(e.halo.fill(0),this.store.updateStrategy.markDirty("nodeHalo"))}dispose(){this.reader.dispose(),this._unsubSelection?.(),this._unsubSelection=null,this.mesh&&(this.scene.remove(this.mesh),this.mesh=null),this.geometry&&(this.geometry.dispose(),this.geometry=null),this.material&&(this.material.dispose(),this.material=null),this.cpuPositionTexture&&(this.cpuPositionTexture.dispose(),this.cpuPositionTexture=null)}};import*as ie from"three";function Wg(a,e,t,r){let n=e[0]-a[0],i=e[1]-a[1],o=r===2?!1:r===1?!0:Math.abs(i)>=Math.abs(n),s=o?i:n,d=s>=0?1:-1,l;return t[1]>=9999?l=t[0]<0?d*Math.min(-t[0],Math.abs(s)):s*vs(t[0],0,1):l=s*vs(.5+t[0],.05,.95),Math.abs(s)<=1e-5?null:o?{P1:[a[0],a[1]+l,a[2]],P2:[e[0],a[1]+l,e[2]],d1:[0,d,0]}:{P1:[a[0]+l,a[1],a[2]],P2:[a[0]+l,e[1],e[2]],d1:[d,0,0]}}function jg(a,e,t,r,n,i){let{P1:o,P2:s,d1:d}=r,l=bn(s,o),u=Math.max(rc(bn(o,t),d),0),c=qg(l),h=Math.max(rc(bn(n,s),d),0),p=c>1e-6?jt(l,1/c):d,m=1e-4*(u+c+h),g=i*Math.min(u,h),y=Math.max(Math.min(g,u,.5*c),m),v=Math.max(Math.min(g,h,.5*c),m),b=Math.max(Math.floor((e-4)*.5),1),x=Math.PI/2,w=Math.max(u-y,0),T=Math.max(c-y-v,0),I=Math.max(h-v,0),R=x*y,S=x*v,P=w+R+T+S+I;if(a<=1){let M=vs(a,0,1);return{p:Sn(t,jt(d,w*M)),s:w*M,L:P}}if(a<=1+b){let M=x*(a-1)/b,N=Sn(bn(o,jt(d,y)),jt(p,y));return{p:Sn(bn(N,jt(p,y*Math.cos(M))),jt(d,y*Math.sin(M))),s:w+y*M,L:P}}if(a<=2+b){let M=a-(1+b);return{p:Sn(o,jt(p,y+T*M)),s:w+R+T*M,L:P}}if(a<=2+2*b){let M=x*(a-(2+b))/b,N=Sn(bn(s,jt(p,v)),jt(d,v));return{p:Sn(bn(N,jt(d,v*Math.cos(M))),jt(p,v*Math.sin(M))),s:w+R+T+v*M,L:P}}let D=Math.max(e-(2+2*b),.001),E=vs((a-(2+2*b))/D,0,1);return{p:Sn(s,jt(d,v+I*E)),s:w+R+T+S+I*E,L:P}}function Ju(a,e,t={}){let r=t.segments??20,n=t.bend!==void 0&&Number.isFinite(t.bend)?[t.bend,9999]:[t.curvature??0,0],i=Wg(a,e,n,t.axis??0);if(!i)return[a,e];let o=[];for(let s=0;s<=r;s++)o.push(jg(s,r,a,i,e,t.radius??.35).p);return o}function vs(a,e,t){return a<e?e:a>t?t:a}function bn(a,e){return[a[0]-e[0],a[1]-e[1],a[2]-e[2]]}function Sn(a,e){return[a[0]+e[0],a[1]+e[1],a[2]+e[2]]}function jt(a,e){return[a[0]*e,a[1]*e,a[2]*e]}function rc(a,e){return a[0]*e[0]+a[1]*e[1]+a[2]*e[2]}function qg(a){return Math.sqrt(rc(a,a))}var ic=4,to=5,bs=16,Gt=4;function Ss(a,e,t){let r=t.length;if(r===0||r>bs)return null;let n=e[0]-a[0],i=e[1]-a[1],o=n*n+i*i;if(o<1e-18)return null;let s=new Float32Array(r*Gt),d=0,l=0,u=0,c=[];for(let h=0;h<r;h++){let p=t[h][0]-a[0],f=t[h][1]-a[1],m=(p*n+f*i)/o,g=(n*f-i*p)/o;s[h*Gt]=m,s[h*Gt+1]=g,u+=Math.hypot(m-d,g-l),c.push(u),d=m,l=g}u+=Math.hypot(1-d,-l);for(let h=0;h<r;h++)s[h*Gt+2]=u>0?c[h]/u:0;return s}function Kg(a,e,t,r){let n=t[r*Gt],i=t[r*Gt+1],o=e[0]-a[0],s=e[1]-a[1],d=e[2]-a[2];return[a[0]+n*o-i*s,a[1]+n*s+i*o,a[2]+n*d]}function $g(a,e,t){let r=[a],n=Math.floor(t.length/Gt);for(let i=0;i<n;i++)r.push(Kg(a,e,t,i));return r.push(e),r}function Zg(a,e){return e?[(a[0]+e[0])/2,(a[1]+e[1])/2,(a[2]+e[2])/2]:a}function eh(a,e,t){let r=(n,i,o)=>Ju(n,e,{bend:i!==void 0&&Number.isFinite(i)?i:void 0,curvature:o,axis:t.axis??0,radius:t.radius??.35,segments:t.segments??20});if(t.shape===3)return r(a,t.bend,t.curvature);if(t.shape===to){let n=t.bend!==void 0&&Number.isFinite(t.bend)?t.bend:.5;return r(Zg(a,t.anchor),n,void 0)}return t.shape===ic?t.route&&t.route.length>=Gt?$g(a,e,t.route):[a,e]:null}function th(a){return 1e4+(a===void 0||a<0?-1:a)}var xs=class a{constructor(e,t,r={}){this.geometry=null;this.material=null;this.mesh=null;this.arrowGeometry=null;this.arrowMaterial=null;this.arrows=null;this.positionProvider=null;this.lastVersion=-1;this.edgeClassifier=new $r;this.pendingSelectionNodes=new Set;this.uploads=new ei;this.lastUploadedElements=0;this.lineArrays=null;this.arrowArrays=null;this.lastEdgeCapacity=0;this.routeTexture=a.makeRouteTexture(new Float32Array(4),1);this.routeTextureSize=1;this.routeOffsets=new Map;this.routeVersionSeen=-1;this.is3D=!0;this.selfLoopCloud=null;this.hoverDimBits=new Uint8Array(0);this.hoverDimStarts=new Float32Array(0);this.scene=e,this.store=t,this.reader=t.changes.createReader({name:"GPUEdgeRenderer",domains:O.Structure}),this.unsubSelection=t.subscribeSelectionChanged(n=>{if(!n){this.pendingSelectionNodes=null;return}let i=this.pendingSelectionNodes;if(i)for(let o of n)i.add(o)}),this.config={maxEdges:r.maxEdges??5e5,lineWidth:r.lineWidth??1,opacity:r.opacity??.8,segments:r.segments??20,hideArrows:r.hideArrows??!1,useCurve:r.useCurve??!1,curveAmount:r.curveAmount??.08,nodeSizeScale:r.nodeSizeScale??1,edgeShape:r.edgeShape??"straight",radialAxis:r.radialAxis??"auto"},this.resolution=new ie.Vector2(window.innerWidth||1,window.innerHeight||1)}init(){this.createEdgeGeometry(),this.createEdgeMaterial(),this.createEdgeMesh(),this.createArrowGeometry(),this.createArrowMaterial(),this.createArrowMesh(),this.arrows&&(this.arrows.visible=!this.config.hideArrows),this.selfLoopCloud=new Ji(this.scene,this.store,this.edgeClassifier,{lineWidth:this.config.lineWidth}),this.selfLoopCloud.init()}createEdgeGeometry(){this.geometry=new ie.InstancedBufferGeometry,this.reader.read(),this.syncRoutes();let e=this.config.segments,t=(e+1)*2,r=[],n=[],i=[],o=[],s=[];for(let f=0;f<=e;f++){let m=f/e;r.push(0,0,0),n.push(-1),i.push(m),o.push(m),r.push(0,0,0),n.push(1),i.push(m),o.push(m)}for(let f=0;f<e;f++){let m=f*2;s.push(m,m+1,m+2),s.push(m+1,m+3,m+2)}if(this.geometry.setAttribute("position",new ie.Float32BufferAttribute(r,3)),this.geometry.setAttribute("side",new ie.Float32BufferAttribute(n,1)),this.geometry.setAttribute("along",new ie.Float32BufferAttribute(i,1)),this.geometry.setAttribute("counters",new ie.Float32BufferAttribute(o,1)),this.geometry.setIndex(s),this.store.edgeCount===0){this.geometry.instanceCount=0;return}let d=this.store.edgeCount,l=this.store.index,u=this.store.edgeState,c=this.store.data;this.hoverDimBits.length!==d&&(this.hoverDimBits=new Uint8Array(d),this.hoverDimStarts=new Float32Array(d)),this.edgeClassifier.classifySlots(c.edges,l.edgeSourceIndices,l.edgeTargetIndices,l.nodeIndexToId);let h=Math.max(this.store.edgeCapacity,d);this.lastEdgeCapacity=h;let p={src:new Float32Array(h),tgt:new Float32Array(h),color:new Float32Array(h*3),width:new Float32Array(h),opacity:new Float32Array(h),selected:new Float32Array(h),highlighted:new Float32Array(h),ctrl:new Float32Array(h*3),sizes:new Float32Array(h*4),flags:new Float32Array(h)};this.lineArrays=p;for(let f=0;f<d;f++)this.packLineSlot(f,p);this.geometry.setAttribute("sourceIndex",new ie.InstancedBufferAttribute(p.src,1)),this.geometry.setAttribute("targetIndex",new ie.InstancedBufferAttribute(p.tgt,1)),this.geometry.setAttribute("edgeColor",new ie.InstancedBufferAttribute(p.color,3)),this.geometry.setAttribute("edgeWidth",new ie.InstancedBufferAttribute(p.width,1)),this.geometry.setAttribute("edgeOpacity",new ie.InstancedBufferAttribute(p.opacity,1)),this.geometry.setAttribute("edgeSelected",new ie.InstancedBufferAttribute(p.selected,1)),this.geometry.setAttribute("edgeHighlighted",new ie.InstancedBufferAttribute(p.highlighted,1)),this.geometry.setAttribute("controlOffset",new ie.InstancedBufferAttribute(p.ctrl,3)),this.geometry.setAttribute("nodeSizes",new ie.InstancedBufferAttribute(p.sizes,4)),this.geometry.setAttribute("edgeFlags",new ie.InstancedBufferAttribute(p.flags,1)),this.geometry.instanceCount=d}hoverValid(){let e=this.store.edgeCount;return this.hoverDimBits.length===e&&this.hoverDimStarts.length===e}packEdgeFlags(e){let t=this.store.edgeState,r=t?.dashed&&t.dashed[e]>0?1:0,n=t?.flow&&t.flow[e]>0?2:0,i=t?.glow&&t.glow[e]>0?4:0,o=t?.tubeGlow&&t.tubeGlow[e]>0?8:0,s=this.hoverValid(),d=s&&this.hoverDimBits[e]?16:0,l=s?this.hoverDimStarts[e]:0;return r+n+i+o+d+l*32}endpointCode(e){let t=this.store.nodeState;return t?Vu(t.shapeIds[e],t.aspects[e]):0}packLineSlot(e,t){let r=this.store.index,n=this.store.edgeState,i=this.store.nodeState,o=r.edgeSourceIndices[e],s=r.edgeTargetIndices[e];if(t.src[e]=o,t.tgt[e]=s,t.flags[e]=this.packEdgeFlags(e),o===s){t.color.fill(0,e*3,e*3+3),t.width[e]=0,t.opacity[e]=0,t.selected[e]=0,t.highlighted[e]=0,t.ctrl.fill(0,e*3,e*3+3),t.sizes.fill(0,e*4,e*4+4);return}let d=!!i&&(i.hidden[o]>.5||i.hidden[s]>.5);n?(t.color[e*3]=n.colors[e*3],t.color[e*3+1]=n.colors[e*3+1],t.color[e*3+2]=n.colors[e*3+2],t.width[e]=n.widths?n.widths[e]:this.config.lineWidth,t.opacity[e]=d?0:n.opacities[e],t.selected[e]=n.selected[e],t.highlighted[e]=n.highlighted?n.highlighted[e]:0):(t.color[e*3]=.5,t.color[e*3+1]=.5,t.color[e*3+2]=.5,t.width[e]=this.config.lineWidth,t.opacity[e]=d?0:this.config.opacity,t.selected[e]=0,t.highlighted[e]=0),this.packCtrl(t.ctrl,e,this.store.data.edges[e].id);let l=i?.selected[o]>0||i?.highlighted[o]>0?1.5:1,u=i?.selected[s]>0||i?.highlighted[s]>0?1.5:1;t.sizes[e*4]=(i?.effectiveSizes[o]??10)*l,t.sizes[e*4+1]=(i?.effectiveSizes[s]??10)*u,t.sizes[e*4+2]=this.endpointCode(o),t.sizes[e*4+3]=this.endpointCode(s)}packArrowSlot(e,t){let r=this.store.index,n=this.store.edgeState,i=this.store.nodeState,o=r.edgeSourceIndices[e],s=r.edgeTargetIndices[e];if(t.src[e]=o,t.tgt[e]=s,t.hoverDim[e]=this.hoverValid()?(this.hoverDimBits[e]?1:0)+this.hoverDimStarts[e]*2:0,o===s){t.color.fill(0,e*3,e*3+3),t.opacity[e]=0,t.scale.fill(0,e*3,e*3+3),t.rotation[e]=0,t.targetSize.fill(0,e*2,e*2+2),t.sourceSize.fill(0,e*2,e*2+2),t.ctrl.fill(0,e*3,e*3+3),t.selected[e]=0;return}let d=!!i&&(i.hidden[o]>.5||i.hidden[s]>.5);if(n){t.color[e*3]=n.colors[e*3],t.color[e*3+1]=n.colors[e*3+1],t.color[e*3+2]=n.colors[e*3+2],t.opacity[e]=d?0:n.opacities[e];let c=(n.widths?n.widths[e]:this.config.lineWidth)*this.config.lineWidth*.008;t.scale[e*3]=c*1.5,t.scale[e*3+1]=.035,t.scale[e*3+2]=c*1.5,t.rotation[e]=n.rotations?n.rotations[e]:0}else{let c=this.config.lineWidth*this.config.lineWidth*.008;t.color[e*3]=.5,t.color[e*3+1]=.5,t.color[e*3+2]=.5,t.opacity[e]=d?0:this.config.opacity,t.scale[e*3]=c*1.5,t.scale[e*3+1]=.035,t.scale[e*3+2]=c*1.5,t.rotation[e]=0}t.selected[e]=n?n.selected[e]:0;let l=i?.selected[s]>0||i?.highlighted[s]>0?1.5:1,u=i?.selected[o]>0||i?.highlighted[o]>0?1.5:1;t.targetSize[e*2]=(i?.effectiveSizes[s]??10)*l,t.targetSize[e*2+1]=this.endpointCode(s),t.sourceSize[e*2]=(i?.effectiveSizes[o]??10)*u,t.sourceSize[e*2+1]=this.endpointCode(o),this.packCtrl(t.ctrl,e,this.store.data.edges[e]?.id)}packCtrl(e,t,r){let n=t*3;if(!r){e[n]=0,e[n+1]=0,e[n+2]=-1;return}let i=this.store.edgeState,o=this.edgeClassifier.readCurveAt(t,r,this.is3D),s=this.edgeClassifier.lastPlaneRotation;Math.abs(o)>.001||this.config.useCurve?(e[n]=Math.abs(o)>.001?o:this.config.curveAmount,e[n+1]=s):(e[n]=0,e[n+1]=0);let d=i?.shapes?i.shapes[t]:-1,l=this.material?.uniforms.defaultEdgeShape.value??0;d>=0?e[n+2]=d:o!==0&&l!==3?e[n+2]=1:e[n+2]=-1;let u=d>=0?d:e[n+2]<0?l:e[n+2],c=i?.bends?i.bends[t]:NaN;if(u===3&&Number.isFinite(c))e[n]=c,e[n+1]=9999;else if(u===ic){let h=this.routeOffsets.get(r),p=h===void 0?void 0:this.store.edgeRoute(r);e[n]=h??0,e[n+1]=p?Math.floor(p.length/Gt):0}else if(u===to){let h=this.store.edgeAnchor(r),p=h===void 0?void 0:this.store.index.getNodeIndex(h);e[n]=Number.isFinite(c)?c:.5,e[n+1]=th(p)}}static makeRouteTexture(e,t){let r=new ie.DataTexture(e,t,t,ie.RGBAFormat,ie.FloatType);return r.minFilter=ie.NearestFilter,r.magFilter=ie.NearestFilter,r.generateMipmaps=!1,r.needsUpdate=!0,r}syncRoutes(){let e=this.store.edgeRouteVersion;if(e===this.routeVersionSeen)return!1;this.routeVersionSeen=e;let t=this.store.edgeRoutes;this.routeOffsets.clear();let r=0;for(let[s,d]of t)this.routeOffsets.set(s,r),r+=Math.floor(d.length/Gt);let n=Math.max(1,Math.ceil(Math.sqrt(r))),i=new Float32Array(n*n*4);for(let[s,d]of t){let l=this.routeOffsets.get(s);i.set(d.subarray(0,Math.floor(d.length/Gt)*Gt),l*4)}let o=this.routeTexture;n===this.routeTextureSize?(o.image.data=i,o.needsUpdate=!0):(this.routeTexture=a.makeRouteTexture(i,n),this.routeTextureSize=n,o.dispose());for(let s of[this.material,this.arrowMaterial])s&&(s.uniforms.routeTexture.value=this.routeTexture,s.uniforms.routeTextureSize.value=this.routeTextureSize);return!0}repackCtrl(){let e=this.store.data.edges,t=this.store.edgeCount||0,r=this.geometry?.getAttribute("controlOffset");if(r){let i=r.array;for(let o=0;o<t;o++)this.packCtrl(i,o,e[o]?.id);this.uploads.markFull(r)}let n=this.arrowGeometry?.getAttribute("controlOffset");if(n){let i=n.array;for(let o=0;o<t;o++)this.packCtrl(i,o,e[o]?.id);this.uploads.markFull(n)}}applyDefaultShape(e){let t=this.material?.uniforms.defaultEdgeShape.value;this.material&&(this.material.uniforms.defaultEdgeShape.value=e),this.arrowMaterial&&(this.arrowMaterial.uniforms.defaultEdgeShape.value=e),t!==void 0&&t!==e&&(t===3||e===3)&&this.repackCtrl()}createEdgeMaterial(){this.material=new ie.ShaderMaterial({vertexShader:Tu,fragmentShader:Mu,uniforms:{positionTexture:{value:null},textureSize:{value:512},spaceSize:{value:1},resolution:{value:this.resolution},sizeAttenuation:{value:1},lineWidthScale:{value:this.config.lineWidth*.05},nodeSizeScale:{value:1},fixedSize:{value:0},mapMode:{value:0},mapDamping:{value:1},mapMaxGrowth:{value:4},maxScreenFraction:{value:.5},sphereRadius:{value:0},arrowLengthWorld:{value:this.config.hideArrows?0:1},globalUseDash:{value:0},globalDashArray:{value:.1},globalDashOffset:{value:0},globalDashRatio:{value:.5},defaultEdgeShape:{value:this.store.registry.resolveEdgeShapeId(this.config.edgeShape??"")},radialAxis:{value:this.config.radialAxis==="vertical"?1:this.config.radialAxis==="horizontal"?2:0},orthoCornerRadius:{value:.35},edgeSegments:{value:this.config.segments},routeTexture:{value:this.routeTexture},routeTextureSize:{value:this.routeTextureSize},visibility:{value:1},alphaTest:{value:.01},time:{value:0},flowSpeed:{value:1},flowColor:{value:new ie.Vector3(.2,1,.5)},u_hoverProgress:{value:0},u_hoverDimOpacity:{value:.15},u_hoverTime:{value:0},u_hoverDuration:{value:200}},transparent:!0,depthWrite:!1,depthTest:!0,premultipliedAlpha:!0,side:ie.DoubleSide})}createEdgeMesh(){!this.geometry||!this.material||(this.mesh=new ie.Mesh(this.geometry,this.material),this.mesh.frustumCulled=!1,this.mesh.name="GPUEdgeRenderer_edges",this.mesh.renderOrder=-1,this.scene.add(this.mesh))}createArrowGeometry(){let e=new ie.ConeGeometry(.8,4,10);if(e.applyMatrix4(new ie.Matrix4().makeTranslation(0,-2,0)),this.arrowGeometry=new ie.InstancedBufferGeometry,e.attributes&&e.attributes.position){let s=e.attributes.position;this.arrowGeometry.setAttribute("position",new ie.BufferAttribute(new Float32Array(s.array),s.itemSize))}if(e.attributes&&e.attributes.normal){let s=e.attributes.normal;this.arrowGeometry.setAttribute("normal",new ie.BufferAttribute(new Float32Array(s.array),s.itemSize))}if(e.index&&this.arrowGeometry.setIndex(new ie.BufferAttribute(new Uint16Array(e.index.array),1)),this.store.edgeCount===0){this.arrowGeometry.instanceCount=0;return}let t=this.store.edgeCount,r=this.store.index,n=this.store.edgeState,i=Math.max(this.store.edgeCapacity,t),o={src:new Float32Array(i),tgt:new Float32Array(i),color:new Float32Array(i*3),opacity:new Float32Array(i),scale:new Float32Array(i*3),rotation:new Float32Array(i),selected:new Float32Array(i),targetSize:new Float32Array(i*2),sourceSize:new Float32Array(i*2),ctrl:new Float32Array(i*3),hoverDim:new Float32Array(i)};this.arrowArrays=o;for(let s=0;s<t;s++)this.packArrowSlot(s,o);this.arrowGeometry.setAttribute("sourceIndex",new ie.InstancedBufferAttribute(o.src,1)),this.arrowGeometry.setAttribute("targetIndex",new ie.InstancedBufferAttribute(o.tgt,1)),this.arrowGeometry.setAttribute("arrowColor",new ie.InstancedBufferAttribute(o.color,3)),this.arrowGeometry.setAttribute("arrowOpacity",new ie.InstancedBufferAttribute(o.opacity,1)),this.arrowGeometry.setAttribute("arrowScale",new ie.InstancedBufferAttribute(o.scale,3)),this.arrowGeometry.setAttribute("arrowRotation",new ie.InstancedBufferAttribute(o.rotation,1)),this.arrowGeometry.setAttribute("targetSize",new ie.InstancedBufferAttribute(o.targetSize,2)),this.arrowGeometry.setAttribute("sourceSize",new ie.InstancedBufferAttribute(o.sourceSize,2)),this.arrowGeometry.setAttribute("controlOffset",new ie.InstancedBufferAttribute(o.ctrl,3)),this.arrowGeometry.setAttribute("edgeSelected",new ie.InstancedBufferAttribute(o.selected,1)),this.arrowGeometry.setAttribute("aHoverDim",new ie.InstancedBufferAttribute(o.hoverDim,1)),this.arrowGeometry.instanceCount=t}createArrowMaterial(){this.arrowMaterial=new ie.ShaderMaterial({vertexShader:Au,fragmentShader:_u,uniforms:{positionTexture:{value:null},textureSize:{value:512},spaceSize:{value:1},useCurve:{value:this.config.useCurve?1:0},resolution:{value:this.resolution},fixedSize:{value:0},nodeSizeScale:{value:1},mapMode:{value:0},mapDamping:{value:1},mapMaxGrowth:{value:4},maxScreenFraction:{value:.5},sphereRadius:{value:0},defaultEdgeShape:{value:this.store.registry.resolveEdgeShapeId(this.config.edgeShape??"")},radialAxis:{value:this.config.radialAxis==="vertical"?1:this.config.radialAxis==="horizontal"?2:0},routeTexture:{value:this.routeTexture},routeTextureSize:{value:this.routeTextureSize},u_hoverProgress:{value:0},u_hoverDimOpacity:{value:.15},u_hoverTime:{value:0},u_hoverDuration:{value:200}},transparent:!0,depthWrite:!1,depthTest:!0,side:ie.DoubleSide})}createArrowMesh(){!this.arrowGeometry||!this.arrowMaterial||(this.arrows=new ie.Mesh(this.arrowGeometry,this.arrowMaterial),this.arrows.frustumCulled=!1,this.arrows.name="GPUEdgeRenderer_arrows",this.arrows.renderOrder=0,this.scene.add(this.arrows))}update(e){if(!this.geometry||!this.material)return;let t=performance.now()/1e3;this.material.uniforms.time&&(this.material.uniforms.time.value=t);let r=this.store,n=r.edgeState;if(!n)return;if(this.material.uniforms.flowSpeed){this.material.uniforms.flowSpeed.value=n.flowSpeed??1;let o=n.flowColor,s=this.material.uniforms.flowColor.value;o?s.set(o[0],o[1],o[2]):s.set(.2,1,.5)}if(r.version===this.lastVersion&&!e)return;this.lastVersion=r.version;let i=e??r.updateStrategy.consumeDirty();if(this.syncRoutes()&&!i.has("edgeShapes")&&this.repackCtrl(),i.has("structure")||i.has("edgeStructure")){if(this.tryApplyStructureChanges()){this.updateDirtyAttributes(i),this.updateResolution(),this.syncStoreGlobals(),this.selfLoopCloud&&this.selfLoopCloud.update();return}this.rebuildGeometry(),this.updateResolution(),this.syncStoreGlobals(),this.selfLoopCloud&&this.selfLoopCloud.update();return}this.updateDirtyAttributes(i),this.updateResolution(),this.syncStoreGlobals(),this.selfLoopCloud&&this.selfLoopCloud.update()}tryApplyStructureChanges(){let e=this.store,t=this.lineArrays,r=this.arrowArrays,n=this.geometry,i=this.arrowGeometry,o=e.edgeCount,s=this.reader.read();if(!n||!i||!t||!r||o===0||e.edgeCapacity!==this.lastEdgeCapacity||o>t.src.length)return!1;if(!s)return!0;if(s.full)return!1;let d=e.index,l=e.data,u=[],c=[],h=new Set,p=new yn,f=Math.max(256,o>>4),m=this.hoverDimBits.length,g=this.hoverDimBits,y=this.hoverDimStarts,v=m>0;if(v){let S=Math.max(m,o);if(g.length<S){let P=new Uint8Array(S);P.set(g),g=P;let D=new Float32Array(S);D.set(y),y=D}}for(let S of s.edges.ops){if(S.op==="add"){c.push(S.id);continue}u.push(S.id),v&&(S.slot!==S.last&&(g[S.slot]=g[S.last],y[S.slot]=y[S.last]),g[S.last]=0,y[S.last]=0),S.movedId!==void 0&&h.add(S.movedId)}v&&(this.hoverDimBits=g.length===o?g:g.slice(0,o),this.hoverDimStarts=y.length===o?y:y.slice(0,o));let b=S=>d.edgeIdToIndex.get(S),x=[];for(let S of c){let P=b(S);if(P===void 0)continue;let D=l.edges[P];x.push({id:D.id,sourceId:D.source,targetId:D.target}),p.add(P,f)}let w=[];for(let S of h){let P=b(S);P!==void 0&&(w.push(S),p.add(P,f))}let T=this.edgeClassifier.applyChanges(u,x,w,b);for(let S of T){let P=b(S);P!==void 0&&p.add(P,f)}for(let S of s.nodes.ops){if(S.op!=="remove"||S.movedId===void 0)continue;let P=d.nodeIdToIndex.get(S.movedId);if(P!==void 0)for(let D of d.edgesOfNode(P))p.add(D,f)}if(this.store.hasEdgeAnchors&&s.nodes.ops.length>0)for(let S=0;S<o;S++){let P=l.edges[S]?.id;P!==void 0&&this.store.edgeAnchor(P)!==void 0&&p.add(S,f)}let I=p.freeze(o),R=0;if(I){if(I.kind==="all")for(let P=0;P<o;P++)this.packLineSlot(P,t),this.packArrowSlot(P,r);else I.forEach(P=>{P>=o||(this.packLineSlot(P,t),this.packArrowSlot(P,r))});let S=(P,D)=>{for(let E of D){let M=P.getAttribute(E);M&&(R+=this.uploads.markSlots(M,I))}};S(n,["sourceIndex","targetIndex","edgeColor","edgeWidth","edgeOpacity","edgeSelected","edgeHighlighted","controlOffset","nodeSizes","edgeFlags"]),S(i,["sourceIndex","targetIndex","arrowColor","arrowOpacity","arrowScale","arrowRotation","targetSize","sourceSize","controlOffset","edgeSelected","aHoverDim"])}return n.instanceCount=o,i.instanceCount=o,this.lastUploadedElements=R,!0}rebuildGeometry(){this.mesh&&(this.scene.remove(this.mesh),this.mesh=null),this.geometry&&(this.geometry.dispose(),this.geometry=null),this.arrows&&(this.scene.remove(this.arrows),this.arrows=null),this.arrowGeometry&&(this.arrowGeometry.dispose(),this.arrowGeometry=null),this.pendingSelectionNodes=new Set,this.createEdgeGeometry(),this.createEdgeMesh(),this.createArrowGeometry(),this.createArrowMesh(),this.arrows&&(this.arrows.visible=!this.config.hideArrows),this.updatePositionUniforms(),this.selfLoopCloud&&(this.selfLoopCloud.update(),this.positionProvider&&this.selfLoopCloud.setPositionProvider(this.positionProvider))}updateDirtyAttributes(e){if(!this.geometry)return;let t=!1;if(e.has("edgeColors")){let n=this.geometry.getAttribute("edgeColor");if(n){let i=this.store.edgeState,o=n.array,s=Math.min(o.length/3,(i?.colors?.length??0)/3);for(let d=0;d<s;d++)o[d*3]=i.colors[d*3],o[d*3+1]=i.colors[d*3+1],o[d*3+2]=i.colors[d*3+2];this.uploads.markFull(n)}if(this.arrowGeometry){let i=this.arrowGeometry.getAttribute("arrowColor");if(i){let o=this.store.edgeState,s=i.array,d=Math.min(s.length/3,(o?.colors?.length??0)/3);for(let l=0;l<d;l++)s[l*3]=o.colors[l*3],s[l*3+1]=o.colors[l*3+1],s[l*3+2]=o.colors[l*3+2];this.uploads.markFull(i)}}}if(e.has("edgeOpacities")||e.has("nodeHidden")){let n=this.store.edgeState,i=this.store.nodeState,o=this.store.index,s=o.edgeSourceIndices,d=o.edgeTargetIndices,l=c=>!!i&&(i.hidden[s[c]]>.5||i.hidden[d[c]]>.5),u=this.geometry.getAttribute("edgeOpacity");if(u&&n){let c=u.array,h=Math.min(c.length,n.opacities.length);for(let p=0;p<h;p++)c[p]=l(p)?0:n.opacities[p];this.uploads.markFull(u)}if(this.arrowGeometry){let c=this.arrowGeometry.getAttribute("arrowOpacity");if(c&&n){let h=c.array,p=Math.min(h.length,n.opacities.length);for(let f=0;f<p;f++)h[f]=l(f)?0:n.opacities[f];this.uploads.markFull(c)}}}if(e.has("edgeWidths")){let n=this.geometry.getAttribute("edgeWidth");if(n){let i=this.store.edgeState,o=n.array,s=Math.min(o.length,i?.widths?.length??0);for(let d=0;d<s;d++)o[d]=i.widths[d];this.uploads.markFull(n)}if(this.arrowGeometry){let i=this.arrowGeometry.getAttribute("arrowScale");if(i){let o=this.store.edgeState,s=this.store.edgeCount||0,d=i.array;for(let l=0;l<s;l++){let c=(o?.widths?o.widths[l]:this.config.lineWidth)*this.config.lineWidth*.008;d[l*3]=c*1.5,d[l*3+1]=.035,d[l*3+2]=c*1.5}this.uploads.markFull(i)}}}if(e.has("edgeTubeGlow")&&(t=!0),e.has("edgeDashed")&&(t=!0),e.has("edgeSelection")){let n=this.geometry.getAttribute("edgeSelected");if(n){let i=this.store.edgeState,o=this.store.edgeCount||0,s=n.array,d=this.store.index,l=this.store.data;for(let u=0;u<o;u++){let c=d.edgeSourceIndices[u],h=d.edgeTargetIndices[u];c===h?s[u]=0:s[u]=i?i.selected[u]:0}this.uploads.markFull(n)}if(this.arrowGeometry){let i=this.arrowGeometry.getAttribute("edgeSelected");if(i){let o=this.store.edgeState,s=this.store.edgeCount||0,d=i.array;for(let l=0;l<s;l++)d[l]=o?o.selected[l]:0;this.uploads.markFull(i)}}}let r=e.has("nodeHighlight")||e.has("nodeSizes")||e.has("nodeShapes");if(r||e.has("nodeSelection")){let n=this.pendingSelectionNodes;this.pendingSelectionNodes=new Set,!r&&n&&n.size>0&&this.updateNodeSizeSlots(n)||this.updateNodeSizeBuffers()}if(e.has("edgeShapes")&&this.repackCtrl(),(e.has("edgeFlow")||e.has("edgeGlow"))&&(t=!0),t){let n=this.geometry.getAttribute("edgeFlags");if(n){let i=this.store.edgeState,o=this.store.edgeCount||0,s=n.array,d=this.hoverDimStarts;for(let l=0;l<o;l++){let u=i?.dashed&&i.dashed[l]>0?1:0,c=i?.flow&&i.flow[l]>0?2:0,h=i?.glow&&i.glow[l]>0?4:0,p=i?.tubeGlow&&i.tubeGlow[l]>0?8:0;s[l]=u+c+h+p+(this.hoverDimBits[l]?16:0)+d[l]*32}this.uploads.markFull(n)}}}updateNodeSizeSlots(e){let t=this.lineArrays,r=this.arrowArrays,n=this.geometry,i=this.arrowGeometry,o=this.store.nodeState,s=this.store.edgeCount;if(!t||!r||!n||!i||!o||s>t.src.length)return!1;let d=this.store.index,l=new yn,u=Math.max(256,s>>4);for(let m of e)if(!(m>=o.selected.length))for(let g of d.edgesOfNode(m))g<s&&l.add(g,u);let c=l.freeze(s);if(!c)return!0;let h=m=>{this.packLineSlot(m,t),this.packArrowSlot(m,r)};if(c.kind==="all")for(let m=0;m<s;m++)h(m);else c.forEach(m=>{m<s&&h(m)});let p=0,f=(m,g)=>{for(let y of g){let v=m.getAttribute(y);v&&(p+=this.uploads.markSlots(v,c))}};return f(n,["nodeSizes"]),f(i,["sourceSize","targetSize"]),this.lastUploadedElements=p,!0}updateNodeSizeBuffers(){let e=this.store.nodeState;if(!e)return;this.store.refreshEffectiveSizes();let t=this.store.index,r=this.store.edgeCount||0;if(this.geometry){let i=this.geometry.getAttribute("nodeSizes");if(i){let o=i.array;for(let s=0;s<r;s++){let d=t.edgeSourceIndices[s],l=t.edgeTargetIndices[s],u=e.selected[d]>0||e.highlighted[d]>0?1.5:1,c=e.selected[l]>0||e.highlighted[l]>0?1.5:1;o[s*4]=(e.effectiveSizes[d]??10)*u,o[s*4+1]=(e.effectiveSizes[l]??10)*c,o[s*4+2]=this.endpointCode(d),o[s*4+3]=this.endpointCode(l)}this.uploads.markFull(i)}}(i=>{if(!i)return;let o=i.getAttribute("sourceSize"),s=i.getAttribute("targetSize");if(!(!o||!s)){for(let d=0;d<r;d++){let l=t.edgeSourceIndices[d],u=t.edgeTargetIndices[d],c=e.selected[l]>0||e.highlighted[l]>0?1.5:1,h=e.selected[u]>0||e.highlighted[u]>0?1.5:1;o.array[d*2]=(e.effectiveSizes[l]??10)*c,o.array[d*2+1]=this.endpointCode(l),s.array[d*2]=(e.effectiveSizes[u]??10)*h,s.array[d*2+1]=this.endpointCode(u)}this.uploads.markFull(o),this.uploads.markFull(s)}})(this.arrowGeometry)}updateResolution(){this.material&&(this.resolution.set(window.innerWidth||1,window.innerHeight||1),this.material.uniforms.resolution.value=this.resolution,this.arrowMaterial&&(this.arrowMaterial.uniforms.resolution.value=this.resolution))}syncStoreGlobals(){let e=this.store;this.arrows&&(this.arrows.visible=e.edgeArrowVisible),this.material&&(this.material.uniforms.arrowLengthWorld.value=e.edgeArrowVisible?1:0),this.material&&(this.material.uniforms.lineWidthScale.value=this.config.lineWidth*.05*e.edgeScale),e.defaultEdgeShape>=0&&this.applyDefaultShape(e.defaultEdgeShape),this.material&&(this.material.uniforms.orthoCornerRadius.value=e.edgeCornerRadius),e.edgeRoutingAxis>=0&&(this.material&&(this.material.uniforms.radialAxis.value=e.edgeRoutingAxis),this.arrowMaterial&&(this.arrowMaterial.uniforms.radialAxis.value=e.edgeRoutingAxis))}setPositionProvider(e){this.positionProvider=e,this.updatePositionUniforms(),this.selfLoopCloud&&this.selfLoopCloud.setPositionProvider(e)}updatePositionUniforms(){let e=this.positionProvider;if(!e)return;let t=null,r=512,n=1;e.mode==="gpu"&&(t=e.getPositionTexture(),r=e.getTextureSize(),n=e.getSpaceSize()),t&&(this.material&&(this.material.uniforms.positionTexture.value=t,this.material.uniforms.textureSize.value=r,this.material.uniforms.spaceSize.value=n),this.arrowMaterial&&(this.arrowMaterial.uniforms.positionTexture.value=t,this.arrowMaterial.uniforms.textureSize.value=r,this.arrowMaterial.uniforms.spaceSize.value=n),this.selfLoopCloud&&this.selfLoopCloud.setSharedPositionTexture(t,r,n))}setSharedPositionTexture(e,t,r){this.material&&(this.material.uniforms.positionTexture.value=e,this.material.uniforms.textureSize.value=t,this.material.uniforms.spaceSize.value=r),this.arrowMaterial&&(this.arrowMaterial.uniforms.positionTexture.value=e,this.arrowMaterial.uniforms.textureSize.value=t,this.arrowMaterial.uniforms.spaceSize.value=r),this.selfLoopCloud&&this.selfLoopCloud.setSharedPositionTexture(e,t,r)}setFixedSize(e){this.material&&(this.material.uniforms.fixedSize.value=e),this.arrowMaterial&&(this.arrowMaterial.uniforms.fixedSize.value=e)}setMapMode(e,t,r){let n=e?1:0,i=r??.3,o=e&&(t??0)>0;this.material&&(this.material.uniforms.mapMode.value=n,this.material.uniforms.mapDamping.value=i,this.material.depthTest=o?!1:!e),this.arrowMaterial&&(this.arrowMaterial.uniforms.mapMode.value=n,this.arrowMaterial.uniforms.mapDamping.value=i,this.arrowMaterial.depthTest=o?!1:!e)}setMapMaxGrowth(e){let t=e===1/0?-1:e;this.material&&(this.material.uniforms.mapMaxGrowth.value=t),this.arrowMaterial&&(this.arrowMaterial.uniforms.mapMaxGrowth.value=t)}setMaxScreenFraction(e){let t=e===1/0?-1:e;this.material&&(this.material.uniforms.maxScreenFraction.value=t),this.arrowMaterial&&(this.arrowMaterial.uniforms.maxScreenFraction.value=t)}setSphereRadius(e){this.material&&(this.material.uniforms.sphereRadius.value=e),this.arrowMaterial&&(this.arrowMaterial.uniforms.sphereRadius.value=e)}createSelfLoopPickingMesh(e){return this.selfLoopCloud?.createPickingMesh(e)??null}setLineWidth(e){this.config.lineWidth=e,this.material&&(this.material.uniforms.lineWidthScale.value=e*.05),this.syncArrowScalesToLineWidth(e)}setLineWidthScale(e){this.setLineWidth(e)}syncArrowScalesToLineWidth(e){if(!this.arrowGeometry)return;let t=this.arrowGeometry.getAttribute("arrowScale");if(!t)return;let r=this.store.edgeState,n=this.store.edgeCount||0,i=t.array;for(let o=0;o<n;o++){let d=(r?.widths?r.widths[o]:e)*e*.008;i[o*3]=d*1.5,i[o*3+1]=.035,i[o*3+2]=d*1.5}this.uploads.markFull(t)}setOpacity(e){}setArrowsVisible(e){this.config.hideArrows=!e,this.arrows&&(this.arrows.visible=e),this.material&&(this.material.uniforms.arrowLengthWorld.value=e?1:0)}setShowArrows(e){this.setArrowsVisible(e)}setDashEnabled(e){this.material&&(this.material.uniforms.globalUseDash.value=e?1:0)}setDashPattern(e,t,r,n){this.material&&(this.material.uniforms.globalUseDash.value=e?1:0,t!==void 0&&(this.material.uniforms.globalDashArray.value=t),r!==void 0&&(this.material.uniforms.globalDashOffset.value=r),n!==void 0&&(this.material.uniforms.globalDashRatio.value=n))}setEdgeShape(e){this.applyDefaultShape(this.store.registry.resolveEdgeShapeId(e))}setOrthoCornerRadius(e){this.material&&(this.material.uniforms.orthoCornerRadius.value=Math.min(Math.max(e,0),1))}setRadialAxis(e){let t=e==="vertical"?1:e==="horizontal"?2:0;this.material&&(this.material.uniforms.radialAxis.value=t),this.arrowMaterial&&(this.arrowMaterial.uniforms.radialAxis.value=t)}setResolution(e,t){this.resolution.set(e,t),this.material&&(this.material.uniforms.resolution.value=this.resolution),this.arrowMaterial&&(this.arrowMaterial.uniforms.resolution.value=this.resolution)}setTime(e){this.material&&(this.material.uniforms.time.value=e)}setNodeSizeScale(e){this.config.nodeSizeScale=e,this.store.setGlobalNodeSizeScale(e)}getMesh(){return this.mesh}getArrowMesh(){return this.arrows}getRenderParams(){let e=this.material?.uniforms;return{lineWidth:(e?.lineWidthScale.value??this.config.lineWidth*.05)/.05,arrowsEnabled:(e?.arrowLengthWorld?.value??0)>.5,defaultEdgeShape:e?.defaultEdgeShape?.value??0,fixedSize:(e?.fixedSize?.value??0)>.5}}getArrowGeometry(){return this.arrowGeometry}getGeometry(){return this.geometry}set3DMode(e){this.is3D!==e&&(this.is3D=e,this.rebuildGeometry())}getEdgeClassifier(){return this.edgeClassifier}reclassifyEdges(){if(!this.geometry)return;let e=this.store.data,t=e.edges.length,r=e.edges.map(s=>({id:s.id,sourceId:s.source,targetId:s.target}));this.edgeClassifier.classify(r);let n=this.geometry.getAttribute("controlOffset"),i=this.geometry.getAttribute("curvature"),o=this.geometry.getAttribute("planeRotation");if(!(!n||!i||!o)){for(let s=0;s<t;s++){let d=e.edges[s].id,l=this.edgeClassifier.getCurveParams(d,this.is3D);if(i.array[s]=l.curvature,o.array[s]=l.planeRotation,Math.abs(l.curvature)>.001||this.config.useCurve){let u=Math.abs(l.curvature)>.001?l.curvature:this.config.curveAmount;n.array[s*3]=u,n.array[s*3+1]=l.planeRotation,n.array[s*3+2]=0}else n.array[s*3]=0,n.array[s*3+1]=0,n.array[s*3+2]=0}if(this.uploads.markFull(n),this.uploads.markFull(i),this.uploads.markFull(o),this.arrowGeometry){let s=this.arrowGeometry.getAttribute("controlOffset");if(s){for(let d=0;d<t;d++){let l=e.edges[d].id,u=this.edgeClassifier.getCurveParams(l,this.is3D);if(Math.abs(u.curvature)>.001||this.config.useCurve){let c=Math.abs(u.curvature)>.001?u.curvature:this.config.curveAmount;s.array[d*3]=c,s.array[d*3+1]=u.planeRotation,s.array[d*3+2]=0}else s.array[d*3]=0,s.array[d*3+1]=0,s.array[d*3+2]=0}this.uploads.markFull(s)}}}}getSelfLoopCloud(){return this.selfLoopCloud}setHoverDimBit(e,t){if(e<0||e>=this.hoverDimBits.length)return;let r=this.hoverDimBits[e]?1:0;if(r===t)return;let n=performance.now(),i=this.material?.uniforms.u_hoverDuration?.value??this.arrowMaterial?.uniforms.u_hoverDuration?.value??500,o=kr(r,this.hoverDimStarts[e],t,i,n);if(this.hoverDimBits[e]=t,this.hoverDimStarts[e]=o,this.geometry){let s=this.geometry.getAttribute("edgeFlags");if(s){let d=s.array,l=d[e],u=l-Math.floor(l/32)*32,c=t?u<16?u+16:u:u>=16?u-16:u;d[e]=c+o*32,this.uploads.isFullPending(s)||Zr(s,e,1),s.needsUpdate=!0}}if(this.arrowGeometry){let s=this.arrowGeometry.getAttribute("aHoverDim");if(s){let d=s.array;d[e]=t+o*2,this.uploads.isFullPending(s)||Zr(s,e,1),s.needsUpdate=!0}}}setHoverUniform(e,t){if(this.material){let r=this.material.uniforms[e];r&&(r.value=t)}if(this.arrowMaterial){let r=this.arrowMaterial.uniforms[e];r&&(r.value=t)}}clearAllHoverDimBits(){let e=performance.now(),t=this.material?.uniforms.u_hoverDuration?.value??this.arrowMaterial?.uniforms.u_hoverDuration?.value??500;if(this.geometry){let r=this.geometry.getAttribute("edgeFlags");if(r){let n=r.array;for(let i=0;i<n.length;i++){let o=n[i]-Math.floor(n[i]/32)*32;if(o>=16){let s=kr(1,this.hoverDimStarts[i],0,t,e);if(this.hoverDimBits[i]=0,this.hoverDimStarts[i]=s,n[i]=o-16+s*32,this.arrowGeometry){let d=this.arrowGeometry.getAttribute("aHoverDim");d&&(d.array[i]=0+s*2)}}}if(this.uploads.markFull(r),this.arrowGeometry){let i=this.arrowGeometry.getAttribute("aHoverDim");i&&this.uploads.markFull(i)}}}}setTubeGlow(e,t){let r=this.store.edgeState;!r||e<0||e>=r.tubeGlow.length||(r.tubeGlow[e]=t,this.store.updateStrategy.markDirty("edgeTubeGlow"))}clearAllEmphasisGlow(){let e=this.store.edgeState;e&&(e.tubeGlow.fill(0),this.store.updateStrategy.markDirty("edgeTubeGlow"))}dispose(){this.reader.dispose(),this.unsubSelection(),this.mesh&&(this.scene.remove(this.mesh),this.mesh=null),this.geometry&&(this.geometry.dispose(),this.geometry=null),this.material&&(this.material.dispose(),this.material=null),this.arrows&&(this.scene.remove(this.arrows),this.arrows=null),this.arrowGeometry&&(this.arrowGeometry.dispose(),this.arrowGeometry=null),this.arrowMaterial&&(this.arrowMaterial.dispose(),this.arrowMaterial=null),this.routeTexture.dispose(),this.selfLoopCloud&&(this.selfLoopCloud.dispose(),this.selfLoopCloud=null)}};import*as qe from"three";var rh=`// modelViewMatrix, projectionMatrix, position are auto-injected by Three.js ShaderMaterial
11
+ // position.xy is used as corner offset [-1, 1]
12
+
13
+ attribute vec2 groupCenter;
14
+ attribute float groupRadius;
15
+ attribute vec4 groupColor;
16
+ attribute float strokeWidth;
17
+
18
+ uniform float DPR;
19
+
20
+ varying vec2 vLocalPos;
21
+ varying float vRadius;
22
+ varying vec4 vColor;
23
+ varying float vStrokeW;
24
+
25
+ void main() {
26
+ vec4 mvCenter = modelViewMatrix * vec4(groupCenter, 0.0, 1.0);
27
+
28
+ float expand = groupRadius * 1.1 + strokeWidth * 2.0;
29
+ vec2 offset = position.xy * expand;
30
+
31
+ vLocalPos = offset;
32
+ vRadius = groupRadius;
33
+ vColor = groupColor;
34
+ vStrokeW = strokeWidth;
35
+
36
+ gl_Position = projectionMatrix * (mvCenter + vec4(offset, 0.0, 0.0));
37
+ }
38
+ `;var nh=`varying vec2 vLocalPos;
39
+ varying float vRadius;
40
+ varying vec4 vColor;
41
+ varying float vStrokeW;
42
+
43
+ void main() {
44
+ float dist = length(vLocalPos);
45
+
46
+ // SDF ring: stroke only, no fill
47
+ float innerEdge = vRadius - vStrokeW;
48
+ // Tight smoothstep for crisp edges (0.05 world-unit transition)
49
+ float ringAlpha = smoothstep(innerEdge - 0.05, innerEdge, dist)
50
+ * (1.0 - smoothstep(vRadius, vRadius + 0.05, dist));
51
+
52
+ float totalA = vColor.a * 0.7 * ringAlpha;
53
+
54
+ if (totalA < 0.005) discard;
55
+
56
+ gl_FragColor = vec4(vColor.rgb, totalA);
57
+ }
58
+ `;var ro=256,Es=class{constructor(e){this.scene=e;this.instanceCount=0;this.centerBuffer=new Float32Array(ro*2),this.radiusBuffer=new Float32Array(ro),this.colorBuffer=new Float32Array(ro*4),this.strokeWidthBuffer=new Float32Array(ro),this.geometry=this.createGeometry(),this.material=new qe.ShaderMaterial({vertexShader:rh,fragmentShader:nh,uniforms:{DPR:{value:window.devicePixelRatio}},transparent:!0,depthWrite:!1,side:qe.DoubleSide}),this.mesh=new qe.Mesh(this.geometry,this.material),this.mesh.frustumCulled=!1,this.mesh.renderOrder=-1,this.scene.add(this.mesh)}createGeometry(){let e=new qe.InstancedBufferGeometry,t=new Float32Array([-1,-1,0,1,-1,0,1,1,0,-1,1,0]);return e.setAttribute("position",new qe.BufferAttribute(t,3)),e.setIndex(new qe.BufferAttribute(new Uint16Array([0,1,2,0,2,3]),1)),e.setAttribute("groupCenter",new qe.InstancedBufferAttribute(this.centerBuffer,2).setUsage(qe.DynamicDrawUsage)),e.setAttribute("groupRadius",new qe.InstancedBufferAttribute(this.radiusBuffer,1).setUsage(qe.DynamicDrawUsage)),e.setAttribute("groupColor",new qe.InstancedBufferAttribute(this.colorBuffer,4).setUsage(qe.DynamicDrawUsage)),e.setAttribute("strokeWidth",new qe.InstancedBufferAttribute(this.strokeWidthBuffer,1).setUsage(qe.DynamicDrawUsage)),e.instanceCount=0,e}update(e){let t=0;for(let[,r]of e){if(r.collapsed||t>=ro)continue;this.centerBuffer[t*2]=r.center.x,this.centerBuffer[t*2+1]=r.center.y,this.radiusBuffer[t]=r.radius;let n=new qe.Color(r.spec.color??"#888888"),i=r.spec.opacity??1;this.colorBuffer[t*4]=n.r,this.colorBuffer[t*4+1]=n.g,this.colorBuffer[t*4+2]=n.b,this.colorBuffer[t*4+3]=i,this.strokeWidthBuffer[t]=r.spec.strokeWidth??.05,t++}this.instanceCount=t,this.geometry.instanceCount=t,this.geometry.getAttribute("groupCenter").needsUpdate=!0,this.geometry.getAttribute("groupRadius").needsUpdate=!0,this.geometry.getAttribute("groupColor").needsUpdate=!0,this.geometry.getAttribute("strokeWidth").needsUpdate=!0}dispose(){this.scene.remove(this.mesh),this.geometry.dispose(),this.material.dispose()}};import*as Pt from"three";var Rs=class{constructor(e){this.scene=e;this.groups=new Map;this.sharedGeo=new Pt.SphereGeometry(1,24,16),this.sharedEdgesGeo=new Pt.EdgesGeometry(this.sharedGeo,1)}update(e){let t=new Set;for(let[r,n]of e){if(n.collapsed)continue;t.add(r);let i=this.groups.get(r);if(!i){let u=new Pt.LineBasicMaterial({color:n.spec.color??"#888888",transparent:!0,opacity:.35,depthWrite:!1}),c=new Pt.LineSegments(this.sharedEdgesGeo,u);c.frustumCulled=!1,c.renderOrder=-1;let h=new Pt.MeshBasicMaterial({color:n.spec.color??"#888888",transparent:!0,opacity:.05,side:Pt.BackSide,depthWrite:!1}),p=new Pt.Mesh(this.sharedGeo,h);p.frustumCulled=!1,p.renderOrder=-1,this.scene.add(c),this.scene.add(p),i={wireframe:c,fill:p},this.groups.set(r,i)}let{x:o,y:s,z:d}=n.center;i.wireframe.position.set(o,s,d),i.wireframe.scale.setScalar(n.radius),i.fill.position.set(o,s,d),i.fill.scale.setScalar(n.radius);let l=n.spec.color??"#888888";i.wireframe.material.color.set(l),i.wireframe.material.opacity=(n.spec.opacity??1)*.35,i.fill.material.color.set(l),i.fill.material.opacity=(n.spec.opacity??1)*.05}for(let[r,n]of this.groups)t.has(r)||(this.scene.remove(n.wireframe),this.scene.remove(n.fill),n.wireframe.material.dispose(),n.fill.material.dispose(),this.groups.delete(r))}dispose(){for(let[,e]of this.groups)this.scene.remove(e.wireframe),this.scene.remove(e.fill),e.wireframe.material.dispose(),e.fill.material.dispose();this.groups.clear(),this.sharedGeo.dispose(),this.sharedEdgesGeo.dispose()}};var Cs=class{constructor(){this.kind="webgl";this.supportsPrimitives=!0}createNodeRenderer(e,t,r={}){return new ys(e,t,r)}createEdgeRenderer(e,t,r={}){return new xs(e,t,r)}createGroupRingRenderer(e){return new Es(e)}createGroupSphereRenderer(e){return new Rs(e)}};var ws=class{constructor(){this.kind="webgpu";this.supportsPrimitives=!1}createNodeRenderer(){throw new En("createNodeRenderer")}createEdgeRenderer(){throw new En("createEdgeRenderer")}createGroupRingRenderer(){throw new En("createGroupRingRenderer")}createGroupSphereRenderer(){throw new En("createGroupSphereRenderer")}};var En=class extends Error{constructor(e){super(`WebGPU render backend: ${e} is not implemented yet`),this.name="WebGPUBackendNotReadyError"}};function no(a){switch(a){case"webgl":return new Cs;case"webgpu":return new ws;default:throw new RangeError(`createRenderBackend: unknown kind ${String(a)}`)}}var ih={nodePickingEnabled:!0,edgePickingEnabled:!0,dragEnabled:!0,hoverEnabled:!0,hoverDebounceMs:100,edgePickingAreaSize:15,backgroundColorIndices:[0,16777215,16119285]};import*as de from"three";function Ts(a,e){let t=Math.max(0,Math.min(a.x,e.width)),r=Math.max(0,Math.min(a.y,e.height)),n=Math.min(a.width-(t-a.x),e.width-t),i=Math.min(a.height-(r-a.y),e.height-r);return n<=0||i<=0?null:{x:t,y:r,width:n,height:i}}function oc(a,e,t,r,n,i,o){if(n<=0||i<=0)return null;let s=t||1,d=r||1,l=Math.max(0,Math.min(Math.round(a/s*n),n-1)),u=Math.max(0,Math.min(Math.round(e/d*i),i-1)),c=Math.floor(o/2),h=Math.max(0,l-c),p=Math.max(0,u-c),f=Math.min(o,n-h),m=Math.min(o,i-p);return f<=0||m<=0?null:{x:h,y:p,width:f,height:m}}import*as oh from"three";function sh(a){let e=()=>{let r=a.renderer.domElement;return!r||r.width<=0||r.height<=0?null:{width:r.width,height:r.height}},t=(r,n)=>{let i=a.getScene(r),o=a.getTarget(r),s=e();if(!i||!o||!s)return null;let d=Ts(n,s);if(!d)return null;o.setSize(s.width,s.height);let l=a.renderer.autoClear,u=a.renderer.getClearColor(new oh.Color).clone(),c=a.renderer.getClearAlpha();a.renderer.autoClear=!1,a.renderer.setClearColor(0,0),a.renderer.setRenderTarget(o),a.renderer.clear(!0,!0,!0),a.renderer.render(i,a.getCamera()),a.renderer.setRenderTarget(null),a.renderer.setClearColor(u,c),a.renderer.autoClear=l;let h=s.height-d.y-d.height,p=new Uint8Array(4*d.width*d.height),f=es();return a.renderer.readRenderTargetPixels(o,d.x,h,d.width,d.height,p),ts("picking",f),{data:rs(p,{width:d.width,height:d.height,bytesPerPixel:4,bytesPerRow:d.width*4,orientation:"bottom-left"}),width:d.width,height:d.height}};return{pathId:"webgl",orientation:"bottom-left",canReadSync:!0,getTargetSize:e,readSync:t,readAsync:(r,n)=>Promise.resolve(t(r,n)),dispose(){}}}var Ms=class{constructor(e=2){this.tolerancePx=e;this.entry=null}put(e,t,r,n){this.entry={x:e,y:t,signature:r,result:n}}peek(e,t,r){let n=this.entry;return!n||n.signature!==r||Math.abs(n.x-e)>this.tolerancePx||Math.abs(n.y-t)>this.tolerancePx?null:n.result}invalidate(){this.entry=null}};var Yg={node:15728639,edge:14680063};function Is(a,e){return a<0||a>Yg[e]?0:(e==="node"?1048576:2097152)+a}function sc(a,e){return a-(e==="node"?1048576:2097152)}function ti(a,e){let t=Is(a,e);return[(t>>16&255)/255,(t>>8&255)/255,(t&255)/255]}function ah(a){return a[0]<<16|a[1]<<8|a[2]}function dh(a,e,t,r){let n=(t*r+e)*4;return a[n]<<16|a[n+1]<<8|a[n+2]}function ac(a){let e=1/0;for(let t in a.attributes){let r=a.attributes[t];if(!r.isInstancedBufferAttribute)continue;let i=(r.meshPerAttribute??1)*r.count;i<e&&(e=i)}e!==1/0&&(a._maxInstanceCount=e)}var Ps=class{constructor(e,t,r,n={}){this.nodePickingMesh=null;this.nodePointPickingMaterial=null;this.edgePickingMaterial=null;this.edgePickingMesh=null;this.selfLoopPickingMesh=null;this.layerNodeHitMeshes=[];this.pickCache=new Ms(2);this.inflightPicks=new Map;this.pickSeq=0;this.webgpuPickingBackend=null;this.getActivePathId=()=>"webgl";this._disposed=!1;this._globeSphereRadius=0;this._debugMaterial=null;this.debugPicking=!1;this._cloudScene=null;this.decodeIdAt=dh;this.decodeId=ah;this.encodeId=ti;this.renderer=e,this.camera=t,this.store=r,this.config={...ih,...n},this.nodePickingScene=new de.Scene,this.edgePickingScene=new de.Scene,this.nodePickingTarget=new de.WebGLRenderTarget(1,1,{minFilter:de.NearestFilter,magFilter:de.NearestFilter,format:de.RGBAFormat,type:de.UnsignedByteType}),this.edgePickingTarget=new de.WebGLRenderTarget(1,1,{minFilter:de.NearestFilter,magFilter:de.NearestFilter,format:de.RGBAFormat,type:de.UnsignedByteType}),this.nodePickingMaterial=new de.ShaderMaterial({vertexShader:Iu,fragmentShader:Pu,uniforms:{positionTexture:{value:null},textureSize:{value:512},spaceSize:{value:1},useCircle:{value:1},fixedSize:{value:0},nodeSizeScale:{value:1},mapMode:{value:0},mapDamping:{value:1},mapMaxGrowth:{value:4},maxScreenFraction:{value:.5},pixelRatio:{value:window.devicePixelRatio||1},minPixelSize:{value:1.5},sphereRadius:{value:0},resolution:{value:new de.Vector2(1,1)}},transparent:!0,depthWrite:!1,depthTest:!1}),this.webglPickingBackend=sh({renderer:this.renderer,getCamera:()=>this.camera,getScene:i=>i==="node"?this.nodePickingScene:this.edgePickingScene,getTarget:i=>i==="node"?this.nodePickingTarget:this.edgePickingTarget})}setupNodePicking(e){if(!(e instanceof de.InstancedBufferGeometry)){this.setupNodePointPicking(e);return}if(this.nodePickingMesh&&!(this.nodePickingMesh instanceof de.Mesh)&&this.dropNodePickingMesh(),!this.nodePickingMesh){let i=new de.InstancedBufferGeometry;for(let o of Object.keys(e.attributes))i.setAttribute(o,e.getAttribute(o));e.index&&i.setIndex(e.index),i.setDrawRange(e.drawRange.start,e.drawRange.count),i.instanceCount=e.instanceCount??e.drawRange.count,this.addIdColorAttribute(i,"node"),ac(i),this.nodePickingMesh=new de.Mesh(i,this.nodePickingMaterial),this.nodePickingMesh.frustumCulled=!1,this.nodePickingScene.add(this.nodePickingMesh);return}let t=this.nodePickingMesh.geometry;for(let i of Object.keys(e.attributes))t.setAttribute(i,e.getAttribute(i));e.index?t.setIndex(e.index):t.setIndex(null),t.setDrawRange(e.drawRange.start,e.drawRange.count),t.instanceCount=e.instanceCount??e.drawRange.count;let r=e.getAttribute("nodeIndex")?.count??0,n=t.getAttribute("idColor");(!n||n.count!==r)&&this.addIdColorAttribute(t,"node"),ac(t)}setupNodePointPicking(e){this.nodePickingMesh&&!(this.nodePickingMesh instanceof de.Points)&&this.dropNodePickingMesh();let t=e.getAttribute("nodeIndex")?.count??0,r;if(this.nodePickingMesh)r=this.nodePickingMesh.geometry;else{r=new de.BufferGeometry;let i=new de.Points(r,this.pointPickingMaterial());i.frustumCulled=!1,this.nodePickingMesh=i,this.nodePickingScene.add(i)}for(let i of Object.keys(e.attributes))i!=="idColor"&&r.setAttribute(i,e.getAttribute(i));r.setDrawRange(e.drawRange.start,e.drawRange.count);let n=r.getAttribute("idColor");if(!n||n.count!==t){let i=new Uint8Array(t*3);for(let o=0;o<t;o++){let s=Is(o,"node");i[o*3]=s>>16&255,i[o*3+1]=s>>8&255,i[o*3+2]=s&255}r.setAttribute("idColor",new de.BufferAttribute(i,3,!0))}}pointPickingMaterial(){if(!this.nodePointPickingMaterial){let e=this.nodePickingMaterial.uniforms;if(!e.maxPointSize){let t=this.renderer.getContext(),r=t.getParameter(t.ALIASED_POINT_SIZE_RANGE);e.maxPointSize={value:r&&r[1]>0?r[1]:64}}this.nodePointPickingMaterial=new de.ShaderMaterial({vertexShader:this.nodePickingMaterial.vertexShader,fragmentShader:this.nodePickingMaterial.fragmentShader,uniforms:e,defines:{KV_POINT_PRIMITIVE:""},transparent:!0,depthWrite:!1,depthTest:!1})}return this.nodePointPickingMaterial}dropNodePickingMesh(){let e=this.nodePickingMesh;e&&(this.nodePickingScene.remove(e),e.geometry.dispose(),this.nodePickingMesh=null)}syncNodeDrawRange(e){if(!this.nodePickingMesh)return;if(this.nodePickingMesh instanceof de.Points){this.nodePickingMesh.geometry.setDrawRange(e.drawRange.start,e.drawRange.count);return}let t=this.nodePickingMesh.geometry;t.setDrawRange(e.drawRange.start,e.drawRange.count),t.instanceCount=e.instanceCount??e.drawRange.count,ac(t)}setupEdgePicking(e,t){this.edgePickingMesh&&this.edgePickingScene.remove(this.edgePickingMesh),this.edgePickingMaterial&&(this.edgePickingMaterial.dispose(),this.edgePickingMaterial=null),this.addIdColorForInstancedEdge(e);let r=t.vertexShader.replace("precision highp float;",`precision highp float;
59
+ #define PICKER 1.0`).replace("attribute float edgeHighlighted;","// attribute float edgeHighlighted; // removed for picking").replace("attribute float edgeOpacity;","// attribute float edgeOpacity; // removed for picking").replace("attribute vec3 edgeColor;",`attribute vec3 edgeColor;
60
+ attribute vec3 idColor;`).replace("void main() {",`float edgeHighlighted = 0.0;
61
+ float edgeOpacity = 1.0;
62
+ void main() {`).replace(" float baseWidth = edgeWidth * lineWidthScale;"," float baseWidth = max(edgeWidth * lineWidthScale * 2.0, 0.03);").replace(" vColor = vec4(edgeColor, edgeOpacity);"," vColor = vec4(idColor, 1.0);"),n={};for(let i in t.uniforms)n[i]=t.uniforms[i];this.edgePickingMaterial=new de.ShaderMaterial({vertexShader:r,fragmentShader:["precision highp float;","varying vec4 vColor;","void main() {"," gl_FragColor = vColor;"," if (gl_FragColor.a < 0.1) discard;","}"].join(`
63
+ `),uniforms:n,transparent:!0,depthWrite:!1,side:de.DoubleSide}),this.edgePickingMesh=new de.Mesh(e,this.edgePickingMaterial),this.edgePickingMesh.frustumCulled=!1,this.edgePickingScene.add(this.edgePickingMesh),this._globeSphereRadius>0&&(n.mapMode!==void 0&&(n.mapMode.value=1),n.sphereRadius!==void 0&&(n.sphereRadius.value=this._globeSphereRadius))}addSelfLoopPickingMesh(e){this.selfLoopPickingMesh=e,e.renderOrder=1,this.edgePickingScene.add(e)}addNodeHitMesh(e){this.layerNodeHitMeshes.indexOf(e)===-1&&(this.layerNodeHitMeshes.push(e),this.nodePickingScene.add(e),this.pickCache.invalidate())}removeNodeHitMesh(e){let t=this.layerNodeHitMeshes.indexOf(e);t!==-1&&(this.layerNodeHitMeshes.splice(t,1),this.nodePickingScene.remove(e),this.pickCache.invalidate())}encodeNodeId(e){return this.encodeId(e,"node")}addIdColorForInstancedEdge(e){let t=e.getAttribute("sourceIndex");if(!t)return;let r=t.count,n=new Float32Array(r*3);for(let i=0;i<r;i++){let[o,s,d]=this.encodeId(i,"edge");n[i*3]=o,n[i*3+1]=s,n[i*3+2]=d}e.setAttribute("idColor",new de.InstancedBufferAttribute(n,3))}addIdColorAttribute(e,t){let r=e.getAttribute("nodeIndex");if(!r)return;let n=r.count,i=new Float32Array(n*3);for(let o=0;o<n;o++){let[s,d,l]=this.encodeId(o,t);i[o*3]=s,i[o*3+1]=d,i[o*3+2]=l}e.setAttribute("idColor",new de.InstancedBufferAttribute(i,3))}updatePositionTexture(e,t,r){this.nodePickingMaterial.uniforms.positionTexture.value=e,this.nodePickingMaterial.uniforms.textureSize.value=t,this.nodePickingMaterial.uniforms.spaceSize.value=r,this.edgePickingMaterial&&(this.edgePickingMaterial.uniforms.positionTexture.value=e,this.edgePickingMaterial.uniforms.textureSize.value=t,this.edgePickingMaterial.uniforms.spaceSize.value=r)}setFixedSize(e){this.nodePickingMaterial.uniforms.fixedSize.value=e}setNodeSizeScale(e){this.store.setGlobalNodeSizeScale(e)}setMinPixelSize(e){this.nodePickingMaterial.uniforms.minPixelSize.value=eo(e)}setMapMode(e,t,r){let n=r??.3;this.nodePickingMaterial.uniforms.mapMode.value=e?1:0,this.nodePickingMaterial.uniforms.mapDamping.value=n,this._globeSphereRadius=e&&t?t:0,this.nodePickingMaterial.uniforms.sphereRadius.value=e?t??0:0,this.edgePickingMaterial&&(this.edgePickingMaterial.uniforms.mapMode!==void 0&&(this.edgePickingMaterial.uniforms.mapMode.value=e?1:0),this.edgePickingMaterial.uniforms.mapDamping!==void 0&&(this.edgePickingMaterial.uniforms.mapDamping.value=n),this.edgePickingMaterial.uniforms.sphereRadius!==void 0&&(this.edgePickingMaterial.uniforms.sphereRadius.value=e?t??0:0))}setMapMaxGrowth(e){if(!this.nodePickingMaterial)return;let t=e===1/0?-1:e;this.nodePickingMaterial.uniforms.mapMaxGrowth.value=t}setMaxScreenFraction(e){if(!this.nodePickingMaterial)return;let t=e===1/0?-1:e;this.nodePickingMaterial.uniforms.maxScreenFraction.value=t}setCloudScene(e){this._cloudScene=e}isNodeFrontFacing(e){if(this._globeSphereRadius<=0||!this._cloudScene)return!0;let t=this.store.positionProvider?.getPositions();if(!t||e*3+2>=t.length)return!0;let r=new de.Vector3(t[e*3],t[e*3+1],t[e*3+2]).normalize();r.applyQuaternion(this._cloudScene.quaternion);let n=new de.Vector3().copy(this.camera.position).sub(this._cloudScene.position).normalize();return r.dot(n)>0}pick(e,t){if(pl(),this.activePickingBackend().canReadSync){if(this.config.nodePickingEnabled&&this.hasNodePickSurface()){let i=this.pickNodes(e,t);if(i.picked)return i}if(this.config.edgePickingEnabled&&this.edgePickingMesh){let i=this.pickEdges(e,t);if(i.picked)return i}return this.createBackgroundResult(e,t)}let n=this.pickCache.peek(e,t,this.cacheSignature());return n||(this.pickAsyncInternal(e,t),this.createBackgroundResult(e,t))}pickAsync(e,t){return pl(),this.pickAsyncInternal(e,t)}pickAsyncInternal(e,t){let r=`${Math.round(e)}:${Math.round(t)}`,n=this.inflightPicks.get(r);if(n)return n;let i=++this.pickSeq,o=this.runPickAsync(e,t).catch(()=>this.createBackgroundResult(e,t)).then(s=>(i===this.pickSeq&&this.pickCache.put(e,t,this.cacheSignature(),s),s)).finally(()=>{this.inflightPicks.delete(r)});return this.inflightPicks.set(r,o),o}async runPickAsync(e,t){let r=this.activePickingBackend();if(this.config.nodePickingEnabled){let n=await this.readPickIndexAsync(r,"node",e,t,1);if(n!==null){let i=this.nodeResultFromIndex(n,e,t);if(i.picked)return i}}if(this.config.edgePickingEnabled&&(r.pathId!=="webgl"||this.edgePickingMesh)){let n=await this.readPickIndexAsync(r,"edge",e,t,this.config.edgePickingAreaSize);if(n!==null){let i=this.edgeResultFromIndex(n,e,t);if(i.picked)return i}}return this.createBackgroundResult(e,t)}async readPickIndexAsync(e,t,r,n,i){if(t==="node"){if(!this.hasNodePickSurface()&&e.pathId==="webgl")return null;e.pathId==="webgl"&&this.syncBeforeNodePick()}else this._cloudScene&&this.syncTransforms(this._cloudScene);let o=e.getTargetSize();if(!o)return null;let s=this.renderer.domElement,d=oc(r,n,s.clientWidth,s.clientHeight,o.width,o.height,i);if(!d)return null;let l=await e.readAsync(t,d);return l?i===1?this.decodeId(l.data):this.findPickedInArea(l.data,l.width):null}setPickingBackend(e,t){e==="webgpu"&&(this.webgpuPickingBackend=t,this.pickCache.invalidate(),this.pickSeq++)}setActivePathId(e){this.getActivePathId=e,this.pickCache.invalidate(),this.pickSeq++}cacheSignature(){let e=this.camera.matrixWorld.elements,t=this.store.changes.versionOf(hu)|0;for(let o=0;o<16;o++)t=Math.imul(t,31)+Math.round(e[o]*1e3)|0;let r=this._cloudScene;if(r){t=Math.imul(t,31)+Math.round(r.position.x*1e3)|0,t=Math.imul(t,31)+Math.round(r.position.y*1e3)|0,t=Math.imul(t,31)+Math.round(r.position.z*1e3)|0,t=Math.imul(t,31)+Math.round(r.scale.x*1e3)|0,t=Math.imul(t,31)+Math.round(r.scale.y*1e3)|0,t=Math.imul(t,31)+Math.round(r.scale.z*1e3)|0;let o=r.quaternion;t=Math.imul(t,31)+Math.round(o.x*1e5)|0,t=Math.imul(t,31)+Math.round(o.y*1e5)|0,t=Math.imul(t,31)+Math.round(o.z*1e5)|0,t=Math.imul(t,31)+Math.round(o.w*1e5)|0}let n=this.activePickingBackend().getTargetSize();n&&(t=Math.imul(t,31)+n.width|0,t=Math.imul(t,31)+n.height|0);let i=this.camera.zoom;return typeof i=="number"&&(t=Math.imul(t,31)+Math.round(i*1e3)|0),t=Math.imul(t,31)+(this.getActivePathId()==="webgpu"?1:0)|0,t}hasNodePickSurface(){return!!this.nodePickingMesh||this.layerNodeHitMeshes.length>0}pickNodes(e,t){return this.hasNodePickSurface()?(this.syncBeforeNodePick(),this.nodeResultFromIndex(this.readPickIndex("node",e,t,1),e,t)):this.createBackgroundResult(e,t)}pickEdges(e,t){return this.edgePickingMesh?(this._cloudScene&&this.syncTransforms(this._cloudScene),this.edgeResultFromIndex(this.readPickIndex("edge",e,t,this.config.edgePickingAreaSize),e,t)):this.createBackgroundResult(e,t)}syncBeforeNodePick(){this._cloudScene&&this.syncTransforms(this._cloudScene);let e=this.renderer.domElement;this.nodePickingMaterial.uniforms.resolution.value.set(e.clientWidth,e.clientHeight)}nodeResultFromIndex(e,t,r){if(!this.isPicked(e))return this.createBackgroundResult(t,r);let n=sc(e,"node");if(n<0)return this.createBackgroundResult(t,r);if(!this.isNodeFrontFacing(n))return this.createBackgroundResult(t,r);let i=this.store.index.getNodeId(n),o=i?this.store.data.nodes[n]:null;return{type:"node",index:n,nodeId:i||"",node:o,screenPosition:{x:t,y:r},ndcPosition:this.screenToNDC(t,r),picked:!0}}edgeResultFromIndex(e,t,r){if(!this.isPicked(e))return this.createBackgroundResult(t,r);let n=sc(e,"edge");if(n<0)return this.createBackgroundResult(t,r);if(this._globeSphereRadius>0&&this._cloudScene){let s=this.store.index.edgeSourceIndices[n],d=this.store.index.edgeTargetIndices[n];if(s!==void 0&&d!==void 0&&!this.isNodeFrontFacing(s)&&!this.isNodeFrontFacing(d))return this.createBackgroundResult(t,r)}let i=this.store.index.getEdgeId(n),o=i?this.store.data.edges[n]:null;return{type:"edge",index:n,edgeId:i||"",edge:o,screenPosition:{x:t,y:r},ndcPosition:this.screenToNDC(t,r),picked:!0}}readPickIndex(e,t,r,n){let i=this.activePickingBackend(),o=i.getTargetSize();if(!o)return 0;let s=this.renderer.domElement,d=oc(t,r,s.clientWidth,s.clientHeight,o.width,o.height,n);if(!d)return 0;let l=i.readSync(e,d);return l?n===1?this.decodeId(l.data):this.findPickedInArea(l.data,l.width):0}activePickingBackend(){return this.getActivePathId()==="webgpu"&&this.webgpuPickingBackend?this.webgpuPickingBackend:this.webglPickingBackend}findPickedInArea(e,t){let r=Math.floor(t/2),n=this.decodeIdAt(e,r,r,t);if(this.isPicked(n))return n;for(let i=1;i<=r;i++)for(let o=-i;o<=i;o++)for(let s=-i;s<=i;s++){if(Math.abs(o)!==i&&Math.abs(s)!==i)continue;let d=r+o,l=r+s;if(d<0||d>=t||l<0||l>=t)continue;let u=this.decodeIdAt(e,d,l,t);if(this.isPicked(u))return u}return 0}isPicked(e){return e!==0&&!this.config.backgroundColorIndices.includes(e)}screenToNDC(e,t){let r=this.renderer.domElement;return{x:e/r.clientWidth*2-1,y:-(t/r.clientHeight)*2+1}}createBackgroundResult(e,t){return{type:"background",index:-1,screenPosition:{x:e,y:t},ndcPosition:this.screenToNDC(e,t),picked:!1}}syncTransforms(e,t){if(this.nodePickingMesh&&e&&(this.nodePickingMesh.position.copy(e.position),this.nodePickingMesh.quaternion.copy(e.quaternion),this.nodePickingMesh.scale.copy(e.scale)),this.edgePickingMesh&&e&&(this.edgePickingMesh.position.copy(e.position),this.edgePickingMesh.quaternion.copy(e.quaternion),this.edgePickingMesh.scale.copy(e.scale)),this.selfLoopPickingMesh&&e&&(this.selfLoopPickingMesh.position.copy(e.position),this.selfLoopPickingMesh.quaternion.copy(e.quaternion),this.selfLoopPickingMesh.scale.copy(e.scale)),e)for(let r of this.layerNodeHitMeshes)r.position.copy(e.position),r.quaternion.copy(e.quaternion),r.scale.copy(e.scale)}renderDebugToScreen(){if(!this.debugPicking||!(this.nodePickingMesh instanceof de.Mesh))return;this._debugMaterial||(this._debugMaterial=new de.ShaderMaterial({vertexShader:this.nodePickingMaterial.vertexShader,fragmentShader:`
64
+ precision highp float;
65
+ varying vec3 vIdColor;
66
+ varying float vHidden;
67
+ varying vec2 vUv;
68
+ uniform float useCircle;
69
+ void main() {
70
+ if (vHidden > 0.5) discard;
71
+ if (useCircle > 0.5) {
72
+ if (length(vUv - vec2(0.5)) > 0.5) discard;
73
+ }
74
+ vec3 c = vIdColor * 255.0;
75
+ float idx = c.r * 65536.0 + c.g * 256.0 + c.b;
76
+ float h = fract(idx * 0.618033988749895);
77
+ vec3 rgb = clamp(abs(mod(h * 6.0 + vec3(0.0, 4.0, 2.0), 6.0) - 3.0) - 1.0, 0.0, 1.0);
78
+ rgb = 0.95 * mix(vec3(1.0), rgb, 0.85);
79
+ gl_FragColor = vec4(rgb, 1.0);
80
+ }
81
+ `,uniforms:this.nodePickingMaterial.uniforms,transparent:!0,depthWrite:!1,depthTest:!1}));let e=this.nodePickingMesh.material;this.nodePickingMesh.material=this._debugMaterial;let t=this.renderer.getClearColor(new de.Color).clone(),r=this.renderer.getClearAlpha(),n=this.renderer.autoClear;this.renderer.autoClear=!1,this.renderer.setClearColor(1118481,1),this.renderer.setRenderTarget(null),this.renderer.clear(!0,!0,!0),this.renderer.render(this.nodePickingScene,this.camera),this.edgePickingMesh&&this.renderer.render(this.edgePickingScene,this.camera),this.renderer.setClearColor(t,r),this.renderer.autoClear=n,this.nodePickingMesh.material=e}setCamera(e){this.camera=e}dispose(){if(!this._disposed){this._disposed=!0,this.nodePickingMesh&&(this.nodePickingScene.remove(this.nodePickingMesh),this.nodePickingMesh.geometry.dispose()),this.edgePickingMesh&&(this.edgePickingScene.remove(this.edgePickingMesh),this.edgePickingMesh.geometry.dispose());for(let e of this.layerNodeHitMeshes)this.nodePickingScene.remove(e);this.layerNodeHitMeshes.length=0,this.nodePickingMaterial.dispose(),this.nodePointPickingMaterial?.dispose(),this.edgePickingMaterial?.dispose(),this.webglPickingBackend.dispose(),this.nodePickingTarget.dispose(),this.edgePickingTarget.dispose(),this.pickCache.invalidate(),this.inflightPicks.clear(),this.webgpuPickingBackend=null}}},ph={TYPE_NODE:1048576,TYPE_EDGE:2097152,TYPE_MASK:15728640,INDEX_MASK:1048575,encodeId:(a,e)=>Is(a,e),decodeId:a=>{let e=a&15728640,t=a&1048575,r="unknown";return e===1048576?r="node":e===2097152&&(r="edge"),{type:r,index:t}}};import*as ht from"three";import*as it from"three";import*as Gr from"three";import Jg from"@mapbox/tiny-sdf";var Qg='system-ui, -apple-system, "PingFang SC", "Microsoft YaHei", "Segoe UI", Roboto, Helvetica, Arial, sans-serif',gh={localFontFamily:Qg,fontWeight:"normal",fontStyle:"normal",fontSize:48,sdfBuffer:6,sdfRadius:16,sdfCutoff:.25};var ri=class{constructor(e){this.glyphCache=new Map;this.shelfX=0;this.shelfY=0;this.shelfHeight=0;this.dirty=!1;this.config={...gh,...e},this.tinySDF=new Jg({fontSize:this.config.fontSize,buffer:this.config.sdfBuffer,radius:this.config.sdfRadius,cutoff:this.config.sdfCutoff,fontFamily:this.config.localFontFamily,fontWeight:this.config.fontWeight,fontStyle:this.config.fontStyle}),this.textureSize=512,this.textureData=new Uint8Array(this.textureSize*this.textureSize),this.atlas=this.createTexture(this.textureData,this.textureSize)}createTexture(e,t){let r=new Gr.DataTexture(e,t,t,Gr.RedFormat,Gr.UnsignedByteType);return r.minFilter=Gr.LinearFilter,r.magFilter=Gr.LinearFilter,r.generateMipmaps=!1,r.needsUpdate=!0,r}ensureGlyph(e){let t=this.glyphCache.get(e);if(t)return t.lastUsed=performance.now(),t;let r;try{r=this.tinySDF.draw(e),(!isFinite(r.width)||!isFinite(r.height)||r.width<=0||r.height<=0)&&(r={data:new Uint8ClampedArray(0),width:0,height:0,glyphWidth:0,glyphHeight:0,glyphTop:0,glyphLeft:0,glyphAdvance:this.config.fontSize*.5})}catch{r={data:new Uint8ClampedArray(0),width:0,height:0,glyphWidth:0,glyphHeight:0,glyphTop:0,glyphLeft:0,glyphAdvance:this.config.fontSize*.5}}let n=this.allocateRegion(Math.max(1,r.width),Math.max(1,r.height));r.width>0&&r.height>0&&this.writeGlyphData(n,r.data,r.width,r.height),this.atlas.needsUpdate=!0;let i={u0:n.x/this.textureSize,v0:n.y/this.textureSize,u1:(n.x+r.width)/this.textureSize,v1:(n.y+r.height)/this.textureSize,glyphWidth:r.glyphWidth,glyphHeight:r.glyphHeight,glyphTop:r.glyphTop,glyphLeft:r.glyphLeft,glyphAdvance:r.glyphAdvance,width:r.width,height:r.height,lastUsed:performance.now()};return this.glyphCache.set(e,i),i}ensureGlyphs(e){let t=[];for(let r of e)t.push(this.ensureGlyph(r));return t}allocateRegion(e,t){this.shelfX+e>this.textureSize&&(this.shelfY+=this.shelfHeight,this.shelfX=0,this.shelfHeight=0),this.shelfY+t>this.textureSize&&(this.textureSize<4096?this.expandTexture():this.evictOldGlyphs());let r={x:this.shelfX,y:this.shelfY,w:e,h:t};return this.shelfX+=e,this.shelfHeight=Math.max(this.shelfHeight,t),r}writeGlyphData(e,t,r,n){for(let i=0;i<n;i++)for(let o=0;o<r;o++){let s=i*r+o,d=(e.y+i)*this.textureSize+(e.x+o);d<this.textureData.length&&(this.textureData[d]=t[s])}}expandTexture(){let e=this.textureSize,t=Math.min(e*2,4096),r=new Uint8Array(t*t);for(let i=0;i<e;i++){let o=i*e,s=i*t;r.set(this.textureData.subarray(o,o+e),s)}let n=e/t;for(let i of this.glyphCache.values())i.u0*=n,i.v0*=n,i.u1*=n,i.v1*=n;this.textureData=r,this.textureSize=t,this.atlas.dispose(),this.atlas=this.createTexture(this.textureData,this.textureSize),this.dirty=!0}evictOldGlyphs(){let e=[...this.glyphCache.entries()].sort(([,r],[,n])=>r.lastUsed-n.lastUsed),t=Math.floor(e.length/2);for(let r=0;r<t;r++)this.glyphCache.delete(e[r][0]);this.rebuildAtlas()}rebuildAtlas(){this.textureData.fill(0),this.shelfX=0,this.shelfY=0,this.shelfHeight=0;for(let[e,t]of this.glyphCache){let r;try{r=this.tinySDF.draw(e),(!isFinite(r.width)||!isFinite(r.height)||r.width<=0||r.height<=0)&&(r={data:new Uint8ClampedArray(0),width:0,height:0,glyphWidth:0,glyphHeight:0,glyphTop:0,glyphLeft:0,glyphAdvance:this.config.fontSize*.5})}catch{r={data:new Uint8ClampedArray(0),width:0,height:0,glyphWidth:0,glyphHeight:0,glyphTop:0,glyphLeft:0,glyphAdvance:this.config.fontSize*.5}}let n=this.allocateRegion(Math.max(1,r.width),Math.max(1,r.height));r.width>0&&r.height>0&&this.writeGlyphData(n,r.data,r.width,r.height),t.u0=n.x/this.textureSize,t.v0=n.y/this.textureSize,t.u1=(n.x+r.width)/this.textureSize,t.v1=(n.y+r.height)/this.textureSize}this.atlas.needsUpdate=!0}getTexture(){return this.atlas}getFontSize(){return this.config.fontSize}getTextureSize(){return this.textureSize}getCacheSize(){return this.glyphCache.size}isDirty(){let e=this.dirty;return this.dirty=!1,e}dispose(){this.atlas.dispose(),this.glyphCache.clear(),this.textureData=new Uint8Array(0)}};var As=class{constructor(e){this.atlas=e}layout(e,t){let r=t||{},n=r.maxLength,i=r.textAlign||"left",o=r.letterSpacing||0,s=(r.scale??1)/this.atlas.getFontSize(),d=e;n!==void 0&&e.length>n&&(d=e.substring(0,n)+"...");let l=[],u=0,c=0,h=0;for(let f=0;f<d.length;f++){let m=d[f],g=this.atlas.ensureGlyph(m);if(m===" "){u+=g.glyphAdvance*s+o;continue}let y=u+g.glyphLeft*s,v=(g.width-g.glyphWidth)/2,b=(g.glyphTop+v)*s,x=g.width*s,w=g.height*s;l.push({entry:g,x:y,y:b,w:x,h:w}),u+=g.glyphAdvance*s+o,h=Math.max(h,w)}c=u,d.length>0&&(c-=o);let p=0;if(i==="center"?p=-c/2:i==="right"&&(p=-c),p!==0)for(let f of l)f.x+=p;return{glyphs:l,totalWidth:c,totalHeight:h,lineCount:1}}measureWidth(e,t){let r=(t??1)/this.atlas.getFontSize(),n=0;for(let i=0;i<e.length;i++){let o=e[i],s=this.atlas.ensureGlyph(o);n+=s.glyphAdvance*r}return n}};var fh=`/**
82
+ * SDF Text Vertex Shader
83
+ *
84
+ * Positions text glyph quads in 3D space relative to anchor positions.
85
+ * Supports per-glyph rotation (for edge labels that follow edge direction).
86
+ *
87
+ * Compatible with Three.js r116 (GLSL 100 / WebGL1+).
88
+ */
89
+
90
+ attribute vec3 anchorPosition;
91
+ attribute float aOpacity;
92
+ attribute float aRotation;
93
+ attribute vec3 aColor;
94
+ // Hover-neighbor-highlight packed \`target + start_ts * 2\` (see arrow.vert.glsl).
95
+ attribute float aHoverDim;
96
+
97
+ uniform float mapMode; // 1.0 = map mode (GPU damping), 0.0 = normal
98
+ uniform float mapDamping; // 0.0 = constant size, 1.0 = full perspective
99
+ uniform float mapMaxGrowth; // text growth cap; 0.75 \xD7 map.maxNodeGrowth, -1 = no cap
100
+ uniform float sphereRadius; // >0 = globe mode, enables back-face culling
101
+ // Hover-neighbor-highlight per-instance fade.
102
+ uniform float u_hoverTime;
103
+ uniform float u_hoverDuration;
104
+
105
+ varying vec2 vUv;
106
+ varying float vOpacity;
107
+ varying vec3 vColor;
108
+ varying float vHoverDim;
109
+
110
+ mat2 rotate2D(float angle) {
111
+ float c = cos(angle);
112
+ float s = sin(angle);
113
+ return mat2(c, s, -s, c);
114
+ }
115
+
116
+ void main() {
117
+ vUv = uv;
118
+ vOpacity = aOpacity;
119
+ vColor = aColor;
120
+ float _hoverTarget = mod(aHoverDim, 2.0);
121
+ float _hoverStart = floor(aHoverDim / 2.0);
122
+ float _hoverDiff = u_hoverTime - _hoverStart;
123
+ if (_hoverDiff < 0.0) _hoverDiff += 524288.0;
124
+ float _hoverT = _hoverStart < 0.5
125
+ ? 1.0
126
+ : clamp(_hoverDiff / max(u_hoverDuration, 1.0), 0.0, 1.0);
127
+ float _hoverEased = _hoverT < 0.5
128
+ ? 4.0 * _hoverT * _hoverT * _hoverT
129
+ : 1.0 - pow(-2.0 * _hoverT + 2.0, 3.0) / 2.0;
130
+ vHoverDim = mix(1.0 - _hoverTarget, _hoverTarget, _hoverEased);
131
+
132
+ // Apply rotation (for edge labels following edge direction)
133
+ vec2 rotatedPos = rotate2D(aRotation) * position.xy;
134
+
135
+ // No Y-flip needed: DataTexture uses flipY=false (v=0 at top),
136
+ // and glyph positions use OpenGL Y-up convention
137
+
138
+ // Transform: anchor in world space + glyph offset in view space.
139
+ // Map mode: multiply by viewZ to cancel perspective, giving constant screen size.
140
+ // The 0.2 factor controls text screen size (tunable).
141
+
142
+
143
+
144
+ vec4 mvAnchor = modelViewMatrix * vec4(anchorPosition, 1.0);
145
+
146
+ // Map mode: CPU uses normal perspective for glyph layout (nodeWorldRadius is constant
147
+ // in world space). The projection then gives 1/viewZ scaling. But nodes use damped
148
+ // scaling: 1/viewZ^\u03B1. To match, we multiply glyph offsets by (viewZ/refDepth)^(1-\u03B1),
149
+ // which converts the 1/viewZ perspective into 1/viewZ^\u03B1 after projection.
150
+ //
151
+ // Equivalent factored form: zoomScale = (viewDepth/refDepth) * growth, where
152
+ // growth = pow(refDepth/viewDepth, damping). This lets us cap \`growth\` at the
153
+ // SAME MAP_MAX_GROWTH as node.vert.glsl, so the label freezes in lockstep with
154
+ // the bubble at deep zoom \u2014 preventing text from spilling outside the bubble.
155
+ float zoomScale = 1.0;
156
+ if (mapMode > 0.5) {
157
+ float viewDepth = max(-mvAnchor.z, 0.001);
158
+ float refDepth = 10.0;
159
+ // Text uses a slightly SHALLOWER cap than node.vert.glsl. Both shaders
160
+ // share the same \`growth\` curve shape, but the same multiplier produces
161
+ // different on-screen sizes because text width scales with character count
162
+ // while node diameter does not \u2014 a full 4\xD7 cap on long labels like "Paris"
163
+ // makes them sprawl outside the bubble at deep zoom.
164
+ //
165
+ // The cap is 0.75 \xD7 map.maxNodeGrowth (BatchTextRenderer.setMapMaxGrowth),
166
+ // knee at half the cap \u2014 the same curve as kvMapGrowth. At the default
167
+ // maxNodeGrowth 4 that is the old hard-coded 3.0/1.5, bit for bit. It used
168
+ // to ignore maxNodeGrowth entirely: a host that tamed nodes to 1.5\xD7 still
169
+ // got 3\xD7 labels at street zoom, far larger than their nodes.
170
+ float raw = pow(refDepth / viewDepth, mapDamping);
171
+ float growth = raw;
172
+ if (mapMaxGrowth >= 0.0) {
173
+ float softKnee = mapMaxGrowth * 0.5;
174
+ float overflow = max(raw - softKnee, 0.0);
175
+ float A = mapMaxGrowth - softKnee;
176
+ growth = min(raw, softKnee) + (A * overflow) / (A + overflow);
177
+ }
178
+ zoomScale = (viewDepth / refDepth) * growth;
179
+ }
180
+
181
+ vec4 mvPos = mvAnchor + vec4(rotatedPos * zoomScale, 0.0, 0.0);
182
+
183
+ // Globe mode: hide text on the back side of the sphere (same logic as nodes).
184
+ // Compare the surface normal at the anchor (pointing outward from sphere center)
185
+ // with the camera-to-anchor direction. Negative dot = facing away \u2192 hide.
186
+ if (sphereRadius > 0.001) {
187
+ vec3 wN = normalize(mat3(modelMatrix) * normalize(anchorPosition));
188
+ vec3 wP = (modelMatrix * vec4(anchorPosition, 1.0)).xyz;
189
+ if (dot(wN, normalize(cameraPosition - wP)) < 0.0) {
190
+ vOpacity = 0.0;
191
+ }
192
+ }
193
+
194
+ gl_Position = projectionMatrix * mvPos;
195
+ }
196
+ `;var mh=`/**
197
+ * SDF Text Fragment Shader
198
+ *
199
+ * Renders text using Signed Distance Field data from a single-channel atlas.
200
+ * Uses fwidth() for automatic anti-aliasing that adapts to zoom level.
201
+ * Optional halo (outline) effect for improved readability.
202
+ *
203
+ * Compatible with Three.js r116 (GLSL 100 / WebGL1+).
204
+ * NOTE: Do NOT place #extension directives here; Three.js injects preamble before this code.
205
+ *
206
+ * TinySDF encoding: value = 255 - 255*(d/radius + cutoff)
207
+ * With cutoff=0.25: edge is at value=191/255\u22480.749 (not 0.5)
208
+ * SDF_EDGE_THRESHOLD = 1.0 - cutoff = 0.75
209
+ */
210
+
211
+ precision highp float;
212
+
213
+ uniform sampler2D uAtlas;
214
+ uniform vec3 uThemeColor;
215
+ uniform float uGlobalOpacity;
216
+
217
+ // Halo effect uniforms
218
+ uniform float uHaloWidth;
219
+ uniform vec3 uHaloColor;
220
+
221
+ // Hover-neighbor-highlight (mirrors node/edge fragment shaders).
222
+ uniform float u_hoverProgress;
223
+ uniform float u_hoverDimOpacity;
224
+
225
+ varying vec2 vUv;
226
+ varying float vOpacity;
227
+ varying vec3 vColor;
228
+ varying float vHoverDim;
229
+
230
+ // TinySDF edge threshold: 1.0 - cutoff (cutoff=0.25 by default)
231
+ const float SDF_EDGE = 0.75;
232
+
233
+ void main() {
234
+ // Sample SDF value from Luminance atlas
235
+ // WebGL1 LUMINANCE format: luminance replicated in R,G,B; alpha=1
236
+ float dist = texture2D(uAtlas, vUv).r;
237
+
238
+ // Adaptive anti-aliasing based on screen-space derivative
239
+ float fw = fwidth(dist);
240
+ float alpha = clamp((dist - SDF_EDGE) / max(fw, 0.001) + 0.5, 0.0, 1.0);
241
+
242
+ // Select color: per-label color if set, otherwise theme color
243
+ vec3 fillColor = (vColor.r + vColor.g + vColor.b) > 0.01 ? vColor : uThemeColor;
244
+
245
+ vec3 finalColor = fillColor;
246
+ float finalAlpha = alpha;
247
+
248
+ // Optional halo/outline effect
249
+ if (uHaloWidth > 0.0) {
250
+ float haloAlpha = clamp((dist - (SDF_EDGE - uHaloWidth)) / max(fw, 0.001) + 0.5, 0.0, 1.0);
251
+ finalColor = mix(uHaloColor, fillColor, alpha);
252
+ finalAlpha = haloAlpha;
253
+ }
254
+
255
+ // Apply hover-neighbor-highlight dim multiplier (mirrors node/edge final).
256
+ float hoverDimMul = mix(1.0, u_hoverDimOpacity, vHoverDim * u_hoverProgress);
257
+ gl_FragColor = vec4(finalColor, finalAlpha * vOpacity * uGlobalOpacity * hoverDimMul);
258
+
259
+ if (gl_FragColor.a < 0.01) discard;
260
+ }
261
+ `;var ni=class{constructor(e){this.idToVertexRange=new Map;this.idHoverEncoded=new Map;this.atlasManager=new ri(e),this.layoutEngine=new As(this.atlasManager),this.capacity=5e3,this.geometry=new it.BufferGeometry,this.allocateBuffers(this.capacity),this.material=new it.ShaderMaterial({uniforms:{uAtlas:{value:this.atlasManager.getTexture()},uThemeColor:{value:new it.Color(16777215)},uGlobalOpacity:{value:1},uHaloWidth:{value:0},uHaloColor:{value:new it.Color(0)},mapMode:{value:0},mapDamping:{value:.3},mapMaxGrowth:{value:3},sphereRadius:{value:0},u_hoverProgress:{value:0},u_hoverDimOpacity:{value:.15},u_hoverTime:{value:0},u_hoverDuration:{value:200}},vertexShader:fh,fragmentShader:mh,transparent:!0,depthWrite:!1,side:it.DoubleSide}),this.mesh=new it.Mesh(this.geometry,this.material),this.mesh.frustumCulled=!1,this.mesh.renderOrder=2,this.geometry.setDrawRange(0,0)}allocateBuffers(e){this.capacity=e;let t=e*4,r=e*6;this.positions=new Float32Array(t*3),this.uvs=new Float32Array(t*2),this.anchorPositions=new Float32Array(t*3),this.opacities=new Float32Array(t),this.rotations=new Float32Array(t),this.colors=new Float32Array(t*3),this.indices=new Uint32Array(r),this.hoverDims=new Float32Array(t),this.geometry.setAttribute("position",new it.BufferAttribute(this.positions,3)),this.geometry.setAttribute("uv",new it.BufferAttribute(this.uvs,2)),this.geometry.setAttribute("anchorPosition",new it.BufferAttribute(this.anchorPositions,3)),this.geometry.setAttribute("aOpacity",new it.BufferAttribute(this.opacities,1)),this.geometry.setAttribute("aRotation",new it.BufferAttribute(this.rotations,1)),this.geometry.setAttribute("aColor",new it.BufferAttribute(this.colors,3)),this.geometry.setAttribute("aHoverDim",new it.BufferAttribute(this.hoverDims,1)),this.geometry.setIndex(new it.BufferAttribute(this.indices,1))}ensureCapacity(e){if(e>this.capacity){let t=this.capacity*2;for(;t<e;)t*=2;this.allocateBuffers(t)}}setEntries(e){let t=0,r=[];for(let f of e){let m=this.layoutEngine.layout(f.text,{scale:f.scale});r.push(m),t+=m.glyphs.length}this.ensureCapacity(t),this.idToVertexRange.clear(),this.hoverDims.fill(0);let n=0,i=0;for(let f=0;f<e.length;f++){let m=e[f],g=r[f],y=n/3,v=m.anchorX,b=m.anchorY,x=m.anchorZ,w=m.opacity??1,T=m.rotation??0,I=m.color??[0,0,0],R=m.offsetX??0,S=m.offsetY??0,P=m.textAlign==="center"?-g.totalWidth/2:m.textAlign==="right"?-g.totalWidth:0,D=m.verticalAlign==="middle"?-g.totalHeight/2:m.verticalAlign==="top"?-g.totalHeight:0;for(let M of g.glyphs){let{entry:N,x:A,y:C,w:F,h:G}=M,L=A+R+P,V=C+S+D,B=n/3,K=L,oe=L+F,Q=V,$=V-G;this.positions[n]=K,this.positions[n+1]=$,this.positions[n+2]=0,this.uvs[B*2]=N.u0,this.uvs[B*2+1]=N.v1,this.positions[n+3]=K,this.positions[n+4]=Q,this.positions[n+5]=0,this.uvs[B*2+2]=N.u0,this.uvs[B*2+3]=N.v0,this.positions[n+6]=oe,this.positions[n+7]=Q,this.positions[n+8]=0,this.uvs[B*2+4]=N.u1,this.uvs[B*2+5]=N.v0,this.positions[n+9]=oe,this.positions[n+10]=$,this.positions[n+11]=0,this.uvs[B*2+6]=N.u1,this.uvs[B*2+7]=N.v1;for(let z=0;z<4;z++){let W=n+z*3,te=B+z;this.anchorPositions[W]=v,this.anchorPositions[W+1]=b,this.anchorPositions[W+2]=x,this.opacities[te]=w,this.rotations[te]=T,this.colors[W]=I[0],this.colors[W+1]=I[1],this.colors[W+2]=I[2]}this.indices[i]=B,this.indices[i+1]=B+1,this.indices[i+2]=B+2,this.indices[i+3]=B,this.indices[i+4]=B+2,this.indices[i+5]=B+3,n+=12,i+=6}let E=n/3;if(E>y){let M=this.idToVertexRange.get(m.id);M?(y<M.start&&(M.start=y),E>M.end&&(M.end=E)):this.idToVertexRange.set(m.id,{start:y,end:E});let N=this.idHoverEncoded.get(m.id);if(N!=null)for(let A=y;A<E;A++)this.hoverDims[A]=N}}this.geometry.setDrawRange(0,i);let o=this.geometry.getAttribute("position");o&&(o.needsUpdate=!0);let s=this.geometry.getAttribute("uv");s&&(s.needsUpdate=!0);let d=this.geometry.getAttribute("anchorPosition");d&&(d.needsUpdate=!0);let l=this.geometry.getAttribute("aOpacity");l&&(l.needsUpdate=!0);let u=this.geometry.getAttribute("aRotation");u&&(u.needsUpdate=!0);let c=this.geometry.getAttribute("aColor");c&&(c.needsUpdate=!0);let h=this.geometry.getAttribute("aHoverDim");h&&(h.needsUpdate=!0);let p=this.geometry.getIndex();p&&(p.needsUpdate=!0),this.material.uniforms.uAtlas.value=this.atlasManager.getTexture()}setHoverDimById(e,t){let r=this.idHoverEncoded.get(e),n=r!=null&&r%2>.5?1:0,i=r!=null?Math.floor(r/2):0,o=performance.now(),s=this.material.uniforms.u_hoverDuration?.value??500,d=kr(n,i,t,s,o),l=t+d*2;this.idHoverEncoded.set(e,l);let u=this.idToVertexRange.get(e);if(!u)return;let c=!1;for(let p=u.start;p<u.end;p++)this.hoverDims[p]!==l&&(this.hoverDims[p]=l,c=!0);if(!c)return;let h=this.geometry.getAttribute("aHoverDim");h&&(Zr(h,u.start,u.end-u.start),h.needsUpdate=!0)}clearAllHoverDim(){let e=performance.now(),t=this.material.uniforms.u_hoverDuration?.value??500,r=new Map;for(let[i,o]of this.idHoverEncoded){if((o%2>.5?1:0)===0){r.set(i,o);continue}let d=Math.floor(o/2),l=kr(1,d,0,t,e);r.set(i,0+l*2)}this.idHoverEncoded=r;for(let[i,o]of this.idHoverEncoded){let s=this.idToVertexRange.get(i);if(s)for(let d=s.start;d<s.end;d++)this.hoverDims[d]=o}let n=this.geometry.getAttribute("aHoverDim");n&&(ms(n,0,this.hoverDims.length),n.needsUpdate=!0)}setHoverUniform(e,t){let r=this.material.uniforms[e];r&&(r.value=t)}getMesh(){return this.mesh}getAtlasManager(){return this.atlasManager}setThemeColor(e){this.material.uniforms.uThemeColor.value.copy(e)}setGlobalOpacity(e){this.material.uniforms.uGlobalOpacity.value=e}setMapMaxGrowth(e){this.material.uniforms.mapMaxGrowth.value=ef(e)}setMapMode(e,t,r){this.material.uniforms.mapMode.value=e?1:0,this.material.uniforms.mapDamping.value=r??.3,t!==void 0?this.material.uniforms.sphereRadius.value=e?t:0:e||(this.material.uniforms.sphereRadius.value=0),this.material.depthTest=!e}dispose(){this.geometry.dispose(),this.material.dispose(),this.atlasManager&&"dispose"in this.atlasManager&&typeof this.atlasManager.dispose=="function"&&this.atlasManager.dispose()}};function ef(a){return a===1/0?-1:a*.75}var dc=class{constructor(e=1e-4){this._baseline=null;this._epsilon=e}update(e){let t=e.length,r=this._baseline;if(!r||r.length!==t){let i=new Float64Array(t);for(let o=0;o<t;o++)i[o]=e[o];return this._baseline=i,!0}let n=!1;for(let i=0;i<t;i++)if(!(Math.abs(e[i]-r[i])<=this._epsilon)){n=!0;break}if(n)for(let i=0;i<t;i++)r[i]=e[i];return n}reset(){this._baseline=null}},lc=class{constructor(e,t,r){this._nums=new Float64Array(0);this._strs=[];this._count=-1;this._numericStride=e,this._stringStride=t,this._write=r,this._scratchNums=new Float64Array(e),this._scratchStrs=new Array(t)}update(e){let t=e.length,r=this._numericStride,n=this._stringStride,i=!1;t!==this._count&&(i=!0,this._count=t,this._nums.length<t*r&&(this._nums=new Float64Array(t*r)),this._strs.length=t*n);let o=this._nums,s=this._strs,d=this._scratchNums,l=this._scratchStrs;for(let u=0;u<t;u++){this._write(e[u],d,l);let c=u*r,h=u*n;if(!i){for(let p=0;p<r;p++)if(o[c+p]!==d[p]){i=!0;break}if(!i){for(let p=0;p<n;p++)if(s[h+p]!==l[p]){i=!0;break}}}for(let p=0;p<r;p++)o[c+p]=d[p];for(let p=0;p<n;p++)s[h+p]=l[p]}return i}reset(){this._count=-1}},ii=class{constructor(e,t,r,n=1e-4){this._dirty=!0;this._view=new dc(n),this._items=new lc(e,t,r)}invalidate(){this._dirty=!0}shouldRecompute(e,t){let r=this._view.update(e),n=this._items.update(t);return this._dirty||r||n?(this._dirty=!1,!0):!1}};var yh=1.585;function cc(a,e,t=1,r=1,n=0,i=0){let o=a*.15,s=Math.max(a*t,n),d=Math.max(a*r,i);return{x:Math.max(s+o,e*.5),y:Math.max(d+o,e*.5)}}function vh(a,e,t,r){let n=Math.hypot(a,e);if(!(n>1e-9))return{rotation:0,offsetX:t,textAlign:"left"};let i=a/n,o=e/n,s=Math.hypot(t*i,r*o),d=Math.atan2(e,a);return i<-1e-6?{rotation:d>0?d-Math.PI:d+Math.PI,offsetX:-s,textAlign:"right"}:{rotation:d,offsetX:s,textAlign:"left"}}var tf={scale:1,maxLength:50,position:"right",color:16777215,lightColor:3355443,darkColor:16777215,autoCaption:!0,lodDistance:1,textScale:1},bh={left:1,center:2,right:3},rf={top:1,middle:2,baseline:3,bottom:4};function nf(a,e,t){e[0]=a.x,e[1]=a.y,e[2]=a.z,e[3]=a.opacity??1e30,e[4]=a.nodeSize??1e30,e[5]=a.angle??1e30,e[6]=a.textAlign?bh[a.textAlign]??1e30:0,e[7]=a.lineIndex??1e30,e[8]=a.lineCount??1e30,e[9]=a.sizeScale??1e30,e[10]=a.extentX??1e30,e[11]=a.extentY??1e30,e[12]=a.worldExtentX??1e30,e[13]=a.worldExtentY??1e30,t[0]=a.id,t[1]=a.text}var io=class{constructor(e,t,r,n={},i){this._visible=!0;this._isDarkTheme=!1;this._isMapMode=!1;this._mapDamping=0;this._maxPointSize=256;this.marginLeft=0;this.marginTop=0;this.radians=0;this.textAlign="left";this.verticalAlign="middle";this.anchorYOffset=!1;this.radial=!1;this.radialCenter=null;this._maxVisibleLabels=500;this._cullCache=new ii(14,2,nf);this._viewSigValues=[];if(this.store=e,this.scene=t,this.camera=r,this.renderer=i??null,this.config={...tf,...n},this._isDarkTheme=n.isDark!==void 0?n.isDark:!0,this.renderer)try{let o=this.renderer.getContext(),s=o.getParameter(o.ALIASED_POINT_SIZE_RANGE);s&&s[1]>0&&(this._maxPointSize=s[1])}catch{}this.batchRenderer=new ni(n.fontConfig),this.batchRenderer.setThemeColor(this.getTextColor()),this.scene.add(this.batchRenderer.getMesh()),this.setLabelPosition(this.config.position)}getTextColor(){let e=this._isDarkTheme?this.config.darkColor:this.config.lightColor;return new ht.Color(e)}setLabelPosition(e){switch(this.verticalAlign="middle",this.anchorYOffset=!1,this.radial=!1,e){case"left":this.marginLeft=-.05,this.marginTop=0,this.radians=0,this.textAlign="right";break;case"right":this.marginLeft=.05,this.marginTop=0,this.radians=0,this.textAlign="left";break;case"top":this.marginLeft=0,this.marginTop=.05,this.radians=0,this.textAlign="center",this.verticalAlign="baseline";break;case"topCenter":this.marginLeft=0,this.marginTop=.05,this.radians=0,this.textAlign="center",this.verticalAlign="baseline";break;case"bottom":this.marginLeft=0,this.marginTop=-.05,this.radians=0,this.textAlign="center",this.verticalAlign="top";break;case"bottomCenter":this.marginLeft=0,this.marginTop=-.05,this.radians=0,this.textAlign="center",this.verticalAlign="top";break;case"center":this.marginLeft=0,this.marginTop=0,this.radians=0,this.textAlign="center",this.verticalAlign="middle";break;case"vertical":this.marginLeft=0,this.marginTop=-.05,this.radians=-Math.PI/2,this.textAlign="left",this.verticalAlign="middle",this.anchorYOffset=!0;break;case"radial":this.marginLeft=.05,this.marginTop=0,this.radians=0,this.textAlign="left",this.radial=!0;break}}setRadialCenter(e){this.radialCenter=e?[e[0],e[1]]:null}boxCentre(e,t,r){let n=1/0,i=-1/0,o=1/0,s=-1/0;for(let d=0;d<e;d++){let l=t(d),u=r(d);l<n&&(n=l),l>i&&(i=l),u<o&&(o=u),u>s&&(s=u)}return n<=i?[(n+i)/2,(o+s)/2]:[0,0]}setFont(e,t){}setScale(e){this.config.scale=e}setTextScale(e){this.config.textScale=e}setNodeSizeScale(e){this.store.setGlobalNodeSizeScale(e)}setMaxLength(e){this.config.maxLength=e}switchTheme(e){this._isDarkTheme=e??!this._isDarkTheme,this.batchRenderer.setThemeColor(this.getTextColor())}setVisible(e){this._visible=e,this.batchRenderer.getMesh().visible=e}setMapMaxGrowth(e){this.batchRenderer.setMapMaxGrowth(e)}setMapMode(e,t,r){this._isMapMode=e,this._mapDamping=r??.3,this.batchRenderer.setMapMode(e,t,r)}get visible(){return this._visible}setMaxVisibleLabels(e){this._maxVisibleLabels=Math.max(1,e)}setHoverDimById(e,t){this.batchRenderer.setHoverDimById(e,t)}clearAllHoverDim(){this.batchRenderer.clearAllHoverDim()}setHoverUniform(e,t){this.batchRenderer.setHoverUniform(e,t)}_fillViewSignature(){let e=this._viewSigValues,t=0,r=this.scene.matrixWorld.elements;for(let o=0;o<16;o++)e[t++]=r[o];let n=this.camera.matrixWorldInverse.elements;for(let o=0;o<16;o++)e[t++]=n[o];let i=this.camera.projectionMatrix.elements;for(let o=0;o<16;o++)e[t++]=i[o];return e[t++]=this.camera.position.x,e[t++]=this.camera.position.y,e[t++]=this.camera.position.z,e[t++]=this.renderer?this.renderer.getPixelRatio():1,e[t++]=this.renderer?this.renderer.domElement.height:0,e[t++]=this.store?.globalNodeSizeScale??1,e[t++]=this.config.scale,e[t++]=this.config.textScale,e[t++]=this.config.maxLength,e[t++]=this.config.lodDistance,e[t++]=this._maxVisibleLabels,e[t++]=this._isMapMode?1:0,e[t++]=this.marginLeft,e[t++]=this.marginTop,e[t++]=this.radians,e[t++]=this.anchorYOffset?1:0,e[t++]=bh[this.textAlign]??0,e[t++]=rf[this.verticalAlign]??0,e[t++]=this.radial?1:0,e[t++]=this.radialCenter?this.radialCenter[0]:1e30,e[t++]=this.radialCenter?this.radialCenter[1]:1e30,e.length=t,e}updateTexts(e){if(!this._visible||!this._cullCache.shouldRecompute(this._fillViewSignature(),e))return;let t=this.config.scale,r=this.config.textScale,n=this.config.maxLength,i=this.camera.position.distanceTo(this.scene.position);if(!this._isMapMode){let R=5*this.config.lodDistance;if(i>R){this.batchRenderer.setEntries([]);return}}let o=2.6,s=800,d=3,l=this._maxPointSize,u=this.renderer?this.renderer.getPixelRatio():1,c=this.camera;if(c.isPerspectiveCamera&&c.projectionMatrix&&(o=c.projectionMatrix.elements[5],o>.01)){s=this.renderer?this.renderer.domElement.height:window.innerHeight||800;let R=new ht.Vector4(0,0,0,1);R.applyMatrix4(this.scene.matrixWorld),R.applyMatrix4(this.camera.matrixWorldInverse),d=Math.max(Math.abs(R.z),.001)}let h=null;if(c.isPerspectiveCamera){let S=new ht.Matrix4().multiplyMatrices(this.camera.matrixWorldInverse,this.scene.matrixWorld).elements;h=[S[2],S[6],S[10],S[14]]}let p=new ht.Frustum,f=new ht.Matrix4;f.multiplyMatrices(this.camera.projectionMatrix,this.camera.matrixWorldInverse);let m=f.clone().multiply(this.scene.matrixWorld);p.setFromProjectionMatrix(m);let g=new ht.Vector3().copy(this.camera.position),y=this.scene.matrixWorld.clone().invert();g.applyMatrix4(y);let v=new ht.Vector3,b=[];for(let R=0;R<e.length;R++){let S=e[R];if(!S.text||S.text.length===0||(v.set(S.x,S.y,S.z),!p.containsPoint(v)))continue;let P=S.x-g.x,D=S.y-g.y,E=S.z-g.z,M=P*P+D*D+E*E;b.push({item:S,dist:M})}let x=this._maxVisibleLabels,w;b.length>x?(b.sort((R,S)=>R.dist-S.dist),w=b.slice(0,x).map(R=>R.item)):w=b.map(R=>R.item);let T=this.radial?this.radialCenter??this.boxCentre(e.length,R=>e[R].x,R=>e[R].y):null,I=w.map((R,S)=>{let P=R.text;n>0&&P.length>n&&(P=P.substring(0,n)+"...");let E=(R.nodeSize||1)*50*u/(o*s),A=yh*(this.store?.globalNodeSizeScale??1)*50*u/(o*s)*t*r*(R.sizeScale??1),C=cc(E,A,R.extentX,R.extentY,R.worldExtentX,R.worldExtentY),F=T&&R.angle===void 0?vh(R.x-T[0],R.y-T[1],C.x,C.y):null,G=F?F.offsetX:this.marginLeft!==0?Math.sign(this.marginLeft)*C.x:0,L=this.marginTop!==0&&!this.anchorYOffset?Math.sign(this.marginTop)*C.y:0,V=R.lineIndex??0,B=R.lineCount??1,K=1.3,oe=0;if(B>1){let Q=K*A;this.verticalAlign==="middle"?oe=-V*Q+(B-1)*.5*Q:this.verticalAlign==="baseline"?oe=V*Q:oe=-V*Q}return{id:R.id??`node-text-${S}`,text:P,anchorX:R.x,anchorY:R.y+(this.anchorYOffset?Math.sign(this.marginTop)*C.y:0),anchorZ:R.z,opacity:R.opacity??1,rotation:R.angle??F?.rotation??this.radians,scale:A,offsetX:this.anchorYOffset?0:G,offsetY:(this.anchorYOffset?0:L)+oe,textAlign:R.textAlign??F?.textAlign??this.textAlign,verticalAlign:this.verticalAlign}});this.batchRenderer.setEntries(I)}updateFromBuffer(e){if(!this._visible)return;this._cullCache.invalidate();let{positions:t,nodeCount:r,textResolver:n,sizeResolver:i,hiddenResolver:o,opacityResolver:s,extentResolver:d}=e,l=this.config.scale,u=this.config.textScale,c=this.config.maxLength,h=this.camera.position.distanceTo(this.scene.position);if(!this._isMapMode){let A=5*this.config.lodDistance;if(h>A){this.batchRenderer.setEntries([]);return}}let p=2.6,f=800,m=3,g=this._maxPointSize,y=this.renderer?this.renderer.getPixelRatio():1,v=this.camera;if(v.isPerspectiveCamera&&v.projectionMatrix&&(p=v.projectionMatrix.elements[5],p>.01)){f=this.renderer?this.renderer.domElement.height:window.innerHeight||800;let A=new ht.Vector4(0,0,0,1);A.applyMatrix4(this.scene.matrixWorld),A.applyMatrix4(this.camera.matrixWorldInverse),m=Math.max(Math.abs(A.z),.001)}let b=null;if(v.isPerspectiveCamera){let C=new ht.Matrix4().multiplyMatrices(this.camera.matrixWorldInverse,this.scene.matrixWorld).elements;b=[C[2],C[6],C[10],C[14]]}let x=new ht.Frustum,w=new ht.Matrix4;w.multiplyMatrices(this.camera.projectionMatrix,this.camera.matrixWorldInverse);let T=w.clone().multiply(this.scene.matrixWorld);x.setFromProjectionMatrix(T);let I=new ht.Vector3().copy(this.camera.position),R=this.scene.matrixWorld.clone().invert();I.applyMatrix4(R);let S=new ht.Vector3,P=Math.min(r,Math.floor(t.length/3)),D=[];for(let A=0;A<P;A++){if(o&&o(A))continue;let C=t[A*3],F=t[A*3+1],G=t[A*3+2];if(S.set(C,F,G),!x.containsPoint(S))continue;let L=C-I.x,V=F-I.y,B=G-I.z,K=L*L+V*V+B*B;D.push({index:A,dist:K})}let E=this._maxVisibleLabels;D.length>E&&(D.sort((A,C)=>A.dist-C.dist),D.length=E);let M=this.radial?this.radialCenter??this.boxCentre(P,A=>o&&o(A)?NaN:t[A*3],A=>o&&o(A)?NaN:t[A*3+1]):null,N=[];for(let A=0;A<D.length;A++){let{index:C}=D[A],F=n(C);if(!F)continue;let G=c>0&&F.length>c?F.substring(0,c)+"...":F,L=t[C*3],V=t[C*3+1],B=t[C*3+2],oe=(i?i(C):1)*50*y/(p*f),z=yh*(this.store?.globalNodeSizeScale??1)*50*y/(p*f)*l*u,W=d?d(C):null,te=W?cc(oe,z,W[0],W[1],W[2],W[3]):cc(oe,z),Ne=M?vh(L-M[0],V-M[1],te.x,te.y):null,Pe=Ne?Ne.offsetX:this.marginLeft!==0?Math.sign(this.marginLeft)*te.x:0,Ve=this.marginTop!==0&&!this.anchorYOffset?Math.sign(this.marginTop)*te.y:0;N.push({id:`buf-${C}`,text:G,anchorX:L,anchorY:V+(this.anchorYOffset?Math.sign(this.marginTop)*te.y:0),anchorZ:B,opacity:s?s(C):1,rotation:Ne?Ne.rotation:this.radians,scale:z,offsetX:this.anchorYOffset?0:Pe,offsetY:this.anchorYOffset?0:Ve,textAlign:Ne?Ne.textAlign:this.textAlign,verticalAlign:this.verticalAlign})}this.batchRenderer.setEntries(N)}update(){}dispose(){this.scene.remove(this.batchRenderer.getMesh()),this.batchRenderer.dispose()}};function aS(a,e,t,r,n){return new io(a,e,t,r,n)}import{useEffect as Ht,useRef as oi}from"react";function of(a,e){if(e===void 0)return null;if(typeof e!="string")return[e[0],e[1]];let t=a.index?.getNodeIndex?.(e),r=a.positionProvider?.getPositions?.();return t===void 0||!r||t*3+1>=r.length?null:[r[t*3],r[t*3+1]]}function Eh({position:a="right",scale:e=1,maxLength:t=50,color:r,lightColor:n,darkColor:i,autoCaption:o=!0,lodDistance:s,isDark:d,theme:l,visible:u=!0,property:c,properties:h,maxVisibleLabels:p,getTextItems:f,textScale:m,radialCenter:g}){let y=dt(),{store:v,cloudScene:b,camera:x,renderer:w,invalidate:T,registerFrameCallback:I,registerMapModeCallback:R,registerMapMaxGrowthCallback:S,registerTextCloud:P}=y,D=_r(),E=pn(),M=gn(),{textScale:N}=Bi(),A=m??N,C=oi(null),F=oi([]),G=oi(-1),L=oi(-1),V=fn(),B=oi(g);B.current=g;let K=z=>z.setRadialCenter(of(v,B.current)),oe=oi({isMapMode:D,mapDamping:E});oe.current={isMapMode:D,mapDamping:E},Ht(()=>{let z={scale:e,maxLength:t,position:a,autoCaption:o,isDark:l?l==="dark":d!==void 0?d:M.isDark,textScale:A};r!==void 0&&(z.color=r),n!==void 0&&(z.lightColor=n),i!==void 0&&(z.darkColor=i),s!==void 0&&(z.lodDistance=s);let W=new io(v,b,x,z,w??void 0);C.current=W;let te=oe.current;return te.isMapMode&&W.setMapMode(!0,void 0,te.mapDamping),W.setMapMaxGrowth(y.api?.map.getMaxNodeGrowth()??4),P("node",W),T(),()=>{I("text-layer",null),P("node",null),W.dispose(),C.current=null}},[b,v,x,w]),Ht(()=>{C.current&&(C.current.setLabelPosition(a),T())},[a,T]);let Q=typeof g=="string"||g===void 0?g:`${g[0]},${g[1]}`;Ht(()=>{T()},[Q,T]),Ht(()=>{C.current&&(C.current.setScale(e),T())},[e,T]),Ht(()=>{C.current&&(C.current.setTextScale(A),T())},[A,T]),Ht(()=>{C.current&&(C.current.setMaxLength(t),T())},[t,T]),Ht(()=>{C.current&&(C.current.setVisible(u),T())},[u,T]),Ht(()=>{C.current&&p!==void 0&&(C.current.setMaxVisibleLabels(p),T())},[p,T]);let $=l?l==="dark":d!==void 0?d:M.isDark;return Ht(()=>{C.current&&(C.current.switchTheme($),T())},[$,T]),Ht(()=>(R("text-layer",(W,te,Ne)=>C.current?.setMapMode(W,te,Ne)),()=>R("text-layer",null)),[R]),Ht(()=>(S("text-layer",z=>C.current?.setMapMaxGrowth(z)),()=>S("text-layer",null)),[S]),Ht(()=>{C.current?.setMapMode(D,void 0,E)},[D,E]),Ht(()=>{let z=C.current;if(!z)return;let W=h&&h.length>0?h:void 0,te=W?void 0:c,Ne=v.data?.nodes?.length??0,Pe=v.visualMapper&&v.visualMapper.categoryConfigs.size>0;if(Ne>=1e4&&!f&&!W&&!Pe){let Oe=xh(v,te);Oe&&(K(z),z.updateFromBuffer(Oe)),T(),I("text-layer",()=>{if(C.current){let st=xh(v,te);st&&(K(C.current),C.current.updateFromBuffer(st))}})}else{let Oe;f?Oe=f(v,v.positionProvider??null):Oe=Sh(v,te,W,v.visualMapper),F.current=Oe,K(z),z.updateTexts(Oe),T(),G.current=v.version,L.current=v.labelVersion,I("text-layer",()=>{let st=C.current;if(!st)return;if(K(st),f){let Lr=f(v,v.positionProvider??null);F.current=Lr,st.updateTexts(Lr);return}if(!(v.version!==G.current||v.labelVersion!==L.current)&&sf(v,F.current)){st.updateTexts(F.current);return}let Bt=Sh(v,te,W,v.visualMapper);F.current=Bt,G.current=v.version,L.current=v.labelVersion,st.updateTexts(Bt)})}},[V,v,c,h,f,T,a,e,A,t,I]),null}var oo=[],Rn=0;function so(){if(Rn<oo.length)return oo[Rn++];let a={x:0,y:0,z:0,text:"",nodeSize:1,lineIndex:void 0,lineCount:void 0};return oo.push(a),Rn++,a}function Rh(a,e,t){let r=Math.min(e.length,20);for(let n=0;n<r;n++){let i=a.index?.getNodeIndex?.(e[n].id);if(i!==void 0&&Math.abs(t[i*3+2])>.01)return!1}return!0}function sf(a,e){if(e.length===0)return!1;let t=a.data?.nodes;if(!t||t.length===0)return!1;let r=a.positionProvider?.getPositions?.();if(!r||typeof a.index?.getNodeIndex!="function")return!1;let i=Rh(a,t,r);for(let o of e){if(o.id===void 0)return!1;let s=a.index.getNodeIndex(o.id);if(s===void 0)return!1;o.x=r[s*3],o.y=r[s*3+1],o.z=i?0:r[s*3+2]}return!0}function ao(a,e,t,r){let n=a.getNodeLabelExtent?.(t);if(!n){e.extentX=e.extentY=e.worldExtentX=e.worldExtentY=void 0;return}let i=a.nodeState?.suppressFill?.[r]===1?0:1;e.extentX=Math.max(i,n.nx),e.extentY=Math.max(i,n.ny),e.worldExtentX=n.wx,e.worldExtentY=n.wy}function Sh(a,e,t,r){let n=a.data?.nodes,i=a.positionProvider;if(!n||n.length===0)return[];let o=i?.getPositions?.();if(!o)return[];let s=Rh(a,n,o);if(r&&r.categoryConfigs.size>0)return af(a,r,n,o,s);Rn=0;let d=t&&t.length>0,l=d?t.length:1;for(let u=0;u<n.length;u++){let c=n[u],h=a.index?.getNodeIndex?.(c.id);if(h===void 0||a.nodeState?.hidden?.[h]===1)continue;let p=o[h*3],f=o[h*3+1],m=s?0:o[h*3+2],g=a.nodeState?.effectiveSizes?.[h]??a.nodeState?.sizes?.[h]??1,y=a.nodeState?.opacities?.[h]??1;if(d)for(let v=0;v<t.length;v++){let b=t[v],x=c.properties?.[b];if(x==null)continue;let w=String(x);if(!w)continue;let T=so();T.id=c.id,T.x=p,T.y=f,T.z=m,T.text=w,T.nodeSize=g,T.opacity=y,ao(a,T,c.id,h),T.angle=void 0,T.textAlign=void 0,T.lineIndex=v,T.lineCount=l}else{let v="";if(e&&c.properties?.[e]!=null?v=String(c.properties[e]):c.caption?v=c.caption:c.properties?.name?v=String(c.properties.name):c.properties?.label?v=String(c.properties.label):c.properties?.title&&(v=String(c.properties.title)),!v)continue;let b=so();b.id=c.id,b.x=p,b.y=f,b.z=m,b.text=v,b.nodeSize=g,b.opacity=y,ao(a,b,c.id,h),b.angle=void 0,b.textAlign=void 0,b.lineIndex=void 0,b.lineCount=void 0}}return oo.slice(0,Rn)}function af(a,e,t,r,n){Rn=0;for(let i=0;i<t.length;i++){let o=t[i],s=a.index?.getNodeIndex?.(o.id);if(s===void 0||a.nodeState?.hidden?.[s]===1)continue;let l=e.getCategoryConfig(o.category)?.captionConfig,u=r[s*3],c=r[s*3+1],h=n?0:r[s*3+2],p=a.nodeState?.effectiveSizes?.[s]??a.nodeState?.sizes?.[s]??1,f=a.nodeState?.opacities?.[s]??1,m=o.caption;if(m){let g=so();g.id=o.id,g.x=u,g.y=c,g.z=h,g.text=m,g.nodeSize=p,g.opacity=f,ao(a,g,o.id,s),g.angle=void 0,g.textAlign=void 0,g.lineIndex=void 0,g.lineCount=void 0;continue}if(l&&l.captions.length>0){let g=0,y=l.captions.length;for(let v of l.captions){let b=Ru(v,o);if(b===null)continue;let x=so();x.id=o.id,x.x=u,x.y=c,x.z=h,x.text=b,x.nodeSize=p,x.opacity=f,ao(a,x,o.id,s),x.angle=void 0,x.textAlign=void 0,x.lineIndex=g,x.lineCount=y,x.sizeScale=v.sizeScale,g++}}else{let g="";if(o.properties?.name?g=String(o.properties.name):o.properties?.label?g=String(o.properties.label):o.properties?.title&&(g=String(o.properties.title)),!g)continue;let y=so();y.id=o.id,y.x=u,y.y=c,y.z=h,y.text=g,y.nodeSize=p,y.opacity=f,ao(a,y,o.id,s),y.angle=void 0,y.textAlign=void 0,y.lineIndex=void 0,y.lineCount=void 0,y.sizeScale=void 0}}return oo.slice(0,Rn)}function xh(a,e){let t=a.data?.nodes,r=a.positionProvider?.getPositions?.();if(!t||t.length===0||!r)return null;let n=l=>{let u=t[l];return u?e&&u.properties?.[e]!=null?String(u.properties[e]):u.caption?u.caption:u.properties?.name?String(u.properties.name):u.properties?.label?String(u.properties.label):u.properties?.title?String(u.properties.title):null:null},i=l=>a.nodeState?.effectiveSizes?.[l]??a.nodeState?.sizes?.[l]??1,o=l=>a.nodeState?.hidden?.[l]===1,s=l=>a.nodeState?.opacities?.[l]??1,d=l=>{let u=t[l],c=u?a.getNodeLabelExtent?.(u.id):void 0;if(!c)return null;let h=a.nodeState?.suppressFill?.[l]===1?0:1;return[Math.max(h,c.nx),Math.max(h,c.ny),c.wx,c.wy]};return{positions:r,nodeCount:t.length,textResolver:n,sizeResolver:i,hiddenResolver:o,opacityResolver:s,extentResolver:d}}import*as Tt from"three";function df(a){let e=0;for(let i=1;i<a.length;i++)e+=a[i].distanceTo(a[i-1]);let t=e/2;for(let i=1;i<a.length;i++){let o=a[i-1],s=a[i],d=o.distanceTo(s);if(d>1e-9&&t<=d)return{point:o.clone().lerp(s,t/d),from:o,to:s};t-=d}let r=a[Math.max(0,a.length-2)],n=a[a.length-1];return{point:n.clone(),from:r,to:n}}var lf={scale:.9,showRelationshipName:!1,useCurve:!0};function cf(a,e,t){e[0]=a.x,e[1]=a.y,e[2]=a.z,e[3]=a.opacity??1e30,e[4]=a.angle??1e30,e[5]=a.curvature??1e30,e[6]=a.nodeSize??1e30;let r=a.sourcePosition;e[7]=r?r.x:1e30,e[8]=r?r.y:1e30,e[9]=r?r.z:1e30;let n=a.targetPosition;e[10]=n?n.x:1e30,e[11]=n?n.y:1e30,e[12]=n?n.z:1e30,t[0]=a.edgeId,t[1]=a.text}var lo=class{constructor(e,t,r,n={},i){this._visible=!0;this._isDarkTheme=!1;this._isMapMode=!1;this._mapDamping=0;this._maxPointSize=256;this._selfLoopOffset=1.5;this._cullCache=new ii(13,2,cf);this._viewSigValues=[];if(this.store=e,this.scene=t,this.camera=r,this.renderer=i??null,this.config={...lf,...n},this._isDarkTheme=n.isDark!==void 0?n.isDark:!0,this.renderer)try{let o=this.renderer.getContext(),s=o.getParameter(o.ALIASED_POINT_SIZE_RANGE);s&&s[1]>0&&(this._maxPointSize=s[1])}catch{}this.batchRenderer=new ni(n.fontConfig),this.batchRenderer.setThemeColor(this.getTextColor()),this.scene.add(this.batchRenderer.getMesh())}getTextColor(){let e=this._isDarkTheme?this.config.darkColor||16777215:this.config.lightColor||3355443;return new Tt.Color(e)}computePerp(e){let t=Math.abs(e.z)<.99?new Tt.Vector3(0,0,1):new Tt.Vector3(1,0,0);return new Tt.Vector3().crossVectors(e,t).normalize()}setSelfLoopOffset(e){this._selfLoopOffset=e}calculateEdgeCenter(e,t,r=0,n){let i=e.distanceTo(t);if(i<.001){let l=this._selfLoopOffset,u=this.camera;if(n!=null&&u.isPerspectiveCamera&&u.projectionMatrix){let c=u.projectionMatrix.elements[5];if(c>.01){let h=this.renderer?this.renderer.domElement.height:window.innerHeight||800,p=this.renderer?this.renderer.getPixelRatio():1;l=n*50*p/(c*h)*8}}return l===this._selfLoopOffset&&n!=null&&(l=n*.04),e.clone().add(new Tt.Vector3(0,l,0))}let o=new Tt.Vector3().addVectors(e,t).multiplyScalar(.5);if(Math.abs(r)<.001)return o;let s=new Tt.Vector3().subVectors(t,e).normalize(),d=o.clone().addScaledVector(this.computePerp(s),r*i);return new Tt.Vector3().addScaledVector(e,.25).addScaledVector(d,.5).addScaledVector(t,.25)}calculateEdgeAngle(e,t,r=0){if(e.distanceTo(t)<.001)return 0;let n=e.clone().applyMatrix4(this.scene.matrixWorld),i=t.clone().applyMatrix4(this.scene.matrixWorld),s=new Tt.Vector3().subVectors(i,n).transformDirection(this.camera.matrixWorldInverse),d=s.x,l=s.y;return d<0&&(d=-d,l=-l),Math.atan2(l,d)}setFont(e,t){}showRelationshipName(e){this.config.showRelationshipName=e}setUseCurve(e){this.config.useCurve=e}setScale(e){this.config.scale=e}setMaxLength(e){this.config.maxLength=e}setNodeSizeScale(e){this.store.setGlobalNodeSizeScale(e)}switchTheme(e){this._isDarkTheme=e??!this._isDarkTheme,this.batchRenderer.setThemeColor(this.getTextColor())}setVisible(e){this._visible=e,this.batchRenderer.getMesh().visible=e}setMapMaxGrowth(e){this.batchRenderer.setMapMaxGrowth(e)}setMapMode(e,t,r){this._isMapMode=e,this._mapDamping=r??.3,this.batchRenderer.setMapMode(e,t,r)}setHoverDimById(e,t){this.batchRenderer.setHoverDimById(e,t)}clearAllHoverDim(){this.batchRenderer.clearAllHoverDim()}setHoverUniform(e,t){this.batchRenderer.setHoverUniform(e,t)}get visible(){return this._visible}_fillViewSignature(){let e=this._viewSigValues,t=0,r=this.scene.matrixWorld.elements;for(let o=0;o<16;o++)e[t++]=r[o];let n=this.camera.matrixWorldInverse.elements;for(let o=0;o<16;o++)e[t++]=n[o];let i=this.camera.projectionMatrix.elements;for(let o=0;o<16;o++)e[t++]=i[o];return e[t++]=this.camera.position.x,e[t++]=this.camera.position.y,e[t++]=this.camera.position.z,e[t++]=this.renderer?this.renderer.getPixelRatio():1,e[t++]=this.renderer?this.renderer.domElement.height:0,e[t++]=this.config.scale||.9,e[t++]=this.config.maxLength||50,e[t++]=this._selfLoopOffset,e.length=t,e}updateTexts(e){if(!this._visible||!this._cullCache.shouldRecompute(this._fillViewSignature(),e))return;let t=this.config.scale||.9,r=this.config.maxLength||50,n=2.6,i=800,o=null,s=3,d=this.renderer?this.renderer.getPixelRatio():1,l=this.camera;if(l.isPerspectiveCamera&&l.projectionMatrix&&(n=l.projectionMatrix.elements[5],n>.01)){i=this.renderer?this.renderer.domElement.height:window.innerHeight||800;let h=new Tt.Vector4(0,0,0,1);h.applyMatrix4(this.scene.matrixWorld),h.applyMatrix4(this.camera.matrixWorldInverse),s=Math.max(Math.abs(h.z),.001);let f=new Tt.Matrix4().multiplyMatrices(this.camera.matrixWorldInverse,this.scene.matrixWorld).elements;o=[f[2],f[6],f[10],f[14]]}let u=this._maxPointSize,c=e.filter(h=>h.text&&h.text.length>0).map((h,p)=>{let f=h.text;r>0&&f.length>r&&(f=f.substring(0,r)+"...");let m=h.x,g=h.y,y=h.z,v=h.angle??0;if(h.path&&h.path.length>=2){let T=df(h.path);m=T.point.x,g=T.point.y,y=T.point.z,v=this.calculateEdgeAngle(T.from,T.to)}else if(h.sourcePosition&&h.targetPosition){let I=h.sourcePosition.distanceTo(h.targetPosition)<.001?0:h.curvature??0,R=this.calculateEdgeCenter(h.sourcePosition,h.targetPosition,I,h.nodeSize);m=R.x,g=R.y,y=R.z,v=this.calculateEdgeAngle(h.sourcePosition,h.targetPosition,I)}let w=(h.nodeSize||1)*50*d/(n*i)*t;return{id:`edge-text-${h.edgeId||p}`,text:f,anchorX:m,anchorY:g,anchorZ:y,opacity:h.opacity??1,rotation:v,scale:w,textAlign:"center",offsetX:0,offsetY:0}});this.batchRenderer.setEntries(c)}update(){}dispose(){this.scene.remove(this.batchRenderer.getMesh()),this.batchRenderer.dispose()}};function mS(a,e,t,r){return new lo(a,e,t,r)}import{useEffect as er,useRef as uc}from"react";import*as _s from"three";function hc({scale:a=.9,maxLength:e=50,showRelationshipName:t=!1,useCurve:r=!0,isDark:n,theme:i,visible:o=!0,property:s,getTextItems:d,textScale:l}){let u=dt(),{store:c,cloudScene:h,camera:p,renderer:f,invalidate:m,registerFrameCallback:g,registerMapModeCallback:y,registerMapMaxGrowthCallback:v,registerTextCloud:b}=u,x=_r(),w=pn(),T=gn(),{edgeTextScale:I}=Bi(),R=l??I,S=uc(null),P=fn(),D=uc([]),E=uc({isMapMode:x,mapDamping:w});E.current={isMapMode:x,mapDamping:w},er(()=>{if(!f)return;let N={scale:a*R,maxLength:e,showRelationshipName:t,useCurve:r,isDark:i?i==="dark":n!==void 0?n:T.isDark},A=new lo(c,h,p,N,f);S.current=A;let C=E.current;return C.isMapMode&&A.setMapMode(!0,void 0,C.mapDamping),A.setMapMaxGrowth(u.api?.map.getMaxNodeGrowth()??4),b("edge",A),m(),()=>{g("edge-text-layer",null),b("edge",null),A.dispose(),S.current=null}},[h,c,p,f]),er(()=>{S.current&&(S.current.setScale(a*R),m())},[a,R,m]),er(()=>{S.current&&(S.current.setMaxLength(e),m())},[e,m]),er(()=>{S.current&&(S.current.showRelationshipName(t),m())},[t,m]),er(()=>{S.current&&(S.current.setUseCurve(r),m())},[r,m]),er(()=>{S.current&&(S.current.setVisible(o),m())},[o,m]);let M=i?i==="dark":n!==void 0?n:T.isDark;return er(()=>{S.current&&(S.current.switchTheme(M),m())},[M,m]),er(()=>(y("edge-text-layer",(A,C,F)=>S.current?.setMapMode(A,C,F)),()=>y("edge-text-layer",null)),[y]),er(()=>(v("edge-text-layer",N=>S.current?.setMapMaxGrowth(N)),()=>v("edge-text-layer",null)),[v]),er(()=>{S.current?.setMapMode(x,void 0,w)},[x,w]),er(()=>{let N=S.current;if(!N)return;let A;d?A=d(c,c.positionProvider??null):A=uf(c,s,t,x),D.current=A,N.updateTexts(A),m(),g("edge-text-layer",()=>{S.current&&D.current.length>0&&S.current.updateTexts(D.current)})},[P,c,s,t,d,x,m,g]),null}function uf(a,e,t,r=!1){let n=a.data?.edges,i=a.positionProvider;if(!n||n.length===0)return[];let o=i?.getPositions?.();if(!o)return[];let s=null,d=()=>s||(s=new $r,r&&s.setBaseCurvature(0),s.classify(n.map(m=>({id:m.id,sourceId:m.source,targetId:m.target}))),s),l=new Map,u=a.edgeState,c=typeof a.defaultEdgeShape=="number"&&a.defaultEdgeShape>=0?a.defaultEdgeShape:0,h=typeof a.edgeRoutingAxis=="number"&&a.edgeRoutingAxis>=0?a.edgeRoutingAxis:0,p=typeof a.edgeCornerRadius=="number"?a.edgeCornerRadius:.35,f=[];for(let m=0;m<n.length;m++){let g=n[m],y="";if(e&&g.properties?.[e]!=null)y=String(g.properties[e]);else if(t&&g.relationship)y=g.relationship;else{let N=l.get(g.relationship);N===void 0&&!l.has(g.relationship)&&(N=a.visualMapper?.getRelationshipConfig?.(g.relationship),l.set(g.relationship,N));let A=N?.captionConfig?.captions;if(A&&A.length>0){let C=[];for(let F of A){let G="";if(F.source.startsWith("property:")){let L=F.source.slice(9),V=g.properties?.[L];V!=null&&(G=String(V))}else F.source==="relationship"?G=g.relationship??"":F.source==="id"&&(G=g.id??"");(G||F.whenEmpty==="blank")&&C.push(G)}y=C.join(" | ")}else g.caption&&(y=g.caption)}if(!y)continue;let v=a.index?.getEdgeIndex?.(g.id);if(v!==void 0&&a.edgeState?.opacities?.[v]===0)continue;let b=a.index?.getNodeIndex?.(g.source),x=a.index?.getNodeIndex?.(g.target);if(b!==void 0&&a.nodeState?.hidden?.[b]===1||x!==void 0&&a.nodeState?.hidden?.[x]===1)continue;let w=a.index?.getNodeIndex?.(g.source),T=a.index?.getNodeIndex?.(g.target);if(w===void 0||T===void 0)continue;let I=new _s.Vector3(o[w*3],o[w*3+1],o[w*3+2]),R=new _s.Vector3(o[T*3],o[T*3+1],o[T*3+2]),S=d().getCurveParams(g.id).curvature,P=v!==void 0&&u?.shapes?u.shapes[v]:-1,D=P>=0?P:S!==0&&c!==3?1:c,E;if(D>=3&&g.source!==g.target){let N=v!==void 0&&u?.bends?u.bends[v]:NaN,A=null;if(D===to){let C=a.edgeAnchor?.(g.id),F=C===void 0?void 0:a.index?.getNodeIndex?.(C);F!==void 0&&(A=[o[F*3],o[F*3+1],o[F*3+2]])}E=eh([I.x,I.y,I.z],[R.x,R.y,R.z],{shape:D,bend:N,curvature:S,axis:h,radius:p,segments:20,anchor:A,route:a.edgeRoute?.(g.id)??null})?.map(C=>new _s.Vector3(C[0],C[1],C[2]))}let M=a.nodeState?.effectiveSizes?.[w]??a.nodeState?.sizes?.[w]??1;f.push({x:0,y:0,z:0,text:y,edgeId:g.id,sourcePosition:I,targetPosition:R,curvature:S,path:E,nodeSize:M,opacity:v!==void 0?a.edgeState?.opacities?.[v]??1:1})}return f}import{useEffect as Ch,useRef as pc}from"react";import*as mr from"three";var Ds=class{constructor(e){this.scene=e;this.sprites=new Map}update(e){let t=new Set;for(let[r,n]of e){if(n.spec.labelVisible===!1||n.collapsed)continue;t.add(r);let i=this.sprites.get(r),o=n.spec.name;i?this.updateLabelTexture(i,o,n.spec.color??"#666666"):(i=this.createLabelSprite(o,n.spec.color??"#666666"),i.renderOrder=3,this.scene.add(i),this.sprites.set(r,i));let s=-(n.radius+.5);i.position.set(n.center.x,n.center.y+s,n.center.z)}for(let[r,n]of this.sprites)t.has(r)||(this.scene.remove(n),n.material.map?.dispose(),n.material.dispose(),this.sprites.delete(r))}createLabelSprite(e,t){let r=document.createElement("canvas"),n=r.getContext("2d"),i=28;n.font=`bold ${i}px sans-serif`;let o=n.measureText(e),s=Math.ceil(o.width)+16,d=i+12;r.width=s,r.height=d,n.font=`bold ${i}px sans-serif`,n.fillStyle=t,n.textAlign="center",n.textBaseline="middle",n.fillText(e,s/2,d/2);let l=new mr.CanvasTexture(r);l.minFilter=mr.LinearFilter;let u=new mr.SpriteMaterial({map:l,transparent:!0,depthWrite:!1}),c=new mr.Sprite(u),h=.025;return c.scale.set(s*h,d*h,1),c}updateLabelTexture(e,t,r){let n=e.material,i=n.map,o=document.createElement("canvas"),s=o.getContext("2d"),d=28;s.font=`bold ${d}px sans-serif`;let l=s.measureText(t),u=Math.ceil(l.width)+16,c=d+12;o.width=u,o.height=c,s.font=`bold ${d}px sans-serif`,s.fillStyle=r,s.textAlign="center",s.textBaseline="middle",s.fillText(t,u/2,c/2),n.map=new mr.CanvasTexture(o),n.map.minFilter=mr.LinearFilter;let h=.025;e.scale.set(u*h,c*h,1),i?.dispose()}dispose(){for(let[,e]of this.sprites){this.scene.remove(e);let t=e.material;t.map?.dispose(),t.dispose()}this.sprites.clear()}};function wh(){let{store:a,cloudScene:e,invalidate:t,renderBackend:r}=dt(),{is3D:n}=cl(),i=Kr(uu),o=pc(null),s=pc(null),d=pc(null);return Ch(()=>()=>{o.current?.dispose(),o.current=null,s.current?.dispose(),s.current=null,d.current?.dispose(),d.current=null},[]),Ch(()=>{if(!a.hasGroupData()){o.current&&(o.current.dispose(),o.current=null),s.current&&(s.current.dispose(),s.current=null),d.current&&(d.current.dispose(),d.current=null),t();return}n?(o.current&&(o.current.dispose(),o.current=null),s.current||(s.current=r.createGroupSphereRenderer(e))):(s.current&&(s.current.dispose(),s.current=null),o.current||(o.current=r.createGroupRingRenderer(e))),d.current||(d.current=new Ds(e)),a.getGroupManager().recomputeAllGeometry();let u=a.groups;n?s.current?.update(u):o.current?.update(u),d.current.update(u),t()},[i,n,a,e,t]),null}var Ns=class{constructor(){this._state={visible:!1,nodeId:null,position:{x:0,y:0}};this.listeners=new Set}get state(){return this._state}show(e,t){this._state={visible:!0,nodeId:e,position:t},this.notify()}hide(){this._state.visible&&(this._state={...this._state,visible:!1},this.notify())}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}dispose(){this._state={visible:!1,nodeId:null,position:{x:0,y:0}},this.listeners.clear()}notify(){for(let e of this.listeners)e()}};function yr(a,e,t){a.layout.applyByName(e,t)}var Yr=class{constructor(e,t){this.type="HideNodes";this.store=e,this.nodeIds=t}execute(){this.store.hideNodes(this.nodeIds)}undo(){this.store.showNodes(this.nodeIds)}},si=class{constructor(e,t){this.type="ShowNodes";this.store=e,this.nodeIds=t}execute(){this.store.showNodes(this.nodeIds)}undo(){this.store.hideNodes(this.nodeIds)}},Xr=class{constructor(e,t){this.type="PinNodes";this.store=e,this.nodeIds=[...t]}execute(){this.priorPinned===void 0&&(this.priorPinned=this.nodeIds.filter(e=>this.store.isPinned(e))),this.store.pinNodes(this.nodeIds)}undo(){if(this.priorPinned===void 0)return;let e=new Set(this.priorPinned),t=this.nodeIds.filter(r=>!e.has(r));t.length>0&&this.store.unpinNodes(t)}},Cn=class{constructor(e,t){this.type="UnpinNodes";this.store=e,this.nodeIds=[...t]}execute(){this.priorPinned===void 0&&(this.priorPinned=this.nodeIds.filter(e=>this.store.isPinned(e))),this.store.unpinNodes(this.nodeIds)}undo(){this.priorPinned===void 0||this.priorPinned.length===0||this.store.pinNodes(this.priorPinned)}},ai=class{constructor(e){this.type="ShowAllNodes";this.store=e,this.previouslyHiddenIds=[];let t=e.nodeState;if(t){for(let r=0;r<e.data.nodes.length;r++)if(t.hidden[r]===1){let n=e.index.nodeIndexToId[r];n&&this.previouslyHiddenIds.push(n)}}}execute(){this.store.showAllNodes()}undo(){this.previouslyHiddenIds.length>0&&this.store.hideNodes(this.previouslyHiddenIds)}},ks=class{constructor(e,t,r){this.type="SetCategoryVisibility";this.store=e,this.category=t,this.visible=r,this.affectedNodeIds=[],this.previousHiddenState=new Map;let n=e.nodeState;for(let i of e.data.nodes)if(i.category===t){this.affectedNodeIds.push(i.id);let o=e.index.nodeIdToIndex.get(i.id);o!==void 0&&n&&this.previousHiddenState.set(i.id,n.hidden[o])}}execute(){this.visible?this.store.showNodes(this.affectedNodeIds):this.store.hideNodes(this.affectedNodeIds)}undo(){if(!this.store.nodeState)return;let t=[],r=[];for(let n of this.affectedNodeIds)(this.previousHiddenState.get(n)??0)>0?r.push(n):t.push(n);r.length>0&&this.store.hideNodes(r),t.length>0&&this.store.showNodes(t)}},co=class{constructor(e,t,r){this.type="visibility/setHighlighted";this.store=e,this.ids=[...t],this.next=r}execute(){let e=this.store.nodeState;if(e){this.prior===void 0&&(this.prior=this.ids.map(t=>{let r=this.store.index.getNodeIndex(t);return r!==void 0?e.highlighted[r]??0:0}));for(let t of this.ids){let r=this.store.index.getNodeIndex(t);r!==void 0&&(e.highlighted[r]=this.next?1:0)}this.store.updateStrategy.markDirty("nodeHighlight"),this.store.notifyChange()}}undo(){if(!this.prior)return;let e=this.store.nodeState;e&&(this.ids.forEach((t,r)=>{let n=this.store.index.getNodeIndex(t);n!==void 0&&(e.highlighted[n]=this.prior[r])}),this.store.updateStrategy.markDirty("nodeHighlight"),this.store.notifyChange())}},Gs=class{constructor(e,t,r){this.type="SetRelationshipVisibility";this.store=e,this.relationship=t,this.visible=r,this.oldEdgeState=new Map;let n=e.edgeState;if(n){for(let i of e.data.edges)if(i.relationship===t){let o=e.index.edgeIdToIndex.get(i.id);o!==void 0&&this.oldEdgeState.set(i.id,{opacity:n.opacities[o],width:n.widths[o]})}}}execute(){let e=this.store.edgeState;if(e){for(let t of this.store.data.edges)if(t.relationship===this.relationship){let r=this.store.index.edgeIdToIndex.get(t.id);r!==void 0&&(e.opacities[r]=this.visible?.8:0,e.widths[r]=this.visible?1:0)}this.store.updateStrategy.markDirty("edgeOpacities"),this.store.updateStrategy.markDirty("edgeWidths"),this.store.notifyChange()}}undo(){let e=this.store.edgeState;if(e){for(let[t,r]of this.oldEdgeState){let n=this.store.index.edgeIdToIndex.get(t);n!==void 0&&(e.opacities[n]=r.opacity,e.widths[n]=r.width)}this.store.updateStrategy.markDirty("edgeOpacities"),this.store.updateStrategy.markDirty("edgeWidths"),this.store.notifyChange()}}};function hf(a){let e=a.positionProvider?.getPositions(),t=a.nodeCount;if(!e||t===0)return{minX:0,maxX:0,minY:0,maxY:0,minZ:0,maxZ:0,centerX:0,centerY:0,centerZ:0,radius:.3,empty:!0};let r=1/0,n=-1/0,i=1/0,o=-1/0,s=1/0,d=-1/0;for(let m=0;m<t;m++){let g=e[m*3],y=e[m*3+1],v=e[m*3+2];g<r&&(r=g),g>n&&(n=g),y<i&&(i=y),y>o&&(o=y),v<s&&(s=v),v>d&&(d=v)}let l=(r+n)/2,u=(i+o)/2,c=(s+d)/2,h=n-r,p=o-i,f=Math.max(h,p,.1)/2;return{minX:r,maxX:n,minY:i,maxY:o,minZ:s,maxZ:d,centerX:l,centerY:u,centerZ:c,radius:f,empty:!1}}function pf(a,e){let t=Math.random()*Math.PI*2;if(a.empty||e===0){let i=Math.sqrt(Math.random())*.8;return[Math.cos(t)*i,Math.sin(t)*i,0]}let n=Math.max(a.radius,.5)*(1+Math.random()*.5);return[a.centerX+Math.cos(t)*n,a.centerY+Math.sin(t)*n,0]}var gf=0;function ff(){return`node-${Date.now()}-${gf++}`}var Hs=class{constructor(e,t){this.type="AddNodes";this.createdIds=[];this.store=e,this.inputs=t.map(r=>({...r,id:r.id??ff(),properties:{...r.properties??{}},labels:r.labels?[...r.labels]:void 0,position:r.position?{...r.position}:void 0}))}execute(){let e=this.store.nodeCount,t=hf(this.store),n={addedNodes:this.inputs.map(o=>({id:o.id,category:o.category,labels:o.labels,properties:{...o.properties??{}}}))};this.store.applyDelta(n);let i=this.store.positionProvider?.getPositions();if(i)for(let o of this.inputs){let s=this.store.index.nodeIdToIndex.get(o.id);if(s!==void 0)if(o.position)i[s*3]=o.position.x,i[s*3+1]=o.position.y,i[s*3+2]=o.position.z??0;else{let d=pf(t,e);i[s*3]=d[0],i[s*3+1]=d[1],i[s*3+2]=d[2]}}return this.createdIds=this.inputs.map(o=>o.id),this.store.notifyChange(),this.createdIds}undo(){let e={removedNodeIds:this.createdIds};this.store.applyDelta(e),this.store.notifyChange()}},Qr=class{constructor(e,t){this.type="RemoveNodes";this.snapshotNodes=[];this.snapshotEdges=[];this.store=e,this.nodeIds=[...t]}execute(){let e=new Set(this.nodeIds),t=this.store.positionProvider?.getPositions()??null;this.snapshotNodes=[];for(let n of this.nodeIds){let i=this.store.index.nodeIdToIndex.get(n);if(i===void 0)continue;let o=this.store.data.nodes[i];if(!o)continue;let s=t?[t[i*3],t[i*3+1],t[i*3+2]]:null,d=this.store.nodeState,l={color:d?[d.colors[i*3],d.colors[i*3+1],d.colors[i*3+2]]:[1,1,1],size:d?d.sizes[i]:1,opacity:d?d.opacities[i]:1,pinned:d?d.pinned[i]:0,hidden:d?d.hidden[i]:0,iconName:this.store.getNodeIconName(o.id)??null,imageUrl:this.store.getNodeImageUrl(o.id)??null,shapeId:d?d.shapeIds[i]:0,aspect:d?d.aspects[i]:1,overrides:d?d.overrides[i]|0:0};this.snapshotNodes.push({data:{id:o.id,category:o.category,labels:o.labels?[...o.labels]:void 0,tags:o.tags?[...o.tags]:void 0,properties:{...o.properties}},position:s,render:l})}this.snapshotEdges=this.store.data.edges.filter(n=>e.has(n.source)||e.has(n.target)).map(n=>({id:n.id,source:n.source,target:n.target,relationship:n.relationship,properties:{...n.properties}}));let r={removedNodeIds:this.nodeIds};this.store.applyDelta(r),this.store.notifyChange()}undo(){let e=this.snapshotNodes.map(o=>({...o.data,properties:{...o.data.properties}})),t=this.snapshotEdges.map(o=>({...o,properties:{...o.properties}})),r={addedNodes:e,...t.length>0?{addedEdges:t}:{}};this.store.applyDelta(r);let n=this.store.positionProvider?.getPositions(),i=this.store.nodeState;for(let o of this.snapshotNodes){let s=this.store.index.nodeIdToIndex.get(o.data.id);if(s!==void 0){if(o.position&&n&&(n[s*3]=o.position[0],n[s*3+1]=o.position[1],n[s*3+2]=o.position[2]),i){let d=o.render;i.colors[s*3]=d.color[0],i.colors[s*3+1]=d.color[1],i.colors[s*3+2]=d.color[2],i.sizes[s]=d.size,i.opacities[s]=d.opacity,i.pinned[s]=d.pinned,i.hidden[s]=d.hidden}o.render.iconName&&this.store.setNodeIcon(o.data.id,o.render.iconName),o.render.imageUrl&&this.store.setNodeImageUrl(o.data.id,o.render.imageUrl),i&&(i.shapeIds[s]=o.render.shapeId,i.aspects[s]=o.render.aspect),this.store.setNodeOverrides(o.data.id,o.render.overrides)}}this.store.notifyChange()}},wn=class{constructor(e,t,r){this.type="UpdateNode";this.oldProperties={};this.store=e,this.nodeId=t,this.newProperties={...r};let n=e.index.nodeIdToIndex.get(t);if(n!==void 0){let i=e.data.nodes[n];i&&(this.oldProperties={...i.properties})}}execute(){let e={updatedNodes:[{id:this.nodeId,previous:{properties:this.oldProperties},next:{properties:this.newProperties}}]};this.store.applyDelta(e),this.store.notifyChange()}undo(){let e={updatedNodes:[{id:this.nodeId,previous:{properties:this.newProperties},next:{properties:this.oldProperties}}]};this.store.applyDelta(e),this.store.notifyChange()}},Fs=class{constructor(e,t,r){this.type="ChangeCategory";this.oldCategory="";this.store=e,this.nodeId=t,this.newCategory=r;let n=e.index.nodeIdToIndex.get(t);if(n!==void 0){let i=e.data.nodes[n];i&&(this.oldCategory=i.category)}}execute(){let e={updatedNodes:[{id:this.nodeId,previous:{category:this.oldCategory},next:{category:this.newCategory}}]};this.store.applyDelta(e),this.store.notifyChange()}undo(){let e={updatedNodes:[{id:this.nodeId,previous:{category:this.newCategory},next:{category:this.oldCategory}}]};this.store.applyDelta(e),this.store.notifyChange()}},zs=class{constructor(e,t,r){this.type="CollectNodes";this.before=[];this.store=e,this.parentId=t,this.childIds=[...r]}execute(){let e=this.store.getCollectionManager();this.before=[...e.collections.get(this.parentId)?.childNodeIds??[]],this.before.length&&e.explode(this.parentId),e.collect(this.parentId,[...this.before,...this.childIds.filter(t=>!this.before.includes(t))])}undo(){let e=this.store.getCollectionManager();e.explode(this.parentId),this.before.length&&e.collect(this.parentId,this.before)}},Bs=class{constructor(e,t){this.type="ExplodeCollection";this.store=e,this.parentId=t,this.childIds=[...e.getCollectionManager().collections.get(t)?.childNodeIds??[]]}execute(){this.store.getCollectionManager().explode(this.parentId)}undo(){this.childIds.length&&this.store.getCollectionManager().collect(this.parentId,this.childIds)}};var mf=0;function yf(){return`edge-${Date.now()}-${mf++}`}var Os=class{constructor(e,t){this.type="AddEdges";this.createdIds=[];this.store=e,this.inputs=t.map(r=>({...r,id:r.id??yf(),properties:{...r.properties??{}}}))}execute(){let t={addedEdges:this.inputs.map(r=>({id:r.id,source:r.source,target:r.target,relationship:r.relationship,properties:{...r.properties??{}}}))};return this.store.applyDelta(t),this.createdIds=this.inputs.map(r=>r.id),this.store.notifyChange(),this.createdIds}undo(){let e={removedEdgeIds:this.createdIds};this.store.applyDelta(e),this.store.notifyChange()}},Jr=class{constructor(e,t){this.type="RemoveEdges";this.snapshotEdges=[];this.store=e,this.edgeIds=[...t]}execute(){let e=new Set(this.edgeIds),t=this.store.edgeState;this.snapshotEdges=[];for(let n of this.store.data.edges){if(!e.has(n.id))continue;let i=this.store.index.edgeIdToIndex.get(n.id),o={color:i!==void 0&&t?[t.colors[i*3],t.colors[i*3+1],t.colors[i*3+2]]:[1,1,1],width:i!==void 0&&t?t.widths[i]:1,opacity:i!==void 0&&t?t.opacities[i]:1};this.snapshotEdges.push({data:{id:n.id,source:n.source,target:n.target,relationship:n.relationship,properties:{...n.properties}},render:o})}let r={removedEdgeIds:this.edgeIds};this.store.applyDelta(r),this.store.notifyChange()}undo(){let e=this.snapshotEdges.map(r=>({...r.data,properties:{...r.data.properties}}));if(e.length>0){let r={addedEdges:e};this.store.applyDelta(r)}let t=this.store.edgeState;if(t)for(let r of this.snapshotEdges){let n=this.store.index.edgeIdToIndex.get(r.data.id);if(n===void 0)continue;let i=r.render;t.colors[n*3]=i.color[0],t.colors[n*3+1]=i.color[1],t.colors[n*3+2]=i.color[2],t.widths[n]=i.width,t.opacities[n]=i.opacity}this.store.notifyChange()}},Tn=class{constructor(e,t,r){this.type="UpdateEdge";this.oldProperties={};this.store=e,this.edgeId=t,this.newProperties={...r};let n=e.index.edgeIdToIndex.get(t);if(n!==void 0){let i=e.data.edges[n];i&&(this.oldProperties={...i.properties})}}execute(){let e={updatedEdges:[{id:this.edgeId,previous:{properties:this.oldProperties},next:{properties:this.newProperties}}]};this.store.applyDelta(e),this.store.notifyChange()}undo(){let e={updatedEdges:[{id:this.edgeId,previous:{properties:this.newProperties},next:{properties:this.oldProperties}}]};this.store.applyDelta(e),this.store.notifyChange()}};function Th(a){return[{id:"core.nodeInfo",label:"Information",icon:"category",group:"info",order:0,visible:e=>e.type==="node",action:e=>a.showNodeInfo?.(e)},{id:"core.edgeInfo",label:"Information",icon:"category",group:"info",order:1,visible:e=>e.type==="edge",action:e=>a.showEdgeInfo?.(e)},{id:"core.layout",label:"Layout",icon:"hub",group:"layout",order:0,visible:()=>!0,children:[{id:"core.layout.circle",label:"Circle",icon:"sports-volleyball",group:"layout",order:0,visible:e=>e.mode!=="globe",action:e=>yr(e.engine,"circle",e.selectedNodeIds.length>0?e.selectedNodeIds:void 0)},{id:"core.layout.grid",label:"Grid",icon:"grid-on",group:"layout",order:1,visible:e=>e.mode!=="globe",action:e=>yr(e.engine,"grid",e.selectedNodeIds.length>0?e.selectedNodeIds:void 0)},{id:"core.layout.line",label:"Line",icon:"horizontal-rule",group:"layout",order:2,visible:e=>e.mode!=="globe",action:e=>yr(e.engine,"line",e.selectedNodeIds.length>0?e.selectedNodeIds:void 0)},{id:"core.layout.tree",label:"Tree",icon:"account-tree",group:"layout",order:3,visible:e=>e.mode!=="globe",action:e=>yr(e.engine,"tree",e.selectedNodeIds.length>0?e.selectedNodeIds:void 0)},{id:"core.layout.spring",label:"Spring",icon:"hub",group:"layout",order:4,visible:e=>e.mode!=="globe",action:e=>yr(e.engine,"spring",e.selectedNodeIds.length>0?e.selectedNodeIds:void 0)},{id:"core.layout.sphere",label:"Sphere",icon:"bubble-chart",group:"layout",order:5,visible:e=>e.mode==="3d"||e.mode==null,action:e=>yr(e.engine,"sphere",e.selectedNodeIds.length>0?e.selectedNodeIds:void 0)},{id:"core.layout.spiral",label:"Spiral",icon:"route",group:"layout",order:6,visible:e=>e.mode!=="globe",action:e=>yr(e.engine,"spiral",e.selectedNodeIds.length>0?e.selectedNodeIds:void 0)},{id:"core.layout.expand",label:"Expand Spacing",icon:"open-in-full",group:"layout",order:10,visible:e=>e.selectedNodeIds.length>1,action:e=>yr(e.engine,"scale-spacing-up",e.selectedNodeIds)},{id:"core.layout.contract",label:"Contract Spacing",icon:"close-fullscreen",group:"layout",order:11,visible:e=>e.selectedNodeIds.length>1,action:e=>yr(e.engine,"scale-spacing-down",e.selectedNodeIds)}]},{id:"core.selectionMenu",label:"Selection",icon:"tag",group:"selection-menu",order:0,visible:()=>!0,children:e=>{let t=e.engine?.ui?.contextMenu?.manager;if(!t)return Promise.resolve([]);let r=t.getItemsInGroup("selection").filter(n=>!n.visible||n.visible(e));return Promise.resolve(r)}},{id:"core.createNode",label:"Add Node",icon:"hub",group:"selection",order:0,visible:e=>e.type==="background"&&(e.engine?.flows.hasCallback("onResolveCategories")??!1),action:e=>{if(!e.interaction){a.createNodeHere?.(e);return}let t={sourceNodeIds:[],targetNodeId:null,dropScreenPosition:e.screenPosition,dropWorldPosition:e.worldPos??{x:0,y:0,z:0}};e.interaction.emitEdgeCreate(t)}},{id:"core.createEdge",label:e=>{let t=e.selectedNodeIds.length;return t>1?`Add ${t} Edges (from selection)`:"Add Edge"},icon:"share",group:"selection",order:1,visible:e=>(e.type==="node"||e.selectedNodeIds.length>0)&&(e.engine?.flows.hasCallback("onResolveRelationships")??!1),action:e=>{if(!e.interaction?.edgeCreate){console.warn("[core.createEdge] EdgeCreateHandler not available; falling back to host action"),a.createEdgeFrom?.(e);return}let t=e.selectedNodeIds.length>0?[...e.selectedNodeIds]:e.nodeId?[e.nodeId]:[];t.length!==0&&e.interaction.edgeCreate.start(t[0],e.screenPosition.x,e.screenPosition.y)}},{id:"core.changeCategory",label:"Change Category",icon:"category",group:"selection",order:2,visible:e=>e.selectedNodeIds.length>0&&(e.engine?.flows.hasCallback("onResolveCategories")??!1),action:e=>a.changeCategory?.(e)},{id:"core.pinToggle",label:e=>{if(!e.nodeId||!e.store)return"Pin";let t=e.store.index.getNodeIndex(e.nodeId);if(t===void 0)return"Pin";let n=e.store.nodeState?.pinned[t]===1?"Unpin":"Pin",i=e.selectedNodeIds.length;return i>1?`${n} All (${i})`:n},icon:"palette",group:"selection",order:10,visible:e=>e.selectedNodeIds.length>0,action:e=>{let t=e.engine?.store??e.store,r=e.nodeId??e.selectedNodeIds[0],n=r!==void 0?t.index.getNodeIndex(r):void 0,o=n!==void 0&&t.nodeState?.pinned[n]===1?Cn:Xr;e.engine.history.execute(new o(t,e.selectedNodeIds))}},{id:"core.hide",label:"Hide",icon:"visibility-off",group:"selection",order:11,danger:!0,visible:e=>e.selectedNodeIds.length>0||e.selectedEdgeIds.length>0,action:e=>{let t=e.engine?.store??e.store;e.engine.history.execute(new Yr(t,e.selectedNodeIds))}},{id:"core.showHidden",label:"Show Hidden",icon:"visibility",group:"selection",order:12,visible:e=>e.type==="background"&&(a.hasHiddenItems?.()??!1),action:e=>{let t=e.engine?.store??e.store;e.engine.history.execute(new ai(t))}},{id:"core.highlight",label:"Highlight",icon:"palette",group:"selection",order:13,visible:e=>e.selectedNodeIds.length>0,action:e=>{let t=e.engine?.store??e.store;e.engine.history.execute(new co(t,e.selectedNodeIds,!0))}},{id:"core.clearHighlight",label:"Clear Highlight",icon:"palette",group:"selection",order:14,visible:e=>(e.engine?.store??e.store).getAllHighlightedIds().length>0,action:e=>{let t=e.engine?.store??e.store,r=t.getAllHighlightedIds();e.engine.history.execute(new co(t,r,!1))}},{id:"core.selectMenu",label:"Select",icon:"filter-alt",group:"select",order:0,visible:()=>!0,children:[{id:"core.selectNeighbors",label:"Select Neighbors",group:"select",order:0,visible:e=>e.selectedNodeIds.length>0,action:e=>{e.engine?.selection.selectNeighbors(e.selectedNodeIds)}},{id:"core.selectAll",label:"Select All",icon:"all-inclusive",group:"select",order:1,visible:()=>!0,action:e=>{e.engine?.selection.selectAll()}},{id:"core.clearSelection",label:"Clear Selection",icon:"close-fullscreen",group:"select",order:2,visible:e=>e.selectedNodeIds.length>0||e.selectedEdgeIds.length>0,action:e=>{e.engine?.selection.clear()}},{id:"core.selectFloating",label:"Select Floating Nodes",group:"select",order:3,visible:()=>!0,action:e=>{e.engine?.selection.selectFloating()}},{id:"core.selectVisible",label:"Select Visible Nodes",group:"select",order:4,visible:()=>!0,action:e=>{e.engine?.selection.selectVisibleNodes()}},{id:"core.selectChildren",label:"Select Children",group:"select",order:5,visible:e=>e.selectedNodeIds.length>0,action:e=>{e.engine?.selection.selectChildren(e.selectedNodeIds)}},{id:"core.selectParents",label:"Select Parents",group:"select",order:6,visible:e=>e.selectedNodeIds.length>0,action:e=>{e.engine?.selection.selectParents(e.selectedNodeIds)}},{id:"core.neighborEdges",label:"Select Neighbor Edges",group:"select",order:7,visible:e=>e.selectedNodeIds.length>0,action:e=>{e.engine?.selection.selectNeighborEdges(e.selectedNodeIds)}},{id:"core.connectionNodes",label:"Select Connection Nodes",group:"select",order:8,visible:e=>e.selectedNodeIds.length>=2,action:e=>{e.engine?.selection.selectConnectionNodes(e.selectedNodeIds)}},{id:"core.invertSelection",label:"Invert Selection",group:"select",order:9,visible:()=>!0,action:e=>{e.engine?.selection.invertSelection()}}]},{id:"core.centerTo",label:"Center To",icon:"center-focus-strong",group:"camera",order:0,visible:e=>e.selectedNodeIds.length>0,action:e=>{e.engine&&e.engine.camera.flyToNodes(e.selectedNodeIds)}},{id:"core.flyOut",label:"Fly Out",icon:"zoom-out",group:"camera",order:1,visible:()=>!0,action:e=>{e.engine&&e.engine.camera.zoomOut(4)}},{id:"core.fitToScreen",label:"Fit to Screen",icon:"fit-view",group:"camera",order:2,visible:()=>!0,action:e=>a.fitToScreen?.(e)},{id:"core.delete",label:"Delete",icon:"delete",group:"danger",order:10,danger:!0,visible:e=>e.selectedNodeIds.length>0||e.selectedEdgeIds.length>0,action:e=>{let t=e.engine?.store??e.store,r=e.engine,n=new Set;for(let i of e.selectedNodeIds)for(let o of t.getIncidentEdgeIds(i))n.add(o);for(let i of e.selectedEdgeIds)n.add(i);r.history.beginTransaction("Delete"),n.size>0&&r.history.execute(new Jr(t,Array.from(n))),e.selectedNodeIds.length>0&&r.history.execute(new Qr(t,e.selectedNodeIds)),r.history.endTransaction()}}]}var en=class{constructor(e,t,r){this.type="DragPositions";this.store=e,this.startPositions=t,this.endPositions=r}execute(){this._applyPositions(this.endPositions)}undo(){this._applyPositions(this.startPositions)}_applyPositions(e){let t=this.store.positionProvider;if(!t)return;let r=t.getPositions();if(r){for(let[n,[i,o,s]]of e){let d=this.store.index.nodeIdToIndex.get(n);d!==void 0&&(r[d*3]=i,r[d*3+1]=o,r[d*3+2]=s)}typeof t.setAllPositions=="function"&&t.setAllPositions(r),this.store.notifyChange()}}},di=class{constructor(e,t){this.type="SetPositions";this.store=e,this.newPositions=t,this.oldPositions=new Map;let n=e.positionProvider?.getPositions();for(let i of t.keys()){let o=e.index.nodeIdToIndex.get(i);o!==void 0&&n&&this.oldPositions.set(i,[n[o*3],n[o*3+1],n[o*3+2]])}}execute(){this._applyPositions(this.newPositions)}undo(){this._applyPositions(this.oldPositions)}_applyPositions(e){let t=this.store.positionProvider;if(!t)return;let r=t.getPositions();if(r){for(let[n,[i,o,s]]of e){let d=this.store.index.nodeIdToIndex.get(n);d!==void 0&&(r[d*3]=i,r[d*3+1]=o,r[d*3+2]=s)}typeof t.setAllPositions=="function"&&t.setAllPositions(r),this.store.notifyChange()}}};var Mn={dark:{background:1842204,isDark:!0},light:{background:16119285,isDark:!1},midnight:{background:858922,isDark:!0},forest:{background:1715738,isDark:!0},warm:{background:16117992,isDark:!1}},uo={dark:"esriDarkGray",light:"esriLightGray",midnight:"esriDarkGray",forest:"esriDarkGray",warm:"esriWorldTopo"},gc={charge:-.01,gravity:.1,linkDistance:.5,linkStrength:1,collision:.15,alpha:.6,alphaDecay:.01,friction:.6};var Ls=class{constructor(){this.handlers=new Map;this._suspendDepth=0;this._buffer=[]}get suspended(){return this._suspendDepth>0}suspend(){this._suspendDepth++}resume(e){if(this._suspendDepth===0||(this._suspendDepth--,this._suspendDepth>0))return;let t=this._buffer;this._buffer=[];let r=t;if(e?.dedupe){let n=new Map;for(let i=0;i<t.length;i++)n.set(t[i].event,i);r=t.filter((i,o)=>n.get(i.event)===o)}for(let{event:n,payload:i}of r)this._dispatch(n,i)}on(e,t){return this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t),()=>this.off(e,t)}once(e,t){let r=n=>{this.off(e,r),t(n)};return this.on(e,r)}off(e,t){this.handlers.get(e)?.delete(t)}emit(e,t){if(this._suspendDepth>0){this._buffer.push({event:e,payload:t});return}this._dispatch(e,t)}_dispatch(e,t){let r=this.handlers.get(e);if(r)for(let n of r)try{n(t)}catch(i){console.error(`EventBus: error in handler for "${e}"`,i)}}removeAllListeners(){this.handlers.clear(),this._buffer=[],this._suspendDepth=0}};function vf(a,e){return typeof e=="string"?a.id===e:Array.isArray(e)?e.includes(a.id):typeof e=="function"?e(a):"category"in e?a.category===e.category:"properties"in e?Object.entries(e.properties).every(([t,r])=>a.properties[t]===r):!1}var Vs=class{constructor(e,t,r,n){this.sortConfig=null;this.limitCount=null;this.store=e,this.executor=t,this.eventBus=r,this.filters=[n]}where(e){return this.filters.push(e),this}sort(e,t="asc"){return this.sortConfig={property:e,order:t},this}limit(e){return this.limitCount=e,this}resolve(){let e=this.store.data.nodes.filter(t=>this.filters.every(r=>vf(t,r)));if(this.sortConfig){let{property:t,order:r}=this.sortConfig,n=r==="asc"?1:-1;e=e.slice().sort((i,o)=>{let s=i.properties[t]??null,d=o.properties[t]??null;return s===null&&d===null?0:s===null?n:d===null||s<d?-n:s>d?n:0})}return this.limitCount!==null&&(e=e.slice(0,this.limitCount)),e}ids(){return this.resolve().map(e=>e.id)}data(){return this.resolve()}count(){return this.resolve().length}select(){let e=this.ids();return this.store.selectNodes(e),this.eventBus.emit("selection:changed",{nodeIds:e,edgeIds:[],source:"api"}),e}deselect(){let e=this.ids();this.store.removeFromSelection(e)}highlight(){let e=this.ids();this.store.highlightNodes(e)}hide(){let e=this.ids();this.executor.execute(new Yr(this.store,e))}show(){let e=this.ids();this.executor.execute(new si(this.store,e))}remove(){let e=this.ids();this.executor.execute(new Qr(this.store,e))}pin(){let e=this.ids();this.executor.execute(new Xr(this.store,e))}update(e){let t=this.ids();for(let r of t)this.executor.execute(new wn(this.store,r,e))}};function Mh(a){return typeof a=="object"&&a!==null&&typeof a.id=="string"}function Ih(a){return typeof a=="object"&&a!==null&&Array.isArray(a.ids)&&a.ids.every(e=>typeof e=="string")}function In(a){if(typeof a=="string")return[a];if(Array.isArray(a))return a.map(t=>typeof t=="string"?t:t.id);if(Ih(a))return[...a.ids];if(Mh(a))return[a.id];let e;try{e=JSON.stringify(a)}catch{e=Object.prototype.toString.call(a)}throw new TypeError(`Invalid NodeSelector: ${e}`)}function Us(a){if(typeof a=="string")return[a];if(Array.isArray(a))return a.map(t=>typeof t=="string"?t:t.id);if(Ih(a))return[...a.ids];if(Mh(a))return[a.id];let e;try{e=JSON.stringify(a)}catch{e=Object.prototype.toString.call(a)}throw new TypeError(`Invalid EdgeSelector: ${e}`)}var Ws=class{constructor(e,t,r){this._motion=null;this._expandOnDoubleClick=!0;this.store=e,this.executor=t,this.eventBus=r}async add(e){let t=new Hs(this.store,e),n=this.executor.execute(t).map(i=>{let o=this.store.index.nodeIdToIndex.get(i);return o!==void 0?this.store.data.nodes[o]:void 0}).filter(i=>i!==void 0);return this.eventBus.emit("nodes:added",{nodes:n}),n}async remove(e){let t=In(e);this.executor.execute(new Qr(this.store,t)),this.eventBus.emit("nodes:removed",{nodeIds:t})}async update(e,t){this.executor.execute(new wn(this.store,e,t)),this.eventBus.emit("nodes:updated",{updates:[{id:e,properties:t}]})}async updateBatch(e){for(let t of e)this.executor.execute(new wn(this.store,t.id,t.properties));this.eventBus.emit("nodes:updated",{updates:e})}async clear(){let e=this.store.data.nodes.map(t=>t.id);e.length>0&&await this.remove(e)}get(e){let t=this.store.index.nodeIdToIndex.get(e);return t===void 0?null:this.store.data.nodes[t]??null}getAll(){return this.store.data.nodes.slice()}count(){return this.store.nodeCount}has(e){return this.store.index.nodeIdToIndex.has(e)}exists(e){return this.has(e)}where(e){return new Vs(this.store,this.executor,this.eventBus,e)}async hide(e){let t=In(e);this.executor.execute(new Yr(this.store,t)),this.eventBus.emit("visibility:changed",{nodeIds:t,visible:!1})}async show(e){let t=In(e);this.executor.execute(new si(this.store,t)),this.eventBus.emit("visibility:changed",{nodeIds:t,visible:!0})}async showAll(){this.executor.execute(new ai(this.store))}isVisible(e){return this.store.isNodeVisible(e)}async pin(e){let t=In(e);t.some(r=>!this.store.isPinned(r))&&(this.executor.execute(new Xr(this.store,t)),this.eventBus.emit("pin:changed",{nodeIds:this.store.getPinnedNodeIds()}))}async unpin(e){let t=In(e);t.some(r=>this.store.isPinned(r))&&(this.executor.execute(new Cn(this.store,t)),this.eventBus.emit("pin:changed",{nodeIds:this.store.getPinnedNodeIds()}))}getPinned(){return this.store.getPinnedNodeIds()}async unpinAll(){let e=this.store.getPinnedNodeIds();e.length!==0&&(this.executor.execute(new Cn(this.store,e)),this.eventBus.emit("pin:changed",{nodeIds:this.store.getPinnedNodeIds()}))}_wireCollectMotion(e){this._motion?.finishAll(),this._motion=e}async collect(e,t,r){let n=this.store.getCollectionManager();if(this.store.index.getNodeIndex(e)===void 0)throw new Error(`nodes.collect: unknown parent node "${e}"`);if(n.isCollected(e))throw new Error(`nodes.collect: "${e}" is inside another collection; explode that first`);let i=new Set(n.collections.get(e)?.childNodeIds??[]),o=[...new Set(In(t))].filter(l=>l!==e&&!i.has(l)&&this.store.index.getNodeIndex(l)!==void 0);for(let l of o)if(n.isCollection(l)||n.isCollected(l))throw new Error(`nodes.collect: "${l}" is already part of a collection; explode it first`);if(o.length===0)return;let s=r?.animate===!1?null:this._motion,d=s?await s.gather(e,o):null;this.executor.execute(new zs(this.store,e,o)),d&&d.size&&this.store.setPositions(d),this.eventBus.emit("collection:changed",{type:"collect",parentId:e})}async explode(e,t){let r=this.getCollected(e);if(r.length===0)return;let n=t?.animate===!1?null:this._motion,i=n?n.positionsOf(r):null;this.executor.execute(new Bs(this.store,e)),this.eventBus.emit("collection:changed",{type:"explode",parentId:e}),n&&i&&await n.spread(e,r,i)}isCollection(e){return this.store.getCollectionManager().isCollection(e)}getCollected(e){return[...this.store.getCollectionManager().collections.get(e)?.childNodeIds??[]]}setExpandOnDoubleClick(e){this._expandOnDoubleClick=e}getExpandOnDoubleClick(){return this._expandOnDoubleClick}};function bf(a,e){return typeof e=="string"?a.id===e:Array.isArray(e)?e.includes(a.id):typeof e=="function"?e(a):"relationship"in e?a.relationship===e.relationship:"source"in e?a.source===e.source:"target"in e?a.target===e.target:!1}var js=class{constructor(e,t,r,n){this.sortConfig=null;this.limitCount=null;this.store=e,this.executor=t,this.eventBus=r,this.filters=[n]}where(e){return this.filters.push(e),this}sort(e,t="asc"){return this.sortConfig={property:e,order:t},this}limit(e){return this.limitCount=e,this}resolve(){let e=this.store.data.edges.filter(t=>this.filters.every(r=>bf(t,r)));if(this.sortConfig){let{property:t,order:r}=this.sortConfig,n=r==="asc"?1:-1;e=e.slice().sort((i,o)=>{let s=i.properties[t]??null,d=o.properties[t]??null;return s===null&&d===null?0:s===null?n:d===null||s<d?-n:s>d?n:0})}return this.limitCount!==null&&(e=e.slice(0,this.limitCount)),e}ids(){return this.resolve().map(e=>e.id)}data(){return this.resolve()}count(){return this.resolve().length}select(){let e=this.ids();return this.store.selectEdges(e),this.eventBus.emit("selection:changed",{nodeIds:[],edgeIds:e,source:"api"}),e}remove(){let e=this.ids();this.executor.execute(new Jr(this.store,e))}update(e){let t=this.ids();for(let r of t)this.executor.execute(new Tn(this.store,r,e))}};var qs=class{constructor(e,t,r){this.store=e,this.executor=t,this.eventBus=r}async add(e){let t=new Os(this.store,e),n=this.executor.execute(t).map(i=>{let o=this.store.index.edgeIdToIndex.get(i);return o!==void 0?this.store.data.edges[o]:void 0}).filter(i=>i!==void 0);return this.eventBus.emit("edges:added",{edges:n}),n}async remove(e){let t=Us(e);this.executor.execute(new Jr(this.store,t)),this.eventBus.emit("edges:removed",{edgeIds:t})}async update(e,t){this.executor.execute(new Tn(this.store,e,t)),this.eventBus.emit("edges:updated",{updates:[{id:e,properties:t}]})}async updateBatch(e){for(let t of e)this.executor.execute(new Tn(this.store,t.id,t.properties));this.eventBus.emit("edges:updated",{updates:e})}async clear(){let e=this.store.data.edges.map(t=>t.id);e.length>0&&await this.remove(e)}get(e){let t=this.store.index.edgeIdToIndex.get(e);return t===void 0?null:this.store.data.edges[t]??null}getAll(){return this.store.data.edges.slice()}count(){return this.store.data.edges.length}has(e){return this.store.index.edgeIdToIndex.has(e)}exists(e){return this.has(e)}where(e){return new js(this.store,this.executor,this.eventBus,e)}between(e,t){return this.store.data.edges.filter(r=>r.source===e&&r.target===t)}connectedTo(e){return this.store.data.edges.filter(t=>t.source===e||t.target===e)}};var Ks=class{constructor(e,t){this.sm=null;this._smWarnedOnce=!1;this.store=e,this.eventBus=t}setSelectionManager(e){this.sm=e}warnFallback(){this._smWarnedOnce||(this._smWarnedOnce=!0,console.warn("SelectionApi: SelectionManager not yet attached; falling back to store-direct path. SelectionManager.state.nodeIds may diverge."))}async selectNodes(e,t="replace"){this.sm?this.sm.selectNodes(e,t):(this.warnFallback(),t==="replace"?this.store.selectNodes(e):t==="add"?this.store.addToSelection(e):t==="remove"?this.store.removeFromSelection(e):t==="toggle"&&e.forEach(r=>this.store.toggleNodeSelection(r))),this.emitChanged("api")}async deselectNodes(e){this.sm?e?this.sm.selectNodes(e,"remove"):this.sm.clearSelection():(this.warnFallback(),e?this.store.removeFromSelection(e):this.store.clearSelection()),this.emitChanged("api")}async toggleNodes(e){this.sm?this.sm.selectNodes(e,"toggle"):(this.warnFallback(),e.forEach(t=>this.store.toggleNodeSelection(t))),this.emitChanged("api")}getSelectedNodeIds(){return this.store.getSelectedNodeIds()}isSelected(e){return this.getSelectedNodeIds().includes(e)}async selectEdges(e,t="replace"){if(this.sm)this.sm.selectEdges(e,t);else if(this.warnFallback(),t==="replace")this.store.selectEdges(e);else if(t==="add"){let r=this.getSelectedEdgeIds();this.store.selectEdges([...new Set([...r,...e])])}else if(t==="remove"){let r=new Set(e),n=this.getSelectedEdgeIds().filter(i=>!r.has(i));this.store.selectEdges(n)}else if(t==="toggle"){let r=new Set(e),n=this.getSelectedEdgeIds(),i=new Set(n),o=[...n.filter(s=>!r.has(s)),...e.filter(s=>!i.has(s))];this.store.selectEdges(o)}this.emitChanged("api")}async deselectEdges(e){if(this.sm)e?this.sm.selectEdges(e,"remove"):this.sm.selectEdges([],"replace");else if(this.warnFallback(),!e)this.store.selectEdges([]);else{let t=new Set(e),r=this.getSelectedEdgeIds().filter(n=>!t.has(n));this.store.selectEdges(r)}this.emitChanged("api")}async toggleEdges(e){let t=Us(e),r=new Set(this.getSelectedEdgeIds()),n=[],i=[];for(let o of t)r.has(o)?i.push(o):n.push(o);n.length&&await this.selectEdges(n,"add"),i.length&&await this.deselectEdges(i)}getSelectedEdgeIds(){let e=this.store.edgeState;if(!e)return[];let t=[];for(let r=0;r<e.selected.length;r++)if(e.selected[r]>0){let n=this.store.index.edgeIndexToId[r];n&&t.push(n)}return t}isSelectedEdge(e){return this.getSelectedEdgeIds().includes(e)}async selectAllEdges(){let e=this.store.data.edges.map(t=>t.id);await this.selectEdges(e,"replace")}async invertEdgeSelection(){let e=new Set(this.getSelectedEdgeIds()),t=this.store.data.edges.map(r=>r.id).filter(r=>!e.has(r));await this.selectEdges(t,"replace")}async clear(){this.sm?this.sm.clearSelection():(this.warnFallback(),this.store.clearSelection()),this.emitChanged("api")}hasSelection(){return this.store.getSelectedNodeIds().length>0||this.getSelectedEdgeIds().length>0}async selectAll(){if(this.sm)this.sm.selectAllNodes();else{this.warnFallback();let e=this.store.data.nodes.map(t=>t.id);this.store.selectNodes(e)}this.emitChanged("api")}async invertSelection(){this.sm?this.sm.invertNodeSelection():(this.warnFallback(),this.store.data.nodes.forEach(t=>this.store.toggleNodeSelection(t.id))),this.emitChanged("api")}async selectFloating(){let e=this.store.data.nodes.filter(t=>this.store.getDegree(t.id)<=1).map(t=>t.id);await this.selectNodes(e,"replace")}async selectVisibleNodes(){let e=this.store.data.nodes.filter(t=>!this.store.isNodeHidden(t.id)).map(t=>t.id);await this.selectNodes(e,"replace")}async selectChildren(e){let t=this.store.getDownstreamNeighborIds(e);await this.selectNodes(t,"replace")}async selectParents(e){let t=this.store.getUpstreamNeighborIds(e);await this.selectNodes(t,"replace")}async selectNeighborEdges(e){let t=new Set;for(let r of e)for(let n of this.store.getIncidentEdgeIds(r))t.add(n);await this.selectEdges(Array.from(t),"replace")}async selectConnectionNodes(e){let t=this.store.getNodesOnShortestPaths(e);await this.selectNodes(t,"replace")}async selectNeighbors(e){let t=new Set;for(let r of e)for(let n of this.store.data.edges)n.source===r&&t.add(n.target),n.target===r&&t.add(n.source);await this.selectNodes(Array.from(t),"add")}async highlight(e){this.store.highlightNodes(e)}async clearHighlight(){this.store.clearHighlight()}emitChanged(e){this.eventBus.emit("selection:changed",{nodeIds:this.store.getSelectedNodeIds(),edgeIds:this.getSelectedEdgeIds(),source:e})}};var Sf={linear:a=>a,easeIn:a=>a*a,easeOut:a=>a*(2-a),easeInOut:a=>a<.5?2*a*a:-1+(4-2*a)*a},$s=class{constructor(e,t,r,n){this._done=!1;this.from={...e},this.to={...t},this.applyFn=r,this.duration=n?.duration??400,this.easingFn=Sf[n?.easing??"easeInOut"],this._onComplete=n?.onComplete,this.startTime=performance.now()}get done(){return this._done}update(e){let t=e-this.startTime,r=Math.min(t/this.duration,1),n=this.easingFn(r);return this.applyFn({x:this.from.x+(this.to.x-this.from.x)*n,y:this.from.y+(this.to.y-this.from.y)*n,z:this.from.z+(this.to.z-this.from.z)*n}),r>=1&&(this._done=!0,this._onComplete?.()),this._done}};import*as Zs from"three";var Ys=class{constructor(e,t,r,n){this._flyDone=null;this._globeFit=null;this.interaction=e,this.layoutRuntime=t??null,this.animationManager=r??null,this.store=n??null}setGlobeFit(e){this._globeFit=e}wireInteraction(e){this.interaction=e}wireLayoutRuntime(e){this.layoutRuntime=e}wireStore(e){this.store=e}getViewState(){if(!this.interaction)return null;let e=this.interaction.drag.getCamera(),t=this.interaction.drag.getCloudScene();return t?{position:[t.position.x,t.position.y,t.position.z],cameraZ:e.position.z,rotation:{x:t.rotation.x,y:t.rotation.y,z:t.rotation.z}}:null}setViewState(e){if(!this.interaction)return;let t=this.interaction.drag.getCamera(),r=this.interaction.drag.getCloudScene();r&&(r.position.set(e.position[0],e.position[1],e.position[2]),t.position.z=e.cameraZ,e.rotation&&r.rotation.set(e.rotation.x,e.rotation.y,e.rotation.z))}computeBBox(e,t=1.5){let r=this.layoutRuntime?.getPositions()??null,n=this.store?.index.nodeIdToIndex,i=r&&n?v=>{let b=n.get(v);return b===void 0?null:{x:r[b*3],y:r[b*3+1],z:r[b*3+2]}}:v=>this.layoutRuntime?.getNodePosition?.(v)??null,o=1/0,s=1/0,d=1/0,l=-1/0,u=-1/0,c=-1/0,h=0;for(let v of e){let b=i(v);b&&(o=Math.min(o,b.x),l=Math.max(l,b.x),s=Math.min(s,b.y),u=Math.max(u,b.y),d=Math.min(d,b.z),c=Math.max(c,b.z),h++)}if(h===0)return null;let p={x:(o+l)/2,y:(s+u)/2,z:(d+c)/2},f=l-o,m=u-s,g=c-d,y=this.computeFitSceneZ(f,m,g,t);return{center:p,offset:y}}computeFitSceneZ(e,t,r,n){let i=this.interaction?.drag.getCamera(),o=f=>!!f&&f.isPerspectiveCamera===!0,s=Math.max(e,t,r,.1);if(!o(i)||!i.fov||!i.aspect)return-s*n;let d=i.fov*Math.PI/180,l=Math.tan(d/2),u=l*i.aspect,c=e>0?e*n/(2*u):0,h=t>0?t*n/(2*l):0,p=Math.max(c,h,r*.5+.5);return i.position.z-p}flyToNodes(e,t){let r=this._globeFit?.(e,t);if(r)return r;if(!this.interaction||!this.layoutRuntime)return Promise.resolve();let n=this.interaction.graphControl;if(!n)return Promise.resolve();let i=this.computeBBox(e,t?.scale);if(!i)return Promise.resolve();let o=t?.offset??i.offset,s=n.computeFlyToTarget(i.center,o);return this.animateToTarget(n,s,t)}flyToAll(e){let t=this._globeFit?.(null,e);if(t)return t;let r=this.interaction?.graphControl,n=this.fitAllTarget(e);return!r||!n?Promise.resolve():this.animateToTarget(r,n,e)}fitStep(e,t){let r=this.interaction?.graphControl,n=this.fitAllTarget(t);if(!r||!n)return!1;let i=r.getFullPosition();return Math.abs(n.x-i.x)+Math.abs(n.y-i.y)+Math.abs(n.z-i.z)>1e-6*(1+Math.abs(i.z))?e>=1?(r.moveSceneTo(n),!0):(r.moveSceneTo({x:i.x+(n.x-i.x)*e,y:i.y+(n.y-i.y)*e,z:i.z+(n.z-i.z)*e}),!0):!1}fitAllTarget(e){if(!this.interaction||!this.layoutRuntime)return null;let t=this.interaction.graphControl;if(!t)return null;let r=this.layoutRuntime.getPositions();if(!r||r.length===0)return null;let n=this.store?.nodeCount??r.length/3,i=Math.min(n,r.length/3)*3;if(i===0)return null;let o=1/0,s=1/0,d=1/0,l=-1/0,u=-1/0,c=-1/0;for(let v=0;v<i;v+=3){let b=r[v],x=r[v+1],w=r[v+2];o=Math.min(o,b),l=Math.max(l,b),s=Math.min(s,x),u=Math.max(u,x),d=Math.min(d,w),c=Math.max(c,w)}let h={x:(o+l)/2,y:(s+u)/2,z:(d+c)/2},p=l-o,f=u-s,m=c-d,g=e?.scale??1.5,y=e?.offset??this.computeFitSceneZ(p,f,m,g);return t.computeFlyToTarget(h,y)}async flyToPosition(e,t){let r=this.interaction?.graphControl;if(!r)throw new Error("CameraApi.flyToPosition: graphControl not available");let n=e instanceof Zs.Vector3?e.clone():new Zs.Vector3(e.x,e.y,e.z),i=r.computeFlyToTarget(n,t?.offset??0);return this.animateToTarget(r,i,t)}cancelFly(){let e=this._flyDone;e&&(this._flyDone=null,this.animationManager?.remove("flyTo"),e())}animateToTarget(e,t,r){let n=r?.duration??400;if(this.cancelFly(),this.animationManager&&n>0){let i=e.getFullPosition(),o=t;return new Promise(s=>{let d=()=>{this._flyDone===d&&(this._flyDone=null),s()};this._flyDone=d,this.animationManager.add("flyTo",new $s(i,o,l=>{e.moveSceneTo(l)},{duration:n,onComplete:d}))})}return e.moveSceneTo(t),Promise.resolve()}async zoomIn(e=2){if(!this.interaction)return;let t=this.interaction.graphControl;t&&t.setZoom(t.getZoom()+e)}async zoomOut(e=2){if(!this.interaction)return;let t=this.interaction.graphControl;t&&t.setZoom(t.getZoom()-e)}setAutoRotate(e,t=.005){this.interaction&&(e?this.interaction.startAutoRotate(t):this.interaction.stopAutoRotate())}resetRotation(e){if(!this.interaction)return Promise.resolve();let t=this.interaction.graphControl;if(!t)return Promise.resolve();let r=e?.smooth??!0,n=e?.duration??400;return t.resetRotation(r,n),Promise.resolve()}worldToScreen(e){let t=this.interaction?.graphControl;if(!t)return null;let r=t.getCamera();if(!r)return null;let n=document.querySelector("#canvas-renderContainer canvas");if(!n)return null;let i=new Zs.Vector3(e.x,e.y,e.z).project(r);return{x:(i.x+1)/2*n.clientWidth,y:(1-i.y)/2*n.clientHeight}}};var Pn=class{constructor(e,t,r){this.type="SetNodeColor";this.oldOverrides=0;this.store=e,this.nodeId=t,this.color=r,this.oldOverrides=e.getNodeOverrides(t);let n=e.index.nodeIdToIndex.get(t);if(n!==void 0&&e.nodeState){let i=e.nodeState.colors;this.oldColor=[i[n*3],i[n*3+1],i[n*3+2]]}else this.oldColor=[1,1,1]}execute(){this.store.setNodeColor(this.nodeId,this.color)}undo(){this.store.setNodeColor(this.nodeId,this.oldColor),this.store.setNodeOverrides(this.nodeId,this.oldOverrides)}},Xs=class{constructor(e,t,r){this.type="SetCategoryColor";this.store=e,this.color=r;let n=e.nodeSlotsOfCategory(t),i=n.length;this.slots=Uint32Array.from(n),this.ids=new Array(i),this.oldColors=new Float32Array(i*3),this.oldOverrides=new Uint8Array(i);let o=e.nodeState,s=e.index;for(let d=0;d<i;d++){let l=n[d];this.ids[d]=s.getNodeId(l),o?(this.oldColors[d*3]=o.colors[l*3],this.oldColors[d*3+1]=o.colors[l*3+1],this.oldColors[d*3+2]=o.colors[l*3+2],this.oldOverrides[d]=o.overrides[l]|0):this.oldColors.fill(1,d*3,d*3+3)}}get count(){return this.slots.length}execute(){this.store.setNodeColorAtSlots(this.currentSlots(),this.color)}undo(){this.store.restoreNodeColorsAtSlots(this.currentSlots(),this.oldColors,this.oldOverrides)}currentSlots(){let e=this.store.index,t=this.slots;for(let r=0;r<t.length;r++)e.getNodeId(t[r])!==this.ids[r]&&(t===this.slots&&(t=this.slots.slice()),t[r]=e.getNodeIndex(this.ids[r])??4294967295);return t}},An=class{constructor(e,t,r){this.type="SetNodeSize";this.oldOverrides=0;this.store=e,this.nodeId=t,this.size=r,this.oldOverrides=e.getNodeOverrides(t);let n=e.index.nodeIdToIndex.get(t);n!==void 0&&e.nodeState?this.oldSize=e.nodeState.sizes[n]:this.oldSize=e.defaultNodeSize}execute(){this.store.setNodeSize(this.nodeId,this.size)}undo(){this.store.setNodeSize(this.nodeId,this.oldSize),this.store.setNodeOverrides(this.nodeId,this.oldOverrides)}},_n=class{constructor(e,t,r){this.type="SetEdgeColor";this.store=e,this.edgeId=t,this.color=r;let n=e.index.edgeIdToIndex.get(t);if(n!==void 0&&e.edgeState){let i=e.edgeState.colors;this.oldColor=[i[n*3],i[n*3+1],i[n*3+2]]}else this.oldColor=[1,1,1]}execute(){this.store.setEdgeColor(this.edgeId,this.color)}undo(){this.store.setEdgeColor(this.edgeId,this.oldColor)}},ho=class{constructor(e,t,r){this.type="SetEdgeWidth";this.store=e,this.edgeId=t,this.width=r;let n=e.index.edgeIdToIndex.get(t);n!==void 0&&e.edgeState?this.oldWidth=e.edgeState.widths[n]:this.oldWidth=1}execute(){this.store.setEdgeWidth(this.edgeId,this.width)}undo(){this.store.setEdgeWidth(this.edgeId,this.oldWidth)}},po=class{constructor(e,t,r){this.type="SetNodeIcon";this.oldOverrides=0;this.store=e,this.nodeId=t,this.icon=r,this.oldOverrides=e.getNodeOverrides(t),this.oldIconName=e.getNodeIconName(t);let n=e.index.nodeIdToIndex.get(t);this.oldIconIndex=n!==void 0&&e.nodeState?e.nodeState.icons[n]:-1}execute(){this.store.setNodeIcon(this.nodeId,this.icon)}undo(){this.oldIconName!==void 0?this.store.setNodeIcon(this.nodeId,this.oldIconName):this.oldIconIndex>=0?this.store.setNodeIcon(this.nodeId,this.oldIconIndex):this.store.setNodeIcon(this.nodeId,null),this.store.setNodeOverrides(this.nodeId,this.oldOverrides)}},go=class{constructor(e,t,r){this.type="SetNodeImage";this.store=e,this.nodeId=t,this.url=r,this.oldUrl=e.getNodeImageUrl(t)??null}execute(){this.store.setNodeImageUrl(this.nodeId,this.url)}undo(){this.store.setNodeImageUrl(this.nodeId,this.oldUrl)}},Qs=class{constructor(e,t){this.type="SetDefaultNodeSize";this.store=e,this.size=t,this.oldSize=e.defaultNodeSize}execute(){this.store.defaultNodeSize=this.size,this.store.notifyChange()}undo(){this.store.defaultNodeSize=this.oldSize,this.store.notifyChange()}},Js=class{constructor(e,t,r){this.type="SetEdgeDashed";this.store=e,this.edgeId=t,this.dashed=r;let n=e.index.edgeIdToIndex.get(t);this.oldDashed=n!==void 0&&e.edgeState?e.edgeState.dashed[n]:0}execute(){this.store.setEdgeDashed(this.edgeId,this.dashed)}undo(){this.store.setEdgeDashed(this.edgeId,this.oldDashed>0)}},xf={0:"straight",1:"curve",2:"radial",3:"orthogonal",4:"routed",5:"family"},tn=class{constructor(e,t,r){this.type="SetEdgeShape";this.store=e,this.edgeId=t,this.shape=r;let n=e.index.edgeIdToIndex.get(t);this.oldShapeValue=n!==void 0&&e.edgeState?e.edgeState.shapes[n]:-1}execute(){this.store.setEdgeShape(this.edgeId,this.shape)}undo(){if(this.oldShapeValue>=0)this.store.setEdgeShape(this.edgeId,xf[this.oldShapeValue]??"straight");else{let e=this.store.index.edgeIdToIndex.get(this.edgeId);e!==void 0&&this.store.edgeState&&(this.store.edgeState.shapes[e]=-1,this.store.updateStrategy.markDirty("edgeShapes"),this.store.notifyChange())}}},li=class{constructor(e,t,r){this.type="SetEdgeBend";this.store=e,this.edgeId=t,this.bend=r;let n=e.index.edgeIdToIndex.get(t);this.oldBend=n!==void 0&&e.edgeState?e.edgeState.bends[n]:NaN}execute(){this.store.setEdgeBend(this.edgeId,this.bend)}undo(){this.store.setEdgeBend(this.edgeId,this.oldBend)}},ci=class{constructor(e,t,r){this.store=e;this.edgeId=t;this.route=r;this.type="SetEdgeRoute";this.oldRoute=e.edgeRoute(t)??null}execute(){this.store.setEdgeRouteEncoded(this.edgeId,this.route)}undo(){this.store.setEdgeRouteEncoded(this.edgeId,this.oldRoute)}},ui=class{constructor(e,t,r){this.store=e;this.edgeId=t;this.anchorNodeId=r;this.type="SetEdgeAnchor";this.oldAnchor=e.edgeAnchor(t)??null}execute(){this.store.setEdgeAnchor(this.edgeId,this.anchorNodeId)}undo(){this.store.setEdgeAnchor(this.edgeId,this.oldAnchor)}},fo=class{constructor(e,t){this.type="SetEdgeScale";this.store=e,this.scale=t,this.oldScale=e.edgeScale}execute(){this.store.edgeScale=this.scale,this.store.notifyChange()}undo(){this.store.edgeScale=this.oldScale,this.store.notifyChange()}},mo=class{constructor(e,t){this.type="SetEdgeArrow";this.store=e,this.visible=t,this.oldVisible=e.edgeArrowVisible}execute(){this.store.edgeArrowVisible=this.visible,this.store.notifyChange()}undo(){this.store.edgeArrowVisible=this.oldVisible,this.store.notifyChange()}};var ea=class{constructor(e,t,r){this._tweenDuration=500;this.store=e,this.executor=t,this.eventBus=r}setTweenDuration(e){this._tweenDuration=e}buildContext(e){let t=this.store.data.nodes,r=e?t.filter(o=>e.includes(o.id)):t,n=this.store.positionProvider?.getPositions(),i=new Map;for(let o of r){let s=this.store.index.nodeIdToIndex.get(o.id);s!==void 0&&n?i.set(o.id,[n[s*3],n[s*3+1],n[s*3+2]]):i.set(o.id,[0,0,0])}return{nodes:r,positions:i,edges:this.store.data.edges}}applyPositions(e){let t=new di(this.store,e);this.executor.execute(t)}async runLayout(e,t){let r=Date.now();this.eventBus.emit("layout:start",{type:e});let n=t(),i=n instanceof Map?n:n.positions,o=!(n instanceof Map)&&(n.edgeParams?.size||n.edgeRoutingAxis)?n:null;if(o){this.executor.beginTransaction(`Layout ${e}`);try{this.applyEdgeShapes(o,i),await this.movePositions(i)}finally{this.executor.endTransaction()}}else await this.movePositions(i);this.eventBus.emit("layout:end",{type:e,duration:Date.now()-r})}applyEdgeShapes(e,t){if(e.edgeRoutingAxis&&(this.store.edgeRoutingAxis=e.edgeRoutingAxis==="horizontal"?2:1,this.store.notifyChange()),!e.edgeParams)return;let r=this.store.positionProvider?.getPositions(),n=i=>{let o=t.get(i);if(o)return o;let s=this.store.index.getNodeIndex(i);return s!==void 0&&r?[r[s*3],r[s*3+1],r[s*3+2]]:null};for(let[i,o]of e.edgeParams){let s=this.store.index.getEdgeIndex(i);if(s!==void 0&&(o.shape!==void 0&&this.executor.execute(new tn(this.store,i,o.shape)),o.bend!==void 0&&this.executor.execute(new li(this.store,i,o.bend===null?NaN:o.bend)),o.anchor!==void 0&&this.executor.execute(new ui(this.store,i,o.anchor)),o.route!==void 0)){let d=this.store.data.edges[s],l=n(d.source),u=n(d.target),c=o.route&&l&&u?Ss(l,u,o.route):null;this.executor.execute(new ci(this.store,i,c))}}}async movePositions(e){let t=this._tweenDuration,r=this.store.positionProvider?.getPositions();if(t>0&&r&&typeof requestAnimationFrame<"u"){let i=new Map;for(let[s]of e){let d=this.store.index.nodeIdToIndex.get(s);d!==void 0&&i.set(s,[r[d*3],r[d*3+1],r[d*3+2]])}let o=new Ll(i,e,{duration:t,easing:"easeInOut"});await new Promise(s=>{let d=()=>{let l=o.tick(performance.now());this.store.setPositions(l),o.done?(this.executor.execute(new en(this.store,i,e)),s()):requestAnimationFrame(d)};requestAnimationFrame(d)})}else this.applyPositions(e);let n=Array.from(e.keys());n.length>0&&this.store.pinNodes(n)}async circle(e,t){return this.runLayout("circle",()=>{let r=this.buildContext(e);return Rl(r,t).positions})}async grid(e,t){return this.runLayout("grid",()=>{let r=this.buildContext(e);return Cl(r,t).positions})}async line(e,t){return this.runLayout("line",()=>{let r=this.buildContext(e);return wl(r,t).positions})}async spiral(e,t){return this.runLayout("spiral",()=>{let r=this.buildContext(e);return Tl(r,t).positions})}async cube(e,t){return this.runLayout("cube",()=>{let r=this.buildContext(e);return Ml(r,t).positions})}async sphere(e,t){return this.runLayout("sphere",()=>{let r=this.buildContext(e);return Il(r,t).positions})}async scatter(e,t){return this.runLayout("scatter",()=>{let r=this.buildContext(e);return Pl(r,t).positions})}async ego(e,t){return this.runLayout("ego",()=>{let r=this.buildContext();if(e&&e.length>0){let n=new Set(e);r.nodes=r.nodes.filter(i=>n.has(i.id))}return kl(r,t).positions})}async tree(e,t){return this.runLayout("tree",()=>Gl(this.buildContext(e),t).positions)}async radialTree(e,t){return this.runLayout("radialTree",()=>Hl(this.buildContext(e),t).positions)}async layered(e,t){return this.runLayout("layered",()=>Fl(this.buildContext(e),t))}async columns(e,t){if(!t||!t.by)throw new Error("[LayoutApi.columns] options.by is required");return this.runLayout("columns",()=>zl(this.buildContext(e),t).positions)}async genealogy(e,t){return this.runLayout("genealogy",()=>Bl(this.buildContext(e),t))}async applyByName(e,t,r){switch(e){case"circle":return this.circle(t);case"grid":return this.grid(t);case"line":return this.line(t);case"spiral":return this.spiral(t);case"sphere":return this.sphere(t);case"cube":return this.cube(t);case"scatter":return this.scatter(t);case"ego":return this.ego(t);case"scale-spacing-up":return this.scale(1.25,t);case"scale-spacing-down":return this.scale(.8,t)}let n=this.store.registry.layouts;if(!n.has(e))throw new Error(`[LayoutApi.applyByName] unknown layout "${e}". Registered: ${n.list().map(i=>i.name).join(", ")}`);return this.runLayout(e,()=>n.execute(e,this.buildContext(t),r))}register(e,t,r){return this.store.registry.layouts.register(e,t,r)}has(e){return this.store.registry.layouts.has(e)}list(){return this.store.registry.layouts.list().map(({name:e,builtin:t,description:r})=>({name:e,builtin:t,description:r}))}async rotate(e,t,r){return this.runLayout("rotate",()=>{let n=this.buildContext(r);return Al(n,{axis:e,degrees:t}).positions})}async scale(e,t){return this.runLayout("scale",()=>{let r=this.buildContext(t),n=typeof e=="number"?{factor:e}:{x:e.x,y:e.y,z:e.z};return _l(r,n).positions})}async shift(e,t){return this.runLayout("shift",()=>{let r=this.buildContext(t);return Dl(r,{x:e.x,y:e.y,z:e.z??0}).positions})}async alignBy(e,t){return this.runLayout("alignBy",()=>{let r=this.buildContext(t);return Nl(r,{axis:e}).positions})}getPosition(e){let t=this.store.index.nodeIdToIndex.get(e);if(t===void 0)return null;let r=this.store.positionProvider?.getPositions();return r?{x:r[t*3],y:r[t*3+1],z:r[t*3+2]}:null}setPositions(e){let t=new Map;for(let{id:r,x:n,y:i,z:o}of e)t.set(r,[n,i,o??0]);this.applyPositions(t)}_writePositionsNoUndo(e){let t=new Map;for(let{id:r,x:n,y:i,z:o}of e)t.set(r,[n,i,o??0]);this.store.setPositions(t)}async explode(e,t={x:0,y:0,z:0}){let r=this.store.positionProvider?.getPositions();if(!r)return;let n=e??this.store.data.nodes.map(s=>s.id),i=[t.x,t.y,t.z],o=new Map;for(let s of n){let d=this.store.index.nodeIdToIndex.get(s);d!==void 0&&o.set(s,[r[d*3],r[d*3+1],r[d*3+2]])}for(let s of n){let d=this.store.index.nodeIdToIndex.get(s);d!==void 0&&(r[d*3]=i[0],r[d*3+1]=i[1],r[d*3+2]=i[2])}this.store.notifyChange(),await this.runLayout("explode",()=>o)}};var ta=class{constructor(e,t,r){this.type="SetNodeBadge";this.store=e,this.nodeId=t,this.next=r,this.prev=e.getNodeBadge(t)}execute(){this.store.setNodeBadge(this.nodeId,this.next)}undo(){this.store.setNodeBadge(this.nodeId,this.prev)}},ra=class{constructor(e){this.type="ClearAllBadges";this.prev=[];this.store=e,this.prev=e.hasBadgeData()?e.listBadges().map(({nodeId:t,spec:r})=>[t,r]):[]}execute(){this.store.clearAllBadges()}undo(){for(let[e,t]of this.prev)this.store.setNodeBadge(e,t)}};var na=class{constructor(e,t,r){this.type="SetNodeCollect";this.label="Set node collect";this.store=e,this.nodeId=t,this.next=r,this._prev=e.getNodeCollect(t)}execute(){this.store.setNodeCollect(this.nodeId,this.next)}undo(){this.store.setNodeCollect(this.nodeId,this._prev)}};var ia=class{constructor(e,t){this.type="CreateTag";this.label="Create tag";this.store=e,this.spec=t}execute(){this.tagId===void 0?this.tagId=this.store.createTag(this.spec):this.store._restoreTag(this.tagId,this.spec,[])}undo(){this.tagId!==void 0&&this.store.deleteTag(this.tagId)}},oa=class{constructor(e,t,r){this.type="AssignTag";this.label="Assign tag";this.store=e,this.tagId=t,this.nodeIds=r,this.prevByNode=new Map;for(let n of r)this.prevByNode.set(n,e.getNodeTag(n)?.id??null)}execute(){this.store.assignTag(this.tagId,[...this.nodeIds])}undo(){this.store.unassignTag(this.tagId,[...this.nodeIds]);for(let[e,t]of this.prevByNode)t!==null&&this.store.assignTag(t,[e])}},sa=class{constructor(e,t,r){this.type="UpdateTag";this.label="Update tag";this.store=e,this.tagId=t,this.patch=r,this.prev=e.getTagSpec(t)}execute(){this.store.updateTag(this.tagId,this.patch)}undo(){this.prev&&this.store.updateTag(this.tagId,this.prev)}},aa=class{constructor(e,t,r){this.type="UnassignTag";this.label="Unassign tag";this.store=e,this.tagId=t,this.nodeIds=r}execute(){this.store.unassignTag(this.tagId,[...this.nodeIds])}undo(){this.store.assignTag(this.tagId,[...this.nodeIds])}},da=class{constructor(e,t){this.type="DeleteTag";this.label="Delete tag";this.store=e,this.tagId=t,this.prevSpec=e.getTagSpec(t),this.prevNodes=e.getTagNodeIds(t)}execute(){this.store.deleteTag(this.tagId)}undo(){this.prevSpec&&this.store._restoreTag(this.tagId,this.prevSpec,this.prevNodes)}},la=class{constructor(e){this.type="ClearAllTags";this.label="Clear all tags";this.store=e,this.snapshot=e.listTags()}execute(){this.store.clearAllTags()}undo(){for(let{id:e,spec:t,nodeIds:r}of this.snapshot)this.store._restoreTag(e,t,r)}};function Ph(a){let e=a.replace("#",""),t=e.length===3?e.split("").map(o=>o+o).join(""):e,r=parseInt(t.slice(0,2),16)/255,n=parseInt(t.slice(2,4),16)/255,i=parseInt(t.slice(4,6),16)/255;return[r,n,i]}function Ah(a,e,t){let[r,n,i]=Ph(a),[o,s,d]=Ph(e),l=Math.round((r+(o-r)*t)*255),u=Math.round((n+(s-n)*t)*255),c=Math.round((i+(d-i)*t)*255);return`#${l.toString(16).padStart(2,"0")}${u.toString(16).padStart(2,"0")}${c.toString(16).padStart(2,"0")}`}var ca=["#e6194b","#3cb44b","#ffe119","#4363d8","#f58231","#911eb4","#42d4f4","#f032e6","#bfef45","#fabed4","#469990","#dcbeff","#9a6324","#fffac8","#800000","#aaffc3","#808000","#ffd8b1","#000075","#a9a9a9"],Ef={auto:0,vertical:1,horizontal:2},ua=class{constructor(e,t,r){this._captionConfig=null;this._captionScale=1;this._edgeArrowVisible=!0;this._globalEdgeShape=null;this._edgeScale=1;this._stylesheetRules=[];this._stub={};this.store=e,this.executor=t,this.eventBus=r}setEdgeBlend(e){this._stub.edgeBlend=!!e}getEdgeBlend(){return this._stub.edgeBlend??!1}async withTransaction(e,t){this.executor.beginTransaction(e);try{return await t()}finally{this.executor.endTransaction()}}async setNodeColor(e,t){this.executor.execute(new Pn(this.store,e,t))}async setNodeColors(e){await this.withTransaction(`Set node colors (${e.length})`,()=>{for(let{id:t,color:r}of e)this.executor.execute(new Pn(this.store,t,r))})}async colorNodesByProperty(e,t){let r=t?.mode??"ordinal",n=t?.category,i=n?this.store.nodesOfCategory(n):this.store.data.nodes,o=i.map(s=>s.properties[e]);await this.withTransaction(`Color nodes by ${e}`,()=>{if(r==="sequential"){let s=o.map(p=>typeof p=="number"?p:parseFloat(String(p??0))||0),d=Math.min(...s),u=Math.max(...s)-d||1,c=t?.colorFrom??"#0000ff",h=t?.colorTo??"#ff0000";for(let p=0;p<i.length;p++){let f=(s[p]-d)/u,m=Ah(c,h,f);this.executor.execute(new Pn(this.store,i[p].id,m))}}else{let s=t?.colorMap??{},d=new Map,l=0;for(let u=0;u<i.length;u++){let c=String(o[u]??""),h;s[c]?h=s[c]:d.has(c)?h=d.get(c):(h=ca[l%ca.length],l++,d.set(c,h)),this.executor.execute(new Pn(this.store,i[u].id,h))}}}),this.eventBus.emit("style:changed",{target:"category",name:t?.category??""})}async setCategoryColor(e,t){this.store.visualMapper.categoryColors.setColor(e,t),await this.withTransaction(`Set ${e} color`,()=>{this.executor.execute(new Xs(this.store,e,t))}),this.eventBus.emit("style:changed",{target:"category",name:e})}getCategoryColor(e){return this.store.visualMapper.categoryColors.getColor(e)}async setNodeSize(e,t){this.executor.execute(new An(this.store,e,t))}async setNodeSizes(e){await this.withTransaction(`Set node sizes (${e.length})`,()=>{for(let{id:t,size:r}of e)this.executor.execute(new An(this.store,t,r))})}async sizeNodesByProperty(e,t){let r=t?.category,n=t?.minSize??5,i=t?.maxSize??30,o=t?.scale??"linear",s=r?this.store.nodesOfCategory(r):this.store.data.nodes,d=s.map(m=>{let g=m.properties[e];return typeof g=="number"?g:parseFloat(String(g??0))||0}),l=Math.min(...d),u=Math.max(...d),c=o==="log"?l>0?0:1-l:o==="sqrt"&&l<0?-l:0,h=m=>{let g=m+c;return o==="sqrt"?Math.sqrt(Math.max(0,g)):o==="log"?Math.log(Math.max(Number.EPSILON,g)):m},p=h(l),f=h(u)-p||1;await this.withTransaction(`Size nodes by ${e}`,()=>{for(let m=0;m<s.length;m++){let g=Math.max(0,Math.min(1,(h(d[m])-p)/f)),y=n+(i-n)*g;this.executor.execute(new An(this.store,s[m].id,y))}}),this.eventBus.emit("style:changed",{target:"category",name:t?.category??""})}async setDefaultNodeSize(e){this.executor.execute(new Qs(this.store,e))}async setNodeIcon(e,t){this.executor.execute(new po(this.store,e,t)),this.store.invalidateTransactionVersion()}async setCategoryIcon(e,t){await this.withTransaction(`Set ${e} icon`,()=>{let r=this.store.nodesOfCategory(e);for(let n of r)this.executor.execute(new po(this.store,n.id,t))}),this.store.invalidateTransactionVersion(),this.eventBus.emit("style:changed",{target:"category",name:e})}getAvailableIcons(){return Array.from(this.store.iconNames.values())}setNodeBadge(e,t){this.executor.execute(new ta(this.store,e,t))}getNodeBadge(e){return this.store.getNodeBadge(e)}clearAllBadges(){this.executor.execute(new ra(this.store))}createTag(e){let t=new ia(this.store,e);return this.executor.execute(t),t.tagId}updateTag(e,t){this.executor.execute(new sa(this.store,e,t))}deleteTag(e){this.executor.execute(new da(this.store,e))}assignTag(e,t){this.executor.execute(new oa(this.store,e,t))}unassignTag(e,t){this.executor.execute(new aa(this.store,e,t))}listTags(){return this.store.listTags()}clearAllTags(){this.executor.execute(new la(this.store))}setNodeTag(e,t){if(t===null){let n=this.store.getNodeTag(e);n&&this.unassignTag(n.id,[e]);return}if(typeof t=="string"){this.assignTag(t,[e]);return}let r=this.createTag(t);this.assignTag(r,[e])}getNodeTag(e){return this.store.getNodeTag(e)}setNodeCollect(e,t){this.executor.execute(new na(this.store,e,t))}getNodeCollect(e){return this.store.getNodeCollect(e)}async setNodeImage(e,t){this.executor.execute(new go(this.store,e,t))}async imageByProperty(e,t){let r=t?.category,n=r?this.store.nodesOfCategory(r):this.store.data.nodes;await this.withTransaction(`Image nodes by ${e}`,()=>{for(let i of n){let o=i.properties[e];typeof o=="string"&&o&&this.executor.execute(new go(this.store,i.id,o))}}),this.eventBus.emit("style:changed",{target:"category",name:r??""})}async setCaptions(e){this._captionConfig=e,this._applyCaptionsToVisualMapper(e),this.eventBus.emit("style:changed",{target:"category",name:e.category??""})}_applyCaptionsToVisualMapper(e){let t=this.store.visualMapper;if(!t)return;let r=e.property?{captions:[{source:`property:${e.property}`,whenEmpty:"hide"}]}:void 0,n=e.category?[e.category]:Array.from(new Set(this.store.data.nodes.map(i=>i.category).filter(i=>!!i)));for(let i of n){let o=t.getCategoryConfig(i);!r&&!o||t.setCategoryConfig({...o,category:i,captionConfig:r},"user")}this.store.notifyChange?.()}async setCaptionScale(e){this._captionScale=e,this.eventBus.emit("style:changed",{target:"category",name:""})}getCaptionConfig(){return this._captionConfig}getCaptionScale(){return this._captionScale}async setEdgeColor(e,t){this.executor.execute(new _n(this.store,e,t))}async colorEdgesByProperty(e,t){let r=t?.mode??"ordinal",n=t?.relationship,i=n?this.store.data.edges.filter(s=>s.relationship===n):this.store.data.edges,o=i.map(s=>s.properties[e]);await this.withTransaction(`Color edges by ${e}`,()=>{if(r==="sequential"){let s=o.map(p=>typeof p=="number"?p:parseFloat(String(p??0))||0),d=Math.min(...s),u=Math.max(...s)-d||1,c=t?.colorFrom??"#0000ff",h=t?.colorTo??"#ff0000";for(let p=0;p<i.length;p++){let f=(s[p]-d)/u,m=Ah(c,h,f);this.executor.execute(new _n(this.store,i[p].id,m))}}else{let s=t?.colorMap??{},d=new Map,l=0;for(let u=0;u<i.length;u++){let c=String(o[u]??""),h;s[c]?h=s[c]:d.has(c)?h=d.get(c):(h=ca[l%ca.length],l++,d.set(c,h)),this.executor.execute(new _n(this.store,i[u].id,h))}}}),this.eventBus.emit("style:changed",{target:"relationship",name:t?.relationship??""})}async setRelationshipColor(e,t){this.store.visualMapper.relationshipColors.setColor(e,t),await this.withTransaction(`Set ${e} color`,()=>{let r=this.store.data.edges.filter(n=>n.relationship===e);for(let n of r)this.executor.execute(new _n(this.store,n.id,t))}),this.eventBus.emit("style:changed",{target:"relationship",name:e})}getRelationshipColor(e){return this.store.visualMapper.relationshipColors.getColor(e)}async setEdgeWidth(e,t){this.executor.execute(new ho(this.store,e,t))}async setRelationshipWidth(e,t){await this.withTransaction(`Set ${e} width`,()=>{let r=this.store.data.edges.filter(n=>n.relationship===e);for(let n of r)this.executor.execute(new ho(this.store,n.id,t))}),this.eventBus.emit("style:changed",{target:"relationship",name:e})}async setEdgeScale(e){this._edgeScale=e,this.executor.execute(new fo(this.store,e))}setEdgeTubeGlow(e,t){let r=Array.isArray(e)?e:[e],n=this.store.edgeState;if(n){for(let i of r){let o=this.store.index.getEdgeIndex(i);o!==void 0&&(n.tubeGlow[o]=t)}this.store.updateStrategy.markDirty("edgeTubeGlow"),this.store.notifyChange()}}clearEdgeTubeGlow(e){let t=this.store.edgeState;if(t){if(e===void 0)t.tubeGlow.fill(0);else{let r=Array.isArray(e)?e:[e];for(let n of r){let i=this.store.index.getEdgeIndex(n);i!==void 0&&(t.tubeGlow[i]=0)}}this.store.updateStrategy.markDirty("edgeTubeGlow"),this.store.notifyChange()}}setNodeHalo(e,t){let r=Array.isArray(e)?e:[e],n=this.store.nodeState;if(n){for(let i of r){let o=this.store.index.getNodeIndex(i);o!==void 0&&(n.halo[o]=t)}this.store.updateStrategy.markDirty("nodeHalo"),this.store.notifyChange()}}clearNodeHalo(e){let t=this.store.nodeState;if(t){if(e===void 0)t.halo.fill(0);else{let r=Array.isArray(e)?e:[e];for(let n of r){let i=this.store.index.getNodeIndex(n);i!==void 0&&(t.halo[i]=0)}}this.store.updateStrategy.markDirty("nodeHalo"),this.store.notifyChange()}}async setEdgeDashed(e,t){await this.withTransaction(`Set edge dashed (${e.length})`,()=>{for(let r of e)this.executor.execute(new Js(this.store,r,t))})}async setEdgeArrowVisible(e){this._edgeArrowVisible=e,this.executor.execute(new mo(this.store,e))}getEdgeArrowVisible(){return this._edgeArrowVisible}async setEdgeShape(e){this._globalEdgeShape=e,this.store.defaultEdgeShape=this.store.registry.resolveEdgeShapeId(e),await this.withTransaction(`Set edge shape to ${e}`,()=>{for(let t of this.store.data.edges)this.executor.execute(new tn(this.store,t.id,e))})}async setEdgeShapes(e,t){await this.withTransaction(`Set edge shapes (${e.length})`,()=>{for(let r of e)this.executor.execute(new tn(this.store,r,t))})}async setRelationshipShape(e,t){await this.withTransaction(`Set ${e} shape`,()=>{let r=this.store.data.edges.filter(n=>n.relationship===e);for(let n of r)this.executor.execute(new tn(this.store,n.id,t))})}async setEdgeBends(e,t){if(t!==null&&!Number.isFinite(t))throw new Error(`setEdgeBends: bend must be a finite number or null, got ${t}`);let r=t===null?NaN:t;await this.withTransaction(`Set edge bends (${e.length})`,()=>{for(let n of e)this.executor.execute(new li(this.store,n,r))})}setEdgeRouting(e){if(e.cornerRadius!==void 0){if(!Number.isFinite(e.cornerRadius))throw new Error(`setEdgeRouting: cornerRadius must be a finite number, got ${e.cornerRadius}`);this.store.edgeCornerRadius=Math.min(Math.max(e.cornerRadius,0),1)}if(e.axis!==void 0){let t=Ef[e.axis];if(t===void 0)throw new Error(`setEdgeRouting: unknown axis "${e.axis}"`);this.store.edgeRoutingAxis=t}this.store.notifyChange()}async setEdgeRoute(e,t){let r=this.store.index.getEdgeIndex(e);if(r===void 0)throw new Error(`setEdgeRoute: unknown edge "${e}"`);let n=null;if(t&&t.length>0){if(t.length>bs)throw new Error(`setEdgeRoute: at most ${bs} points, got ${t.length}`);let i=t.map((l,u)=>{let c=l.z??0;if(!Number.isFinite(l.x)||!Number.isFinite(l.y)||!Number.isFinite(c))throw new Error(`setEdgeRoute: point ${u} is not finite`);return[l.x,l.y,c]}),o=this.store.data.edges[r],s=this.nodePosition(o.source),d=this.nodePosition(o.target);if(!s||!d)throw new Error(`setEdgeRoute: positions of edge "${e}" are not available yet`);if(n=Ss(s,d,i),!n)throw new Error(`setEdgeRoute: the two nodes of edge "${e}" share one position`)}this.executor.execute(new ci(this.store,e,n))}async setEdgeAnchor(e,t){if(this.store.index.getEdgeIndex(e)===void 0)throw new Error(`setEdgeAnchor: unknown edge "${e}"`);if(t!==null&&this.store.index.getNodeIndex(t)===void 0)throw new Error(`setEdgeAnchor: unknown node "${t}"`);this.executor.execute(new ui(this.store,e,t))}nodePosition(e){let t=this.store.index.getNodeIndex(e),r=this.store.positionProvider?.getPositions();return t===void 0||!r||r.length<t*3+3?null:[r[t*3],r[t*3+1],r[t*3+2]]}async setCategoryVisibility(e,t){this.executor.execute(new ks(this.store,e,t))}async setRelationshipVisibility(e,t){this.executor.execute(new Gs(this.store,e,t))}async applyStylesheet(e){this._stylesheetRules=e,await this.withTransaction(`Apply stylesheet (${e.length} rule${e.length===1?"":"s"})`,async()=>{for(let t of e)if(t.category){if(t.color&&await this.setCategoryColor(t.category,t.color),t.size!==void 0){let r=this.store.nodesOfCategory(t.category);for(let n of r)this.executor.execute(new An(this.store,n.id,t.size))}t.icon&&await this.setCategoryIcon(t.category,t.icon)}else t.relationship&&t.color&&await this.setRelationshipColor(t.relationship,t.color)}),this.eventBus.emit("style:changed",{target:"category",name:""})}async clearStyles(){this._stylesheetRules=[],this._captionConfig=null,this._captionScale=1,this._globalEdgeShape=null,this._edgeScale=1,this._edgeArrowVisible=!0,await this.withTransaction("Clear styles",()=>{this.executor.execute(new fo(this.store,1)),this.executor.execute(new mo(this.store,!0))}),this.eventBus.emit("style:changed",{target:"category",name:""})}};var ha=class{constructor(e,t,r=[]){this.type="AddCategory";this.store=e,this.name=t,this.properties=r}execute(){let e=this.store.getSchema();if(e.categories.some(r=>r.name===this.name))return;let t={...e,categories:[...e.categories,{name:this.name,properties:this.properties}]};this.store.setSchema(t),this.store.notifyChange()}undo(){let e=this.store.getSchema(),t={...e,categories:e.categories.filter(r=>r.name!==this.name)};this.store.setSchema(t),this.store.notifyChange()}},pa=class{constructor(e,t){this.type="RemoveCategory";this.removedEntry=null;this.store=e,this.name=t;let n=e.getSchema().categories.find(i=>i.name===t);n&&(this.removedEntry={name:n.name,properties:n.properties.map(i=>({...i}))})}execute(){let e=this.store.getSchema(),t={...e,categories:e.categories.filter(r=>r.name!==this.name)};this.store.setSchema(t),this.store.notifyChange()}undo(){if(!this.removedEntry)return;let e=this.store.getSchema();if(e.categories.some(r=>r.name===this.removedEntry.name))return;let t={...e,categories:[...e.categories,this.removedEntry]};this.store.setSchema(t),this.store.notifyChange()}},ga=class{constructor(e,t,r=[]){this.type="AddRelationship";this.store=e,this.name=t,this.properties=r}execute(){let e=this.store.getSchema();if(e.relationships.some(r=>r.name===this.name))return;let t={...e,relationships:[...e.relationships,{name:this.name,properties:this.properties}]};this.store.setSchema(t),this.store.notifyChange()}undo(){let e=this.store.getSchema(),t={...e,relationships:e.relationships.filter(r=>r.name!==this.name)};this.store.setSchema(t),this.store.notifyChange()}},fa=class{constructor(e,t){this.type="RemoveRelationship";this.removedEntry=null;this.store=e,this.name=t;let n=e.getSchema().relationships.find(i=>i.name===t);n&&(this.removedEntry={name:n.name,properties:n.properties.map(i=>({...i}))})}execute(){let e=this.store.getSchema(),t={...e,relationships:e.relationships.filter(r=>r.name!==this.name)};this.store.setSchema(t),this.store.notifyChange()}undo(){if(!this.removedEntry)return;let e=this.store.getSchema();if(e.relationships.some(r=>r.name===this.removedEntry.name))return;let t={...e,relationships:[...e.relationships,this.removedEntry]};this.store.setSchema(t),this.store.notifyChange()}};var fc=class{constructor(e,t,r){this.type="RenameCategory";this.affectedNodes=[];this.store=e,this.oldName=t,this.newName=r}execute(){let e=this.store.getSchema(),t=e.categories.map(r=>r.name===this.oldName?{...r,name:this.newName}:r);this.store.setSchema({...e,categories:t}),this.affectedNodes=[];for(let r of this.store.data.nodes)r.category===this.oldName&&(this.affectedNodes.push({node:r,oldCategory:r.category}),r.category=this.newName);this.store.notifyChange()}undo(){let e=this.store.getSchema(),t=e.categories.map(r=>r.name===this.newName?{...r,name:this.oldName}:r);this.store.setSchema({...e,categories:t});for(let{node:r,oldCategory:n}of this.affectedNodes)r.category=n;this.store.notifyChange()}},mc=class{constructor(e,t,r){this.type="RenameRelationship";this.affectedEdges=[];this.store=e,this.oldName=t,this.newName=r}execute(){let e=this.store.getSchema(),t=e.relationships.map(r=>r.name===this.oldName?{...r,name:this.newName}:r);this.store.setSchema({...e,relationships:t}),this.affectedEdges=[];for(let r of this.store.data.edges)r.relationship===this.oldName&&(this.affectedEdges.push({edge:r,oldRelationship:r.relationship}),r.relationship=this.newName);this.store.notifyChange()}undo(){let e=this.store.getSchema(),t=e.relationships.map(r=>r.name===this.newName?{...r,name:this.oldName}:r);this.store.setSchema({...e,relationships:t});for(let{edge:r,oldRelationship:n}of this.affectedEdges)r.relationship=n;this.store.notifyChange()}},ma=class{constructor(e,t,r){this.store=e,this.executor=t,this.eventBus=r}getSchema(){return this.store.getSchema()}getNodeTypes(){return this.store.getSchema().categories.map(e=>e.name)}getEdgeTypes(){return this.store.getSchema().relationships.map(e=>e.name)}getNodeType(e){return this.store.getSchema().categories.find(t=>t.name===e)}getEdgeType(e){return this.store.getSchema().relationships.find(t=>t.name===e)}getNodeTypeProperties(e){return this.getNodeType(e)?.properties??[]}getEdgeTypeProperties(e){return this.getEdgeType(e)?.properties??[]}async addNodeType(e,t=[]){this.store.getSchema().categories.some(n=>n.name===e)||(this.executor.execute(new ha(this.store,e,t)),this.emitSchemaChanged("category","add"))}async removeNodeType(e){this.executor.execute(new pa(this.store,e)),this.emitSchemaChanged("category","remove")}async renameNodeType(e,t){this.executor.execute(new fc(this.store,e,t)),this.emitSchemaChanged("category","rename")}async addEdgeType(e,t=[]){this.store.getSchema().relationships.some(n=>n.name===e)||(this.executor.execute(new ga(this.store,e,t)),this.emitSchemaChanged("relationship","add"))}async removeEdgeType(e){this.executor.execute(new fa(this.store,e)),this.emitSchemaChanged("relationship","remove")}async renameEdgeType(e,t){this.executor.execute(new mc(this.store,e,t)),this.emitSchemaChanged("relationship","rename")}infer(){return this.store.queries.inferSchema()}stats(){let e=this.store.data.nodes,t=this.store.data.edges,r={},n={};for(let l of e){r[l.category]=(r[l.category]??0)+1,n[l.category]||(n[l.category]={});for(let u of Object.keys(l.properties))l.properties[u]!==null&&l.properties[u]!==void 0&&(n[l.category][u]=(n[l.category][u]??0)+1)}let i={};for(let[l,u]of Object.entries(r)){i[l]={};for(let[c,h]of Object.entries(n[l]??{}))i[l][c]=u>0?h/u:0}let o={},s={};for(let l of t){o[l.relationship]=(o[l.relationship]??0)+1,s[l.relationship]||(s[l.relationship]={});for(let u of Object.keys(l.properties))l.properties[u]!==null&&l.properties[u]!==void 0&&(s[l.relationship][u]=(s[l.relationship][u]??0)+1)}let d={};for(let[l,u]of Object.entries(o)){d[l]={};for(let[c,h]of Object.entries(s[l]??{}))d[l][c]=u>0?h/u:0}return{nodeCount:e.length,edgeCount:t.length,categoryCount:Object.keys(r).length,relationshipCount:Object.keys(o).length,categoryCounts:r,relationshipCounts:o,categoryCoverage:i,relationshipCoverage:d}}emitSchemaChanged(e,t){this.eventBus.emit("schema:changed",{type:e,action:t})}};var ya=class{constructor(e){this.executor=e}execute(e){return this.executor.execute(e)}flush(){this.executor.flush()}beginTransaction(e){this.executor.beginTransaction(e)}endTransaction(){this.executor.endTransaction()}async transaction(e,t){this.beginTransaction(e);try{return await t()}finally{this.endTransaction()}}get inTransaction(){return this.executor.inTransaction}undo(){this.executor.undo()}redo(){this.executor.redo()}canUndo(){return this.executor.canUndo}canRedo(){return this.executor.canRedo}clear(){this.executor.clear()}getUndoStack(){return this.executor.getUndoStack()}getRedoStack(){return this.executor.getRedoStack()}};var yo={nodesAdded:0,nodesRemoved:0,edgesAdded:0,edgesRemoved:0};var Rf=0;function hi(a){return`${a}-${Date.now()}-${Rf++}`}var va=class{constructor(e,t,r={}){this.snapshot={deletedNodes:[],deletedEdges:[],addedEdges:[],survivorUpdates:[]};this.store=e,this.config=t,this.options=r,this.type="category"in t&&t.category?"MergeNodes":"MergeEdges"}execute(){let{config:e,options:t,store:r}=this,n="category"in e&&e.category!=null,i="relationship"in e&&e.relationship!=null;if(n&&i)throw new TypeError("Provide either category or relationship, not both");if(!n&&!i)throw new TypeError("Provide either category or relationship");return n?this._mergeNodes(e.category,e.keys,t):this._mergeEdges(e.relationship,e.keys,t)}_mergeNodes(e,t,r){let n=this.store,i=n.data.nodes.filter(c=>c.category===e&&n.isNodeVisible(c.id));if(i.length===0)return{...yo};let o=new Map;for(let c of i){let h=JSON.stringify(t.map(p=>c.properties[p]??null));o.has(h)||o.set(h,[]),o.get(h).push(c)}let s=[],d=[],l=[],u=[];for(let c of o.values()){if(c.length<2)continue;let h=c[0],p=c.slice(1);u.push({id:h.id,oldProps:{...h.properties}});let f={...h.properties};for(let y of c)f={...f,...y.properties};if(r.clearUnselectedProperties){let y={};for(let v of t)v in f&&(y[v]=f[v]);f=y}let m=new Set(p.map(y=>y.id)),g=n.data.edges.filter(y=>m.has(y.source)||m.has(y.target));for(let y of g){let v={...y,id:hi("e"),source:m.has(y.source)?h.id:y.source,target:m.has(y.target)?h.id:y.target};v.source!==v.target&&l.push(v)}s.push(...p.map(y=>({...y,properties:{...y.properties}}))),d.push(...g.map(y=>({...y,properties:{...y.properties}}))),n.replaceNodeProperties(h.id,f)}return this.snapshot={deletedNodes:s,deletedEdges:d,addedEdges:l,survivorUpdates:u},n.applyDelta({removedEdgeIds:d.map(c=>c.id),removedNodeIds:s.map(c=>c.id),addedEdges:l}),n.notifyChange(),{nodesAdded:0,nodesRemoved:s.length,edgesAdded:l.length,edgesRemoved:d.length}}_mergeEdges(e,t,r){let n=this.store,i=n.data.edges.filter(d=>d.relationship===e&&n.isNodeVisible(d.source)&&n.isNodeVisible(d.target));if(i.length===0)return{...yo};let o=new Map;for(let d of i){let[l,u]=r.directional?[d.source,d.target]:[d.source,d.target].sort(),c=JSON.stringify([l,u,...t.map(h=>d.properties?.[h]??null)]);o.has(c)||o.set(c,[]),o.get(c).push(d)}let s=[];for(let d of o.values())d.length<2||s.push(...d.slice(1).map(l=>({...l,properties:{...l.properties}})));return this.snapshot={deletedNodes:[],deletedEdges:s,addedEdges:[],survivorUpdates:[]},n.applyDelta({removedEdgeIds:s.map(d=>d.id)}),n.notifyChange(),{nodesAdded:0,nodesRemoved:0,edgesAdded:0,edgesRemoved:s.length}}undo(){let{snapshot:e,store:t}=this;t.applyDelta({removedEdgeIds:e.addedEdges.map(r=>r.id),addedNodes:e.deletedNodes,addedEdges:e.deletedEdges});for(let r of e.survivorUpdates)t.replaceNodeProperties(r.id,r.oldProps);t.notifyChange()}},ba=class{constructor(e,t,r={}){this.type="ExtractNodes";this.snapshot={createdNodeIds:[],createdEdgeIds:[],restoredSourceProps:[]};this.store=e,this.config=t,this.options=r}execute(){let{store:e,config:t,options:r}=this,{targetCategory:n,props:i}=t,{sourceCategory:o,keys:s=[],relationship:d="HAS",inheritLinks:l=!1,skipEmpty:u=!0}=r,c=e.data.nodes.filter(g=>!(!e.isNodeVisible(g.id)||o&&g.category!==o||u&&!i.some(v=>{let b=g.properties[v];return b!=null&&b!==""})));if(c.length===0)return{...yo};let h=new Map,p=[],f=[],m=[];for(let g of c){m.push({id:g.id,props:{...g.properties}});let y=s.length>0?JSON.stringify(s.map(w=>g.properties[w]??null)):null,v;if(y!==null&&h.has(y))v=h.get(y);else{v=hi("extracted");let w={};for(let I of i)I in g.properties&&(w[I]=g.properties[I]);let T={id:v,category:n,properties:w};p.push(T),y!==null&&h.set(y,v)}let b={...g.properties};for(let w of i)delete b[w];e.replaceNodeProperties(g.id,b);let x={id:hi("e"),source:g.id,target:v,relationship:d,properties:{}};if(f.push(x),l){let w=e.data.edges.filter(T=>T.source===g.id||T.target===g.id);for(let T of w){let I={...T,id:hi("e"),source:T.source===g.id?v:T.source,target:T.target===g.id?v:T.target,properties:{...T.properties}};f.push(I)}}}return this.snapshot={createdNodeIds:p.map(g=>g.id),createdEdgeIds:f.map(g=>g.id),restoredSourceProps:m},e.applyDelta({addedNodes:p,addedEdges:f}),e.notifyChange(),{nodesAdded:p.length,nodesRemoved:0,edgesAdded:f.length,edgesRemoved:0}}undo(){let{snapshot:e,store:t}=this;t.applyDelta({removedEdgeIds:e.createdEdgeIds,removedNodeIds:e.createdNodeIds});for(let r of e.restoredSourceProps)t.replaceNodeProperties(r.id,r.props);t.notifyChange()}};function _h(a,e,t,r){let n=e.filter(i=>typeof i=="number");switch(a){case"count":return e.length;case"sum":return n.reduce((i,o)=>i+o,0);case"average":return n.length?n.reduce((i,o)=>i+o,0)/n.length:null;case"max":return n.length?Math.max(...n):null;case"min":return n.length?Math.min(...n):null;case"concatenate":return e.join(t.separator??", ");case"takeFirst":return e[0]??null;case"custom":if(!r)throw new TypeError("formulaFn is required when formula is 'custom'");return r(e);default:return null}}var Sa=class{constructor(e,t,r={}){this.type="AggregateProperties";this.snapshot={updates:[]};this.store=e,this.config=t,this.options=r}execute(){let{store:e,config:t,options:r}=this,{formula:n,sourceProperty:i}=t,{depth:o=1,from:s,to:d,along:l,targetProperty:u,formulaFn:c}=r;if(n==="custom"&&!c)throw new TypeError("formulaFn is required when formula is 'custom'");let h=s?new Set(Array.isArray(s)?s:[s]):null,p=d?new Set(Array.isArray(d)?d:[d]):null,f=l?new Set(Array.isArray(l)?l:[l]):null,m=e.data.nodes.filter(v=>!(!e.isNodeVisible(v.id)||p&&!p.has(v.category))),g=u??`${n}_${i}`,y=[];for(let v of m){let b=new Set([v.id]),x=[{nodeId:v.id,hop:0}],w=[];for(;x.length;){let{nodeId:I,hop:R}=x.pop();if(R>=o)continue;let S=e.data.edges.filter(P=>(P.source===I||P.target===I)&&(!f||f.has(P.relationship)));for(let P of S){let D=P.source===I?P.target:P.source;if(b.has(D))continue;b.add(D);let E=e.data.nodes.find(M=>M.id===D);E&&((!h||h.has(E.category))&&i in E.properties&&w.push(E.properties[i]),x.push({nodeId:D,hop:R+1}))}}let T=_h(n,w,r,c);y.push({id:v.id,oldProps:{...v.properties}}),e.replaceNodeProperties(v.id,{...v.properties,[g]:T})}return this.snapshot={updates:y},e.notifyChange(),{nodesAdded:0,nodesRemoved:0,edgesAdded:0,edgesRemoved:0}}undo(){let{snapshot:e,store:t}=this;for(let r of e.updates)t.replaceNodeProperties(r.id,r.oldProps);t.notifyChange()}},xa=class{constructor(e,t,r={}){this.type="ShortcutNodes";this.snapshot={deletedNodes:[],deletedEdges:[],addedEdges:[]};this.store=e,this.config=t,this.options=r}execute(){let{store:e,config:t,options:r}=this,{through:n,incomingRelationship:i,outgoingRelationship:o}=t,{sourceCategory:s,targetCategory:d,newRelationship:l,countPaths:u=!1,countProperty:c="count",aggregate:h}=r,p=e.data.nodes.filter(b=>b.category===n&&e.isNodeVisible(b.id));if(p.length===0)return{...yo};let f=e.data.edges,m=new Map;for(let b of p){let x=f.filter(I=>i?I.relationship===i&&I.target===b.id:I.target===b.id||I.source===b.id).map(I=>I.source===b.id?I.target:I.source).filter(I=>!s||e.data.nodes.find(R=>R.id===I)?.category===s),w=f.filter(I=>o?I.relationship===o&&I.source===b.id:I.source===b.id||I.target===b.id).map(I=>I.source===b.id?I.target:I.source).filter(I=>!d||e.data.nodes.find(R=>R.id===I)?.category===d),T=new Set;for(let I of x)for(let R of w){if(I===R)continue;let S=[I,R].sort().join("\u2194");m.has(S)||m.set(S,{a:I,c:R,bNodes:[]}),T.has(S)||(T.add(S),m.get(S).bNodes.push(b))}}let g=l??i??"SHORTCUT",y=[];for(let[,{a:b,c:x,bNodes:w}]of m){if(f.some(I=>(I.source===b&&I.target===x||I.source===x&&I.target===b)&&I.relationship===g))continue;let T={};if(u&&(T[c]=w.length),h)for(let I of h){let R=w.map(S=>S.properties[I.sourceProperty]).filter(S=>S!=null);T[I.targetProperty??`${I.formula}_${I.sourceProperty}`]=_h(I.formula,R,{},void 0)}y.push({id:hi("sc"),source:b,target:x,relationship:g,properties:T})}let v=f.filter(b=>p.some(x=>x.id===b.source||x.id===b.target));return this.snapshot={deletedNodes:p.map(b=>({...b,properties:{...b.properties}})),deletedEdges:v.map(b=>({...b,properties:{...b.properties}})),addedEdges:y},e.applyDelta({removedEdgeIds:v.map(b=>b.id),removedNodeIds:p.map(b=>b.id),addedEdges:y}),e.notifyChange(),{nodesAdded:0,nodesRemoved:p.length,edgesAdded:y.length,edgesRemoved:v.length}}undo(){let{snapshot:e,store:t}=this;t.applyDelta({removedEdgeIds:e.addedEdges.map(r=>r.id),addedNodes:e.deletedNodes,addedEdges:e.deletedEdges}),t.notifyChange()}},Ea=class{constructor(e,t,r={}){this.type="LinkNodes";this.snapshot={addedEdgeIds:[]};this.store=e,this.config=t,this.options=r}execute(){let{store:e,config:t,options:r}=this,{sourceProperty:n,targetProperty:i,relationship:o="LINKED_TO"}=t,{sourceCategory:s,targetCategory:d,matchType:l="exact",matchFn:u}=r,c=e.data.nodes.filter(y=>!(!e.isNodeVisible(y.id)||s&&y.category!==s)),h=e.data.nodes.filter(y=>!(!e.isNodeVisible(y.id)||d&&y.category!==d)),p=y=>{let v=String(y??"");return l==="case-insensitive"?v.toLowerCase():v},f=new Map;for(let y of h){let v=y.properties[i];if(v==null)continue;let b=p(v);f.has(b)||f.set(b,[]),f.get(b).push(y.id)}let m=new Set(e.data.edges.filter(y=>y.relationship===o).map(y=>`${y.source}\u2192${y.target}`)),g=[];for(let y of c){let v=y.properties[n];if(v==null)continue;let b;u?b=h.filter(x=>u(v,x.properties[i])).map(x=>x.id):b=f.get(p(v))??[];for(let x of b){if(y.id===x)continue;let w=`${y.id}\u2192${x}`;m.has(w)||(m.add(w),g.push({id:hi("link"),source:y.id,target:x,relationship:o,properties:{}}))}}return this.snapshot={addedEdgeIds:g.map(y=>y.id)},g.length&&(e.applyDelta({addedEdges:g}),e.notifyChange()),{nodesAdded:0,nodesRemoved:0,edgesAdded:g.length,edgesRemoved:0}}undo(){this.snapshot.addedEdgeIds.length&&(this.store.applyDelta({removedEdgeIds:this.snapshot.addedEdgeIds}),this.store.notifyChange())}};var Ra=class{constructor(e,t){this.store=e,this.executor=t}merge(e,t){try{return Promise.resolve(this.executor.execute(new va(this.store,e,t)))}catch(r){return Promise.reject(r)}}extract(e,t){return Promise.resolve(this.executor.execute(new ba(this.store,e,t)))}aggregate(e,t){try{return Promise.resolve(this.executor.execute(new Sa(this.store,e,t)))}catch(r){return Promise.reject(r)}}shortcut(e,t){return Promise.resolve(this.executor.execute(new xa(this.store,e,t)))}link(e,t){return Promise.resolve(this.executor.execute(new Ea(this.store,e,t)))}};function At(a){if(!(a===void 0||a==="*"))return Array.isArray(a)?a:[a]}function Hr(a,e){if(a===void 0)return e;if(typeof a=="number")return a;if(a instanceof Date)return a.getTime();let t=new Date(a).getTime();return Number.isFinite(t)?t:e}var Mt=class{constructor(e,t,r,n,i){this.mgr=e;this.id=t;this.spec=r;this.type=n;this.target=i}update(e){let t=e;switch(this.type){case"range":{let r=this.spec,n=r.range??[-1/0,1/0],i=t.range,o=[t.min??i?.[0]??n[0]??-1/0,t.max??i?.[1]??n[1]??1/0],s={...r,range:o,...t.on!==void 0?{categories:At(t.on)}:{},...t.includeNull!==void 0?{includeNull:t.includeNull}:{},...t.invert!==void 0?{invert:t.invert}:{}};this.spec=s,this.mgr.addFilter(this.id,s);return}case"dateRange":{let r=this.spec,n=r.range??[-1/0,1/0],i=t.range,o=[t.after!==void 0?Hr(t.after,-1/0):i?.[0]??n[0]??-1/0,t.before!==void 0?Hr(t.before,1/0):i?.[1]??n[1]??1/0],s={...r,range:o,...t.granularity!==void 0?{granularity:t.granularity}:{},...t.on!==void 0?{categories:At(t.on)}:{},...t.includeNull!==void 0?{includeNull:t.includeNull}:{},...t.invert!==void 0?{invert:t.invert}:{}};this.spec=s,this.mgr.addFilter(this.id,s);return}case"match":{let n={...this.spec};t.oneOf!==void 0?n.values=t.oneOf instanceof Set?t.oneOf:new Set(t.oneOf):t.values!==void 0&&(n.values=t.values instanceof Set?t.values:new Set(t.values)),t.regex!==void 0&&(n.regex=t.regex),t.on!==void 0&&(n.categories=At(t.on)),t.includeNull!==void 0&&(n.includeNull=t.includeNull),t.invert!==void 0&&(n.invert=t.invert),this.spec=n,this.mgr.addFilter(this.id,n);return}case"degree":{let r=this.spec,n=r.range??[0,1/0],i=t.range,o=[t.min??i?.[0]??n[0]??0,t.max??i?.[1]??n[1]??1/0],s=t.direction==="in"?"inDegree":t.direction==="out"?"outDegree":t.direction==="both"?"degree":t.metric??r.metric,d={...r,range:o,metric:s,...t.invert!==void 0?{invert:t.invert}:{}};this.spec=d,this.mgr.addFilter(this.id,d);return}default:{this.spec={...this.spec,...e},this.mgr.addFilter(this.id,this.spec);return}}}invert(e){if(this.spec.type==="group")return;let t=e??!(this.spec.invert??!1);this.mgr.setInvert(this.id,t),this.spec={...this.spec,invert:t}}remove(){this.mgr.removeFilter(this.id)}isActive(){return this.mgr.getFilter(this.id)!==void 0}toString(){return this.id}};var Ca=class{constructor(e,t){this.mgr=e;this.register=t;this.nextAutoId=1}range(e){let t=e.id??`range-${this.nextAutoId++}`,r={type:"range",target:"node",property:e.property,valueType:"number",domain:[-1/0,1/0],range:[e.min??-1/0,e.max??1/0],categories:At(e.on),includeNull:e.includeNull??!0,invert:e.invert??!1};this.mgr.addFilter(t,r);let n=new Mt(this.mgr,t,r,"range","nodes");return this.register?.(n),n}dateRange(e){let t=e.id??`dateRange-${this.nextAutoId++}`,r=Hr(e.after,-1/0),n=Hr(e.before,1/0),i={type:"range",target:"node",property:e.property,valueType:"date",granularity:e.granularity,domain:[-1/0,1/0],range:[r,n],categories:At(e.on),includeNull:e.includeNull??!0,invert:e.invert??!1};this.mgr.addFilter(t,i);let o=new Mt(this.mgr,t,i,"dateRange","nodes");return this.register?.(o),o}match(e){let t=e.id??`match-${this.nextAutoId++}`,r=e.property==="category"?"_category":e.property==="id"?"_id":e.property,n=e.oneOf instanceof Set?e.oneOf:e.oneOf?new Set(e.oneOf):new Set,i={type:"categorical",target:"node",property:r,values:n,regex:e.regex,categories:At(e.on),includeNull:e.includeNull??!0,invert:e.invert??!1};this.mgr.addFilter(t,i);let o=new Mt(this.mgr,t,i,"match","nodes");return this.register?.(o),o}predicate(e,t){let r=t?.id??`predicate-${this.nextAutoId++}`,n={type:"predicate",target:"node",predicate:e,categories:At(t?.on),invert:t?.invert??!1};this.mgr.addFilter(r,n);let i=new Mt(this.mgr,r,n,"predicate","nodes");return this.register?.(i),i}degree(e){let t=e.id??`degree-${this.nextAutoId++}`,n={type:"topology",target:"node",metric:e.direction==="in"?"inDegree":e.direction==="out"?"outDegree":"degree",range:[e.min??0,e.max??1/0],invert:e.invert??!1};this.mgr.addFilter(t,n);let i=new Mt(this.mgr,t,n,"degree","nodes");return this.register?.(i),i}};var wa=class{constructor(e,t){this.mgr=e;this.register=t;this.nextAutoId=1}range(e){let t=e.id??`range-${this.nextAutoId++}`,r={type:"range",target:"edge",property:e.property,valueType:"number",domain:[-1/0,1/0],range:[e.min??-1/0,e.max??1/0],categories:At(e.on),includeNull:e.includeNull??!0,invert:e.invert??!1};this.mgr.addFilter(t,r);let n=new Mt(this.mgr,t,r,"range","edges");return this.register?.(n),n}dateRange(e){let t=e.id??`dateRange-${this.nextAutoId++}`,r=Hr(e.after,-1/0),n=Hr(e.before,1/0),i={type:"range",target:"edge",property:e.property,valueType:"date",granularity:e.granularity,domain:[-1/0,1/0],range:[r,n],categories:At(e.on),includeNull:e.includeNull??!0,invert:e.invert??!1};this.mgr.addFilter(t,i);let o=new Mt(this.mgr,t,i,"dateRange","edges");return this.register?.(o),o}match(e){let t=e.id??`match-${this.nextAutoId++}`,r=e.property==="relationship"?"_relationship":e.property==="id"?"_id":e.property,n=e.oneOf instanceof Set?e.oneOf:e.oneOf?new Set(e.oneOf):new Set,i={type:"categorical",target:"edge",property:r,values:n,regex:e.regex,categories:At(e.on),includeNull:e.includeNull??!0,invert:e.invert??!1};this.mgr.addFilter(t,i);let o=new Mt(this.mgr,t,i,"match","edges");return this.register?.(o),o}predicate(e,t){let r=t?.id??`predicate-${this.nextAutoId++}`,n={type:"predicate",target:"edge",predicate:e,categories:At(t?.on),invert:t?.invert??!1};this.mgr.addFilter(r,n);let i=new Mt(this.mgr,r,n,"predicate","edges");return this.register?.(i),i}};var Ta=class{constructor(e){this.mgr=e}start(e,t){if(e.type!=="range"&&e.type!=="dateRange")throw new Error(`filter.playback.start: handle type '${e.type}' is not animatable; only 'range' and 'dateRange' are supported.`);this.ensureFiniteDomain(e.id),this.mgr.startPlayback({filterId:e.id,windowSize:t.windowSize,step:t.step,duration:t.durationMs,loop:t.loop,reverse:t.reverse,mode:t.mode})}pause(e){this.mgr.pausePlayback(e.id)}resume(e){this.mgr.resumePlayback(e.id)}stop(e){this.mgr.stopPlayback(e.id)}isPlaying(e){return this.mgr.isPlaying(e.id)}progress(e){return this.mgr.getPlaybackProgress(e.id)}ensureFiniteDomain(e){let t=this.mgr.getFilter(e);if(!t||t.type!=="range")return;let[r,n]=t.domain??[0,0];if(Number.isFinite(r)&&Number.isFinite(n))return;let i=t.range,o={...t,domain:null};this.mgr.addFilter(e,o),this.mgr.setRange(e,i)}};var vo=class{constructor(e,t){this.store=e;this.mgr=t;this.nextGroupId=1;this.handles=new Map;let r=n=>this.handles.set(n.id,n);this.nodes=new Ca(t,r),this.edges=new wa(t,r),this.playback=new Ta(t)}list(){return Array.from(this.handles.values()).filter(e=>e.isActive())}clear(){this.mgr.clearAll(),this.handles.clear()}matchCount(){return this.mgr.getMatchCount()}onChange(e){return this.mgr.onResult(e)}setTransition(e){this.mgr.setTransition(e)}getTransitionMs(){return this.mgr.getTransitionMs()}any(e,t){return this.makeGroup("or",e,t)}all(e,t){return this.makeGroup("and",e,t)}makeGroup(e,t,r){if(t.length===0){let h=e==="or"?"any":"all";throw new Error(`filter.${h}: children must be a non-empty array of FilterHandle.`)}let n=e==="or"?"any":"all",i=r?.id??`${n}-${this.nextGroupId++}`,o=t[0].target==="edges"?"edge":"node",s=[];for(let h of t){let p=h;s.push({id:p.id,entry:p.spec}),this.mgr.removeFilter(p.id),this.handles.delete(p.id)}let d={type:"group",target:o,operator:e,children:s.map(h=>h.entry)};this.mgr.addFilter(i,d);let l=new Mt(this.mgr,i,d,n,o==="node"?"nodes":"edges"),u=r?.cleanupChildren??!0,c=l.remove.bind(l);return l.remove=()=>{if(c(),this.handles.delete(l.id),!u)for(let{id:h,entry:p}of s)this.mgr.addFilter(h,p)},this.handles.set(l.id,l),l}filterByNeighborhood(e,t){throw new TypeError("api.filter.filterByNeighborhood was misnamed. Use api.filter.nodes.degree({ min }) for the prior degree-filter behaviour, or file an issue if you need true hop-distance neighbourhood filtering.")}};var Cf=[{regex:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/,precision:"minute",parse:a=>new Date(a[0]).getTime()},{regex:/^(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})\s+(\d{1,2}):(\d{2})(?::(\d{2}))?/,precision:"minute",parse:a=>new Date(+a[1],+a[2]-1,+a[3],+a[4],+a[5],+(a[6]||0)).getTime()},{regex:/^(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})$/,precision:"day",parse:a=>new Date(+a[1],+a[2]-1,+a[3]).getTime()},{regex:/^(\d{4})[-/.](\d{1,2})$/,precision:"month",parse:a=>new Date(+a[1],+a[2]-1,1).getTime()},{regex:/^(\d{4})$/,precision:"year",parse:a=>{let e=+a[1];return e>=1900&&e<=2200?new Date(e,0,1).getTime():NaN}}],Dh=new Date("1900-01-01").getTime(),wf=new Date("2200-01-01").getTime(),Tf=1e9,Mf=1e10;function pi(a){if(a==null)return null;if(typeof a=="number")return isFinite(a)?a>1e12&&a<wf?{timestamp:a,original:a,detectedPrecision:"minute"}:a>=Tf&&a<Mf?{timestamp:a*1e3,original:a,detectedPrecision:"minute"}:a>Dh&&a<=1e12?{timestamp:a,original:a,detectedPrecision:"minute"}:null:null;if(typeof a!="string")return null;let e=a.trim();if(e.length<4)return null;for(let t of Cf){let r=e.match(t.regex);if(r){let n=t.parse(r);if(!isNaN(n)&&n>=Dh)return{timestamp:n,original:a,detectedPrecision:t.precision}}}return null}function vr(a,e){let t=new Date(a);switch(e){case"year":return new Date(t.getFullYear(),0,1).getTime();case"month":return new Date(t.getFullYear(),t.getMonth(),1).getTime();case"day":return new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime();case"hour":return new Date(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours()).getTime();case"minute":return new Date(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes()).getTime()}}function gi(a,e){let t=new Date(a);switch(e){case"year":return new Date(t.getFullYear()+1,0,1).getTime();case"month":return new Date(t.getFullYear(),t.getMonth()+1,1).getTime();case"day":return new Date(t.getFullYear(),t.getMonth(),t.getDate()+1).getTime();case"hour":{let r=new Date(t.getTime());return r.setHours(r.getHours()+1,0,0,0),r.getTime()}case"minute":{let r=new Date(t.getTime());return r.setMinutes(r.getMinutes()+1,0,0),r.getTime()}}}function fi(a,e,t){if(t<=0)return a;let r=new Date(a);switch(e){case"year":return new Date(r.getFullYear()+t,0,1).getTime();case"month":return new Date(r.getFullYear(),r.getMonth()+t,1).getTime();default:{let n=a;for(let i=0;i<t;i++)n=gi(n,e);return n}}}function eE(a,e){let t=new Date(a);switch(e){case"year":return new Date(t.getFullYear()-1,0,1).getTime();case"month":return new Date(t.getFullYear(),t.getMonth()-1,1).getTime();case"day":return new Date(t.getFullYear(),t.getMonth(),t.getDate()-1).getTime();case"hour":{let r=new Date(t.getTime());return r.setHours(r.getHours()-1,0,0,0),r.getTime()}case"minute":{let r=new Date(t.getTime());return r.setMinutes(r.getMinutes()-1,0,0),r.getTime()}}}function Nh(a,e){let t=new Date(a),r=s=>String(s).padStart(2,"0"),n=String(t.getFullYear()),i=r(t.getMonth()+1),o=r(t.getDate());switch(e){case"year":return n;case"month":return`${n}-${i}`;case"day":return`${n}-${i}-${o}`;case"hour":return`${n}-${i}-${o} ${r(t.getHours())}:00`;case"minute":return`${n}-${i}-${o} ${r(t.getHours())}:${r(t.getMinutes())}`}}function Ma(a,e=100){let t=a.slice(0,e),r=0,n=0,i="minute",o=["year","month","day","hour","minute"];for(let s of t){if(s==null)continue;n++;let d=pi(s);if(d){r++;let l=o.indexOf(d.detectedPrecision),u=o.indexOf(i);l<u&&(i=d.detectedPrecision)}}return n===0?null:r/n>=.8?{isDate:!0,granularity:i}:null}function If(a){return"relationship"in a?a.relationship:a.category}var Pf=1e6;function yc(a,e){let{property:t,granularity:r,categories:n}=e,i=n&&n.length?new Set(n):null,o=[];for(let g of a){if(i&&!i.has(If(g)))continue;let y=pi(g.properties[t]);y&&o.push(y.timestamp)}if(o.length===0)return{bins:[],domain:null,granularity:r};let s=o[0],d=o[0];for(let g of o)g<s&&(s=g),g>d&&(d=g);let l=[],u=new Map,c=vr(s,r),h=vr(d,r),p=0;for(;c<=h&&p++<Pf;)u.set(c,l.length),l.push(c),c=gi(c,r);let f=new Array(l.length).fill(0);for(let g of o){let y=u.get(vr(g,r));y!==void 0&&f[y]++}return{bins:l.map((g,y)=>({start:g,end:gi(g,r),count:f[y],label:Nh(g,r)})),domain:[s,d],granularity:r}}var Ia=class{constructor(e,t){this.store=e;this.filter=t;this.source=null;this.range=null;this.cursor=null;this.handle=null;this.playTimer=0;this.annotations=new Map;this.nextAnnId=1;this.rangeSubs=new Set;this.cursorSubs=new Set;this.playingSubs=new Set}setSource(e){let t=!this.source||this.source.target!==e.target||this.source.property!==e.property;this.source=e,t&&this.handle&&(this.handle.remove(),this.handle=null,this.range&&this.setRange(this.range))}getSource(){return this.source}autoDetectSource(){for(let e of["edge","node"]){let t=e==="edge"?this.store.getEdges():this.store.getNodes();if(t.length===0)continue;let r=new Set;for(let n of t)for(let i of Object.keys(n.properties))r.add(i);for(let n of r){let i=Ma(t.map(o=>o.properties[n]));if(i?.isDate)return this.source={target:e,property:n,granularity:i.granularity},this.source}}return null}getBins(){if(!this.source)return[];let e=this.source.target==="edge"?this.store.getEdges():this.store.getNodes();return yc(e,this.source).bins}getDomain(){if(!this.source)return null;let e=this.source.target==="edge"?this.store.getEdges():this.store.getNodes();return yc(e,this.source).domain}setRange(e){if(this.range=e,this.source)if(e===null)this.handle?.remove(),this.handle=null;else if(this.handle)this.handle.update({after:e[0],before:e[1]});else{let t=this.source.target==="edge"?this.filter.edges:this.filter.nodes;this.handle=t.dateRange({property:this.source.property,after:e[0],before:e[1],granularity:this.source.granularity,on:this.source.categories??"*"})}this.rangeSubs.forEach(t=>t(e))}getRange(){return this.range}onRangeChange(e){return this.rangeSubs.add(e),()=>this.rangeSubs.delete(e)}setCursor(e){this.cursor=e,this.cursorSubs.forEach(t=>t(e))}getCursor(){return this.cursor}onCursorChange(e){return this.cursorSubs.add(e),()=>this.cursorSubs.delete(e)}play(e={}){let t=this.getDomain();if(!t)return;let[r,n]=t,i=n-r;if(i<=0)return;let o=this.range?Math.max(1,this.range[1]-this.range[0]):i*.1,s=this.range?this.range[0]:r,d=e.loop??!1,l=e.durationMs??6e3,u=50,c=Math.max(1,i*(u/l)*(e.step??1)),h=e.mode??"slide",p=h==="slide"?this.slideStepper(s,o,r,n,c,d):this.growStepper(h,r,n,c,d),f=this.isPlaying();if(this.clearTimer(),typeof setInterval>"u"){f&&this.playingSubs.forEach(m=>m(!1));return}this.playTimer=setInterval(()=>{p()||this.stopTimer()},u),f||this.playingSubs.forEach(m=>m(!0))}slideStepper(e,t,r,n,i,o){return this.setRange([e,Math.min(e+t,n)]),()=>{if(e+=i,e+t>=n){if(!o)return this.setRange([n-t,n]),!1;e=r}return this.setRange([e,e+t]),!0}}growStepper(e,t,r,n,i){let o=this.range,s=e==="expand"?o?o[0]:t:o?o[1]:r,d=e==="expand"?r:s,l=e==="expand"?s:o?o[0]:t,u=o?e==="expand"?o[1]:o[0]:l,c=u<d?u:l,h=p=>e==="expand"?[s,p]:[p,s];return this.setRange(h(c)),()=>(c+=n,c>=d?(e==="expand"&&this.setRange(h(d)),i?(c=l-n,!0):!1):(this.setRange(h(c)),!0))}pause(){this.stopTimer()}stop(){this.stopTimer()}isPlaying(){return this.playTimer!==0}onPlayingChange(e){return this.playingSubs.add(e),()=>this.playingSubs.delete(e)}clearTimer(){this.playTimer&&(clearInterval(this.playTimer),this.playTimer=0)}stopTimer(){this.playTimer&&(this.clearTimer(),this.playingSubs.forEach(e=>e(!1)))}addAnnotation(e){let t=`ann-${this.nextAnnId++}`;return this.annotations.set(t,{id:t,...e}),t}removeAnnotation(e){this.annotations.delete(e)}getAnnotations(){return[...this.annotations.values()]}};var Pa=class{constructor(e,t,r,n){this.type="nodeRipple";this.active=!0;this.startTime=0;if(this.id=e,this.store=t,this.nodeIds=r,this.duration=n?.duration??0,this.intensity=n?.intensity??1,!(n?.loop??!0)&&(!n?.duration||n.duration<=0))throw new Error(`[${this.type}] loop:false requires a positive duration; got ${n?.duration}`);n?.color&&(t.rippleColor=n.color),n?.speed!==void 0&&(t.rippleSpeed=n.speed),n?.rings!==void 0&&(t.rippleRings=n.rings);let o=t.nodeState;if(o)for(let s of r){let d=t.index.getNodeIndex(s);d!==void 0&&(o.ripple[d]=this.intensity)}t.updateStrategy.markDirty("nodeRipple"),t.notifyChange()}tick(e,t){this.startTime===0&&(this.startTime=e),this.duration>0&&(e-this.startTime)*1e3>this.duration&&(this.active=!1)}dispose(){let e=this.store.nodeState;if(e)for(let t of this.nodeIds){let r=this.store.index.getNodeIndex(t);r!==void 0&&(e.ripple[r]=0)}this.store.updateStrategy.markDirty("nodeRipple"),this.store.notifyChange()}};var Aa=class{constructor(e,t,r,n){this.type="nodeBreathe";this.active=!0;this.startTime=0;if(this.id=e,this.store=t,this.nodeIds=r,this.duration=n?.duration??0,this.amplitude=n?.amplitude??1,!(n?.loop??!0)&&(!n?.duration||n.duration<=0))throw new Error(`[${this.type}] loop:false requires a positive duration; got ${n?.duration}`);let o=t.nodeState;if(o)for(let s of r){let d=t.index.getNodeIndex(s);d!==void 0&&(o.breathe[d]=this.amplitude)}t.updateStrategy.markDirty("nodeBreathe"),t.notifyChange()}tick(e,t){this.startTime===0&&(this.startTime=e),this.duration>0&&(e-this.startTime)*1e3>this.duration&&(this.active=!1)}dispose(){let e=this.store.nodeState;if(e)for(let t of this.nodeIds){let r=this.store.index.getNodeIndex(t);r!==void 0&&(e.breathe[r]=0)}this.store.updateStrategy.markDirty("nodeBreathe"),this.store.notifyChange()}};var kh={linear:a=>a,easeIn:a=>a*a,easeOut:a=>a*(2-a),easeInOut:a=>a<.5?2*a*a:-1+(4-2*a)*a},_a=class{constructor(e,t,r,n){this.type="nodeEntrance";this.active=!0;this.startTime=0;this.completed=!1;this.id=e,this.store=t,this.nodeIds=r,this.config={duration:n?.duration??600,stagger:n?.stagger??50,easing:n?.easing??"easeOut"},this.easingFn=kh[this.config.easing]??kh.easeOut,this.originalSizes=new Map,this.originalOpacities=new Map;let i=t.nodeState;if(i){for(let o of r){let s=t.index.getNodeIndex(o);s!==void 0&&(this.originalSizes.set(o,i.sizes[s]),this.originalOpacities.set(o,i.opacities[s]),i.sizes[s]=0,i.opacities[s]=0)}t.updateStrategy.markDirty("nodeSizes"),t.updateStrategy.markDirty("nodeOpacities"),t.notifyChange()}}tick(e,t){if(this.startTime===0&&(this.startTime=e),this.completed)return;let r=this.store.nodeState;if(!r)return;let n=(e-this.startTime)*1e3,i=!0;for(let o=0;o<this.nodeIds.length;o++){let s=this.nodeIds[o],d=this.store.index.getNodeIndex(s);if(d===void 0)continue;let l=o*this.config.stagger,u=n-l;if(u<=0)r.sizes[d]=0,r.opacities[d]=0,i=!1;else if(u>=this.config.duration){let c=this.originalSizes.get(s)??10,h=this.originalOpacities.get(s)??1;r.sizes[d]=c,r.opacities[d]=h}else{let c=u/this.config.duration,h=this.easingFn(c),p=this.originalSizes.get(s)??10,f=this.originalOpacities.get(s)??1;r.sizes[d]=p*h,r.opacities[d]=f*h,i=!1}}this.store.updateStrategy.markDirty("nodeSizes"),this.store.updateStrategy.markDirty("nodeOpacities"),this.store.notifyChange(),i&&(this.completed=!0,this.active=!1)}dispose(){let e=this.store.nodeState;if(e){for(let[t,r]of this.originalSizes){let n=this.store.index.getNodeIndex(t);n!==void 0&&(e.sizes[n]=r)}for(let[t,r]of this.originalOpacities){let n=this.store.index.getNodeIndex(t);n!==void 0&&(e.opacities[n]=r)}this.store.updateStrategy.markDirty("nodeSizes"),this.store.updateStrategy.markDirty("nodeOpacities"),this.store.notifyChange()}}};var Da=class{constructor(e,t,r,n){this.type="edgeFlow";this.active=!0;this.startTime=0;if(this.id=e,this.store=t,this.edgeIds=r,this.duration=n?.duration??0,this.intensity=n?.intensity??1,!(n?.loop??!0)&&(!n?.duration||n.duration<=0))throw new Error(`[${this.type}] loop:false requires a positive duration; got ${n?.duration}`);let o=t.edgeState;if(o){for(let s of r){let d=t.index.getEdgeIndex(s);d!==void 0&&(o.flow[d]=this.intensity)}n?.speed!==void 0&&(o.flowSpeed=n.speed),n?.color!==void 0&&(o.flowColor=n.color)}t.updateStrategy.markDirty("edgeFlow"),t.notifyChange()}tick(e,t){this.startTime===0&&(this.startTime=e),this.duration>0&&(e-this.startTime)*1e3>this.duration&&(this.active=!1)}dispose(){let e=this.store.edgeState;if(e)for(let t of this.edgeIds){let r=this.store.index.getEdgeIndex(t);r!==void 0&&(e.flow[r]=0)}this.store.updateStrategy.markDirty("edgeFlow"),this.store.notifyChange()}};var Na=class{constructor(e,t,r,n){this.type="edgeGlow";this.active=!0;this.startTime=0;if(this.id=e,this.store=t,this.edgeIds=r,this.duration=n?.duration??0,this.intensity=n?.intensity??1,!(n?.loop??!0)&&(!n?.duration||n.duration<=0))throw new Error(`[${this.type}] loop:false requires a positive duration; got ${n?.duration}`);let o=t.edgeState;if(o)for(let s of r){let d=t.index.getEdgeIndex(s);d!==void 0&&(o.glow[d]=this.intensity)}t.updateStrategy.markDirty("edgeGlow"),t.notifyChange()}tick(e,t){this.startTime===0&&(this.startTime=e),this.duration>0&&(e-this.startTime)*1e3>this.duration&&(this.active=!1)}dispose(){let e=this.store.edgeState;if(e)for(let t of this.edgeIds){let r=this.store.index.getEdgeIndex(t);r!==void 0&&(e.glow[r]=0)}this.store.updateStrategy.markDirty("edgeGlow"),this.store.notifyChange()}};var ka=class{constructor(e,t,r,n){this.type="edgeDraw";this.active=!0;this.startTime=0;this.completed=!1;this.id=e,this.store=t,this.edgeIds=r,this.config={duration:n?.duration??800,stagger:n?.stagger??100},this.originalOpacities=new Map;let i=t.edgeState;if(i){for(let o of r){let s=t.index.getEdgeIndex(o);s!==void 0&&(this.originalOpacities.set(o,i.opacities[s]),i.opacities[s]=0)}t.updateStrategy.markDirty("edgeOpacities"),t.notifyChange()}}tick(e,t){if(this.startTime===0&&(this.startTime=e),this.completed)return;let r=this.store.edgeState;if(!r)return;let n=(e-this.startTime)*1e3,i=!0;for(let o=0;o<this.edgeIds.length;o++){let s=this.edgeIds[o],d=this.store.index.getEdgeIndex(s);if(d===void 0)continue;let l=o*this.config.stagger,u=n-l;if(u<=0)r.opacities[d]=0,i=!1;else if(u>=this.config.duration){let c=this.originalOpacities.get(s)??1;r.opacities[d]=c}else{let c=u/this.config.duration,h=this.originalOpacities.get(s)??1;r.opacities[d]=h*c,i=!1}}this.store.updateStrategy.markDirty("edgeOpacities"),this.store.notifyChange(),i&&(this.completed=!0,this.active=!1)}dispose(){let e=this.store.edgeState;if(e){for(let[t,r]of this.originalOpacities){let n=this.store.index.getEdgeIndex(t);n!==void 0&&(e.opacities[n]=r)}this.store.updateStrategy.markDirty("edgeOpacities"),this.store.notifyChange()}}};var Ga=class{constructor(e,t,r,n){this.type="metricPulse";this.active=!0;this.startTime=-1;if(this.id=e,this.store=t,this.nodeIds=r,this.duration=n?.duration??5e3,this.speed=n?.speed??2,this.maxAmplitude=n?.maxAmplitude??.3,!(n?.loop??!0)&&(!n?.duration||n.duration<=0))throw new Error(`[${this.type}] loop:false requires a positive duration; got ${n?.duration}`);this.normalizedValues=new Map,this.originalSizes=new Map;let o=new Map;for(let c of r){let h;if(n?.values)h=n.values.get(c);else if(n?.property){let p=t.queries.getNode(c);if(p){let f=p.properties[n.property];typeof f=="number"&&(h=f)}}h!==void 0&&o.set(c,h)}let s=n?.minValue,d=n?.maxValue;if(s===void 0||d===void 0){let c=Array.from(o.values());c.length>0?(s===void 0&&(s=Math.min(...c)),d===void 0&&(d=Math.max(...c))):(s=0,d=1)}let l=d-s;for(let c of r){let h=o.get(c)??s,p=l>0?(h-s)/l:0;this.normalizedValues.set(c,p)}let u=t.nodeState;if(u)for(let c of r){let h=t.index.getNodeIndex(c);h!==void 0&&this.originalSizes.set(c,u.sizes[h])}}tick(e,t){if(this.startTime<0&&(this.startTime=e),this.duration>0&&(e-this.startTime)*1e3>this.duration){this.active=!1;return}let r=this.store.nodeState;if(!r)return;let n=e-this.startTime;for(let i of this.nodeIds){let o=this.store.index.getNodeIndex(i);if(o===void 0)continue;let d=(this.normalizedValues.get(i)??0)*this.maxAmplitude,l=this.originalSizes.get(i)??10,u=1+d*Math.sin(n*this.speed*2*Math.PI);r.sizes[o]=l*u}this.store.updateStrategy.markDirty("nodeSizes"),this.store.notifyChange()}dispose(){let e=this.store.nodeState;if(e){for(let[t,r]of this.originalSizes){let n=this.store.index.getNodeIndex(t);n!==void 0&&(e.sizes[n]=r)}this.store.updateStrategy.markDirty("nodeSizes"),this.store.notifyChange()}}};var Gh={linear:a=>a,easeIn:a=>a*a,easeOut:a=>a*(2-a),easeInOut:a=>a<.5?2*a*a:-1+(4-2*a)*a},Ha=class{constructor(e,t,r,n){this.type="nodeExplosion";this.active=!0;this.startTime=0;this.targets=new Map;this.completed=!1;this.id=e,this.store=t,this.nodeIds=r,this.config={duration:n?.duration??800,easing:n?.easing??"easeOut",center:n?.center??{x:0,y:0,z:0}},this.center=[this.config.center.x,this.config.center.y,this.config.center.z],this.easingFn=Gh[this.config.easing]??Gh.easeOut;let i=t.positionProvider?.getPositions();if(i){for(let o of r){let s=t.index.getNodeIndex(o);s!==void 0&&(this.targets.set(o,[i[s*3],i[s*3+1],i[s*3+2]]),i[s*3]=this.center[0],i[s*3+1]=this.center[1],i[s*3+2]=this.center[2])}t.positionProvider&&"markNeedsUpdate"in t.positionProvider&&t.positionProvider.markNeedsUpdate(),t.notifyChange()}}tick(e,t){if(this.startTime===0&&(this.startTime=e),this.completed)return;let r=this.store.positionProvider?.getPositions();if(!r)return;let n=(e-this.startTime)*1e3,i=Math.min(n/this.config.duration,1),o=this.easingFn(i);for(let d of this.nodeIds){let l=this.store.index.getNodeIndex(d);if(l===void 0)continue;let u=this.targets.get(d);u&&(r[l*3]=this.center[0]+(u[0]-this.center[0])*o,r[l*3+1]=this.center[1]+(u[1]-this.center[1])*o,r[l*3+2]=this.center[2]+(u[2]-this.center[2])*o)}let s=this.store.positionProvider;s&&"markNeedsUpdate"in s&&s.markNeedsUpdate(),this.store.notifyChange(),i>=1&&(this.completed=!0,this.active=!1)}dispose(){let e=this.store.positionProvider?.getPositions();if(e){for(let[t,r]of this.targets){let n=this.store.index.getNodeIndex(t);n!==void 0&&(e[n*3]=r[0],e[n*3+1]=r[1],e[n*3+2]=r[2])}this.store.positionProvider&&"markNeedsUpdate"in this.store.positionProvider&&this.store.positionProvider.markNeedsUpdate(),this.store.notifyChange()}}};var Fa=class{constructor(e,t){this.nextId=1;this.store=e,this.effectManager=t}get manager(){return this.effectManager}nodeRipple(e,t){let r=Array.isArray(e)?e:[e],n=`ripple-${this.nextId++}`;return this.effectManager.addEffect(new Pa(n,this.store,r,t)),n}nodeBreathe(e,t){let r=Array.isArray(e)?e:[e],n=`breathe-${this.nextId++}`;return this.effectManager.addEffect(new Aa(n,this.store,r,t)),n}nodeEntrance(e,t){let r=Array.isArray(e)?e:[e],n=`nodeEntrance-${this.nextId++}`;return this.effectManager.addEffect(new _a(n,this.store,r,t)),n}nodeExplosion(e,t){let r=Array.isArray(e)?e:[e],n=`nodeExplosion-${this.nextId++}`;return this.effectManager.addEffect(new Ha(n,this.store,r,t)),n}edgeFlow(e,t){let r=Array.isArray(e)?e:[e],n=`flow-${this.nextId++}`;return this.effectManager.addEffect(new Da(n,this.store,r,t)),n}edgeGlow(e,t){let r=Array.isArray(e)?e:[e],n=`glow-${this.nextId++}`;return this.effectManager.addEffect(new Na(n,this.store,r,t)),n}edgeDraw(e,t){let r=Array.isArray(e)?e:[e],n=`edgeDraw-${this.nextId++}`;return this.effectManager.addEffect(new ka(n,this.store,r,t)),n}metricPulse(e,t){let r=Array.isArray(e)?e:[e],n=`metricPulse-${this.nextId++}`;return this.effectManager.addEffect(new Ga(n,this.store,r,t)),n}stop(e){this.effectManager.removeEffect(e)}stopAll(e){this.effectManager.stopAll(e)}};var za=class{constructor(e,t,r,n){this.type="pathHighlight";this.active=!0;this.startTime=-1;this.currentSegment=-1;this.holdStartTime=0;this.id=e,this.store=t,this.path=r,this.config={segmentDuration:n?.segmentDuration??300,color:n?.color??[1,.8,0],leaveTrail:n?.leaveTrail??!0,holdDuration:n?.holdDuration??2e3},this.originalNodeColors=new Map,this.originalNodeSizes=new Map,this.originalEdgeGlows=new Map,this.originalEdgeColors=new Map,this.segments=[];for(let s=0;s<r.length-1;s++){let d=r[s],l=r[s+1],u=t.queries.getEdgesBetween(d,l);u.length>0&&this.segments.push({edgeId:u[0],fromNodeId:d,toNodeId:l})}let i=t.nodeState;if(i)for(let s of r){let d=t.index.getNodeIndex(s);d!==void 0&&(this.originalNodeColors.set(s,[i.colors[d*3],i.colors[d*3+1],i.colors[d*3+2]]),this.originalNodeSizes.set(s,i.sizes[d]))}let o=t.edgeState;if(o)for(let s of this.segments){let d=t.index.getEdgeIndex(s.edgeId);d!==void 0&&(this.originalEdgeGlows.set(s.edgeId,o.glow[d]),this.originalEdgeColors.set(s.edgeId,[o.colors[d*3],o.colors[d*3+1],o.colors[d*3+2]]))}}tick(e,t){if(this.startTime<0&&(this.startTime=e),this.segments.length===0){this.active=!1;return}let r=(e-this.startTime)*1e3,n=this.config.segmentDuration,i=Math.floor(r/n);i!==this.currentSegment&&i<this.segments.length&&(this.currentSegment=i,this.applySegment(i)),i>=this.segments.length&&(this.holdStartTime===0&&(this.holdStartTime=e),(e-this.holdStartTime)*1e3>=this.config.holdDuration&&(this.active=!1))}applySegment(e){let t=this.segments[e],r=this.store.edgeState,n=this.store.nodeState,[i,o,s]=this.config.color;if(r){let d=this.store.index.getEdgeIndex(t.edgeId);d!==void 0&&(r.glow[d]=1,r.colors[d*3]=i,r.colors[d*3+1]=o,r.colors[d*3+2]=s),this.store.updateStrategy.markDirty("edgeGlow"),this.store.updateStrategy.markDirty("edgeColors")}if(n){let d=this.store.index.getNodeIndex(t.toNodeId);if(d!==void 0){n.colors[d*3]=i,n.colors[d*3+1]=o,n.colors[d*3+2]=s;let l=this.originalNodeSizes.get(t.toNodeId)??10;n.sizes[d]=l*1.3}if(e===0){let l=this.store.index.getNodeIndex(t.fromNodeId);if(l!==void 0){n.colors[l*3]=i,n.colors[l*3+1]=o,n.colors[l*3+2]=s;let u=this.originalNodeSizes.get(t.fromNodeId)??10;n.sizes[l]=u*1.3}}this.store.updateStrategy.markDirty("nodeColors"),this.store.updateStrategy.markDirty("nodeSizes")}if(!this.config.leaveTrail&&e>0){let d=this.segments[e-1];if(r){let l=this.store.index.getEdgeIndex(d.edgeId);if(l!==void 0){r.glow[l]=this.originalEdgeGlows.get(d.edgeId)??0;let u=this.originalEdgeColors.get(d.edgeId)??[.5,.5,.5];r.colors[l*3]=u[0],r.colors[l*3+1]=u[1],r.colors[l*3+2]=u[2]}}}this.store.notifyChange()}dispose(){let e=this.store.nodeState;if(e){for(let[r,n]of this.originalNodeColors){let i=this.store.index.getNodeIndex(r);i!==void 0&&(e.colors[i*3]=n[0],e.colors[i*3+1]=n[1],e.colors[i*3+2]=n[2])}for(let[r,n]of this.originalNodeSizes){let i=this.store.index.getNodeIndex(r);i!==void 0&&(e.sizes[i]=n)}this.store.updateStrategy.markDirty("nodeColors"),this.store.updateStrategy.markDirty("nodeSizes")}let t=this.store.edgeState;if(t){for(let[r,n]of this.originalEdgeGlows){let i=this.store.index.getEdgeIndex(r);i!==void 0&&(t.glow[i]=n)}for(let[r,n]of this.originalEdgeColors){let i=this.store.index.getEdgeIndex(r);i!==void 0&&(t.colors[i*3]=n[0],t.colors[i*3+1]=n[1],t.colors[i*3+2]=n[2])}this.store.updateStrategy.markDirty("edgeGlow"),this.store.updateStrategy.markDirty("edgeColors")}this.store.notifyChange()}};var Ba=class{constructor(e,t,r,n){this.type="cascadeHighlight";this.active=!0;this.startTime=-1;this.currentHop=0;this.nextHopTime=0;this.id=e,this.store=t,this.sourceNodeIds=r,this.config={delayPerHop:n?.delayPerHop??400,maxHops:n?.maxHops??1/0,color:n?.color??[.2,.6,1],direction:n?.direction??"both",wavefrontScale:n?.wavefrontScale??1.5},this.wavefront=new Set(r),this.previousWavefront=new Set,this.visited=new Map,this.originalNodeColors=new Map,this.originalNodeSizes=new Map,this.originalEdgeGlows=new Map;let i=t.nodeState;if(i)for(let s of t.data.nodes){let d=t.index.getNodeIndex(s.id);d!==void 0&&(this.originalNodeColors.set(s.id,[i.colors[d*3],i.colors[d*3+1],i.colors[d*3+2]]),this.originalNodeSizes.set(s.id,i.sizes[d]))}let o=t.edgeState;if(o)for(let s of t.data.edges){let d=t.index.getEdgeIndex(s.id);d!==void 0&&this.originalEdgeGlows.set(s.id,o.glow[d])}for(let s of r)this.visited.set(s,0),this.applyWavefrontNode(s)}tick(e,t){if(this.startTime<0&&(this.startTime=e,this.nextHopTime=e+this.config.delayPerHop/1e3),e>=this.nextHopTime&&this.currentHop<this.config.maxHops){for(let n of this.wavefront)this.settleNode(n);this.currentHop++;let r=new Set;for(let n of this.wavefront){let i=this.store.queries.getNeighbors(n);for(let o of i)this.config.direction==="out"&&o.direction!=="out"||this.config.direction==="in"&&o.direction!=="in"||this.visited.has(o.nodeId)||(r.add(o.nodeId),this.visited.set(o.nodeId,this.currentHop),this.applyWavefrontNode(o.nodeId),this.applyEdgeGlow(o.edgeId))}this.previousWavefront=this.wavefront,this.wavefront=r,this.nextHopTime=e+this.config.delayPerHop/1e3,r.size===0&&(this.nextHopTime=1/0,this.active=!1)}}applyWavefrontNode(e){let t=this.store.nodeState;if(!t)return;let r=this.store.index.getNodeIndex(e);if(r===void 0)return;let[n,i,o]=this.config.color;t.colors[r*3]=n,t.colors[r*3+1]=i,t.colors[r*3+2]=o;let s=this.originalNodeSizes.get(e)??10;t.sizes[r]=s*this.config.wavefrontScale,this.store.updateStrategy.markDirty("nodeColors"),this.store.updateStrategy.markDirty("nodeSizes"),this.store.notifyChange()}settleNode(e){let t=this.store.nodeState;if(!t)return;let r=this.store.index.getNodeIndex(e);if(r===void 0)return;let n=this.originalNodeSizes.get(e)??10;t.sizes[r]=n;let i=this.originalNodeColors.get(e)??[.5,.5,.5],[o,s,d]=this.config.color,l=.4;t.colors[r*3]=i[0]+(o-i[0])*l,t.colors[r*3+1]=i[1]+(s-i[1])*l,t.colors[r*3+2]=i[2]+(d-i[2])*l,this.store.updateStrategy.markDirty("nodeColors"),this.store.updateStrategy.markDirty("nodeSizes"),this.store.notifyChange()}applyEdgeGlow(e){let t=this.store.edgeState;if(!t)return;let r=this.store.index.getEdgeIndex(e);r!==void 0&&(t.glow[r]=1,this.store.updateStrategy.markDirty("edgeGlow"),this.store.notifyChange())}dispose(){let e=this.store.nodeState;if(e){for(let[r,n]of this.originalNodeColors){let i=this.store.index.getNodeIndex(r);i!==void 0&&(e.colors[i*3]=n[0],e.colors[i*3+1]=n[1],e.colors[i*3+2]=n[2])}for(let[r,n]of this.originalNodeSizes){let i=this.store.index.getNodeIndex(r);i!==void 0&&(e.sizes[i]=n)}this.store.updateStrategy.markDirty("nodeColors"),this.store.updateStrategy.markDirty("nodeSizes")}let t=this.store.edgeState;if(t){for(let[r,n]of this.originalEdgeGlows){let i=this.store.index.getEdgeIndex(r);i!==void 0&&(t.glow[i]=n)}this.store.updateStrategy.markDirty("edgeGlow")}this.store.notifyChange()}};var Oa=new WeakMap,mi=class{constructor(e,t,r,n){this.type="focusContext";this.active=!0;this.startTime=0;this.completed=!1;this.disposed=!1;this.id=e,this.store=t,this.focusedNodeIds=new Set(r),this.config={contextOpacity:n?.contextOpacity??.15,contextEdgeOpacity:n?.contextEdgeOpacity??.08,focusScale:n?.focusScale??1.3,duration:n?.duration??500},this.originalNodeOpacities=new Map,this.originalNodeSizes=new Map,this.originalEdgeOpacities=new Map;let i=Oa.get(t);i||(i={nodeOpacities:new Map,nodeSizes:new Map,edgeOpacities:new Map,members:[]},Oa.set(t,i)),i.members.push(this),this.baseline=i,this.pristineNodeOpacities=i.nodeOpacities,this.pristineNodeSizes=i.nodeSizes,this.pristineEdgeOpacities=i.edgeOpacities,this.targetNodeOpacities=new Map,this.targetNodeSizes=new Map,this.targetEdgeOpacities=new Map;let o=t.nodeState,s=t.edgeState;if(o)for(let d of t.data.nodes){let l=t.index.getNodeIndex(d.id);if(l===void 0)continue;let u=o.opacities[l],c=o.sizes[l];this.pristineNodeOpacities.has(d.id)||(this.pristineNodeOpacities.set(d.id,u),this.pristineNodeSizes.set(d.id,c)),this.originalNodeOpacities.set(d.id,u),this.originalNodeSizes.set(d.id,c)}if(s)for(let d of t.data.edges){let l=t.index.getEdgeIndex(d.id);if(l===void 0)continue;let u=s.opacities[l];this.pristineEdgeOpacities.has(d.id)||this.pristineEdgeOpacities.set(d.id,u),this.originalEdgeOpacities.set(d.id,u)}this.recomputeTargets()}setFocusedNodes(e){this.focusedNodeIds=new Set(e);let t=this.store.nodeState,r=this.store.edgeState;if(t)for(let n of this.store.data.nodes){let i=this.store.index.getNodeIndex(n.id);i!==void 0&&(this.originalNodeOpacities.set(n.id,t.opacities[i]),this.originalNodeSizes.set(n.id,t.sizes[i]))}if(r)for(let n of this.store.data.edges){let i=this.store.index.getEdgeIndex(n.id);i!==void 0&&this.originalEdgeOpacities.set(n.id,r.opacities[i])}this.recomputeTargets(),this.startTime=0,this.completed=!1}recomputeTargets(){this.targetNodeOpacities.clear(),this.targetNodeSizes.clear(),this.targetEdgeOpacities.clear();for(let[e,t]of this.pristineNodeOpacities){let r=this.pristineNodeSizes.get(e)??10;this.focusedNodeIds.has(e)?(this.targetNodeOpacities.set(e,t),this.targetNodeSizes.set(e,r*this.config.focusScale)):(this.targetNodeOpacities.set(e,this.config.contextOpacity),this.targetNodeSizes.set(e,r))}for(let e of this.store.data.edges){let t=this.pristineEdgeOpacities.get(e.id);if(t===void 0)continue;let r=this.focusedNodeIds.has(e.source)&&this.focusedNodeIds.has(e.target);this.targetEdgeOpacities.set(e.id,r?t:this.config.contextEdgeOpacity)}}tick(e,t){if(this.startTime===0&&(this.startTime=e),this.completed)return;let r=(e-this.startTime)*1e3,n=Math.min(r/this.config.duration,1),i=n*(2-n),o=this.store.nodeState,s=this.store.edgeState;if(o){for(let d of this.store.data.nodes){let l=this.store.index.getNodeIndex(d.id);if(l===void 0)continue;let u=this.originalNodeOpacities.get(d.id)??1,c=this.targetNodeOpacities.get(d.id)??u;o.opacities[l]=u+(c-u)*i;let h=this.originalNodeSizes.get(d.id)??10,p=this.targetNodeSizes.get(d.id)??h;o.sizes[l]=h+(p-h)*i}this.store.updateStrategy.markDirty("nodeOpacities"),this.store.updateStrategy.markDirty("nodeSizes")}if(s){for(let d of this.store.data.edges){let l=this.store.index.getEdgeIndex(d.id);if(l===void 0)continue;let u=this.originalEdgeOpacities.get(d.id)??1,c=this.targetEdgeOpacities.get(d.id)??u;s.opacities[l]=u+(c-u)*i}this.store.updateStrategy.markDirty("edgeOpacities")}this.store.notifyChange(),n>=1&&(this.completed=!0)}dispose(){if(this.disposed)return;this.disposed=!0;let e=this.baseline.members,t=e.indexOf(this);if(t>=0&&e.splice(t,1),e.length>0){e[e.length-1].setFocusedNodes([...e[e.length-1].focusedNodeIds]);return}Oa.get(this.store)===this.baseline&&Oa.delete(this.store);let r=this.store.nodeState;if(r){for(let[i,o]of this.pristineNodeOpacities){let s=this.store.index.getNodeIndex(i);s!==void 0&&(r.opacities[s]=o)}for(let[i,o]of this.pristineNodeSizes){let s=this.store.index.getNodeIndex(i);s!==void 0&&(r.sizes[s]=o)}this.store.updateStrategy.markDirty("nodeOpacities"),this.store.updateStrategy.markDirty("nodeSizes")}let n=this.store.edgeState;if(n){for(let[i,o]of this.pristineEdgeOpacities){let s=this.store.index.getEdgeIndex(i);s!==void 0&&(n.opacities[s]=o)}this.store.updateStrategy.markDirty("edgeOpacities")}this.store.notifyChange()}};var Af={contextOpacity:.12,contextEdgeOpacity:.06,focusScale:1},La=class{constructor(e,t,r=null,n=null){this.nextId=1;this._clickDimEnabled=!1;this._clickDimUnsub=null;this._clickDimAnchor=null;this._clickDimEffectId=null;this._restoreOnBackground=!0;this._restoreUnsub=null;this._restoreListeners=new Set;this.store=e,this.effectManager=t,this.hoverEmphasisSource=r,this.interaction=n}get hoverEmphasis(){let e=this.hoverEmphasisSource;return typeof e=="function"?e():e}wireInteraction(e){this.interaction=e,this._clickDimEnabled&&this._installClickDim(),this._installRestoreOnBackground()}restore(){this._clickDimAnchor=null,this._clickDimEffectId=null,this.effectManager.stopAll("focusContext"),this.effectManager.stopAll("pathHighlight"),this.effectManager.stopAll("cascadeHighlight"),this.hoverEmphasis?.clearExternalKeepSet();for(let e of[...this._restoreListeners])try{e()}catch(t){console.error("EmphasisApi.onRestore listener error:",t)}}onRestore(e){return this._restoreListeners.add(e),()=>{this._restoreListeners.delete(e)}}setRestoreOnBackgroundClick(e){this._restoreOnBackground!==e&&(this._restoreOnBackground=e,this._installRestoreOnBackground())}isRestoreOnBackgroundClickEnabled(){return this._restoreOnBackground}_installRestoreOnBackground(){this._restoreUnsub?.(),this._restoreUnsub=null;let e=this.interaction;!this._restoreOnBackground||!e||(this._restoreUnsub=e.onClick(t=>{t.type==="background"&&(e.lastClickWasDrag||this.restore())}))}pathHighlight(e,t){let r=`pathHighlight-${this.nextId++}`;return this.effectManager.addEffect(new za(r,this.store,e,t)),r}cascadeHighlight(e,t){let r=Array.isArray(e)?e:[e],n=`cascadeHighlight-${this.nextId++}`;return this.effectManager.addEffect(new Ba(n,this.store,r,t)),n}focusContext(e,t){let r=Array.isArray(e)?e:[e],n=`focusContext-${this.nextId++}`;return this.effectManager.addEffect(new mi(n,this.store,r,t)),n}retargetFocusContext(e,t){let r=Array.isArray(e)?e:[e],n=this.effectManager.findByType("focusContext");return n&&n instanceof mi?(n.setFocusedNodes(r),n.id):this.focusContext(r,t)}stop(e){this.effectManager.removeEffect(e)}stopAll(e){this.effectManager.stopAll(e)}setClickDimEnabled(e){this._clickDimEnabled!==e&&(this._clickDimEnabled=e,e?this._installClickDim():(this._uninstallClickDim(),this._clearClickDim()))}isClickDimEnabled(){return this._clickDimEnabled}_installClickDim(){this._uninstallClickDim(),this.interaction&&(this._clickDimUnsub=this.interaction.onClick(e=>{this._onClickDim(e)}))}_uninstallClickDim(){this._clickDimUnsub?.(),this._clickDimUnsub=null}_onClickDim(e){if(e.type==="node"&&e.nodeId){if(this._clickDimAnchor?.kind==="node"&&this._clickDimAnchor.id===e.nodeId){this._clearClickDim();return}let{nodeIds:t}=this.traceNeighbor({nodeIds:[e.nodeId],depth:1});this._focusClickDim(t),this._clickDimAnchor={kind:"node",id:e.nodeId}}else if(e.type==="edge"&&e.edgeId){if(this._clickDimAnchor?.kind==="edge"&&this._clickDimAnchor.id===e.edgeId){this._clearClickDim();return}let r=(this.store.data.edges??[]).find(n=>n.id===e.edgeId);if(!r)return;this._focusClickDim([r.source,r.target]),this._clickDimAnchor={kind:"edge",id:e.edgeId}}else this._clearClickDim()}_focusClickDim(e){let t=this._clickDimEffectId?this.effectManager.get(this._clickDimEffectId):null;if(t instanceof mi){t.setFocusedNodes(e);return}this._clickDimEffectId=this.focusContext(e,Af)}_clearClickDim(){this._clickDimAnchor&&(this._clickDimEffectId&&this.stop(this._clickDimEffectId),this._clickDimEffectId=null,this._clickDimAnchor=null)}setHoverDimOpacity(e){this.hoverEmphasis?.setConfig({dimOpacity:e})}setHoverDuration(e){this.hoverEmphasis?.setConfig({duration:e})}setEmphasisGlowEnabled(e){this.hoverEmphasis?.setConfig({glowEnabled:e})}setEmphasisGlowStrength(e){this.hoverEmphasis?.setConfig({glowStrength:Math.max(0,e)})}setEmphasisHaloStrength(e){this.hoverEmphasis?.setConfig({haloStrength:Math.max(0,e)})}dimExcept(e,t={}){let r=this.hoverEmphasis;if(!r)return;let n=new Set(e),i;if(t.edgeIds)i=t.edgeIds;else{let o=new Set,s=this.store.data.edges??[];for(let d of s)n.has(d.source)&&n.has(d.target)&&o.add(d.id);i=o}r.setExternalKeepSet(n,i)}dimNeighborhood(e,t=1){let r=this.hoverEmphasis;if(!r)return;let n=new Set([e]),i=new Set,o=new Set([e]),s=this.store.queries;for(let d=0;d<t&&o.size>0;d++){let l=new Set;for(let u of o){let c=s.getNeighbors(u);for(let h of c)i.add(h.edgeId),n.has(h.nodeId)||(n.add(h.nodeId),l.add(h.nodeId))}o=l}r.setExternalKeepSet(n,i)}traceNeighbor(e){let t=e.direction??"both",r=e.along?new Set(Array.isArray(e.along)?e.along:[e.along]):null,n=this.store.data.edges??[],i=new Map;for(let c of n)i.set(c.id,c);let o=new Set(e.nodeIds??[]),s=new Set;for(let c of e.edgeIds??[]){let h=i.get(c);h&&(s.add(c),o.add(h.source),o.add(h.target))}let d=new Set(o),l=new Set(o),u=this.store.queries;for(let c=0;c<e.depth&&l.size>0;c++){let h=new Set;for(let p of l)for(let f of u.getNeighbors(p))if(!(t==="in"&&f.direction!=="in")&&!(t==="out"&&f.direction!=="out")){if(r){let m=i.get(f.edgeId);if(!m||!r.has(m.relationship??""))continue}s.add(f.edgeId),d.has(f.nodeId)||(d.add(f.nodeId),h.add(f.nodeId))}l=h}return{nodeIds:[...d],edgeIds:[...s]}}clearDim(){this.hoverEmphasis?.clearExternalKeepSet()}setTraceDim(e,t){let r=this.hoverEmphasis;if(!r)return;let n=new Set(e),i;if(t)i=t;else{let o=new Set,s=this.store.data.edges??[];for(let d of s)n.has(d.source)&&n.has(d.target)&&o.add(d.id);i=o}r.setExternalKeepSet(n,i)}clearTrace(){this.hoverEmphasis?.clearExternalKeepSet()}};var Va=class{constructor(e,t,r,n){this.type="heatDiffusion";this.active=!0;this.startTime=0;this.currentHop=0;this.nextHopTime=0;this.id=e,this.store=t,this.sourceNodeIds=r,this.config={color:n?.color??[1,.3,.1],delayPerHop:n?.delayPerHop??500,maxHops:n?.maxHops??5,decay:n?.decay??.7,holdDuration:n?.holdDuration??3e3},this.wavefront=new Set(r),this.visited=new Map,this.originalColors=new Map;let i=t.nodeState;if(i)for(let o of t.data.nodes){let s=t.index.getNodeIndex(o.id);s!==void 0&&this.originalColors.set(o.id,[i.colors[s*3],i.colors[s*3+1],i.colors[s*3+2]])}for(let o of r)this.visited.set(o,0),this.applyColor(o,1)}tick(e,t){if(this.startTime===0&&(this.startTime=e,this.nextHopTime=e+this.config.delayPerHop/1e3),e>=this.nextHopTime&&this.currentHop<this.config.maxHops){this.currentHop++;let r=new Set;for(let n of this.wavefront){let i=this.store.queries.getNeighbors(n);for(let o of i)if(!this.visited.has(o.nodeId)){r.add(o.nodeId),this.visited.set(o.nodeId,this.currentHop);let s=Math.pow(this.config.decay,this.currentHop);this.applyColor(o.nodeId,s)}}this.wavefront=r,this.nextHopTime=e+this.config.delayPerHop/1e3,r.size===0&&(this.nextHopTime=1/0)}if(this.wavefront.size===0&&this.config.holdDuration>0){let r=(this.config.delayPerHop*this.currentHop+this.config.holdDuration)/1e3;e-this.startTime>r&&(this.active=!1)}}applyColor(e,t){let r=this.store.nodeState;if(!r)return;let n=this.store.index.getNodeIndex(e);if(n===void 0)return;let i=this.originalColors.get(e)??[.5,.5,.5],[o,s,d]=this.config.color;r.colors[n*3]=i[0]+(o-i[0])*t,r.colors[n*3+1]=i[1]+(s-i[1])*t,r.colors[n*3+2]=i[2]+(d-i[2])*t,this.store.updateStrategy.markDirty("nodeColors"),this.store.notifyChange()}dispose(){let e=this.store.nodeState;if(e){for(let[t,r]of this.originalColors){let n=this.store.index.getNodeIndex(t);n!==void 0&&(e.colors[n*3]=r[0],e.colors[n*3+1]=r[1],e.colors[n*3+2]=r[2])}this.store.updateStrategy.markDirty("nodeColors"),this.store.notifyChange()}}};var Ua=class{constructor(e,t,r){this.type="propertyColor";this.active=!0;this.startTime=0;this.completed=!1;this.id=e,this.store=t;let n=r.colorMin??[.2,.4,1],i=r.colorMax??[1,.2,.2],o=r.duration??800,s=r.property;this.startColors=new Map,this.targetColors=new Map,this.nodeIds=[];let d=new Map;for(let h of t.data.nodes){let p=h.properties[s];typeof p=="number"&&d.set(h.id,p)}let l=r.minValue,u=r.maxValue;if(l===void 0||u===void 0){let h=Array.from(d.values());h.length>0?(l===void 0&&(l=Math.min(...h)),u===void 0&&(u=Math.max(...h))):(l=0,u=1)}this.config={property:s,colorMin:n,colorMax:i,duration:o,minValue:l,maxValue:u};let c=t.nodeState;if(c){let h=u-l;for(let p of t.data.nodes){let f=t.index.getNodeIndex(p.id);if(f===void 0)continue;let m=d.get(p.id);if(m===void 0)continue;this.nodeIds.push(p.id),this.startColors.set(p.id,[c.colors[f*3],c.colors[f*3+1],c.colors[f*3+2]]);let g=h>0?(m-l)/h:0;this.targetColors.set(p.id,[n[0]+(i[0]-n[0])*g,n[1]+(i[1]-n[1])*g,n[2]+(i[2]-n[2])*g])}}}tick(e,t){if(this.startTime===0&&(this.startTime=e),this.completed)return;let r=this.store.nodeState;if(!r)return;let n=(e-this.startTime)*1e3,i=Math.min(n/this.config.duration,1),o=i*(2-i);for(let s of this.nodeIds){let d=this.store.index.getNodeIndex(s);if(d===void 0)continue;let l=this.startColors.get(s),u=this.targetColors.get(s);!l||!u||(r.colors[d*3]=l[0]+(u[0]-l[0])*o,r.colors[d*3+1]=l[1]+(u[1]-l[1])*o,r.colors[d*3+2]=l[2]+(u[2]-l[2])*o)}this.store.updateStrategy.markDirty("nodeColors"),this.store.notifyChange(),i>=1&&(this.completed=!0,this.active=!1)}dispose(){let e=this.store.nodeState;if(e){for(let t of this.nodeIds){let r=this.store.index.getNodeIndex(t);if(r===void 0)continue;let n=this.targetColors.get(t);n&&(e.colors[r*3]=n[0],e.colors[r*3+1]=n[1],e.colors[r*3+2]=n[2])}this.store.updateStrategy.markDirty("nodeColors"),this.store.notifyChange()}}};var Wa=class{constructor(e,t,r){this.type="clusterReveal";this.active=!0;this.startTime=0;this.completed=!1;this.id=e,this.store=t,this.originalNodeSizes=new Map,this.originalNodeOpacities=new Map,this.originalEdgeOpacities=new Map,this.clusterNodes=new Map,this.revealedClusters=new Set;for(let s of t.data.nodes){let d=s.category||"Default";this.clusterNodes.has(d)||this.clusterNodes.set(d,[]),this.clusterNodes.get(d).push(s.id)}let n;if(r?.clusterOrder&&r.clusterOrder.length>0)n=r.clusterOrder;else{let s=new Set;n=[];for(let d of t.data.nodes){let l=d.category||"Default";s.has(l)||(s.add(l),n.push(l))}}this.config={clusterOrder:n,delayPerCluster:r?.delayPerCluster??800,clusterAnimDuration:r?.clusterAnimDuration??600};let i=t.nodeState;if(i){for(let s of t.data.nodes){let d=t.index.getNodeIndex(s.id);d!==void 0&&(this.originalNodeSizes.set(s.id,i.sizes[d]),this.originalNodeOpacities.set(s.id,i.opacities[d]),i.sizes[d]=0,i.opacities[d]=0)}t.updateStrategy.markDirty("nodeSizes"),t.updateStrategy.markDirty("nodeOpacities")}let o=t.edgeState;if(o){for(let s of t.data.edges){let d=t.index.getEdgeIndex(s.id);d!==void 0&&(this.originalEdgeOpacities.set(s.id,o.opacities[d]),o.opacities[d]=0)}t.updateStrategy.markDirty("edgeOpacities")}t.notifyChange()}tick(e,t){if(this.startTime===0&&(this.startTime=e),this.completed)return;let r=(e-this.startTime)*1e3,n=this.store.nodeState,i=this.store.edgeState;if(!n)return;let o=!1,s=new Set;for(let d=0;d<this.config.clusterOrder.length;d++){let l=this.config.clusterOrder[d],u=d*this.config.delayPerCluster,c=r-u,h=this.clusterNodes.get(l)??[];if(c<=0){o=!0;continue}if(c>=this.config.clusterAnimDuration){if(!this.revealedClusters.has(l)){this.revealedClusters.add(l);for(let p of h){let f=this.store.index.getNodeIndex(p);f!==void 0&&(n.sizes[f]=this.originalNodeSizes.get(p)??10,n.opacities[f]=this.originalNodeOpacities.get(p)??1)}}for(let p of h)s.add(p)}else{o=!0;let p=c/this.config.clusterAnimDuration,f=p*(2-p);for(let m of h){let g=this.store.index.getNodeIndex(m);if(g===void 0)continue;let y=this.originalNodeSizes.get(m)??10,v=this.originalNodeOpacities.get(m)??1;n.sizes[g]=y*f,n.opacities[g]=v*f,s.add(m)}}}if(this.store.updateStrategy.markDirty("nodeSizes"),this.store.updateStrategy.markDirty("nodeOpacities"),i){for(let d of this.store.data.edges){let l=this.store.index.getEdgeIndex(d.id);l!==void 0&&(s.has(d.source)&&s.has(d.target)?i.opacities[l]=this.originalEdgeOpacities.get(d.id)??1:i.opacities[l]=0)}this.store.updateStrategy.markDirty("edgeOpacities")}this.store.notifyChange(),o||(this.completed=!0,this.active=!1)}dispose(){let e=this.store.nodeState;if(e){for(let[r,n]of this.originalNodeSizes){let i=this.store.index.getNodeIndex(r);i!==void 0&&(e.sizes[i]=n)}for(let[r,n]of this.originalNodeOpacities){let i=this.store.index.getNodeIndex(r);i!==void 0&&(e.opacities[i]=n)}this.store.updateStrategy.markDirty("nodeSizes"),this.store.updateStrategy.markDirty("nodeOpacities")}let t=this.store.edgeState;if(t){for(let[r,n]of this.originalEdgeOpacities){let i=this.store.index.getEdgeIndex(r);i!==void 0&&(t.opacities[i]=n)}this.store.updateStrategy.markDirty("edgeOpacities")}this.store.notifyChange()}};var ja=class{constructor(e,t){this.nextId=1;this.store=e,this.effectManager=t}heatDiffusion(e,t){let r=Array.isArray(e)?e:[e],n=`heatDiffusion-${this.nextId++}`;return this.effectManager.addEffect(new Va(n,this.store,r,t)),n}propertyColor(e){let t=`propertyColor-${this.nextId++}`;return this.effectManager.addEffect(new Ua(t,this.store,e)),t}clusterReveal(e){let t=`clusterReveal-${this.nextId++}`;return this.effectManager.addEffect(new Wa(t,this.store,e)),t}stop(e){this.effectManager.removeEffect(e)}stopAll(e){this.effectManager.stopAll(e)}};var qa=class{constructor(e,t,r,n){this.type="timelineReplay";this.active=!0;this.startTime=-1;this.nextEventIndex=0;this.completed=!1;this.entranceDuration=400;this.id=e,this.store=t,this.events=[...r].sort((i,o)=>i.time-o.time),this.config={speed:n?.speed??1,animateEntrance:n?.animateEntrance??!0,animateEdgeDraw:n?.animateEdgeDraw??!0,loop:n?.loop??!1},this.recentlyAddedNodes=new Map,this.recentlyAddedEdges=new Map}tick(e,t){if(this.startTime<0&&(this.startTime=e),this.completed)return;let r=(e-this.startTime)*1e3*this.config.speed;for(;this.nextEventIndex<this.events.length;){let n=this.events[this.nextEventIndex];if(n.time>r)break;this.processEvent(n,e),this.nextEventIndex++}this.config.animateEntrance&&this.animateRecentNodes(e),this.config.animateEdgeDraw&&this.animateRecentEdges(e),this.nextEventIndex>=this.events.length&&this.recentlyAddedNodes.size===0&&this.recentlyAddedEdges.size===0&&(this.config.loop?(this.startTime=e,this.nextEventIndex=0):(this.completed=!0,this.active=!1))}processEvent(e,t){switch(e.type){case"addNode":{let r=e.data;if(this.store.applyDelta({addedNodes:[r]}),this.config.animateEntrance){let n=this.store.nodeState;if(n){let i=this.store.index.getNodeIndex(r.id);i!==void 0&&(n.sizes[i]=0,n.opacities[i]=0,this.store.updateStrategy.markDirty("nodeSizes"),this.store.updateStrategy.markDirty("nodeOpacities"))}this.recentlyAddedNodes.set(r.id,t)}break}case"addEdge":{let r=e.data;if(this.store.applyDelta({addedEdges:[r]}),this.config.animateEdgeDraw){let n=this.store.edgeState;if(n){let i=this.store.index.getEdgeIndex(r.id);i!==void 0&&(n.opacities[i]=0,this.store.updateStrategy.markDirty("edgeOpacities"))}this.recentlyAddedEdges.set(r.id,t)}break}case"removeNode":{let r=e.data;this.store.applyDelta({removedNodeIds:[r.id]});break}case"removeEdge":{let r=e.data;this.store.applyDelta({removedEdgeIds:[r.id]});break}case"updateNode":{let r=e.data;this.store.applyDelta({updatedNodes:[{id:r.id,next:{properties:r.properties}}]});break}}this.store.notifyChange()}animateRecentNodes(e){let t=this.store.nodeState;if(!t)return;let r=!1,n=[];for(let[i,o]of this.recentlyAddedNodes){let s=(e-o)*1e3,d=this.store.index.getNodeIndex(i);if(d===void 0){n.push(i);continue}if(s>=this.entranceDuration)t.sizes[d]=10,t.opacities[d]=1,n.push(i);else{let l=s/this.entranceDuration,u=l*(2-l);t.sizes[d]=10*u,t.opacities[d]=u}r=!0}for(let i of n)this.recentlyAddedNodes.delete(i);r&&(this.store.updateStrategy.markDirty("nodeSizes"),this.store.updateStrategy.markDirty("nodeOpacities"),this.store.notifyChange())}animateRecentEdges(e){let t=this.store.edgeState;if(!t)return;let r=!1,n=[];for(let[i,o]of this.recentlyAddedEdges){let s=(e-o)*1e3,d=this.store.index.getEdgeIndex(i);if(d===void 0){n.push(i);continue}if(s>=this.entranceDuration)t.opacities[d]=1,n.push(i);else{let l=s/this.entranceDuration;t.opacities[d]=l}r=!0}for(let i of n)this.recentlyAddedEdges.delete(i);r&&(this.store.updateStrategy.markDirty("edgeOpacities"),this.store.notifyChange())}dispose(){this.recentlyAddedNodes.clear(),this.recentlyAddedEdges.clear()}};var Ka=class{constructor(e,t){this.nextId=1;this.store=e,this.effectManager=t}timelineReplay(e,t){let r=`timelineReplay-${this.nextId++}`;return this.effectManager.addEffect(new qa(r,this.store,e,t)),r}stop(e){this.effectManager.removeEffect(e)}stopAll(){this.effectManager.stopAll("timelineReplay")}};var $a=class{constructor(e,t,r){this._mode="2D";this._maxScreenFraction=.5;this._setMaxScreenFraction=null;this._nodeSizeScale=1;this._setNodeSizeScale=null;this.renderPath=null;this.events=e,this.interaction=t,this._minimapVisible=r?.minimapVisible??!0,this._theme=r?.theme??"dark"}wireInteraction(e){this.interaction=e}wireRenderPath(e){this.renderPath=e}setWebGPURenderPathEnabled(e){this.renderPath?.setHostEnabled(e)}isWebGPURenderPathEnabled(){return this.renderPath?.isHostEnabled()??!1}isMinimapVisible(){return this._minimapVisible}setMinimapVisible(e){this._minimapVisible!==e&&(this._minimapVisible=e,this.events.emit("view:changed",{minimapVisible:e}))}getTheme(){return this._theme}setTheme(e){this._theme!==e&&(this._theme=e,this.events.emit("view:changed",{theme:e}))}getMode(){return this._mode}setMode(e){this._mode!==e&&(this._mode=e,this.events.emit("view:changed",{mode:e}))}setMaxScreenFraction(e){e===1/0||(!Number.isFinite(e)||e<=0)&&(console.warn(`[RendererApi] maxScreenFraction must be > 0 or Infinity, got ${e}, fallback ${.5}`),e=.5),this._maxScreenFraction=e,this._setMaxScreenFraction?.(e)}getMaxScreenFraction(){return this._maxScreenFraction}wireMaxScreenFraction(e){this._setMaxScreenFraction=e,e(this._maxScreenFraction)}setNodeSizeScale(e){(!Number.isFinite(e)||e<=0)&&(console.warn(`[RendererApi] nodeSizeScale must be > 0 and finite, got ${e}, fallback ${1}`),e=1),this._nodeSizeScale=e,this._setNodeSizeScale?.(e)}getNodeSizeScale(){return this._nodeSizeScale}wireNodeSizeScale(e){this._setNodeSizeScale=e,e(this._nodeSizeScale)}screenshot(e){return new Promise((t,r)=>{if(!this.interaction){r(new Error("RendererApi.screenshot: renderer not available (interaction manager is null)"));return}this.interaction.getRenderer().domElement.toBlob(i=>{if(!i){r(new Error("RendererApi.screenshot: failed to encode canvas to PNG blob"));return}t(i)},"image/png")})}};var _f=[{id:"info",order:0},{id:"expand",order:10},{id:"layout",order:20},{id:"selection-menu",order:25},{id:"selection",order:26},{id:"select",order:30},{id:"create",order:35},{id:"camera",order:40},{id:"edit",order:45},{id:"more",order:80},{id:"danger",order:90}],Za=class{constructor(){this.groups=new Map;this.items=new Map;this.hiddenIds=new Set;this.overrides=new Map;this.listeners=new Set;this.CONSUMED_GROUPS=new Set(["selection"]);this._state={visible:!1,position:{x:0,y:0},context:null,sections:[]};for(let e of _f)this.groups.set(e.id,e)}get state(){return this._state}registerGroup(e){this.groups.set(e.id,e)}registerItem(e){return this.items.set(e.id,e),this.groups.has(e.group)||this.groups.set(e.group,{id:e.group,order:50}),()=>this.unregisterItem(e.id)}registerItems(e){let t=e.map(r=>this.registerItem(r));return()=>t.forEach(r=>r())}unregisterItem(e){this.items.delete(e)}getItemsInGroup(e){let t=[];for(let r of this.items.values())if(r.group===e&&!this.hiddenIds.has(r.id)){let n=this.getEffectiveItem(r.id);n&&t.push(n)}return t.sort((r,n)=>(r.order??0)-(n.order??0))}overrideItem(e,t){this.overrides.set(e,{...this.overrides.get(e),...t})}hideItem(e){this.hiddenIds.add(e)}showItem(e){this.hiddenIds.delete(e)}show(e){let t=this.resolveMenu(e);this._state={visible:!0,position:e.screenPosition,context:e,sections:t},this.notify()}hide(){this._state.visible&&(this._state={visible:!1,position:{x:0,y:0},context:null,sections:[]},this.notify())}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notify(){for(let e of this.listeners)try{e()}catch(t){console.error("ContextMenuManager listener error:",t)}}getEffectiveItem(e){let t=this.items.get(e);if(!t)return;let r=this.overrides.get(e);return r?{...t,...r}:t}resolveMenu(e){let t=new Map;for(let i of this.items.keys()){if(this.hiddenIds.has(i))continue;let o=this.getEffectiveItem(i);if(!o||o.visible&&!o.visible(e)||Array.isArray(o.children)&&!o.children.some(c=>!c.visible||c.visible(e)))continue;let s=typeof o.label=="function"?o.label(e):o.label,d=o.enabled?o.enabled(e):!0,l={id:o.id,label:s,icon:o.icon,enabled:d,danger:o.danger??!1,action:o.action,children:o.children,hasAsyncChildren:typeof o.children=="function"};t.has(o.group)||t.set(o.group,[]),t.get(o.group).push(l)}for(let[,i]of t)i.sort((o,s)=>{let d=this.getEffectiveItem(o.id),l=this.getEffectiveItem(s.id);return(d?.order??0)-(l?.order??0)});let r=Array.from(this.groups.values()).sort((i,o)=>i.order-o.order),n=[];for(let i of r){if(this.CONSUMED_GROUPS.has(i.id))continue;let o=t.get(i.id);o&&o.length>0&&n.push({groupId:i.id,items:o})}return n}dispose(){this.items.clear(),this.groups.clear(),this.hiddenIds.clear(),this.overrides.clear(),this.listeners.clear()}};var Ya=class{constructor(){this.manager=new Za}register(e){return this.manager.registerItem(e)}registerAll(e){return this.manager.registerItems(e)}registerGroup(e){this.manager.registerGroup(e)}unregister(e){this.manager.unregisterItem(e)}override(e,t){this.manager.overrideItem(e,t)}hide(e){this.manager.hideItem(e)}show(e){this.manager.showItem(e)}showAt(e){this.manager.show(e)}dismiss(){this.manager.hide()}dispose(){this.manager.dispose()}};var Xa=class{constructor(){this.contextMenu=new Ya}};var Qa=class{constructor(e,t,r,n){this.type="AddFilter";this.store=e,this.filterManager=t,this.filterId=r,this.filterEntry=n}execute(){this.filterManager.addFilter(this.filterId,this.filterEntry)}undo(){this.filterManager.removeFilter(this.filterId)}};var Ja=class{constructor(e,t,r){this.store=e;this.filterManager=t;this.executor=r;this.nextFilterId=1}traceNeighbors(e,t){let r=`trace-${this.nextFilterId++}`;return this.executor.execute(new Qa(this.store,this.filterManager,r,{type:"topology",target:"node",metric:"outDegree",range:[t??2,1/0]})),r}};var ed=class{constructor(e,t){this._dragMode="node";this.store=e,this.events=t}get gm(){return this.store.getGroupManager()}create(e,t){let r=this.gm.createGroup(e,t);return this.events.emit("group:created",{groupId:r,spec:t}),r}createByAttribute(e,t){let r=this.gm.createGroupsByAttribute(e),n=[];for(let[,i]of r){if(t){let s=this.store.getGroupById(i);s&&Object.assign(s.spec,t)}let o=this.store.getGroupById(i)?.spec??{name:""};this.events.emit("group:created",{groupId:i,spec:o}),n.push(i)}return n}createFromClusters(e,t){let r=new Map(Object.entries(e)),n=this.gm.createGroupsFromClusters(r),i=[];for(let[,o]of n){if(t){let d=this.store.getGroupById(o);d&&Object.assign(d.spec,t)}let s=this.store.getGroupById(o)?.spec??{name:""};this.events.emit("group:created",{groupId:o,spec:s}),i.push(o)}return i}createBy(e,t){let r=typeof t=="function"?t:t?()=>t:void 0,n=this.gm.createGroupsByFunction(e,r),i=[];for(let[,o]of n){let d=this.store.getGroupById(o)?.spec??{name:""};this.events.emit("group:created",{groupId:o,spec:d}),i.push(o)}return i}list(){return this.store.listGroups()}get(e){return this.store.getGroupById(e)}getByNode(e){return this.store.getGroupForNode(e)}getMembers(e){return this.store.getGroupMembers(e)}update(e,t){let r=this.store.getGroupById(e);if(!r){console.warn(`[GroupsApi] update: unknown groupId ${e}`);return}Object.assign(r.spec,t),t.anchorNodeId!==void 0&&r.collapsed&&t.anchorNodeId!==r.anchorNodeId&&this.setAnchor(e,t.anchorNodeId),this.store.updateStrategy.markDirty("groups"),this.store.notifyChange(),this.events.emit("group:updated",{groupId:e,changes:t})}addNodes(e,t){this.gm.addNodesToGroup(e,t),this.events.emit("group:members-changed",{groupId:e,added:t,removed:[]})}removeNodes(e,t){this.gm.removeNodesFromGroup(e,t),this.events.emit("group:members-changed",{groupId:e,added:[],removed:t})}collapse(e){this.gm.collapseGroup(e),this.events.emit("group:collapsed",{groupId:e})}expand(e){this.gm.expandGroup(e),this.events.emit("group:expanded",{groupId:e})}toggle(e){let t=this.store.getGroupById(e);t&&(t.collapsed?this.expand(e):this.collapse(e))}collapseAll(){let e=this.store.listGroups();for(let t of e)t.collapsed||this.collapse(t.id)}expandAll(){let e=this.store.listGroups();for(let t of e)t.collapsed&&this.expand(t.id)}getAnchor(e){return this.store.getGroupById(e)?.anchorNodeId??null}setAnchor(e,t){let r=this.store.getGroupById(e);if(!r)return;let n=r.anchorNodeId;if(!r.collapsed){r.spec.anchorNodeId=t;return}r.memberNodeIds.has(t)&&r.anchorNodeId!==t&&(this.gm.switchAnchor(e,t),r.spec.anchorNodeId=t,this.events.emit("group:anchor-changed",{groupId:e,from:n,to:t}))}getAggregatedEdges(e){return this.store.getAggregatedEdges().filter(r=>r.sourceGroupId===e?!0:r.target.kind==="group"&&r.target.groupId===e)}dissolve(e){this.store.getGroupById(e)?.collapsed&&this.expand(e),this.gm.dissolveGroup(e),this.events.emit("group:dissolved",{groupId:e})}dissolveAll(){let e=this.store.listGroups().map(t=>t.id);for(let t of e)this.dissolve(t)}setDragMode(e){this._dragMode=e}getDragMode(){return this._dragMode}};var Df="https://nominatim.openstreetmap.org/search";function Nf(a){return Array.isArray(a)?a.flatMap(e=>{let t=Number(e?.lat),r=Number(e?.lon);if(!Number.isFinite(t)||!Number.isFinite(r))return[];let n=e.boundingbox,i;if(Array.isArray(n)&&n.length===4){let o=Number(n[0]),s=Number(n[1]),d=Number(n[2]),l=Number(n[3]);[o,s,d,l].every(Number.isFinite)&&(i={south:o,north:s,west:d,east:l})}return[{id:e.place_id!=null?String(e.place_id):`${t},${r}`,name:String(e.display_name??""),center:{lat:t,lng:r},bbox:i,raw:e}]}):[]}async function kf(a,e){let t=new URL(Df);t.searchParams.set("q",a),t.searchParams.set("format","jsonv2"),t.searchParams.set("limit",String(e?.limit??10)),e?.language&&t.searchParams.set("accept-language",e.language);let r=await fetch(t.toString(),{signal:e?.signal,headers:{Accept:"application/json"}});if(!r.ok)throw new Error(`Nominatim search failed: ${r.status} ${r.statusText}`);return Nf(await r.json())}var Hh={key:"nominatim",name:"OpenStreetMap (Nominatim)",search:kf};import*as yi from"three";var bo=class{constructor(e,t){this.mapScale=e,this.sphereRadius=t??Jt*e}getScale(){return this.mapScale}getSphereRadius(){return this.sphereRadius}latLngToWorld(e,t,r){return this.latLngElevToWorld(e,t,0,r)}latLngElevToWorld(e,t,r,n){if(n==="planar"){let i=ou(e,t);return new yi.Vector3(i.x*this.mapScale,i.y*this.mapScale,r)}else{let i=su(e,t),o=this.sphereRadius+r;return new yi.Vector3(i.x*o,i.y*o,i.z*o)}}applyElevation(e,t,r){if(r==="planar")return{x:e.x,y:e.y,z:t};let n=Math.sqrt(e.x**2+e.y**2+e.z**2);if(n===0)return{...e};let i=(n+t)/n;return{x:e.x*i,y:e.y*i,z:e.z*i}}lerpPosition(e,t,r,n,i){if(i<=0)return this.latLngToWorld(e,t,r);if(i>=1)return this.latLngToWorld(e,t,n);let o=this.latLngToWorld(e,t,r),s=this.latLngToWorld(e,t,n);return o.lerp(s,i)}screenCenterToLatLng(e,t){if(t==="planar"){let r=-e.x/this.mapScale,n=-e.y/this.mapScale,i=Jt,o=r/i;return{lat:(2*Math.atan(Math.exp(n/i))-Math.PI/2)*(180/Math.PI),lng:o*(180/Math.PI)}}else{let r=this.sphereRadius,n=-e.x/r,i=-e.y/r,o=n*n+i*i;if(o>=1)return null;let s=Math.sqrt(1-o),d=new yi.Vector3(n,i,s),l=Xo(d);return{lat:l.latitude,lng:l.longitude}}}latLngToCloudSceneXY(e,t,r){let n=this.latLngToWorld(e,t,r);return new yi.Vector2(-n.x,-n.y)}getScaledEarthRadius(){return Jt*this.mapScale}getScaledEarthPerimeter(){return Vi*this.mapScale}static scaleForRadius(e){return e/Jt}static scaleForWidth(e){return e/Vi}};import*as xt from"three";var vc={min:0,max:60};function Fh(){return{...vc}}function zh(a){let e=vc.min*Math.PI/180,t=vc.max*Math.PI/180;return Math.max(e,Math.min(t,a))}function Bh(a){let r=Math.abs(Math.cos(a));return .05+(.3-.05)*r}var St=class St{constructor(e,t,r){this.interaction=null;this._enabled=!1;this._mode=null;this._pitchRad=0;this._is3D=!1;this._pitchAnimId=null;this._pivotNormal=null;this._capturedCameraPos=null;this._capturedCameraQuat=null;this._lastAppliedScenePosZ=null;this._lastAppliedPitchRad=null;this._setMapDamping=null;this._maxNodeGrowth=4;this._setMapMaxGrowth=null;this._activeProvider=null;this._providers=new Map;this._activeGeocoder=null;this._geocoders=new Map;this._cloudScene=null;this._camera=null;this._globeControl=null;this._layoutController=null;this._mapSize=10;this._globeRadius=5;this._cameraZ=6;this._flyToCancel=null;this._pendingView=null;this._lastGeoLayout=null;this._autoFitOff=null;this._autoFitDebounceId=null;this._autoFitDuration=600;this._autoFitDebounceMs=200;this._transitioning=!1;this._pendingSwapToken=null;this._nextSwapToken=1;this._mapNodeState=new Map;this._defaultCoordProvider=new bo(1);this.elevation={get:e=>this._mapNodeState.get(e)?.elevation,set:(e,t)=>{let r=Array.isArray(e)?e:[e];for(let n of r)this._nodeState(n).elevation=t;this._reapplyElevationFor(r)},fromProperty:(e,t)=>{let r=t?.unit??1,n=t?.default!==void 0,i=t?.default??0,o=[];for(let s of this.store.data.nodes){let d=s.properties?.[e],l;if(d==null)l=n?i:void 0;else if(typeof d=="number"&&Number.isFinite(d))l=d;else if(typeof d=="string"){let u=parseFloat(d);l=Number.isFinite(u)?u:n?i:void 0}else l=n?i:void 0;l!==void 0&&(this._nodeState(s.id).elevation=l*r,o.push(s.id))}this._reapplyElevationFor(o)},clear:e=>{let t=e===void 0?this._idsWithElevation():Array.isArray(e)?e:[e];for(let r of t){let n=this._mapNodeState.get(r);n&&(delete n.elevation,this._pruneNodeState(r))}this._reapplyElevationFor(t)},entries:()=>new Map(this._elevation),applyLayout:e=>{if(e.mode==="manual")return;let t=e.spacing,r=e.maxLayers??16,n=e.anchorPredicate??(c=>{let h=c.properties?.lat,p=c.properties?.lng,f=typeof h=="string"?parseFloat(h):h,m=typeof p=="string"?parseFloat(p):p;return Number.isFinite(f)&&Number.isFinite(m)}),i=this.store.data.nodes,o=e.layerBy==="hop"||e.layerBy===void 0?null:e.layerBy;if(e.mode==="stacked"){this._applyStackedLayout(i,n,t,r,e.pickAnchor);return}if(o){let c=[];for(let h of i){let p=n(h)?0:o(h)*t;this._nodeState(h.id).elevation=p,c.push(h.id)}this._reapplyElevationFor(c);return}let s=this._buildAdjacency(),d=new Map,l=[];for(let c of i)n(c)&&(d.set(c.id,0),l.push(c.id));for(;l.length;){let c=l.shift(),h=d.get(c);if(!(h>=r))for(let p of s.get(c)??[])d.has(p)||(d.set(p,h+1),l.push(p))}let u=[];for(let c of i){let h=d.get(c.id),p=h!==void 0?h*t:0;this._nodeState(c.id).elevation=p,u.push(c.id)}this._reapplyElevationFor(u)}};this.store=e,this.executor=t,this.events=r,this._initBuiltInProviders(),this.registerGeocoder(Hh),this._activeGeocoder="nominatim",this.events.on("graph:dataReset",()=>{this._mapNodeState.clear()})}_nodeState(e){let t=this._mapNodeState.get(e);return t||(t={pinnedByMap:!1},this._mapNodeState.set(e,t)),t}_pruneNodeState(e){let t=this._mapNodeState.get(e);t&&t.elevation===void 0&&t.appliedElevation===void 0&&!t.pinnedByMap&&this._mapNodeState.delete(e)}_idsWithElevation(){let e=[];for(let[t,r]of this._mapNodeState)r.elevation!==void 0&&e.push(t);return e}_clearAppliedElevation(){for(let[e,t]of this._mapNodeState)t.appliedElevation!==void 0&&(delete t.appliedElevation,this._pruneNodeState(e))}_hasMapPinnedNodes(){for(let e of this._mapNodeState.values())if(e.pinnedByMap)return!0;return!1}get _elevation(){let e=new Map;for(let[t,r]of this._mapNodeState)r.elevation!==void 0&&e.set(t,r.elevation);return e}get _appliedElevation(){let e=new Map;for(let[t,r]of this._mapNodeState)r.appliedElevation!==void 0&&e.set(t,r.appliedElevation);return e}get _geoPinnedIds(){let e=new Set;for(let[t,r]of this._mapNodeState)r.pinnedByMap&&e.add(t);return e}_initBuiltInProviders(){for(let[e,t]of Object.entries(nu)){let n=Oi[e];typeof n=="function"&&this._providers.set(e,{key:e,name:t.name,description:t.description,tileUrl:n,requiresConfig:!1,maxZoom:t.maxLevel??18})}this._providers.set("mapboxStreets",{key:"mapboxStreets",name:"Mapbox Streets",description:"Mapbox Streets (requires API key)",tileUrl:e=>Oi.mapboxStreets(e.accessToken),requiresConfig:!0,maxZoom:22}),this._providers.set("mapboxSatellite",{key:"mapboxSatellite",name:"Mapbox Satellite",description:"Mapbox Satellite (requires API key)",tileUrl:e=>Oi.mapboxSatellite(e.accessToken),requiresConfig:!0,maxZoom:22}),this._providers.set("mapboxDark",{key:"mapboxDark",name:"Mapbox Dark",description:"Mapbox Dark (requires API key)",tileUrl:e=>Oi.mapboxDark(e.accessToken),requiresConfig:!0,maxZoom:22})}wireInteraction(e){this.interaction=e}_viewChanged(){this.interaction?.requestRender()}wireLayoutController(e){this._layoutController=e}wireScene(e,t){this._cloudScene=e,this._camera=t,t&&(this._cameraZ=t.position.z),this._flushPendingView()}reassertGeoLayout(e){return this.applyGeoLayout({...this._lastGeoLayout,mode:e})}_deferView(e){return this._pendingView=e,Promise.resolve()}_flushPendingView(){let e=this._pendingView;!e||!this._enabled||!this._mode||!this._cloudScene||(this._pendingView=null,e())}wireGlobeControl(e){this._globeControl=e}registerProvider(e){this._providers.set(e.key,e),this.events.emit("map:providerRegistered",{key:e.key})}unregisterProvider(e){return this._providers.has(e)?this._activeProvider===e?(console.warn(`[MapApi] unregisterProvider: "${e}" is currently active. Switch provider first.`),!1):(this._providers.delete(e),this.events.emit("map:providerUnregistered",{key:e}),!0):!1}listProviders(){return Array.from(this._providers.values())}getProvider(e){return this._providers.get(e)??null}resolveTileUrl(e,t){let r=this._providers.get(e);if(!r)return console.warn(`[MapApi] resolveTileUrl: unknown provider key "${e}"`),null;let{tileUrl:n}=r;return r.requiresConfig?!t||Object.keys(t).length===0?(console.warn(`[MapApi] resolveTileUrl: provider "${e}" requires config but none was provided`),null):n(t):n}async enableMap(e){if(this._pendingSwapToken=null,this._enabled)return;let t=e?.mode??(this._is3D?"spherical":"planar"),r=e?.provider??iu;this._enabled=!0,this._mode=t,this._activeProvider=r,this._mapSize=e?.mapSize??this.computeAdaptiveMapSize(t)??10,this._globeRadius=e?.globeRadius??5,this._defaultCoordProvider=new bo(this._mapSize/Vi,this._globeRadius),this._clearAppliedElevation(),this._reapplyElevationFor(this._idsWithElevation()),this._flushPendingView(),this.events.emit("map:enabled",{mode:t,provider:r})}computeAdaptiveMapSize(e){if(e!=="planar")return null;let t=this.store.data.nodes;if(t.length<2)return null;let r=bc(t,"auto");if(!r)return null;let n=new Zn(1),i=1/0,o=-1/0,s=1/0,d=-1/0,l=0;for(let m of t){let g=m.properties??{},y=Number(g[r.lat]),v=Number(g[r.lng]);if(!Number.isFinite(y)||!Number.isFinite(v))continue;let b=n.latLngToWorld(y,v);b.x<i&&(i=b.x),b.x>o&&(o=b.x),b.y<s&&(s=b.y),b.y>d&&(d=b.y),l++}if(l<2)return null;let u=Math.max(o-i,d-s);if(u<1e-9)return null;let c=3,h=10,p=400,f=c/u;return Math.max(h,Math.min(p,f))}beginLayerSwap(){let e=this._nextSwapToken++;return this._pendingSwapToken=e,e}disableMap(e){let t=e?.swapToken;if(t!==void 0&&t===this._pendingSwapToken){this._pendingSwapToken=null;return}this._pendingSwapToken=null,this._hasMapPinnedNodes()&&this.releaseGeoLayout([]),this._mapNodeState.clear(),this._enabled&&(this._enabled=!1,this._mode=null,this._activeProvider=null,this._pitchRad=0,this._camera&&this._capturedCameraPos&&this._camera.position.copy(this._capturedCameraPos),this._camera&&this._capturedCameraQuat&&(this._camera.quaternion.copy(this._capturedCameraQuat),this._camera.updateMatrixWorld()),this._pivotNormal=null,this._capturedCameraPos=null,this._capturedCameraQuat=null,this._lastAppliedScenePosZ=null,this._lastAppliedPitchRad=null,this._cloudScene&&(this._cloudScene.rotation.x=0),this._reheatLayout(),this.events.emit("map:disabled",{}))}_reheatLayout(){let e=this._layoutController??this.store.positionProvider?.layoutController;if(e&&(e.c&&(e.c._enable=!0),typeof e.restart=="function")){e.restart();return}let t=this.store._layoutRuntime?.engine?.controller?.simulation;t&&typeof t.alpha=="function"&&(t.alpha(.5),t.restart?.())}isEnabled(){return this._enabled}getMode(){return this._mode}getMapSize(){return this._mapSize}setProvider(e,t){if(!this._providers.has(e)){console.warn(`[MapApi] setProvider: unknown provider key "${e}"`);return}this._activeProvider=e,this.events.emit("map:providerChanged",{provider:e})}getActiveProvider(){return this._activeProvider}_computeZoomLevel(e){let t=this._mode==="spherical"?this._globeRadius:0,r=Math.max(this._cameraZ-e-t,1e-4),n=St.VIEWPORT_H/(2*Math.tan(St.HALF_VERT_FOV_RAD)*r);if(this._mode==="spherical"){let i=2*Math.PI*this._globeRadius;return Math.log2(i*n/St.TARGET_TILE_PX)}return Math.log2(this._mapSize*n/St.TARGET_TILE_PX)}_zoomLevelToSceneZ(e){let t=this._mode==="spherical",r=t?2*Math.PI*this._globeRadius:this._mapSize,n=Math.pow(2,e)*St.TARGET_TILE_PX/r,i=St.VIEWPORT_H/(2*Math.tan(St.HALF_VERT_FOV_RAD)*n);return this._cameraZ-i-(t?this._globeRadius:0)}async flyTo(e,t){if(!this._enabled||!this._mode||!this._cloudScene)return this._deferView(()=>this.flyTo(e,t));this._flyToCancel&&(this._flyToCancel(),this._flyToCancel=null);let r=t?.duration??600,n=this._cloudScene;if(this._mode==="planar"){let i=this._defaultCoordProvider.latLngToCloudSceneXY(e.lat,e.lng,"planar"),o=n.position.x,s=n.position.y,d=n.position.z,l=i.x,u=i.y,c=t?.zoomLevel!==void 0?this._zoomLevelToSceneZ(t.zoomLevel):d;if(r<=0){n.position.set(l,u,c),this._viewChanged();return}return new Promise(h=>{let p,f=performance.now(),m=!1;this._flyToCancel=()=>{m=!0,cancelAnimationFrame(p),h()};let g=()=>{if(m)return;let y=performance.now()-f,v=Math.min(y/r,1),b=v*v*(3-2*v);n.position.set(o+(l-o)*b,s+(u-s)*b,d+(c-d)*b),this._viewChanged(),v<1?p=requestAnimationFrame(g):(this._flyToCancel=null,h())};p=requestAnimationFrame(g)})}else{let i=e.lat*Math.PI/180,o=e.lng*Math.PI/180,s=88*Math.PI/180,d=Math.max(-s,Math.min(s,i)),l=-o,u=new xt.Quaternion().setFromAxisAngle(new xt.Vector3(0,1,0),l),c=new xt.Quaternion().setFromAxisAngle(new xt.Vector3(1,0,0),d),h=new xt.Quaternion().multiplyQuaternions(c,u),p=n.position.z,f=t?.zoomLevel!==void 0?this._zoomLevelToSceneZ(t.zoomLevel):p,m=()=>{this._globeControl&&this._globeControl.setOrientation(l,d)},g=n.position.x,y=n.position.y;if(r<=0){n.quaternion.copy(h),n.position.x=0,n.position.y=0,f!==p&&(n.position.z=f),m(),this._viewChanged();return}let v=n.quaternion.clone();return new Promise(b=>{let x,w=performance.now(),T=!1;this._flyToCancel=()=>{T=!0,cancelAnimationFrame(x),b()};let I=()=>{if(T)return;let R=performance.now()-w,S=Math.min(R/r,1),P=S*S*(3-2*S);n.quaternion.slerpQuaternions(v,h,P),f!==p&&(n.position.z=p+(f-p)*P),n.position.x=g*(1-P),n.position.y=y*(1-P),this._viewChanged(),S<1?x=requestAnimationFrame(I):(n.quaternion.copy(h),n.position.x=0,n.position.y=0,f!==p&&(n.position.z=f),this._flyToCancel=null,m(),b())};x=requestAnimationFrame(I)})}}async fitToNodes(e){return this._fitToNodes(null,e)}fitNodesOnGlobe(e,t){return!this._enabled||this._mode!=="spherical"||!this._cloudScene?null:this._fitToNodes(e,t)}async _fitToNodes(e,t){if(!this._enabled||!this._mode||!this._cloudScene)return;let r=this.store.positionProvider?.getPositions();if(!r||r.length<3)return;let n=null;if(e){let v=this.store.index.nodeIdToIndex;n=[];for(let b of e){let x=v.get(b);x!==void 0&&x*3+2<r.length&&n.push(x*3)}if(n.length===0)return}let i=1/0,o=1/0,s=-1/0,d=-1/0,l=n?n.length:r.length/3;for(let v=0;v<l;v++){let b=n?n[v]:v*3,x=r[b],w=r[b+1];i=Math.min(i,x),s=Math.max(s,x),o=Math.min(o,w),d=Math.max(d,w)}let u=(i+s)/2,c=(o+d)/2,h=s-i,p=d-o,f=Math.max(h,p,.001),m=this._cloudScene;if(this._mode==="planar"){let v=-u,b=-c,x=f*1.5/(2*Math.tan(St.HALF_VERT_FOV_RAD)),w=this._cameraZ-x,T=m.position.x,I=m.position.y,R=m.position.z,S=t?.duration??600;if(S<=0){m.position.set(v,b,w),this._viewChanged();return}return new Promise(P=>{let D,E=performance.now(),M=()=>{let N=performance.now()-E,A=Math.min(N/S,1),C=A*A*(3-2*A);m.position.set(T+(v-T)*C,I+(b-I)*C,R+(w-R)*C),this._viewChanged(),A<1?D=requestAnimationFrame(M):P()};D=requestAnimationFrame(M)})}let g={south:1/0,north:-1/0,west:1/0,east:-1/0},y=!1;for(let v=0;v<l;v++){let b=n?n[v]:v*3,x=r[b],w=r[b+1],T=r[b+2],I=Math.hypot(x,w,T);if(I<.5*this._globeRadius)continue;let R=Math.asin(w/I)*(180/Math.PI),S=Math.atan2(x/I,T/I)*(180/Math.PI);y=!0,R<g.south&&(g.south=R),R>g.north&&(g.north=R),S<g.west&&(g.west=S),S>g.east&&(g.east=S)}if(y)return this.flyToBounds(g,{mode:"spherical",duration:t?.duration})}setAutoFit(e,t){if(t?.debounceMs!==void 0&&(this._autoFitDebounceMs=t.debounceMs),t?.duration!==void 0&&(this._autoFitDuration=t.duration),this._autoFitOff&&(this._autoFitOff(),this._autoFitOff=null),this._autoFitDebounceId!==null&&(clearTimeout(this._autoFitDebounceId),this._autoFitDebounceId=null),!e)return;let r=()=>{this._autoFitDebounceId!==null&&clearTimeout(this._autoFitDebounceId),this._autoFitDebounceId=setTimeout(()=>{this._autoFitDebounceId=null,this.fitToNodes({duration:this._autoFitDuration})},this._autoFitDebounceMs)};this._autoFitOff=this.events.on("graph:deltaApplied",r),r()}isAutoFit(){return this._autoFitOff!==null}getCenter(){return!this._enabled||!this._mode||!this._cloudScene?null:this._defaultCoordProvider.screenCenterToLatLng(this._cloudScene.position,this._mode)}getZoomLevel(){return!this._enabled||!this._mode||!this._cloudScene?null:this._computeZoomLevel(this._cloudScene.position.z)}setZoomLevel(e){!this._enabled||!this._mode||!this._cloudScene||(this._cloudScene.position.z=this._zoomLevelToSceneZ(e),this._viewChanged())}getPitch(){return this._pitchRad*180/Math.PI}wireIs3D(e){this._is3D=e}wireMapDamping(e){this._setMapDamping=e}setMaxNodeGrowth(e){e===1/0||(!Number.isFinite(e)||e<=0)&&(console.warn(`[MapApi] maxNodeGrowth must be > 0 or Infinity, got ${e}, fallback 4`),e=4),this._maxNodeGrowth=e,this._setMapMaxGrowth?.(e)}getMaxNodeGrowth(){return this._maxNodeGrowth}wireMapMaxGrowth(e){this._setMapMaxGrowth=e,e(this._maxNodeGrowth)}pitchBounds(){return Fh()}setPitch(e,t){let r=zh(e*Math.PI/180);if(Math.abs(r-this._pitchRad)<1e-5)return;this._pitchAnimId!==null&&(cancelAnimationFrame(this._pitchAnimId),this._pitchAnimId=null);let n=t?.animate??!1,i=t?.durationMs??400;if(!n||i<=0){this._setPitchImmediate(r);return}let o=this._pitchRad,s=performance.now(),d=()=>{let l=performance.now()-s,u=Math.min(l/i,1),c=u*u*(3-2*u),h=o+(r-o)*c;this._setPitchImmediate(h),u<1?this._pitchAnimId=requestAnimationFrame(d):this._pitchAnimId=null};this._pitchAnimId=requestAnimationFrame(d)}_setPitchImmediate(e){this._applyPitch(e),this._pitchRad=e,this._setMapDamping?.(Bh(e)),this.events.emit("map:pitchChanged",{pitch:e*180/Math.PI})}_applyPitch(e){this._is3D&&this._cloudScene&&(this._mode==="spherical"?this._applyPitchSpherical(e):this._mode==="planar"&&this._applyPitchPlanar(e))}_applyPitchSpherical(e){let t=this._camera,r=this._cloudScene;if(!t||!r)return;if(this._pivotNormal==null||this._capturedCameraPos==null){let l=new xt.Vector3().subVectors(t.position,r.position),u=l.length();if(u<1e-4)return;this._pivotNormal=l.clone().multiplyScalar(1/u),this._capturedCameraPos=t.position.clone(),this._capturedCameraQuat=t.quaternion.clone()}if(this._lastAppliedPitchRad===e&&this._lastAppliedScenePosZ===r.position.z)return;let n=this._pivotNormal,i=new xt.Vector3().copy(r.position).addScaledVector(n,this._globeRadius),o=new xt.Vector3().subVectors(this._capturedCameraPos,i),s=Math.cos(e),d=Math.sin(e);t.position.set(i.x+o.x,i.y+o.y*s-o.z*d,i.z+o.y*d+o.z*s),t.lookAt(i),t.updateMatrixWorld(),this._lastAppliedPitchRad=e,this._lastAppliedScenePosZ=r.position.z}_applyPitchPlanar(e){let t=this._cloudScene;t&&(t.rotation.x=-e,t.updateMatrixWorld())}reapplyPitch(){this._applyPitch(this._pitchRad)}latLngToWorld(e,t,r){let n=r??this._mode??"planar",i=this._defaultCoordProvider.latLngToWorld(e,t,n);return{x:i.x,y:i.y,z:i.z}}worldToLatLng(e,t,r,n){let i=n??this._mode??"planar",o=this._defaultCoordProvider.getScale();if(i==="planar"){let s=e/o,d=t/o,l=s/Jt;return{lat:(2*Math.atan(Math.exp(d/Jt))-Math.PI/2)*180/Math.PI,lng:l*180/Math.PI}}else{let s=Jt*o,d=e/s,l=t/s,u=r/s,c=Math.sqrt(d*d+l*l+u*u);if(c===0)return null;let h=Xo(new xt.Vector3(d/c,l/c,u/c));return{lat:h.latitude,lng:h.longitude}}}groundKmToWorld(e,t){if(this._mode==="spherical")return e*1e3*(this._globeRadius/Jt);let r=this._defaultCoordProvider.getScale(),n=Math.cos(t*Math.PI/180),i=Math.abs(n)<1e-6?1e-6:n;return e*1e3/i*r}_viewportSize(){let e=this._camera?.domElement,t=e?.clientWidth??St.VIEWPORT_H*(this._camera?.aspect??1),r=e?.clientHeight??St.VIEWPORT_H;return{width:t,height:r}}latLngToScreen(e,t){if(!this._enabled||!this._mode||!this._cloudScene||!this._camera)return null;let r=this._defaultCoordProvider.latLngToWorld(e,t,this._mode),{width:n,height:i}=this._viewportSize();return xu(r,this._cloudScene,this._camera,n,i)}screenToLatLng(e,t){if(!this._enabled||!this._mode||!this._cloudScene||!this._camera)return null;let{width:r,height:n}=this._viewportSize();if(this._mode==="planar"){let i=Eu(e,t,this._cloudScene,this._camera,r,n);return i?this.worldToLatLng(i.x,i.y,0,"planar"):null}else{let i=e/r*2-1,o=-(t/n)*2+1;this._cloudScene.updateMatrixWorld(!1),this._camera.updateMatrixWorld(!1);let s=new xt.Raycaster;s.setFromCamera(new xt.Vector2(i,o),this._camera);let d=this._cloudScene.matrixWorld.clone().invert(),l=Jt,u=s.ray.origin.clone().applyMatrix4(d),c=s.ray.direction.clone().transformDirection(d).normalize(),h=c.dot(c),p=2*u.dot(c),f=u.dot(u)-l*l,m=p*p-4*h*f;if(m<0)return null;let g=(-p-Math.sqrt(m))/(2*h);if(g<0)return null;let y=new xt.Vector3(u.x+g*c.x,u.y+g*c.y,u.z+g*c.z);return this.worldToLatLng(y.x,y.y,y.z,"spherical")}}async transition(e,t){if(!this._enabled||this._mode===e||this._transitioning)return;let r=this._mode;this._transitioning=!0,this.events.emit("map:modeChanged",{from:r,to:e}),this._mode=e;let n=this._cloudScene;n&&(n.position.x=0,n.position.y=0,n.quaternion.identity(),n.updateMatrix()),this._transitioning=!1,this._clearAppliedElevation(),this._reapplyElevationFor(this._idsWithElevation()),this.events.emit("map:transitionComplete",{mode:e})}isTransitioning(){return this._transitioning}cancelTransition(){this._transitioning=!1}buildGeoPositionProvider(e){let t=this.store.data.nodes;if(t.length===0)return{provider:null,geoNodeIds:[],nonGeoNodeIds:[],resolvedMapping:null};let r=bc(t,e.geoMapping??"auto");if(!r)return{provider:null,geoNodeIds:[],nonGeoNodeIds:t.map(c=>c.id),resolvedMapping:null};let n=new Float32Array(t.length*3);if((e.nonGeoFill??"preserve")==="preserve"){let c=this.store.positionProvider?.getPositions();if(c){let h=Math.min(n.length,c.length);n.set(c.subarray(0,h))}}let i=e.mode==="planar"?new Zn(e.mapSize??10):null,o=e.globeRadius??5,s=[],d=[];for(let c=0;c<t.length;c++){let h=t[c].properties??{},p=Number(h[r.lat]),f=Number(h[r.lng]);if(!Number.isFinite(p)||!Number.isFinite(f)){d.push(t[c].id);continue}if(i){let m=i.latLngToWorld(p,f);n[c*3]=m.x,n[c*3+1]=m.y,n[c*3+2]=0}else{let m=Li(p,f,o);n[c*3]=m.x,n[c*3+1]=m.y,n[c*3+2]=m.z}s.push(t[c].id)}if(s.length===0)return{provider:null,geoNodeIds:[],nonGeoNodeIds:d,resolvedMapping:r};let l=new Xn(n),u=this.store;return l.setIndexBridge({getNodeIndex:c=>u.index.getNodeIndex(c),getNodeCount:()=>u.nodeCount,get structureEpoch(){return u.structureEpoch}}),{provider:l,geoNodeIds:s,nonGeoNodeIds:d,resolvedMapping:r}}applyGeoLayout(e){let{mode:t,...r}=e;this._lastGeoLayout=r;let n=this.store.data.nodes;if(n.length===0)return{geoNodeIds:[],nonGeoNodeIds:[],disconnectedNonGeoIds:[],resolvedMapping:null};let i=bc(n,e.geoMapping??"auto");if(!i)return{geoNodeIds:[],nonGeoNodeIds:n.map(G=>G.id),disconnectedNonGeoIds:[],resolvedMapping:null};let o=this.store.positionProvider,s=o?.getPositions();if(!o||!s)return{geoNodeIds:[],nonGeoNodeIds:n.map(G=>G.id),disconnectedNonGeoIds:[],resolvedMapping:i};let d=e.mode==="planar",l=this._enabled?this._mapSize:e.mapSize??10,u=d?new Zn(l):null,c=e.globeRadius??5,h=[],p=[],f=1/0,m=-1/0,g=1/0,y=-1/0,v=1/0,b=-1/0;for(let G of n){let L=G.properties??{},V=Number(L[i.lat]),B=Number(L[i.lng]);if(!Number.isFinite(V)||!Number.isFinite(B)){p.push(G.id);continue}let K=this.store.index.nodeIdToIndex.get(G.id);if(K===void 0){p.push(G.id);continue}if(u){let z=u.latLngToWorld(V,B);s[K*3]=z.x,s[K*3+1]=z.y,s[K*3+2]=0}else{let z=Li(V,B,c);s[K*3]=z.x,s[K*3+1]=z.y,s[K*3+2]=z.z}let oe=s[K*3],Q=s[K*3+1],$=s[K*3+2];oe<f&&(f=oe),oe>m&&(m=oe),Q<g&&(g=Q),Q>y&&(y=Q),$<v&&(v=$),$>b&&(b=$),h.push(G.id)}let x=h.length>=2?Math.hypot(m-f,y-g,b-v):0,w=e.nonGeoStrategy??"autoPlace",T=e.nonGeoFallback??"preserve",I=e.autoPlaceJitter??(x>1e-9?.03*x:.15),R=[],S=[],P=[];if(p.length>0){let G=new Set(p),L=new Map,V=($,z)=>{let W=L.get($);W?W.push(z):L.set($,[z])};for(let $ of this.store.data.edges){let z=$.source,W=$.target;G.has(z)&&V(z,W),G.has(W)&&V(W,z)}let B=($,z,W,te)=>{if(!d){let Ne=Math.hypot(z,W,te);if(Ne>1e-6){let Pe=c/Ne;z*=Pe,W*=Pe,te*=Pe}else z=0,W=0,te=c}s[$*3]=z+(Math.random()-.5)*2*I,s[$*3+1]=W+(Math.random()-.5)*2*I,s[$*3+2]=d?0:te+(Math.random()-.5)*2*I},K=new Set(h),oe=!0;for(;oe;){oe=!1;let $=[];for(let z of p){if(K.has(z))continue;let W=L.get(z);if(!W)continue;let te=0,Ne=0,Pe=0,Ve=0;for(let st of W){if(!K.has(st))continue;let et=this.store.index.nodeIdToIndex.get(st);et!==void 0&&(te+=s[et*3],Ne+=s[et*3+1],Pe+=s[et*3+2],Ve++)}if(Ve===0)continue;let Oe=this.store.index.nodeIdToIndex.get(z);$.push({idx:Oe??-1,id:z,cx:te/Ve,cy:Ne/Ve,cz:Pe/Ve})}for(let z of $)w==="autoPlace"&&z.idx>=0&&(B(z.idx,z.cx,z.cy,z.cz),S.push(z.id)),K.add(z.id),oe=!0}for(let $ of p)K.has($)||R.push($);if(w==="autoPlace"&&T==="geoCentroid"&&h.length>0){let $=0,z=0,W=0;for(let Ne of h){let Pe=this.store.index.nodeIdToIndex.get(Ne);Pe!==void 0&&($+=s[Pe*3],z+=s[Pe*3+1],W+=s[Pe*3+2])}let te=h.length;for(let Ne of R){let Pe=this.store.index.nodeIdToIndex.get(Ne);Pe!==void 0&&(B(Pe,$/te,z/te,W/te),S.push(Ne))}}else if(d){let $=w==="autoPlace"?R:p;for(let z of $){let W=this.store.index.nodeIdToIndex.get(z);W!==void 0&&(s[W*3+2]=0,P.push(z))}}}let D=[...h,...p],E=new Map;for(let G of D){let L=this.store.index.nodeIdToIndex.get(G);L!==void 0&&E.set(G,[s[L*3],s[L*3+1],s[L*3+2]])}this.store.setPositions(E);let M=[...h,...S,...P],N=[];for(let G of M){let L=this._mapNodeState.get(G);L&&(delete L.appliedElevation,L.elevation!==void 0&&N.push(G))}this._reapplyElevationFor(N);let A=[];for(let G of h)this.store.isPinned(G)||A.push(G);h.length>0&&this.store.pinNodes(h);for(let G of A)this._nodeState(G).pinnedByMap=!0;let C=e.pinAutoPlaced??!0;if(w==="autoPlace"&&C&&S.length>0){let G=S.filter(L=>!this.store.isPinned(L));this.store.pinNodes(S);for(let L of G)this._nodeState(L).pinnedByMap=!0}let F=e.alphaBump??.5;if(F>0){let G=this.store._layoutRuntime?.engine?.controller?.simulation;G&&typeof G.alpha=="function"&&(G.alpha(F),G.restart?.())}return{geoNodeIds:h,nonGeoNodeIds:p,disconnectedNonGeoIds:R,resolvedMapping:i}}releaseGeoLayout(e){this._lastGeoLayout=null;let t=e.length>0?new Set(e):null,r=[];for(let[i,o]of this._mapNodeState)o.pinnedByMap&&(t===null||t.has(i))&&r.push(i);if(r.length===0)return;this.store.unpinNodes(r),this.store.positionProvider?.layoutController?.unpinNodes?.(r);for(let i of r){let o=this._mapNodeState.get(i);o&&(o.pinnedByMap=!1,this._pruneNodeState(i))}}_applyStackedLayout(e,t,r,n,i){let o=this.store.positionProvider;if(!o)return;let s=o.getPositions();if(!s)return;let d=this._buildAdjacency(),l=new Set,u=new Map;for(let g of e)u.set(g.id,g),t(g)&&l.add(g.id);let c=new Map,h=new Map;for(let g of l)c.set(g,g),h.set(g,0);for(let g of e){if(l.has(g.id))continue;let y=(d.get(g.id)??[]).filter(b=>l.has(b));if(y.length===0)continue;let v=y[0];if(y.length>1&&i){let b=y.map(w=>u.get(w)).filter(Boolean),x=i(g,b);typeof x=="string"&&l.has(x)&&(v=x)}c.set(g.id,v),h.set(g.id,1)}let p=[];for(let g of c.keys())l.has(g)||p.push(g);for(;p.length;){let g=p.shift(),y=h.get(g);if(y>=n)continue;let v=c.get(g);for(let b of d.get(g)??[])c.has(b)||(c.set(b,v),h.set(b,y+1),p.push(b))}let f=[];for(let[g,y]of c){if(l.has(g))continue;let v=this.store.index.nodeIdToIndex.get(g),b=this.store.index.nodeIdToIndex.get(y);if(v===void 0||b===void 0)continue;s[v*3]=s[b*3],s[v*3+1]=s[b*3+1],s[v*3+2]=s[b*3+2];let x=this._nodeState(g);delete x.appliedElevation,x.elevation=(h.get(g)??1)*r,f.push(g)}if(f.length===0)return;let m=new Map;for(let g of f){let y=this.store.index.nodeIdToIndex.get(g);y!==void 0&&m.set(g,[s[y*3],s[y*3+1],s[y*3+2]])}this.store.setPositions(m),this._reapplyElevationFor(f)}_reapplyElevationFor(e){if(this._transitioning||!this._mode)return;let t=this.store.positionProvider;if(!t||e.length===0)return;let r=t.getPositions();if(!r)return;let n=this._mode,i=!1;for(let s of e){let d=this.store.index.nodeIdToIndex.get(s);if(d===void 0)continue;let l=r[d*3],u=r[d*3+1],c=r[d*3+2],h=this._mapNodeState.get(s)?.appliedElevation??0,p,f,m;if(n==="planar")p=l,f=u,m=c-h;else{let v=this._defaultCoordProvider.applyElevation({x:l,y:u,z:c},-h,n);p=v.x,f=v.y,m=v.z}let g=this._mapNodeState.get(s)?.elevation??0,y=this._defaultCoordProvider.applyElevation({x:p,y:f,z:m},g,n);if(r[d*3]=y.x,r[d*3+1]=y.y,r[d*3+2]=y.z,i=!0,g===0){let v=this._mapNodeState.get(s);v&&(delete v.appliedElevation,this._pruneNodeState(s))}else this._nodeState(s).appliedElevation=g}if(!i)return;let o=new Map;for(let s of e){let d=this.store.index.nodeIdToIndex.get(s);d!==void 0&&o.set(s,[r[d*3],r[d*3+1],r[d*3+2]])}this.store.setPositions(o)}_buildAdjacency(){let e=new Map;for(let t of this.store.data.edges){let r=t.source,n=t.target;e.has(r)||e.set(r,[]),e.has(n)||e.set(n,[]),e.get(r).push(n),e.get(n).push(r)}return e}async positionNodesByGeo(e,t){if(!this._enabled||!this._mode)return;let r=t?this.store.data.nodes.filter(i=>t.includes(i.id)):this.store.data.nodes,n=new Map;for(let i of r){let o=Number(i.properties[e.latProperty]),s=Number(i.properties[e.lngProperty]);if(!isFinite(o)||!isFinite(s))continue;let d=this.latLngToWorld(o,s);n.set(i.id,[d.x,d.y,d.z])}n.size!==0&&this.executor.execute(new di(this.store,n))}getNodeGeoPosition(e){let t=this.store.index.nodeIdToIndex.get(e);if(t===void 0)return null;let r=this.store.positionProvider?.getPositions();if(!r)return null;let n=r[t*3],i=r[t*3+1],o=r[t*3+2];return this.worldToLatLng(n,i,o)}registerGeocoder(e){this._geocoders.set(e.key,e),this.events.emit("geocoder:registered",{key:e.key})}unregisterGeocoder(e){let t=this._geocoders.delete(e);return t&&this._activeGeocoder===e&&console.warn(`[MapApi] unregisterGeocoder: removed the active geocoder "${e}". Call setGeocoder() before search().`),t}listGeocoders(){return Array.from(this._geocoders.values())}setGeocoder(e){if(!this._geocoders.has(e))throw new Error(`Unknown geocoder: ${e}`);this._activeGeocoder=e,this.events.emit("geocoder:changed",{key:e})}getActiveGeocoder(){return this._activeGeocoder}async search(e,t){let r=this._activeGeocoder,n=r?this._geocoders.get(r):void 0;if(!n)throw new Error("No active geocoder. Call registerGeocoder + setGeocoder first.");return n.search(e,t)}async flyToBounds(e,t){let r=t?.mode??this._mode??"planar",n=t?.duration??600,i=t?.padding??0,o={lat:(e.south+e.north)/2,lng:(e.west+e.east)/2},s=1,d=1e-6,l=Math.max(e.north-e.south,d),u=Math.max(e.east-e.west,d),c=i*(360/this._mapSize),h=l+2*c,p=u+2*c,f=Math.log2(360/p),m=Math.log2(360/h),g=22,y=0,v=Math.min(f,m)-s,b=Math.max(y,Math.min(g,v));if(r==="spherical"){let w=this._cameraZ-this._globeRadius-.001,T=this._computeZoomLevel(w);Number.isFinite(T)&&(b=Math.min(b,T));let R=this._globeRadius/Math.sin(.8*St.HALF_VERT_FOV_RAD),S=this._computeZoomLevel(this._cameraZ-R);Number.isFinite(S)&&(b=Math.max(b,Number.isFinite(T)?Math.min(S,T):S))}return this.flyTo(o,{duration:n,mode:r,zoomLevel:b})}};St.VIEWPORT_H=800,St.HALF_VERT_FOV_RAD=21*Math.PI/180,St.TARGET_TILE_PX=256;var td=St,Gf=["lat","latitude"],Hf=["lng","lon","long","longitude"];function Oh(a){return typeof a=="string"?[a]:a}function bc(a,e){let t=(e==="auto"?Gf:Oh(e.lat)).map(n=>n.toLowerCase()),r=(e==="auto"?Hf:Oh(e.lng)).map(n=>n.toLowerCase());for(let n of a){let i=n.properties??{},o=Object.keys(i);if(o.length===0)continue;let s=o.map(h=>h.toLowerCase()),d;for(let h of t){let p=s.indexOf(h);if(p>=0){d=o[p];break}}if(d===void 0)continue;let l;for(let h of r){let p=s.indexOf(h);if(p>=0){l=o[p];break}}if(l===void 0)continue;let u=Number(i[d]),c=Number(i[l]);if(Number.isFinite(u)&&Number.isFinite(c))return{lat:d,lng:l}}return null}var rd=class{constructor(){this.callbacks={}}setSchemaCallbacks(e){this.callbacks={...this.callbacks,...e}}hasCallback(e){return typeof this.callbacks[e]=="function"}};var nd=class{constructor(e,t={}){this.store=e;this.opts=t}propertyKeys(e="nodes"){let t=new Set;for(let r of this._iterate(e))if(r.properties)for(let n of Object.keys(r.properties))t.add(n);return[...t].sort()}values(e,t={}){let r=t.limit??this.opts.defaultValueLimit??50,n=new Set;for(let i of this._iterate(t.scope??"nodes")){let o=i.properties?.[e];if(o!=null&&(n.add(o),n.size>=r))break}return[...n]}cardinality(e,t="nodes"){let r=new Set;for(let n of this._iterate(t)){let i=n.properties?.[e];i!=null&&r.add(i)}return r.size}*_iterate(e){let t=e==="nodes"?this.store.data.nodes:this.store.data.edges;for(let r of t)yield r}};var id=class{constructor(e,t){this.store=e;this.hoverHandler=t}wireHoverHandler(e){this.hoverHandler=e}set(e){if(!e){this.store.setHoveredNode(null);return}e.kind==="node"&&this.store.setHoveredNode(e.id)}get(){let e=this.hoverHandler?.hoveredNodeId??null;return e?{kind:"node",id:e}:null}};var od=class{constructor(){this.hostRef=null;this.mounted=new Map;this.pending=[]}mount(e,t,r,n){if(!this.hostRef){this.pending.push({name:e,factory:t,config:r,opts:n});return}this.mounted.has(e)&&this.unmount(e);let i=du(this.hostRef,e,t,r,n);this.mounted.set(e,i)}update(e,t){let r=this.pending.find(n=>n.name===e);if(r){r.config=t;return}this.mounted.get(e)?.update(t)}unmount(e){this.pending=this.pending.filter(t=>t.name!==e),this.mounted.get(e)?.dispose(),this.mounted.delete(e)}has(e){return this.mounted.has(e)||this.pending.some(t=>t.name===e)}list(){return[...this.mounted.keys(),...this.pending.map(e=>e.name)]}_wireHost(e){if(e===this.hostRef)return;for(let r of this.mounted.values())r.dispose();if(this.mounted.clear(),this.hostRef=e,!e)return;let t=this.pending;this.pending=[];for(let r of t)this.mount(r.name,r.factory,r.config,r.opts)}};var sd=class{constructor(){this.items=new Map;this.subs=new Set}set(e){for(let t of e)this.items.set(t.id,t);this.emit()}update(e,t){let r=this.items.get(e);r&&(this.items.set(e,{...r,...t}),this.emit())}remove(e){this.items.delete(e)&&this.emit()}clear(){this.items.size&&(this.items.clear(),this.emit())}getAll(){return[...this.items.values()]}onChange(e){return this.subs.add(e),()=>this.subs.delete(e)}emit(){for(let e of this.subs)e()}};var Ff=new Set(["id","nodeId","position","template","placement","offset","connector","maxWidth","interactive","draggable","variant","hideNode","scale","className","style","html","render","element"]),ad=class{constructor(){this.manager=new sd}set(e,t){let r=Array.isArray(e)?e:[{...t,nodeId:e}];this.manager.set(r.map((n,i)=>this.toItem(n,i)))}update(e,t){this.manager.update(e,t)}has(e){return this.manager.getAll().some(t=>t.id===e)}clear(e){e!==void 0?this.manager.remove(e):this.manager.clear()}toItem(e,t){if(!e.nodeId&&!e.position)throw new Error("[cards] spec needs nodeId or position");return{id:e.id??(e.nodeId?`card:${e.nodeId}`:`card:pos:${t}`),nodeId:e.nodeId,position:e.position,content:this.resolveContent(e),placement:e.placement??"auto",offset:e.offset??[12,0],connector:e.connector??!1,maxWidth:e.maxWidth??280,interactive:e.interactive??!0,draggable:e.draggable??!1,variant:e.variant??"card",hideNode:e.hideNode??!1,scale:e.scale??0,className:e.className,style:e.style}}resolveContent(e){if("template"in e&&e.template){let t={};for(let[r,n]of Object.entries(e))Ff.has(r)||(t[r]=n);return{kind:"preset",preset:e.template,data:t}}if("html"in e&&typeof e.html=="string")return{kind:"html",html:e.html};if("render"in e&&typeof e.render=="function")return{kind:"render",fn:e.render};if("element"in e&&e.element)return{kind:"element",el:e.element};throw new Error("[cards] spec needs one of: template, html, render, element")}};var dd=class{constructor(e){this.filters=new Map;this.playbacks=new Map;this.dateCache=new Map;this.resultCallbacks=new Set;this.lastResult=null;this.presets=new Map;this.batchDepth=0;this.batchDirty=!1;this._pendingReplay=!1;this._transitionMs=0;this._fadeStartTs=null;this._nodeOpacityFrom=null;this._nodeOpacityTo=null;this._nodeHiddenTarget=null;this._edgeOpacityFrom=null;this._edgeOpacityTo=null;this._fadeRafId=0;this.store=e}setTransition(e){this._transitionMs=Math.max(0,e.durationMs)}getTransitionMs(){return this._transitionMs}addFilter(e,t){let r=t;if(t.type==="range"&&t.domain===null){let n=this.inferDomain(t);r={...t,domain:n,range:[...n]}}t.type==="categorical"&&!t.allValues&&(r={...t,allValues:this.inferAllValues(t)}),this.filters.set(e,r),this.requestEvaluate()}removeFilter(e){this.stopPlayback(e),this.filters.delete(e),this.requestEvaluate()}clearAll(){this.stopAllPlayback(),this.filters.clear(),this.store.setVisibleNodes(null),this.applyNodeRenderState(null),this.resetEdgeVisibility(),this.notifyResult(this.buildFullResult())}getFilter(e){return this.filters.get(e)}getFilterIds(){return Array.from(this.filters.keys())}getAllFilters(){return this.filters}get hasActiveFilters(){return this.filters.size>0}setRange(e,t){let r=this.filters.get(e);r?.type==="range"&&(r.range=t,this.requestEvaluate())}setValues(e,t){let r=this.filters.get(e);r?.type==="categorical"&&(r.values=t,this.requestEvaluate())}setRegex(e,t){let r=this.filters.get(e);r?.type==="categorical"&&(r.regex=t,this.requestEvaluate())}setInvert(e,t){let r=this.filters.get(e);r&&r.type!=="group"&&(r.invert=t,this.requestEvaluate())}beginBatch(){this.batchDepth++}endBatch(){this.batchDepth--,this.batchDepth<=0&&(this.batchDepth=0,this.batchDirty&&(this.batchDirty=!1,this.evaluate()))}requestEvaluate(){this.batchDepth>0?this.batchDirty=!0:this.evaluate()}replayPending(){this._pendingReplay&&(this._pendingReplay=!1,this.evaluate())}evaluate(){let e=[],t=[];for(let o of this.filters.values()){let s=this.getEntryTarget(o);s==="node"?e.push(o):s==="edge"&&t.push(o)}let r=null;if(e.length>0){let o=this.store.data.nodes;r=[];for(let s of o)e.every(d=>this.matchEntry(d,s,s.id))&&r.push(s.id)}this.store.setVisibleNodes(r),this.applyNodeRenderState(r);let n=this.applyEdgeVisibility(t,r),i={visibleNodeIds:r??this.store.data.nodes.map(o=>o.id),visibleEdgeIds:n,totalNodes:this.store.nodeCount,totalEdges:this.store.data.edges.length};this.lastResult=i,this.notifyResult(i)}applyNodeRenderState(e){let t=this.store.nodeState;if(!t){this._pendingReplay=!0;return}let r=this.store.data.nodes,n=r.length,i=e?new Set(e):null,o=new Float32Array(n),s=new Uint8Array(n);for(let l=0;l<n;l++){let u=i===null||i.has(r[l].id);o[l]=u?1:0,s[l]=u?0:1}if(this._transitionMs<=0){for(let l=0;l<n;l++)t.hidden[l]=s[l],t.opacities[l]=o[l];this.store.updateStrategy.markDirty("nodeHidden"),this.store.updateStrategy.markDirty("nodeOpacities"),this.store.notifyChange();return}let d=new Float32Array(n);for(let l=0;l<n;l++)d[l]=t.opacities[l],t.hidden[l]=0;this._nodeOpacityFrom=d,this._nodeOpacityTo=o,this._nodeHiddenTarget=s,this._fadeStartTs=typeof performance<"u"?performance.now():Date.now(),this.store.updateStrategy.markDirty("nodeHidden"),this.store.updateStrategy.markDirty("nodeOpacities"),this.store.notifyChange(),this._scheduleFadeTick()}_scheduleFadeTick(){if(this._fadeRafId!==0)return;let e=typeof requestAnimationFrame<"u"?requestAnimationFrame:t=>setTimeout(()=>t(Date.now()),16);this._fadeRafId=e(()=>this._fadeTick())}_cancelFadeTick(){if(this._fadeRafId===0)return;(typeof cancelAnimationFrame<"u"?cancelAnimationFrame:t=>clearTimeout(t))(this._fadeRafId),this._fadeRafId=0}_fadeTick(){this._fadeRafId=0;let e=this.store.nodeState,t=this.store.edgeState;if(this._fadeStartTs===null||!e&&!t){this._endFade();return}let n=(typeof performance<"u"?performance.now():Date.now())-this._fadeStartTs,i=Math.min(1,n/this._transitionMs),o=1-Math.pow(1-i,3);if(e&&this._nodeOpacityFrom&&this._nodeOpacityTo){let s=this._nodeOpacityFrom,d=this._nodeOpacityTo,l=Math.min(s.length,d.length,e.opacities.length);for(let u=0;u<l;u++)e.opacities[u]=s[u]+(d[u]-s[u])*o;this.store.updateStrategy.markDirty("nodeOpacities")}if(t&&this._edgeOpacityFrom&&this._edgeOpacityTo){let s=this._edgeOpacityFrom,d=this._edgeOpacityTo,l=Math.min(s.length,d.length,t.opacities.length);for(let u=0;u<l;u++)t.opacities[u]=s[u]+(d[u]-s[u])*o;this.store.updateStrategy.markDirty("edgeOpacities")}if(this.store.notifyChange(),i>=1){if(e&&this._nodeHiddenTarget){for(let s=0;s<e.hidden.length;s++)e.hidden[s]=this._nodeHiddenTarget[s]??0;this.store.updateStrategy.markDirty("nodeHidden"),this.store.notifyChange()}this._endFade()}else this._scheduleFadeTick()}_endFade(){this._fadeStartTs=null,this._nodeOpacityFrom=null,this._nodeOpacityTo=null,this._nodeHiddenTarget=null,this._edgeOpacityFrom=null,this._edgeOpacityTo=null,this._cancelFadeTick()}matchEntry(e,t,r){return e.type==="group"?this.matchGroup(e,t,r):this.matchFilter(e,t,r)}matchGroup(e,t,r){return e.children.length===0?!0:e.operator==="and"?e.children.every(n=>this.matchEntry(n,t,r)):e.children.some(n=>this.matchEntry(n,t,r))}matchFilter(e,t,r){if(e.categories?.length){let i="category"in t?t.category:t.relationship;if(!e.categories.includes(i))return!0}let n;switch(e.type){case"range":n=this.matchRange(e,t,r);break;case"categorical":n=this.matchCategorical(e,t);break;case"predicate":n=e.predicate(t);break;case"topology":n=this.matchTopology(e,r);break}return e.invert?!n:n}matchRange(e,t,r){let n=null;if(e.valueType==="date")n=this.getOrBuildDateCache(e.property,e.target).get(r)??null;else{let i=this.resolvePropertyValue(e.property,t);n=typeof i=="number"?i:null}return n===null?e.includeNull!==!1:n>=e.range[0]&&n<=e.range[1]}matchCategorical(e,t){let r=this.resolvePropertyValue(e.property,t);if(r==null)return e.includeNull!==!1;let n=String(r);return e.regex?e.regex.test(n):e.values.has(n)}resolvePropertyValue(e,t){switch(e){case"_category":return"category"in t?t.category:null;case"_relationship":return"relationship"in t?t.relationship:null;case"_id":return t.id;default:return t.properties[e]??null}}matchTopology(e,t){let r=this.store.queries,n;switch(e.metric){case"degree":n=r.getDegree(t);break;case"inDegree":n=r.getInDegree(t);break;case"outDegree":n=r.getOutDegree(t);break}return n>=e.range[0]&&n<=e.range[1]}getEntryTarget(e){return e.target}applyEdgeVisibility(e,t){let r=this.store.edgeState,n=this.store.data.edges,i=[];if(!r)return i;let o=t?new Set(t):null,s=n.length,d=new Float32Array(s);for(let u=0;u<s;u++){let c=n[u],h=o===null||o.has(c.source)&&o.has(c.target),p=e.length===0||e.every(m=>this.matchEntry(m,c,c.id)),f=h&&p;d[u]=f?1:0,f&&i.push(c.id)}if(this._transitionMs<=0){for(let u=0;u<s;u++)r.opacities[u]=d[u];return this.store.updateStrategy.markDirty("edgeOpacities"),this.store.notifyChange(),i}let l=new Float32Array(s);for(let u=0;u<s;u++)l[u]=r.opacities[u];return this._edgeOpacityFrom=l,this._edgeOpacityTo=d,this.store.updateStrategy.markDirty("edgeOpacities"),this.store.notifyChange(),this._fadeStartTs===null&&(this._fadeStartTs=typeof performance<"u"?performance.now():Date.now()),this._scheduleFadeTick(),i}resetEdgeVisibility(){let e=this.store.edgeState;if(!e)return;let t=this.store.data.edges.length,r=new Float32Array(t);for(let i=0;i<t;i++)r[i]=1;if(this._transitionMs<=0){for(let i=0;i<t;i++)e.opacities[i]=1;this.store.updateStrategy.markDirty("edgeOpacities"),this.store.notifyChange();return}let n=new Float32Array(t);for(let i=0;i<t;i++)n[i]=e.opacities[i];this._edgeOpacityFrom=n,this._edgeOpacityTo=r,this._fadeStartTs===null&&(this._fadeStartTs=typeof performance<"u"?performance.now():Date.now()),this.store.updateStrategy.markDirty("edgeOpacities"),this.store.notifyChange(),this._scheduleFadeTick()}getMatchCount(e){let t=this.store.data.nodes,r=this.store.data.edges,n=0,i=0;if(e){let o=this.filters.get(e);if(!o)return{matchedNodes:t.length,totalNodes:t.length,matchedEdges:r.length,totalEdges:r.length};if(this.getEntryTarget(o)==="node"){for(let d of t)this.matchEntry(o,d,d.id)&&n++;i=r.length}else{n=t.length;for(let d of r)this.matchEntry(o,d,d.id)&&i++}}else{let o=[...this.filters.values()].filter(d=>this.getEntryTarget(d)==="node"),s=[...this.filters.values()].filter(d=>this.getEntryTarget(d)==="edge");for(let d of t)o.every(l=>this.matchEntry(l,d,d.id))&&n++;for(let d of r)s.every(l=>this.matchEntry(l,d,d.id))&&i++}return{matchedNodes:n,totalNodes:this.store.nodeCount,matchedEdges:i,totalEdges:r.length}}getOrBuildDateCache(e,t){let r=`${t}:${e}`,n=this.dateCache.get(r);if(n)return n;let i=t==="node"?this.store.data.nodes:this.store.data.edges,o=new Map;for(let s of i){let d=pi(s.properties[e]);d&&o.set(s.id,d.timestamp)}return this.dateCache.set(r,o),o}invalidateCache(){this.dateCache.clear()}inferDomain(e){let t=e.target==="node"?this.store.data.nodes:this.store.data.edges;if(e.valueType==="date"){let i=this.getOrBuildDateCache(e.property,e.target),o=1/0,s=-1/0;for(let d of i.values())d<o&&(o=d),d>s&&(s=d);return e.granularity&&o<=s&&(o=vr(o,e.granularity),s=gi(vr(s,e.granularity),e.granularity)),o<=s?[o,s]:[0,0]}let r=1/0,n=-1/0;for(let i of t){let o=i.properties[e.property];typeof o=="number"&&isFinite(o)&&(o<r&&(r=o),o>n&&(n=o))}return r<=n?[r,n]:[0,0]}inferAllValues(e){let t=e.target==="node"?this.store.data.nodes:this.store.data.edges,r=new Set;for(let n of t){let i=n.properties[e.property];i!=null&&r.add(String(i))}return Array.from(r).sort()}detectPropertyType(e,t){let r=t==="node"?this.store.data.nodes:this.store.data.edges,n=r.slice(0,Math.min(100,r.length)),i=0,o=0,s=0;for(let d of n){let l=d.properties[e];l!=null&&(s++,pi(l)!==null?i++:typeof l=="number"&&o++)}return s===0?"string":i/s>=.8?"date":o/s>=.8?"number":"string"}startPlayback(e){this.stopPlayback(e.filterId);let t=this.filters.get(e.filterId);if(t?.type!=="range"||!t.domain)return;let r=this.computePlaybackWindows(t,e);if(r.length===0)return;let n=e.reverse?-1:1,i=e.reverse?r.length-1:0,o=(e.duration??5e3)/r.length,s={config:e,windows:r,currentIndex:i,direction:n,intervalId:0,paused:!1};s.intervalId=window.setInterval(()=>{s.paused||(this.setRange(e.filterId,s.windows[s.currentIndex]),s.currentIndex+=s.direction,(s.currentIndex>=s.windows.length||s.currentIndex<0)&&(e.loop?s.currentIndex=s.direction>0?0:s.windows.length-1:this.stopPlayback(e.filterId)))},o),this.playbacks.set(e.filterId,s)}computePlaybackWindows(e,t){let[r,n]=e.domain,i=[],o=t.mode??"slide";if(e.valueType==="date"&&e.granularity){let s=e.granularity,d=t.step??1;if(o==="slide"){let l=vr(r,s);for(;l<n;){let u=Math.min(fi(l,s,t.windowSize),n);i.push([l,u]),l=fi(l,s,d)}}else if(o==="expand"){let l=vr(r,s),u=fi(l,s,1);for(;u<=n;)i.push([l,u]),u=fi(u,s,d);(i.length===0||i[i.length-1][1]<n)&&i.push([l,n])}else if(o==="shrink"){let l=vr(r,s);for(;l<n;)i.push([l,n]),l=fi(l,s,d)}}else{let s=t.windowSize,d=t.step??s;if(o==="slide"){let l=r;for(;l<n;)i.push([l,Math.min(l+s,n)]),l+=d}else if(o==="expand"){let l=r+s;for(;l<=n;)i.push([r,l]),l+=t.step??s;(i.length===0||i[i.length-1][1]<n)&&i.push([r,n])}else if(o==="shrink"){let l=r;for(;l<n;)i.push([l,n]),l+=t.step??s}}return i}pausePlayback(e){let t=this.playbacks.get(e);t&&(t.paused=!0)}resumePlayback(e){let t=this.playbacks.get(e);t&&(t.paused=!1)}stopPlayback(e){let t=this.playbacks.get(e);t&&(clearInterval(t.intervalId),this.playbacks.delete(e))}stopAllPlayback(){for(let[e]of this.playbacks)this.stopPlayback(e)}isPlaying(e){let t=this.playbacks.get(e);return t!==void 0&&!t.paused}getPlaybackProgress(e){let t=this.playbacks.get(e);return!t||t.windows.length<=1?0:Math.max(0,Math.min(1,t.currentIndex/(t.windows.length-1)))}onResult(e){return this.resultCallbacks.add(e),this.lastResult&&e(this.lastResult),()=>this.resultCallbacks.delete(e)}getLastResult(){return this.lastResult}notifyResult(e){for(let t of this.resultCallbacks)t(e)}buildFullResult(){return{visibleNodeIds:this.store.data.nodes.map(e=>e.id),visibleEdgeIds:this.store.data.edges.map(e=>e.id),totalNodes:this.store.nodeCount,totalEdges:this.store.data.edges.length}}savePreset(e){let t=[];for(let[n,i]of this.filters){let o=this.serializeEntry(i);o&&t.push({id:n,entry:o})}let r={name:e,createdAt:Date.now(),filters:t};return this.presets.set(e,r),r}loadPreset(e){this.beginBatch(),this.stopAllPlayback(),this.filters.clear();for(let{id:t,entry:r}of e.filters){let n=this.deserializeEntry(r);n&&this.filters.set(t,n)}this.endBatch()}deletePreset(e){this.presets.delete(e)}listPresets(){return Array.from(this.presets.values())}exportPresets(){return JSON.stringify(Array.from(this.presets.values()))}importPresets(e){let t;try{t=JSON.parse(e)}catch{return}if(Array.isArray(t))for(let r of t)r&&typeof r.name=="string"&&Array.isArray(r.filters)&&this.presets.set(r.name,r)}serializeEntry(e){switch(e.type){case"range":{let{label:t,...r}=e;return r}case"categorical":{let{label:t,values:r,regex:n,...i}=e;return{...i,valuesArray:Array.from(r)}}case"topology":{let{label:t,...r}=e;return r}case"predicate":return null;case"group":{let t=e.children.map(r=>this.serializeEntry(r)).filter(r=>r!==null);return{type:"group",target:e.target,operator:e.operator,children:t}}}}deserializeEntry(e){if(e.type==="range"||e.type==="topology")return e;if(e.type==="categorical"){let{valuesArray:t,...r}=e;return{...r,type:"categorical",values:new Set(t)}}if(e.type==="group"){let t=e,r=t.children.map(n=>this.deserializeEntry(n)).filter(n=>n!==null);return{type:"group",target:t.target,operator:t.operator,children:r}}return null}addAutoRangeFilter(e,t,r="node"){let n=this.detectPropertyType(t,r);if(n==="date"){let i=(r==="node"?this.store.data.nodes:this.store.data.edges).map(s=>s.properties[t]),o=zf(i);this.addFilter(e,{type:"range",target:r,property:t,valueType:"date",granularity:o?.granularity??"day",domain:null,range:[0,0]})}else n==="number"&&this.addFilter(e,{type:"range",target:r,property:t,valueType:"number",domain:null,range:[0,0]})}addDegreeFilter(e,t,r=1/0){this.addFilter(e,{type:"topology",target:"node",metric:"degree",range:[t,r]})}addOrGroup(e,t,r){this.addFilter(e,{type:"group",target:t,operator:"or",children:r})}onDataChanged(){this.invalidateCache(),this.hasActiveFilters&&this.evaluate()}dispose(){this.stopAllPlayback(),this._endFade(),this.filters.clear(),this.dateCache.clear(),this.resultCallbacks.clear(),this.presets.clear(),this.lastResult=null}};function zf(a){return Ma(a)}var ld=class{constructor(){this.effects=new Map;this._time=0;this._lastTick=0;this._onInvalidate=null}setInvalidateCallback(e){this._onInvalidate=e}addEffect(e){this.removeEffect(e.id),this.effects.set(e.id,e),this._onInvalidate?.()}removeEffect(e){let t=this.effects.get(e);t&&(t.dispose(),this.effects.delete(e),this._onInvalidate?.())}get(e){return this.effects.get(e)??null}get hasActiveEffects(){return this.effects.size>0}get time(){return this._time}tick(e){let t=this._lastTick>0?(e-this._lastTick)/1e3:0;this._lastTick=e,this._time+=t;for(let[r,n]of this.effects){if(!n.active){n.dispose(),this.effects.delete(r);continue}n.tick(this._time,t)}return this.effects.size>0?(this._onInvalidate?.(),!0):!1}findByType(e){for(let t of this.effects.values())if(t.type===e)return t;return null}stopAll(e){let t=!1;for(let[r,n]of this.effects)(!e||n.type===e)&&(n.dispose(),this.effects.delete(r),t=!0);t&&this._onInvalidate?.()}dispose(){this._onInvalidate=null,this.stopAll()}};var cd=class{constructor(){this.tweens=new Map;this._onInvalidate=null}setInvalidateCallback(e){this._onInvalidate=e}add(e,t){this.tweens.delete(e),this.tweens.set(e,t),this._onInvalidate?.()}remove(e){this.tweens.delete(e)}get hasActiveTweens(){return this.tweens.size>0}tick(e){if(this.tweens.size===0)return!1;for(let[t,r]of this.tweens)r.update(e),r.done&&this.tweens.delete(t);return this.tweens.size>0?(this._onInvalidate?.(),!0):!1}cancelAll(){this.tweens.clear()}dispose(){this.tweens.clear(),this._onInvalidate=null}};var ud=class{constructor(e,t={}){this.undoStack=[];this.redoStack=[];this.pendingGroup=null;this.commitTimer=null;this._transactionDepth=0;this._transactionLabel=null;this._microtaskScheduled=!1;this.eventBus=e,this.maxStackSize=t.maxStackSize??100,this.autoCommitDelay=t.autoCommitDelay??300}execute(e){this.pendingGroup||(this.pendingGroup=[]);let t=e.execute();return this.pendingGroup.push(e),this._transactionDepth===0&&this.resetCommitTimer(),t}beginTransaction(e){this._transactionDepth===0&&(this.pendingGroup&&this.pendingGroup.length>0&&this.commit(),this.cancelCommitTimer(),this._transactionLabel=e??null),this._transactionDepth++}endTransaction(){this._transactionDepth<=0||(this._transactionDepth--,this._transactionDepth===0&&(this.commitWithLabel(this._transactionLabel),this._transactionLabel=null))}get inTransaction(){return this._transactionDepth>0}undo(){this.pendingGroup&&this.commit();let e=this.undoStack.pop();if(e){for(let t=e.commands.length-1;t>=0;t--)e.commands[t].undo();this.redoStack.push(e),this.emitHistoryChanged()}}redo(){this.pendingGroup&&this.commit();let e=this.redoStack.pop();if(e){for(let t of e.commands)t.execute();this.undoStack.push(e),this.emitHistoryChanged()}}get canUndo(){return this.undoStack.length>0||this.pendingGroup!==null&&this.pendingGroup.length>0}get canRedo(){return this.redoStack.length>0}clear(){this.cancelCommitTimer(),this._transactionDepth=0,this._transactionLabel=null,this._microtaskScheduled=!1,this.pendingGroup=null,this.undoStack=[],this.redoStack=[],this.emitHistoryChanged()}getUndoStack(){let e=this.undoStack.map(t=>t.label);return this.pendingGroup&&this.pendingGroup.length>0&&e.push(this.generateLabel(this.pendingGroup)+" (pending)"),e}getRedoStack(){return this.redoStack.map(e=>e.label)}flush(){this.pendingGroup&&this.commit()}dispose(){this.cancelCommitTimer(),this._transactionDepth=0,this._microtaskScheduled=!1,this.pendingGroup=null}commit(){this.commitWithLabel(null)}commitWithLabel(e){if(this.cancelCommitTimer(),!this.pendingGroup||this.pendingGroup.length===0){this.pendingGroup=null;return}this.undoStack.push({commands:this.pendingGroup,label:e??this.generateLabel(this.pendingGroup),timestamp:Date.now()}),this.pendingGroup=null,this.redoStack=[],this.undoStack.length>this.maxStackSize&&this.undoStack.shift(),this.emitHistoryChanged()}resetCommitTimer(){this._microtaskScheduled||(this._microtaskScheduled=!0,Promise.resolve().then(()=>{this._microtaskScheduled=!1,this._transactionDepth===0&&this.pendingGroup&&this.commit()}))}cancelCommitTimer(){this.commitTimer!==null&&(clearTimeout(this.commitTimer),this.commitTimer=null),this._microtaskScheduled=!1}generateLabel(e){let t=new Map;for(let n of e)t.set(n.type,(t.get(n.type)||0)+1);let r=[];for(let[n,i]of t)r.push(i>1?`${n} x${i}`:n);return r.join(", ")}emitHistoryChanged(){let e=this.undoStack[this.undoStack.length-1];this.eventBus.emit("history:changed",{canUndo:this.canUndo,canRedo:this.canRedo,lastAction:e?.label??""})}};import{Vector3 as So}from"three";function Lh(a,e,t,r){let n=a.clone().normalize(),i=e.clone().normalize(),o=Math.max(-1,Math.min(1,n.dot(i))),s=Math.acos(o),d=Math.sin(s);if(d<1e-5)return n.lerp(i,t).normalize().multiplyScalar(r);let l=Math.sin((1-t)*s)/d,u=Math.sin(t*s)/d;return n.multiplyScalar(l).add(i.multiplyScalar(u)).multiplyScalar(r)}function Vh(a,e,t){return a*Math.sin(e*.5)*t}function Uh(a,e,t){let r=o=>{let d=a.getEdges().find(h=>h.id===o);if(!d)throw new Error(`[EdgeDebugApi] edge "${o}" not found`);let l=a.positionProvider?.getPositions();if(!l)throw new Error("[EdgeDebugApi] no positionProvider attached");let u=a.index.nodeIdToIndex.get(d.source),c=a.index.nodeIdToIndex.get(d.target);if(u===void 0||c===void 0)throw new Error(`[EdgeDebugApi] endpoint index missing for edge "${o}"`);return{a:new So(l[u*3],l[u*3+1],l[u*3+2]),b:new So(l[c*3],l[c*3+1],l[c*3+2])}},n=(o,s,d)=>{let{a:l,b:u}=r(o),c=e();if(c<=.001)return l.clone().lerp(u,s);let h=Lh(l,u,s,c);if(Math.abs(d)<1e-6)return h;let p=l.clone().normalize(),f=u.clone().normalize(),m=Math.max(-1,Math.min(1,p.dot(f))),g=Math.acos(m),v=Math.sin(g)<1e-5?new So(0,1,0):new So().crossVectors(p,f).normalize(),b=h.clone().normalize(),x=new So().crossVectors(b,v).normalize();return h.addScaledVector(x,Vh(d,g,c))},i=(o,s)=>s<=1?.5:o/(s-1);return{getEdgeArcSamples(o,s,d=0){let l=[];for(let u=0;u<s;u++){let c=n(o,i(u,s),d);l.push({x:c.x,y:c.y,z:c.z})}return l},getEdgePointAtT(o,s,d=0){let l=n(o,s,d);return{x:l.x,y:l.y,z:l.z}},getEdgeOpacityProfile(o,s,d=0){let l=t();if(!l)throw new Error("[EdgeDebugApi] camera not wired (call api.debug.wireScene first)");let u=[];for(let c=0;c<s;c++){let h=n(o,i(c,s),d),p=h.clone().normalize(),f=l.position.clone().sub(h).normalize();u.push(p.dot(f)<0?0:1)}return u}}}var hd=class{constructor(e){this._sphereRadius=0;this._camera=null;this.edge=Uh(e,()=>this._sphereRadius,()=>this._camera)}wireScene(e){this._camera=e}setSphereRadius(e){this._sphereRadius=e}getSphereRadius(){return this._sphereRadius}};var Bf=a=>a<.5?2*a*a:1-(-2*a+2)**2/2,Sc=class{constructor(e,t,r,n,i){this.store=e;this.from=t;this.to=r;this.ms=n;this.onDone=i;this.done=!1;this.t0=null}update(e){if(this.done)return!0;this.t0===null&&(this.t0=e);let t=this.ms>0?Math.min(1,(e-this.t0)/this.ms):1,r=Bf(t),n=new Map;for(let[i,o]of this.from){let s=this.to.get(i);s&&n.set(i,[o[0]+(s[0]-o[0])*r,o[1]+(s[1]-o[1])*r,o[2]+(s[2]-o[2])*r])}return this.store.setPositions(n),t>=1&&(this.done=!0,this.onDone()),this.done}finish(){this.done||(this.store.setPositions(this.to),this.done=!0,this.onDone())}},pd=class{constructor(e,t,r=450){this.store=e;this.animations=t;this.durationMs=r;this.seq=0;this.running=new Map}positionsOf(e){let t=new Map,r=this.store.positionProvider?.getPositions();if(!r)return t;for(let n of e){let i=this.store.index.getNodeIndex(n);i!==void 0&&t.set(n,[r[i*3],r[i*3+1],r[i*3+2]])}return t}async gather(e,t){let r=this.positionsOf(t),n=this.positionsOf([e]).get(e);if(!n||r.size===0)return r;let i=new Map;for(let o of r.keys())i.set(o,n);return await this.run(e,r,i),r}spread(e,t,r){let n=this.positionsOf([e]).get(e);if(!n||t.length===0)return Promise.resolve();let i=new Map,o=new Map,s=t.filter(c=>{let h=r.get(c);return!h||Math.hypot(h[0]-n[0],h[1]-n[1],h[2]-n[2])<.001}),d=this.store.index.getNodeIndex(e),u=((d!==void 0?this.store.nodeState?.sizes[d]:void 0)||1)*Math.max(2.5,.9*Math.sqrt(s.length));s.forEach((c,h)=>{let p=h/s.length*Math.PI*2;r.set(c,[n[0]+u*Math.cos(p),n[1]+u*Math.sin(p),n[2]])});for(let c of t){let h=r.get(c);h&&(o.set(c,n),i.set(c,h))}return this.store.setPositions(o),this.run(e,o,i)}run(e,t,r){return this.running.get(e)?.finish(),new Promise(n=>{let i=new Sc(this.store,t,r,this.durationMs,()=>{this.running.get(e)===i&&this.running.delete(e),n()});this.running.set(e,i),this.animations.add(`collect:${e}:${this.seq++}`,i),this.store.notifyChange()})}finishAll(){for(let e of[...this.running.values()])e.finish()}};var gd=class{constructor(e,t,r){this.capabilities={edgeBlend:"stub",iconMode:"implemented",fogDensity:"none",worldMap:"implemented",graph:"implemented",convertCloudPoint:"implemented",drawingCamera:"implemented",cloudScene:"implemented",dragSelection:"stub",drawingControls:"stub",mouseStream:"stub",drawingEnabled:"stub"};this._filterUnsubscribes=[];this._layoutController=null;this._lazy=new Map;this._interaction=null;this._collectDblClickUnsub=null;this._currentDimensions=r?.initialDimensions??3,this.store=e,this.events=new Ls,e.setEventBus(this.events),this.executor=new ud(this.events,{maxStackSize:r?.maxUndoStackSize,autoCommitDelay:r?.autoCommitDelay}),this.nodes=new Ws(e,this.executor,this.events),this.edges=new qs(e,this.executor,this.events),this.selection=new Ks(e,this.events),this.animationManager=new cd,this.camera=new Ys(t,r?.layoutRuntime,this.animationManager,e),this.layout=new ea(e,this.executor,this.events),this.style=new ua(e,this.executor,this.events),this.types=new ma(e,this.executor,this.events),this.history=new ya(this.executor),this.transform=new Ra(e,this.executor);let n=new dd(e);this._filterManager=n,this.filter=new vo(e,n),this.timeline=new Ia(e,this.filter),this.query=new Ja(e,n,this.executor),this._filterUnsubscribes=[this.events.on("graph:renderStateAllocated",()=>{n.replayPending()}),this.events.on("graph:dataReset",()=>{n.onDataChanged()})],this.groups=new ed(e,this.events),this.map=new td(e,this.executor,this.events),this.camera.setGlobeFit((i,o)=>this.map.fitNodesOnGlobe(i,{duration:o?.duration})),this.events.on("map:enabled",()=>this.camera.cancelFly()),this._interaction=t,this.ui=new Xa,this.effectManager=new ld,this.animations=new Fa(e,this.effectManager),this.emphasis=new La(e,this.effectManager,r?.hoverEmphasis??null,t),this.hover=new id(e,null),this.overlays=new ja(e,this.effectManager),this.layers=new od,this.cards=new ad,this.playback=new Ka(e,this.effectManager),this.renderer=new $a(this.events,t),this.flows=new rd,this.schema=new nd(e),t&&this.wireCollections(t),this.debug=new hd(e),this.defineLazyNamespaces(r);for(let i of["executor","effectManager","animationManager","_filterManager","_filterUnsubscribes","_currentDimensions","_layoutController","_interaction","_lazy"]){let o=Object.getOwnPropertyDescriptor(this,i);o&&Object.defineProperty(this,i,{...o,enumerable:!1})}}defineLazyNamespaces(e){for(let t of Fu)Object.defineProperty(this,t,{configurable:!0,enumerable:Ul(t)!==void 0,get:()=>{let r=this._lazy.get(t);if(r)return r;let n=Ul(t);if(!n)throw new Error(`api.${t} is not installed: ${Wl(t)}.`);let i=n({store:this.store,executor:this.executor,events:this.events,interaction:this._interaction,nodes:this.nodes,edges:this.edges,selection:this.selection,layers:this.layers,map:this.map,algorithmWorker:e?.algorithmWorker});return this._lazy.set(t,i),i}})}batch(e,t={}){this.events.suspend();let r=()=>this.events.resume({dedupe:t.dedupeEvents}),n;try{n=e()}catch(i){throw r(),i}return n instanceof Promise?n.then(i=>(r(),i),i=>{throw r(),i}):(r(),n)}wireInteraction(e){this.camera.wireInteraction(e),this.renderer.wireInteraction(e),this._interaction=e,this._lazy.get("io")?.wireInteraction(e),this.map.wireInteraction(e),this.selection.setSelectionManager(e?.selection??null),this.hover.wireHoverHandler(e?.hover??null),this.emphasis.wireInteraction(e),this.wireCollections(e)}wireCollections(e){this.nodes._wireCollectMotion(e?new pd(this.store,this.animationManager):null),this._collectDblClickUnsub?.(),this._collectDblClickUnsub=e?.onDblClick(t=>{if(!this.nodes.getExpandOnDoubleClick()||t.type!=="node"||!t.nodeId)return;let r=t.nodeId;if(this.nodes.isCollection(r)){this.nodes.explode(r);return}let n=this.store._nodeToGroup?.get(r),i=n?this.store._groups?.get(n):void 0;i&&i.collapsed&&i.anchorNodeId===r&&this.groups.expand(i.id)})??null}wireLayoutRuntime(e){this.camera.wireLayoutRuntime(e)}wireLayoutController(e){this._layoutController=e,this.map.wireLayoutController(e)}setDimensions(e){if(e===this._currentDimensions)return;this._currentDimensions=e;let t=this._layoutController;if(t&&typeof t.transitionDimensions=="function"&&t.transitionDimensions(e),this.renderer.setMode(e===2?"2D":"3D"),this.map.isEnabled()){let r=e===3?"spherical":"planar";this.map.getMode()!==r&&this.map.transition(r)}}getDimensions(){return this._currentDimensions}dispose(){this._collectDblClickUnsub?.(),this._collectDblClickUnsub=null,this.nodes._wireCollectMotion(null),this._lazy.get("algorithms")?.dispose(),this.effectManager.dispose(),this.animationManager.dispose(),this.ui.contextMenu.dispose(),this.executor.dispose();for(let e of this._filterUnsubscribes)e();this._filterUnsubscribes=[],this._filterManager.dispose(),this.events.emit("destroy",{}),this.events.removeAllListeners()}};import*as fd from"three";var Of={panSpeed:.001,rotateSpeed:.005,zoomSpeed:.002,zoomMin:-1e4,zoomMax:1e4,enablePan:!0,enableRotate:!0,enableZoom:!0,mapMode:!1,onPitchDelta:void 0},Wh=5e-4,Lf=200;function Vf(a,e=1){let t=a.deltaMode===1?a.deltaY*40:a.deltaMode===2?a.deltaY*800:a.deltaY;return Math.max(-1,Math.min(1,t/Lf*e))}var md=class md{constructor(e,t,r,n={}){this._preMapZoomSpeed=null;this._coordinatorEnabled=!0;this.isLeftDrag=!1;this.isRightDrag=!1;this.prevMouse={x:0,y:0};this._pivotProvider=null;this._rotationPivot=null;this._rotationResetAnim=null;this._zoomAnim=null;this._wheelIdleTimer=null;this._onWheelIdle=null;this._canvas=null;this.listeners={change:[]};this._stepZoomAnim=()=>{if(!this._zoomAnim)return;let e=this.camera,t=this.object.position,r=e.position.z,n=.18,i=Math.LN2*.25,o=this._zoomAnim.targetZ-t.z,s=Math.abs(r-t.z)||1e-4,d=Math.abs(r-this._zoomAnim.targetZ)||1e-4,l=Math.log(d/s);if(Math.abs(l)<.001){let m=s;t.z=this._zoomAnim.targetZ;let g=Math.abs(r-t.z)||1e-4;t.x+=this._zoomAnim.cursorMx*2*this._zoomAnim.tanH*(g-m),t.y+=this._zoomAnim.cursorMy*2*this._zoomAnim.tanV*(g-m),this._zoomAnim=null,this.notifyChange();return}let u=n,c=s+(d-s)*n,h=Math.log(c/s);if(Math.abs(h)>i){let m=s*Math.exp(Math.sign(h)*i),g=d-s;u=g!==0?(m-s)/g:n,u=Math.max(0,Math.min(1,u))}let p=s;t.z+=o*u;let f=Math.abs(r-t.z)||1e-4;t.x+=this._zoomAnim.cursorMx*2*this._zoomAnim.tanH*(f-p),t.y+=this._zoomAnim.cursorMy*2*this._zoomAnim.tanV*(f-p),this.notifyChange(),this._zoomAnim.rafId=requestAnimationFrame(this._stepZoomAnim)};this.camera=e,this.object=t,this.domElement=r,this.config={...Of,...n},this.boundMouseDown=this.onMouseDown.bind(this),this.boundMouseMove=this.onMouseMove.bind(this),this.boundMouseUp=this.onMouseUp.bind(this),this.boundWheel=this.onWheel.bind(this),this.boundContextMenu=this.onContextMenu.bind(this),this.connect()}setCanvas(e){this._canvas=e}isCanvasEvent(e){return this._canvas===null||e.target===this._canvas}connect(){this.domElement.addEventListener("mousedown",this.boundMouseDown),this.domElement.addEventListener("mousemove",this.boundMouseMove),this.domElement.addEventListener("mouseup",this.boundMouseUp),this.domElement.addEventListener("mouseleave",this.boundMouseUp),this.domElement.addEventListener("wheel",this.boundWheel,{passive:!1}),this.domElement.addEventListener("contextmenu",this.boundContextMenu)}disconnect(){this.domElement.removeEventListener("mousedown",this.boundMouseDown),this.domElement.removeEventListener("mousemove",this.boundMouseMove),this.domElement.removeEventListener("mouseup",this.boundMouseUp),this.domElement.removeEventListener("mouseleave",this.boundMouseUp),this.domElement.removeEventListener("wheel",this.boundWheel),this.domElement.removeEventListener("contextmenu",this.boundContextMenu)}dispose(){this.cancelRotationReset(),this.cancelZoomAnim(),this.disconnect(),this.listeners.change=[]}onChange(e){this.listeners.change.push(e)}offChange(e){this.listeners.change=this.listeners.change.filter(t=>t!==e)}getCamera(){return this.camera}notifyChange(){this.listeners.change.forEach(e=>e())}onMouseDown(e){if(this.isCanvasEvent(e)&&this._coordinatorEnabled){if(e.button===0&&this.config.enablePan)this.cancelZoomAnim(),this.isLeftDrag=!0,this.prevMouse={x:e.clientX,y:e.clientY};else if(e.button===2&&this.config.enableRotate){this.isRightDrag=!0,this.prevMouse={x:e.clientX,y:e.clientY};let t=this._pivotProvider?.();this._rotationPivot=t?new fd.Vector3(t.x,t.y,t.z):null}}}onMouseMove(e){if(this._coordinatorEnabled){if(this.isLeftDrag){let t=Math.max(Math.abs(this.camera.position.z-this.object.position.z),1e-4),r=this.config.panSpeed*t,n=(e.clientX-this.prevMouse.x)*r,i=(e.clientY-this.prevMouse.y)*r;this.object.position.x+=n,this.object.position.y-=i,this.prevMouse={x:e.clientX,y:e.clientY},this.notifyChange()}else if(this.isRightDrag){if(!this.config.enableRotate){this.isRightDrag=!1;return}let t=e.clientX-this.prevMouse.x,r=e.clientY-this.prevMouse.y;if(this.prevMouse={x:e.clientX,y:e.clientY},this.config.mapMode){if(this.config.onPitchDelta){let n=r*.5;Math.abs(n)>.001&&this.config.onPitchDelta(n)}}else this.rotate(t*this.config.rotateSpeed,r*this.config.rotateSpeed),this.notifyChange()}}}onMouseUp(){this.isLeftDrag=!1,this.isRightDrag=!1,this._rotationPivot=null}onWheel(e){if(!this.isCanvasEvent(e)||!this.config.enableZoom)return;e.preventDefault();let t=this.camera,r=this.object.position;if(!this.config.mapMode){let b=r.z,x=Math.abs(t.position.z-b)+.5,w=e.deltaY*this.config.zoomSpeed*x;r.z=Math.max(this.config.zoomMin,Math.min(this.config.zoomMax,b-w));let T=t.position.z-b,I=t.position.z-r.z;this.applyZoomToCursorOffset(e,T,I,t,r),this.notifyChange();return}let n=this._zoomAnim?.targetZ??r.z,i=Math.max(Math.abs(t.position.z-n),1e-4),o=Vf(e,this.config.zoomSpeed/Wh),s=Math.max(1e-4,i*2**o),d=Math.max(Math.abs(t.position.z-r.z),1e-4);s=Math.max(d/4,Math.min(d*4,s));let l=t.position.z-s;l=Math.max(this.config.zoomMin,Math.min(this.config.zoomMax,l));let u=this.domElement.getBoundingClientRect(),c=(e.clientX-u.left)/u.width-.5,h=-((e.clientY-u.top)/u.height-.5),f=(t.fov??42)/2*(Math.PI/180),m=t.aspect>.1?t.aspect:u.width/u.height,g=Math.atan(Math.tan(f)*m),y=Math.tan(g),v=Math.tan(f);this._zoomAnim?(this._zoomAnim.targetZ=l,this._zoomAnim.cursorMx=c,this._zoomAnim.cursorMy=h,this._zoomAnim.tanH=y,this._zoomAnim.tanV=v):this._zoomAnim={targetZ:l,cursorMx:c,cursorMy:h,tanH:y,tanV:v,rafId:requestAnimationFrame(this._stepZoomAnim)},this._wheelIdleTimer!==null&&clearTimeout(this._wheelIdleTimer),this._wheelIdleTimer=setTimeout(()=>{if(this._wheelIdleTimer=null,!this._onWheelIdle||!this._zoomAnim)return;let b=this.camera.position.z,x=this._onWheelIdle(this._zoomAnim.targetZ,b);if(x===null||!Number.isFinite(x))return;let w=Math.max(this.config.zoomMin,Math.min(this.config.zoomMax,x));this._zoomAnim.targetZ=w},md.WHEEL_IDLE_MS)}cancelZoomAnim(){if(this._wheelIdleTimer!==null&&(clearTimeout(this._wheelIdleTimer),this._wheelIdleTimer=null),this._zoomAnim){cancelAnimationFrame(this._zoomAnim.rafId);let e=this.camera,t=this.object.position,r=e.position.z,n=Math.abs(r-t.z)||1e-4;t.z=this._zoomAnim.targetZ;let i=Math.abs(r-t.z)||1e-4;t.x+=this._zoomAnim.cursorMx*2*this._zoomAnim.tanH*(i-n),t.y+=this._zoomAnim.cursorMy*2*this._zoomAnim.tanV*(i-n),this._zoomAnim=null,this.notifyChange()}}setWheelIdleSnap(e){this._onWheelIdle=e}applyZoomToCursorOffset(e,t,r,n,i){let o=this.domElement.getBoundingClientRect(),s=(e.clientX-o.left)/o.width-.5,d=-((e.clientY-o.top)/o.height-.5),u=(n.fov??42)/2*(Math.PI/180),c=n.aspect>.1?n.aspect:o.width/o.height,h=Math.atan(Math.tan(u)*c);i.x+=s*2*Math.tan(h)*(r-t),i.y+=d*2*Math.tan(u)*(r-t)}onContextMenu(e){this.isCanvasEvent(e)&&e.preventDefault()}get enabled(){return this._coordinatorEnabled}set enabled(e){this._coordinatorEnabled=e,e||(this.isLeftDrag=!1,this.isRightDrag=!1)}reset(){this.object.position.set(0,0,-15),this.object.rotation.set(0,0,0),this.notifyChange()}getZoom(){return this.object.position.z}setZoom(e){this.object.position.z=Math.max(this.config.zoomMin,Math.min(this.config.zoomMax,e)),this.notifyChange()}getPosition(){return{x:this.object.position.x,y:this.object.position.y}}pan(e,t){this.object.position.x+=e,this.object.position.y+=t,this.notifyChange()}setPosition(e,t){this.object.position.x=e,this.object.position.y=t,this.notifyChange()}rotate(e,t){this.object.rotation.y+=e,this.object.rotation.x+=t,this.notifyChange()}setMapMode(e){e&&!this.config.mapMode?(this._preMapZoomSpeed=this.config.zoomSpeed,this.config.zoomSpeed=Wh):!e&&this.config.mapMode&&this._preMapZoomSpeed!==null&&(this.config.zoomSpeed=this._preMapZoomSpeed,this._preMapZoomSpeed=null),this.config.mapMode=e}setPivotProvider(e){this._pivotProvider=e}setEnableRotate(e){this.config.enableRotate=e,e||(this.isRightDrag=!1)}setEnablePan(e){this.config.enablePan=e,e||(this.isLeftDrag=!1)}setEnableZoom(e){this.config.enableZoom=e}computeFlyToTarget(e,t=0){let r=new fd.Vector3(e.x,e.y,e.z),n=this.object.localToWorld(r.clone()),o=this.object.position.clone().sub(n).add(new fd.Vector3(0,0,t));return{x:o.x,y:o.y,z:o.z}}moveSceneTo(e){this.object.position.set(e.x,e.y,e.z),this.notifyChange()}getFullPosition(){return{x:this.object.position.x,y:this.object.position.y,z:this.object.position.z}}setZoomSpeed(e){this.config.zoomSpeed=e}getZoomSpeed(){return this.config.zoomSpeed}setZoomRange(e,t){this.config.zoomMin=e,this.config.zoomMax=t,this.object.position.z=Math.max(this.config.zoomMin,Math.min(this.config.zoomMax,this.object.position.z))}getZoomRange(){return{min:this.config.zoomMin,max:this.config.zoomMax}}getRotation(){return{x:this.object.rotation.x,y:this.object.rotation.y,z:this.object.rotation.z}}resetRotation(e=!0,t=400){this.cancelRotationReset();let{x:r,y:n,z:i}=this.object.rotation;if(Math.abs(r)<1e-6&&Math.abs(n)<1e-6&&Math.abs(i)<1e-6)return;if(!e||t<=0){this.object.rotation.set(0,0,0),this.notifyChange();return}this._rotationResetAnim={startX:r,startY:n,startZ:i,startTime:performance.now(),duration:t,rafId:null};let o=()=>{let s=this._rotationResetAnim;if(!s)return;let d=performance.now()-s.startTime,l=Math.min(d/s.duration,1),u=1-Math.pow(1-l,3);this.object.rotation.x=s.startX*(1-u),this.object.rotation.y=s.startY*(1-u),this.object.rotation.z=s.startZ*(1-u),this.notifyChange(),l>=1?(this.object.rotation.set(0,0,0),this.notifyChange(),this._rotationResetAnim=null):s.rafId=requestAnimationFrame(o)};this._rotationResetAnim.rafId=requestAnimationFrame(o)}cancelRotationReset(){this._rotationResetAnim?.rafId!=null&&cancelAnimationFrame(this._rotationResetAnim.rafId),this._rotationResetAnim=null}};md.WHEEL_IDLE_MS=180;var vi=md;var yd=class{constructor(e){this.listeners=new Set;this._disposed=!1;this.store=e,this.state={nodeIds:new Set,edgeIds:new Set,anchorNodeId:null}}get selectedNodeIds(){return Array.from(this.state.nodeIds)}get selectedEdgeIds(){return Array.from(this.state.edgeIds)}get hasSelection(){return this.state.nodeIds.size>0||this.state.edgeIds.size>0}get nodeCount(){return this.state.nodeIds.size}get edgeCount(){return this.state.edgeIds.size}get anchorNodeId(){return this.state.anchorNodeId}isNodeSelected(e){return this.state.nodeIds.has(e)}isEdgeSelected(e){return this.state.edgeIds.has(e)}selectNodes(e,t="replace"){let r=[],n=[];switch(t){case"replace":n.push(...this.state.nodeIds),this.state.nodeIds.clear();for(let i of e)this.isValidNodeId(i)&&(this.state.nodeIds.add(i),r.push(i));this.state.anchorNodeId=e[0]||null;break;case"add":for(let i of e)this.isValidNodeId(i)&&!this.state.nodeIds.has(i)&&(this.state.nodeIds.add(i),r.push(i));break;case"remove":for(let i of e)this.state.nodeIds.has(i)&&(this.state.nodeIds.delete(i),n.push(i));this.state.anchorNodeId&&n.includes(this.state.anchorNodeId)&&(this.state.anchorNodeId=this.state.nodeIds.size>0?this.state.nodeIds.values().next().value:null);break;case"toggle":for(let i of e)this.isValidNodeId(i)&&(this.state.nodeIds.has(i)?(this.state.nodeIds.delete(i),n.push(i)):(this.state.nodeIds.add(i),r.push(i)));break}this.syncSelectionToStore(),(r.length>0||n.length>0)&&this.emit({mode:t,addedNodeIds:r,removedNodeIds:n,addedEdgeIds:[],removedEdgeIds:[],selection:this.getSelectionSnapshot()})}selectGroup(e,t="replace"){let r=this.store.getGroupMembers(e);this.selectNodes(r,t)}selectEdges(e,t="replace"){let r=[],n=[];switch(t){case"replace":n.push(...this.state.edgeIds),this.state.edgeIds.clear();for(let i of e)this.isValidEdgeId(i)&&(this.state.edgeIds.add(i),r.push(i));break;case"add":for(let i of e)this.isValidEdgeId(i)&&!this.state.edgeIds.has(i)&&(this.state.edgeIds.add(i),r.push(i));break;case"remove":for(let i of e)this.state.edgeIds.has(i)&&(this.state.edgeIds.delete(i),n.push(i));break;case"toggle":for(let i of e)this.isValidEdgeId(i)&&(this.state.edgeIds.has(i)?(this.state.edgeIds.delete(i),n.push(i)):(this.state.edgeIds.add(i),r.push(i)));break}this.syncEdgeSelectionToStore(),(r.length>0||n.length>0)&&this.emit({mode:t,addedNodeIds:[],removedNodeIds:[],addedEdgeIds:r,removedEdgeIds:n,selection:this.getSelectionSnapshot()})}clearSelection(e){let t=Array.from(this.state.nodeIds),r=Array.from(this.state.edgeIds);t.length===0&&r.length===0||(this.state.nodeIds.clear(),this.state.edgeIds.clear(),this.state.anchorNodeId=null,e?.syncStore!==!1&&this.store.clearSelection(),this.emit({mode:"replace",addedNodeIds:[],removedNodeIds:t,addedEdgeIds:[],removedEdgeIds:r,selection:this.getSelectionSnapshot()}))}selectAllNodes(){let e=this.store.data.nodes.map(t=>t.id);this.selectNodes(e,"replace")}invertNodeSelection(){let e=new Set(this.store.data.nodes.map(r=>r.id)),t=[];for(let r of e)this.state.nodeIds.has(r)||t.push(r);this.selectNodes(t,"replace")}selectOrphanNodes(){let e=new Set;for(let r of this.store.data.edges)e.add(r.source),e.add(r.target);let t=this.store.data.nodes.filter(r=>!e.has(r.id)).map(r=>r.id);this.selectNodes(t,"replace")}selectNodesWhere(e){let t=this.store.data.nodes.filter((r,n)=>e(this.store.index.getNodeId(n)||"",n)).map(r=>r.id);this.selectNodes(t,"replace")}expandSelectionToNeighbors(e=1){let t=new Set(this.state.nodeIds);for(let r=0;r<e;r++){let n=new Set;for(let i of this.store.data.edges)t.has(i.source)&&n.add(i.target),t.has(i.target)&&n.add(i.source);for(let i of n)t.add(i)}this.selectNodes(Array.from(t),"replace")}selectConnectedEdges(){let e=[];for(let t of this.store.data.edges)(this.state.nodeIds.has(t.source)||this.state.nodeIds.has(t.target))&&e.push(t.id);this.selectEdges(e,"replace")}handleNodeClick(e,t){let r="replace";t.ctrlKey||t.metaKey?r="add":t.altKey?r="remove":t.shiftKey&&(r="toggle"),this.selectNodes([e],r)}handleEdgeClick(e,t){let r="replace";t.ctrlKey||t.metaKey?r="add":t.altKey?r="remove":t.shiftKey&&(r="toggle"),this.selectEdges([e],r)}handleBackgroundClick(){this.clearSelection()}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}isValidNodeId(e){return this.store.index.getNodeIndex(e)!==void 0}isValidEdgeId(e){return this.store.index.getEdgeIndex(e)!==void 0}syncSelectionToStore(){this.store.selectNodes(Array.from(this.state.nodeIds))}syncEdgeSelectionToStore(){this.store.selectEdges(Array.from(this.state.edgeIds))}getSelectionSnapshot(){return{nodeIds:new Set(this.state.nodeIds),edgeIds:new Set(this.state.edgeIds),anchorNodeId:this.state.anchorNodeId}}emit(e){for(let t of this.listeners)try{t(e)}catch(r){console.error("SelectionManager listener error:",r)}}syncFromStore(){let e=this.store.getSelectedNodeIds();this.state.nodeIds=new Set(e),this.state.anchorNodeId=e[0]||null}dispose(){this._disposed||(this._disposed=!0,this.listeners.clear())}};import*as tr from"three";var Uf={dragThreshold:3,pinAfterDrag:!0,enabled:!0},vd=class{constructor(e,t,r,n,i={}){this.cloudScene=null;this._onPositionsWritten=null;this.state={active:!1,nodeIds:[],startWorldPosition:null,currentWorldPosition:null,delta:null,dragPlane:null};this.nodeStartPositions=new Map;this.dragOffset=new tr.Vector3;this.potentialDrag=null;this.raycaster=new tr.Raycaster;this.onDragStartListeners=new Set;this.onDragMoveListeners=new Set;this.onDragEndListeners=new Set;this.activeGroupId=null;this._disposed=!1;this.renderer=e,this.camera=t,this.store=r,this.selectionManager=n,this.config={...Uf,...i}}get isDragging(){return this.state.active}get draggedNodeIds(){return this.state.nodeIds}get enabled(){return this.config.enabled}set enabled(e){this.config.enabled=e,!e&&this.state.active&&this.cancelDrag()}onGroupDragStart(e,t,r){this.activeGroupId=e;let n=this.store.getGroupMembers(e);n.length!==0&&this.onMouseDown(n[0],t,r)}onMouseDown(e,t,r){!this.config.enabled||this.state.active||(this.potentialDrag={nodeId:e,screenX:t,screenY:r})}onMouseMove(e,t){if(!this.config.enabled)return!1;if(this.potentialDrag&&!this.state.active){let r=e-this.potentialDrag.screenX,n=t-this.potentialDrag.screenY;Math.sqrt(r*r+n*n)>=this.config.dragThreshold&&this.startDrag(this.potentialDrag.nodeId,this.potentialDrag.screenX,this.potentialDrag.screenY)}return this.state.active?(this.updateDrag(e,t),!0):!1}onMouseUp(){this.potentialDrag=null,this.state.active&&this.endDrag()}cancelDrag(){if(!this.state.active){this.potentialDrag=null;return}for(let[e,t]of this.nodeStartPositions)this.writeLocalPosition(e,t);this.markPositionsDirty(),this.resetState()}startDrag(e,t,r){this.cloudScene&&this.cloudScene.updateMatrixWorld(!0);let n;this.selectionManager.isNodeSelected(e)?n=this.selectionManager.selectedNodeIds:(n=[e],this.selectionManager.selectNodes([e],"replace"));let i=this.getNodeLocalPosition(e);if(!i){this.potentialDrag=null;return}let o=i.clone();this.cloudScene&&this.cloudScene.localToWorld(o);let s=new tr.Vector3;this.camera.getWorldDirection(s);let d=new tr.Plane;d.setFromNormalAndCoplanarPoint(s,o);let l=this.getPlaneIntersection(t,r,d);if(!l){this.potentialDrag=null;return}let u=l.clone();this.cloudScene&&this.cloudScene.worldToLocal(u),this.dragOffset.copy(u).sub(i),this.nodeStartPositions.clear();for(let c of n){let h=this.getNodeLocalPosition(c);h&&this.nodeStartPositions.set(c,h.clone())}this.state={active:!0,nodeIds:n,startWorldPosition:{x:l.x,y:l.y,z:l.z},currentWorldPosition:{x:l.x,y:l.y,z:l.z},delta:{x:0,y:0,z:0},dragPlane:d},this.potentialDrag=null,this.emitDragStart({nodeIds:n,startPosition:this.state.startWorldPosition,screenPosition:{x:t,y:r}})}updateDrag(e,t){if(!this.state.active||!this.state.dragPlane)return;let r=this.getPlaneIntersection(e,t,this.state.dragPlane);if(!r)return;let n=r.clone();this.cloudScene&&this.cloudScene.worldToLocal(n);let i=n.sub(this.dragOffset),o=this.state.nodeIds[0],s=this.nodeStartPositions.get(o);if(!s)return;let d=i.clone().sub(s),l=[];for(let c of this.state.nodeIds){let h=this.nodeStartPositions.get(c);if(h){let p=h.clone().add(d);this.writeLocalPosition(c,p);let f=this.store.index.getNodeIndex(c);f!==void 0&&l.push(f)}}this._onPositionsWritten&&l.length>0?this._onPositionsWritten(l):this.markPositionsDirty();let u={x:d.x,y:d.y,z:d.z};if(this.state.currentWorldPosition={x:r.x,y:r.y,z:r.z},this.state.delta=u,this.store.hasGroupData()){if(this.activeGroupId)this.store.getGroupManager().recomputeGroupGeometry(this.activeGroupId);else for(let c of this.state.nodeIds){let h=this.store.getGroupForNode(c);h&&this.store.getGroupManager().recomputeGroupGeometry(h.id)}this.store.updateStrategy.markDirty("groups"),this.store.notifyChange()}this.emitDragMove({nodeIds:this.state.nodeIds,currentPosition:this.state.currentWorldPosition,delta:u,screenPosition:{x:e,y:t}})}endDrag(){if(!this.state.active)return;let e=this.state.delta||{x:0,y:0,z:0},t=this.state.currentWorldPosition||{x:0,y:0,z:0};this.config.pinAfterDrag&&this.store.pinNodes(this.state.nodeIds),this.emitDragEnd({nodeIds:this.state.nodeIds,finalPosition:t,totalDelta:e}),this.activeGroupId=null,this.resetState()}resetState(){this.state={active:!1,nodeIds:[],startWorldPosition:null,currentWorldPosition:null,delta:null,dragPlane:null},this.nodeStartPositions.clear(),this.dragOffset.set(0,0,0)}getNodeLocalPosition(e){let t=this.store.index.getNodeIndex(e);if(t===void 0)return null;let r=this.store.positionProvider;if(!r)return null;let n=r.getPositions();return n?new tr.Vector3(n[t*3],n[t*3+1],n[t*3+2]):null}writeLocalPosition(e,t){let r=this.store.index.getNodeIndex(e);if(r===void 0)return;let n=this.store.positionProvider;if(n){if("updatePosition"in n&&typeof n.updatePosition=="function"){n.updatePosition(r,t.x,t.y,t.z);return}"writePositions"in n&&typeof n.writePositions=="function"&&n.writePositions(new Map([[e,[t.x,t.y,t.z]]]))}}markPositionsDirty(){let e=this.store.positionProvider;e&&"markNeedsUpdate"in e&&typeof e.markNeedsUpdate=="function"&&e.markNeedsUpdate()}getPlaneIntersection(e,t,r){let n=this.screenToNDC(e,t);this.raycaster.setFromCamera(new tr.Vector2(n.x,n.y),this.camera);let i=new tr.Vector3;return this.raycaster.ray.intersectPlane(r,i)?i:null}screenToNDC(e,t){let r=this.renderer.domElement;return{x:e/r.clientWidth*2-1,y:-(t/r.clientHeight)*2+1}}getRendererElement(){return this.renderer.domElement}getCamera(){return this.camera}getCloudScene(){return this.cloudScene}onDragStart(e){return this.onDragStartListeners.add(e),()=>this.onDragStartListeners.delete(e)}onDragMove(e){return this.onDragMoveListeners.add(e),()=>this.onDragMoveListeners.delete(e)}onDragEnd(e){return this.onDragEndListeners.add(e),()=>this.onDragEndListeners.delete(e)}emitDragStart(e){for(let t of this.onDragStartListeners)try{t(e)}catch(r){console.error("DragHandler.onDragStart listener error:",r)}}emitDragMove(e){for(let t of this.onDragMoveListeners)try{t(e)}catch(r){console.error("DragHandler.onDragMove listener error:",r)}}emitDragEnd(e){for(let t of this.onDragEndListeners)try{t(e)}catch(r){console.error("DragHandler.onDragEnd listener error:",r)}}setCamera(e){this.camera=e}setCloudScene(e){this.cloudScene=e}setOnPositionsWritten(e){this._onPositionsWritten=e}dispose(){this._disposed||(this._disposed=!0,this.cancelDrag(),this.onDragStartListeners.clear(),this.onDragMoveListeners.clear(),this.onDragEndListeners.clear())}};var bi=class{constructor(e){this.groups=e}setGroups(e){this.groups=e}testPoint(e,t,r){if(!this.groups)return null;let n=null,i=1/0;for(let[o,s]of this.groups){if(s.collapsed)continue;let d=e-s.center.x,l=t-s.center.y,u=r-s.center.z;Math.sqrt(d*d+l*l+u*u)<=s.radius&&s.radius<i&&(n=o,i=s.radius)}return n}};var Wf=40,jf=4,qf={throttleMs:Wf,delayMs:0,leaveDelayMs:180,enabled:!0};function Si(){return typeof performance<"u"?performance.now():Date.now()}var bd=class{constructor(e,t,r={}){this.groupHitTest=new bi(null);this.state={nodeId:null,edgeId:null,screenPosition:null};this.lastPickTime=-1/0;this.lastPickCostMs=0;this.throttleTimer=null;this.delayTimer=null;this.leaveTimer=null;this.pendingPosition=null;this.listeners=new Set;this.hoverEmphasis=null;this._disposed=!1;this.store=e,this.picker=t;let{debounceMs:n,...i}=r;this.config={...qf,...i},n!==void 0&&r.throttleMs===void 0&&(this.config.throttleMs=n)}setHoverEmphasis(e){this.hoverEmphasis=e}get hoveredNodeId(){return this.state.nodeId}get hoveredEdgeId(){return this.state.edgeId}get isHovering(){return this.state.nodeId!==null||this.state.edgeId!==null}get enabled(){return this.config.enabled}set enabled(e){this.config.enabled=e,e||this.clearHover()}onMouseMove(e,t){if(!this.config.enabled||(this.pendingPosition={x:e,y:t},this.throttleTimer))return;let r=this.pickInterval(),n=Si()-this.lastPickTime;n>=r?(this.lastPickTime=Si(),this.runHoverCheck()):this.throttleTimer=setTimeout(()=>{this.throttleTimer=null,this.lastPickTime=Si(),this.runHoverCheck()},r-n)}pickInterval(){return Math.max(this.config.throttleMs,jf*this.lastPickCostMs)}runHoverCheck(){this.delayTimer&&(clearTimeout(this.delayTimer),this.delayTimer=null),this.pendingPosition&&(this.config.delayMs>0?this.delayTimer=setTimeout(()=>{this.delayTimer=null,this.checkHover()},this.config.delayMs):this.checkHover())}checkHoverImmediate(e,t){this.config.enabled&&(this.throttleTimer&&(clearTimeout(this.throttleTimer),this.throttleTimer=null),this.delayTimer&&(clearTimeout(this.delayTimer),this.delayTimer=null),this.pendingPosition={x:e,y:t},this.lastPickTime=Si(),this.checkHover())}onMouseLeave(){this.throttleTimer&&(clearTimeout(this.throttleTimer),this.throttleTimer=null),this.delayTimer&&(clearTimeout(this.delayTimer),this.delayTimer=null),this.pendingPosition=null,this.leaveTimer&&(clearTimeout(this.leaveTimer),this.leaveTimer=null),this.clearHover()}clearHover(){if(!this.state.nodeId&&!this.state.edgeId)return;let e=this.getCurrentType();this.store.setHoveredNode(null);let t={...this.state};this.state={nodeId:null,edgeId:null,screenPosition:null},this.emit({previous:e,current:{type:"background",id:null},screenPosition:t.screenPosition||{x:0,y:0}}),this.hoverEmphasis?.onHoverLeave()}checkHover(){if(!this.pendingPosition)return;let{x:e,y:t}=this.pendingPosition,r=Si();this.picker.pickAsync(e,t).then(n=>{if(this.lastPickCostMs=Si()-r,this._disposed)return;let i=this.pendingPosition;!i||i.x!==e||i.y!==t||this.applyPickResult(n,e,t)})}applyPickResult(e,t,r){let n=this.getCurrentType(),i=!1,o=null,s=null;if(e.type==="node"&&e.picked){this.leaveTimer&&(clearTimeout(this.leaveTimer),this.leaveTimer=null);let d=e.nodeId;if(this.state.nodeId!==d){let l=this.state.nodeId!==null||this.state.edgeId!==null;this.state.nodeId=d,this.state.edgeId=null,this.state.screenPosition={x:t,y:r},this.store.setHoveredNode(d);let u=this.store.index.getNodeIndex(d);u!=null&&(o=l?"move":"enter",s={kind:"node",id:d,index:u}),i=!0}}else if(e.type==="edge"&&e.picked){this.leaveTimer&&(clearTimeout(this.leaveTimer),this.leaveTimer=null);let d=e.edgeId;if(this.state.edgeId!==d){let l=this.state.nodeId!==null||this.state.edgeId!==null;this.state.nodeId=null,this.state.edgeId=d,this.state.screenPosition={x:t,y:r},this.store.setHoveredNode(null);let u=this.store.index.getEdgeIndex(d);u!=null&&(o=l?"move":"enter",s={kind:"edge",id:d,index:u}),i=!0}}else(this.state.nodeId||this.state.edgeId)&&!this.leaveTimer&&(this.leaveTimer=setTimeout(()=>{if(this.leaveTimer=null,this.state.nodeId||this.state.edgeId){let d=this.getCurrentType(),l=this.state.screenPosition||{x:t,y:r};this.state.nodeId=null,this.state.edgeId=null,this.state.screenPosition={x:t,y:r},this.store.setHoveredNode(null),this.emit({previous:d,current:this.getCurrentType(),screenPosition:l}),this.hoverEmphasis?.onHoverLeave()}},this.config.leaveDelayMs));i&&(vu(),this.emit({previous:n,current:this.getCurrentType(),screenPosition:{x:t,y:r}}),this.hoverEmphasis&&(o==="enter"&&s?this.hoverEmphasis.onHoverEnter(s):o==="move"&&s?this.hoverEmphasis.onHoverMove(s):o==="leave"&&this.hoverEmphasis.onHoverLeave()))}getCurrentType(){return this.state.nodeId?{type:"node",id:this.state.nodeId}:this.state.edgeId?{type:"edge",id:this.state.edgeId}:{type:"background",id:null}}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}emit(e){for(let t of this.listeners)try{t(e)}catch(r){console.error("HoverHandler listener error:",r)}}setThrottleMs(e){this.config.throttleMs=e}setDebounceMs(e){this.setThrottleMs(e)}setDelayMs(e){this.config.delayMs=e}dispose(){this._disposed||(this._disposed=!0,this.throttleTimer&&(clearTimeout(this.throttleTimer),this.throttleTimer=null),this.delayTimer&&(clearTimeout(this.delayTimer),this.delayTimer=null),this.leaveTimer&&(clearTimeout(this.leaveTimer),this.leaveTimer=null),this.listeners.clear())}};function Kf(){if(typeof navigator>"u")return"windows";let a=navigator.userAgent.toLowerCase();return a.includes("mac")?"mac":a.includes("linux")?"linux":"windows"}var xo={mod:"\u2318",shift:"\u21E7",alt:"\u2325",ctrl:"\u2303",enter:"\u21A9",backspace:"\u232B",delete:"\u2326",escape:"\u238B",arrowup:"\u2191",arrowdown:"\u2193",arrowleft:"\u2190",arrowright:"\u2192",tab:"\u21E5",space:"\u2423"},Sd=class{constructor(e){this.platform=e??Kf(),this.isMac=this.platform==="mac",this.isWindows=this.platform==="windows",this.isLinux=this.platform==="linux"}resolveModKey(){return this.isMac?"meta":"ctrl"}normalizeEvent(e){return{key:e.key.length===1?e.key.toLowerCase():e.key,mod:this.isMac?e.metaKey:e.ctrlKey,shift:e.shiftKey,alt:e.altKey,ctrl:this.isMac?e.ctrlKey:!1}}parseBinding(e){let t=e.split("+").map(n=>n.trim()),r={key:""};for(let n of t){let i=n.toLowerCase();switch(i){case"mod":r.mod=!0;break;case"shift":r.shift=!0;break;case"alt":case"opt":case"option":r.alt=!0;break;case"ctrl":case"control":r.ctrl=!0;break;default:r.key=i;break}}return r}formatForDisplay(e){return this.isMac?this.formatMac(e):this.formatWindows(e)}toCanonicalKey(e){let t=[];return e.mod&&t.push("mod"),e.shift&&t.push("shift"),e.alt&&t.push("alt"),e.ctrl&&t.push("ctrl"),t.push(e.key.toLowerCase()),t.join("+")}bindingsMatch(e,t){return e.key.toLowerCase()===t.key.toLowerCase()&&!!e.mod==!!t.mod&&!!e.shift==!!t.shift&&!!e.alt==!!t.alt&&!!e.ctrl==!!t.ctrl}formatMac(e){let t=[];return e.ctrl&&t.push(xo.ctrl),e.alt&&t.push(xo.alt),e.shift&&t.push(xo.shift),e.mod&&t.push(xo.mod),t.push(this.formatKeyMac(e.key)),t.join("")}formatWindows(e){let t=[];return e.ctrl&&t.push("Ctrl"),e.mod&&t.push("Ctrl"),e.alt&&t.push("Alt"),e.shift&&t.push("Shift"),t.push(this.formatKeyWindows(e.key)),t.join("+")}formatKeyMac(e){let t=xo[e.toLowerCase()];return t||(e.length===1?e.toUpperCase():e.charAt(0).toUpperCase()+e.slice(1))}formatKeyWindows(e){let t=e.toLowerCase();return t==="arrowup"?"\u2191":t==="arrowdown"?"\u2193":t==="arrowleft"?"\u2190":t==="arrowright"?"\u2192":e.length===1?e.toUpperCase():e.charAt(0).toUpperCase()+e.slice(1)}};var xd=class{constructor(e={}){this.commands=new Map;this.bindingIndex=new Map;this._enabled=!0;this.platform=e.platformAdapter??new Sd,this.target=e.target??document,this._debug=e.debug??!1,this.boundKeyDown=this.handleKeyDown.bind(this),this.target.addEventListener("keydown",this.boundKeyDown)}register(e,t){this.commands.has(e.id)&&(this.log(`Warning: overwriting existing command "${e.id}"`),this.unregister(e.id));let r={...e,handler:t,activeBinding:{...e.defaultBinding}};this.commands.set(e.id,r),this.indexBinding(e.id,r.activeBinding),this.log(`Registered: ${e.id} \u2192 ${this.platform.formatForDisplay(r.activeBinding)}`)}registerAll(e){for(let t of e)this.register(t)}unregister(e){let t=this.commands.get(e);if(!t)return;let r=this.platform.toCanonicalKey(t.activeBinding);this.bindingIndex.get(r)===e&&this.bindingIndex.delete(r),this.commands.delete(e)}setHandler(e,t){let r=this.commands.get(e);if(!r){this.log(`Warning: setHandler called for unknown command "${e}"`);return}r.handler=t}removeHandler(e){let t=this.commands.get(e);t&&(t.handler=void 0)}setBinding(e,t){let r=this.commands.get(e);if(!r)return null;let n=this.platform.toCanonicalKey(r.activeBinding);if(this.bindingIndex.get(n)===e&&this.bindingIndex.delete(n),t===null)return r.activeBinding={key:""},null;let i=this.checkConflict(t,e);return r.activeBinding={...t},this.indexBinding(e,t),i}resetBinding(e){let t=this.commands.get(e);t&&this.setBinding(e,t.defaultBinding)}resetAllBindings(){for(let[e]of this.commands)this.resetBinding(e)}getCommand(e){return this.commands.get(e)}getBinding(e){let t=this.commands.get(e);return!t||t.activeBinding.key===""?null:t.activeBinding}getCommandForBinding(e){let t=this.platform.toCanonicalKey(e),r=this.bindingIndex.get(t);return r?this.commands.get(r)??null:null}getAllCommands(){return Array.from(this.commands.values())}getCommandsByCategory(e){return this.getAllCommands().filter(t=>t.category===e)}getConflicts(){let e=new Map;for(let[r,n]of this.commands){if(n.activeBinding.key==="")continue;let i=this.platform.toCanonicalKey(n.activeBinding),o=e.get(i);o?o.push(r):e.set(i,[r])}let t=[];for(let[,r]of e)if(r.length>1){let n=this.commands.get(r[0]);t.push({binding:n.activeBinding,commandIds:r})}return t}get enabled(){return this._enabled}enable(){this._enabled=!0}disable(){this._enabled=!1}get platformAdapter(){return this.platform}dispose(){this.target.removeEventListener("keydown",this.boundKeyDown),this.commands.clear(),this.bindingIndex.clear()}handleKeyDown(e){if(!this._enabled||!(e instanceof KeyboardEvent)||this.isInputFocused(e)||this.isModifierKey(e.key))return;let t=this.platform.normalizeEvent(e),r=this.platform.toCanonicalKey(t),n=this.bindingIndex.get(r);if(!n)return;let i=this.commands.get(n);if(i&&!(i.when&&!this.evaluateWhen(i.when))){if(!i.handler){this.log(`Command "${n}" matched but has no handler`);return}e.preventDefault(),e.stopPropagation(),this.log(`Executing: ${n}`);try{i.handler()}catch(o){console.error(`KeyboardShortcutManager: error in handler for "${n}":`,o)}}}indexBinding(e,t){let r=this.platform.toCanonicalKey(t),n=this.bindingIndex.get(r);n&&n!==e&&this.log(`Warning: binding "${r}" conflicts \u2014 "${e}" overwrites "${n}"`),this.bindingIndex.set(r,e)}checkConflict(e,t){let r=this.platform.toCanonicalKey(e),n=this.bindingIndex.get(r);return n&&n!==t?{binding:e,commandIds:[n,t]}:null}isInputFocused(e){let t=e.target;if(!t)return!1;let r=t.tagName;if(r==="INPUT"||r==="TEXTAREA"||r==="SELECT"||t.isContentEditable)return!0;let n=t.getAttribute("role");return!!(n==="textbox"||n==="searchbox"||n==="combobox"||t.closest('[role="textbox"], [role="searchbox"], [role="combobox"]'))}isModifierKey(e){return e==="Control"||e==="Shift"||e==="Alt"||e==="Meta"}evaluateWhen(e){return!0}log(e){this._debug&&console.log(`[KeyboardShortcutManager] ${e}`)}};import*as Ft from"three";import*as rr from"three";var Ed=class{constructor(e){this._store=e;this._sourceNodeIds=[];this._ghostWorldPos=new rr.Vector3;this._active=!1;this._geometry=new rr.BufferGeometry,this._positions=new Float32Array(384),this._geometry.setAttribute("position",new rr.BufferAttribute(this._positions,3)),this._material=new rr.LineDashedMaterial({color:6413051,dashSize:.05,gapSize:.03,transparent:!0,opacity:.75,depthTest:!1}),this._line=new rr.LineSegments(this._geometry,this._material),this._line.frustumCulled=!1,this._line.visible=!1,this._line.renderOrder=999}get active(){return this._active}attach(e){e.add(this._line)}detach(){this._line.parent?.remove(this._line)}start(e){this._sourceNodeIds=[...e];let t=this._sourceNodeIds.length*6;t>this._positions.length&&(this._positions=new Float32Array(t),this._geometry.setAttribute("position",new rr.BufferAttribute(this._positions,3))),this._active=!0,this._line.visible=!0,this._writeBuffer()}setGhostWorldPos(e){this._ghostWorldPos.set(e.x,e.y,e.z),this._writeBuffer()}end(){this._active=!1,this._line.visible=!1,this._sourceNodeIds=[]}dispose(){this.end(),this.detach(),this._geometry.dispose(),this._material.dispose()}_writeBuffer(){if(!this._active)return;let e=this._store.positionProvider;if(!e)return;let t=e.getPositions();if(!t)return;let r=this._store.index,n=0;for(let s of this._sourceNodeIds){let d=r.getNodeIndex(s);d===void 0||t.length<(d+1)*3||(this._positions[n++]=t[d*3],this._positions[n++]=t[d*3+1],this._positions[n++]=t[d*3+2],this._positions[n++]=this._ghostWorldPos.x,this._positions[n++]=this._ghostWorldPos.y,this._positions[n++]=this._ghostWorldPos.z)}for(let s=n;s<this._positions.length;s++)this._positions[s]=0;let i=this._geometry.attributes.position;i.needsUpdate=!0;let o=this._sourceNodeIds.length;this._geometry.setDrawRange(0,o*2),this._line.computeLineDistances()}};var Rd=class{constructor(e,t,r,n,i,o={}){this.renderer=null;this.cloudScene=null;this._active=!1;this.sourceNodeId=null;this.sourceNodeIds=[];this.currentMouseScreen={x:0,y:0};this.snapTargetNodeId=null;this.dragPlane=null;this._onComplete=null;this._requestRender=null;this.store=e,this.selection=t,this.picker=r,this.camera=n,this.container=i,this._overlay=new Ed(e)}setCloudScene(e){this.cloudScene=e,e&&(this._overlay.detach(),this._overlay.attach(e))}setCamera(e){this.camera=e}setRenderer(e){this.renderer=e}set onComplete(e){this._onComplete=e}set requestRender(e){this._requestRender=e}setOnPositionsWritten(e){}get active(){return this._active}attachOverlay(e){this._overlay.detach(),this._overlay.attach(e)}start(e,t,r){this._active&&this.cancel(),this._active=!0,this.sourceNodeId=e,this.currentMouseScreen={x:t,y:r},this.snapTargetNodeId=null,this.selection.isNodeSelected(e)?this.sourceNodeIds=[...this.selection.selectedNodeIds]:this.sourceNodeIds=[e];let n=this.getNodePosition(e);if(n){let o=new Ft.Vector3(n.x,n.y,n.z);this.cloudScene&&this.cloudScene.localToWorld(o);let s=new Ft.Vector3;this.camera.getWorldDirection(s),this.dragPlane=new Ft.Plane,this.dragPlane.setFromNormalAndCoplanarPoint(s,o)}let i=this.screenToLocal(t,r);this._overlay.start(this.sourceNodeIds),this._overlay.setGhostWorldPos(i),this._requestRender?.()}move(e,t){if(!this._active)return;this.currentMouseScreen={x:e,y:t};let r=this.picker.pick(e,t);if(r.type==="node"&&r.picked){let n=r.nodeId;this.sourceNodeIds.includes(n)?this.snapTargetNodeId=null:this.snapTargetNodeId=n}else this.snapTargetNodeId=null;if(this.snapTargetNodeId){let n=this.getNodePosition(this.snapTargetNodeId);n&&this._overlay.setGhostWorldPos(n)}else{let n=this.screenToLocal(e,t);this._overlay.setGhostWorldPos(n)}this._requestRender?.()}end(){if(!this._active)return;this._active=!1;let{x:e,y:t}=this.currentMouseScreen,r=this.screenToLocal(e,t),n={sourceNodeIds:[...this.sourceNodeIds],targetNodeId:this.snapTargetNodeId,dropScreenPosition:{x:e,y:t},dropWorldPosition:{x:r.x,y:r.y,z:r.z}};this._overlay.end(),this._resetState(),this._requestRender?.(),this._onComplete?.(n)}cancel(){this._active=!1,this._overlay.end(),this._resetState(),this._requestRender?.()}dispose(){this.cancel(),this._overlay.dispose()}_resetState(){this.sourceNodeId=null,this.sourceNodeIds=[],this.snapTargetNodeId=null,this.dragPlane=null}getNodePosition(e){let t=this.store.index.getNodeIndex(e);if(t===void 0)return null;let r=this.store.positionProvider?.getPositions();return!r||r.length<(t+1)*3?null:{x:r[t*3],y:r[t*3+1],z:r[t*3+2]}}screenToLocal(e,t){let r=this.renderer?.domElement,n=r?r.clientWidth:this.container.clientWidth,i=r?r.clientHeight:this.container.clientHeight,o=e/n*2-1,s=-(t/i)*2+1,d=new Ft.Raycaster;d.setFromCamera(new Ft.Vector2(o,s),this.camera);let l=this.dragPlane||new Ft.Plane(new Ft.Vector3(0,0,1),0),u=new Ft.Vector3;return d.ray.intersectPlane(l,u)?(this.cloudScene&&this.cloudScene.worldToLocal(u),u):new Ft.Vector3}};var $f=[{id:"nav.panUp",category:"navigation",label:"shortcuts.nav.panUp",defaultBinding:{key:"ArrowUp"}},{id:"nav.panDown",category:"navigation",label:"shortcuts.nav.panDown",defaultBinding:{key:"ArrowDown"}},{id:"nav.panLeft",category:"navigation",label:"shortcuts.nav.panLeft",defaultBinding:{key:"ArrowLeft"}},{id:"nav.panRight",category:"navigation",label:"shortcuts.nav.panRight",defaultBinding:{key:"ArrowRight"}},{id:"nav.zoomIn",category:"navigation",label:"shortcuts.nav.zoomIn",defaultBinding:{key:"=",mod:!0}},{id:"nav.zoomOut",category:"navigation",label:"shortcuts.nav.zoomOut",defaultBinding:{key:"-",mod:!0}},{id:"nav.flyToSelected",category:"navigation",label:"shortcuts.nav.flyToSelected",defaultBinding:{key:"0",mod:!0}},{id:"nav.resetPosition",category:"navigation",label:"shortcuts.nav.resetPosition",defaultBinding:{key:"r",alt:!0,shift:!0}},{id:"nav.turntableY",category:"navigation",label:"shortcuts.nav.turntableY",defaultBinding:{key:"y",shift:!0}},{id:"nav.rotateLeft",category:"navigation",label:"shortcuts.nav.rotateLeft",defaultBinding:{key:"["}},{id:"nav.rotateRight",category:"navigation",label:"shortcuts.nav.rotateRight",defaultBinding:{key:"]"}},{id:"nav.resetRotation",category:"navigation",label:"shortcuts.nav.resetRotation",defaultBinding:{key:"o",shift:!0}}],Zf=[{id:"sel.selectAll",category:"selection",label:"shortcuts.sel.selectAll",defaultBinding:{key:"a",mod:!0}},{id:"sel.deselectAll",category:"selection",label:"shortcuts.sel.deselectAll",defaultBinding:{key:"Escape"}},{id:"sel.invertSelection",category:"selection",label:"shortcuts.sel.invertSelection",defaultBinding:{key:"i",shift:!0}},{id:"sel.selectOrphans",category:"selection",label:"shortcuts.sel.selectOrphans",defaultBinding:{key:"d",shift:!0}}],Yf=[{id:"edit.delete",category:"editing",label:"shortcuts.edit.delete",defaultBinding:{key:"Delete"}},{id:"edit.deleteAlt",category:"editing",label:"shortcuts.edit.delete",defaultBinding:{key:"Backspace"}},{id:"edit.pinToggle",category:"editing",label:"shortcuts.edit.pinToggle",defaultBinding:{key:"p",shift:!0}},{id:"edit.expand",category:"editing",label:"shortcuts.edit.expand",defaultBinding:{key:"x",shift:!0}}],Xf=[{id:"view.saveView",category:"view",label:"shortcuts.view.saveView",defaultBinding:{key:"s",mod:!0}},{id:"view.fullScreen",category:"view",label:"shortcuts.view.fullScreen",defaultBinding:{key:"f",shift:!0}},{id:"view.hideMenu",category:"view",label:"shortcuts.view.hideMenu",defaultBinding:{key:""}},{id:"view.nodeInfo",category:"view",label:"shortcuts.view.nodeInfo",defaultBinding:{key:"i",mod:!0}}],Qf=[{id:"data.undo",category:"data",label:"shortcuts.data.undo",defaultBinding:{key:"z",mod:!0}},{id:"data.redo",category:"data",label:"shortcuts.data.redo",defaultBinding:{key:"y",mod:!0}},{id:"data.redoAlt",category:"data",label:"shortcuts.data.redo",defaultBinding:{key:"z",mod:!0,shift:!0}},{id:"data.history",category:"data",label:"shortcuts.data.history",defaultBinding:{key:"h",mod:!0,shift:!0}},{id:"data.clearGraph",category:"data",label:"shortcuts.data.clearGraph",defaultBinding:{key:"c",alt:!0,shift:!0}}],Jf=[{id:"tools.leafTrimming",category:"tools",label:"shortcuts.tools.leafTrimming",defaultBinding:{key:"l",shift:!0}},{id:"tools.calcDegree",category:"tools",label:"shortcuts.tools.calcDegree",defaultBinding:{key:"g",shift:!0}},{id:"tools.enhanceTable",category:"tools",label:"shortcuts.tools.enhanceTable",defaultBinding:{key:"t",shift:!0}}],em=[{id:"group.toggleDragMode",category:"groups",label:"shortcuts.group.toggleDragMode",defaultBinding:{key:"g",alt:!0}},{id:"group.createFromSelection",category:"groups",label:"shortcuts.group.createFromSelection",defaultBinding:{key:"g",mod:!0}},{id:"group.dissolveSelected",category:"groups",label:"shortcuts.group.dissolveSelected",defaultBinding:{key:"g",mod:!0,shift:!0}},{id:"group.toggleCollapse",category:"groups",label:"shortcuts.group.toggleCollapse",defaultBinding:{key:"Enter"}}],jh=[...$f,...Zf,...Yf,...Xf,...Qf,...Jf,...em];import*as qt from"three";import*as Fr from"three";var tm={dragThreshold:3,globeMode:!1,debug:!1},Cd=class{constructor(e,t,r,n,i,o={}){this.pathSelectHandler=null;this.edgeCreateHandler=null;this.store=null;this.hoverEmphasis=null;this.groupHitTest=new bi(null);this.raycaster=new Fr.Raycaster;this.currentMode="idle";this.mouseDownPosition=null;this.pickedOnDown=null;this.modKeyOnDown=!1;this.pickedNodeIdOnDown=null;this.graphControlWasEnabled=!0;this.dragHandlerWasEnabled=!0;this._bgGestureExternal=!1;this.picker=e,this.dragHandler=t,this.graphControl=r,this.selectionManager=n,this.hoverHandler=i,this.config={...tm,...o}}setGlobeMode(e){this.config.globeMode=e,this.debug(`Globe mode: ${e}`)}get globeMode(){return this.config.globeMode}setBackgroundGestureExternal(e){this._bgGestureExternal=e}setPathSelectHandler(e){this.pathSelectHandler=e}setEdgeCreateHandler(e){this.edgeCreateHandler=e}setStore(e){this.store=e}setHoverEmphasis(e){this.hoverEmphasis=e}getMode(){return this.currentMode}handleMouseDown(e,t,r){if(this.hoverEmphasis?.onMouseDown(e.button),this.currentMode!=="idle"){this.debug(`Ignoring mousedown - already in mode: ${this.currentMode}`);return}this.mouseDownPosition={x:t,y:r};let n=this.picker.pick(t,r);if(this.pickedOnDown=n,this.debug(`MouseDown at (${t}, ${r}), picked: ${n.type}, button: ${e.button}`),e.button===0)if(this.modKeyOnDown=e.ctrlKey||e.metaKey,n.type==="node"&&n.picked){let i=n.nodeId;if(this.store?.hasGroupData()){let o=this.store.getGroupForNode(i),s=this.store.getGroupManager()?.getDragMode?.();if(o&&s==="group"){let d=this.store.getGroupMembers(o.id);this.selectionManager.selectNodes(d,"replace"),this.dragHandler.activeGroupId=o.id}}this.enterPotentialDragMode(n,t,r)}else if(e.shiftKey&&this.pathSelectHandler){let i=e.ctrlKey||e.metaKey?"add":e.altKey?"remove":"replace";this.enterPathSelectMode(t,r,i)}else{if(this.store?.hasGroupData()){this.groupHitTest.setGroups(this.store.groups);let i=this.testGroupHit(t,r);if(i){let o=this.store.getGroupMembers(i);this.selectionManager.selectNodes(o,"replace"),this.dragHandler.onGroupDragStart(i,t,r),this.currentMode="potential-drag",this.graphControlWasEnabled=this.graphControl.enabled,this.graphControl.enabled=!1,this.debug(`Group ring hit: ${i}, entering group drag`);return}}if(this._bgGestureExternal)return;this.enterPanMode()}else if(e.button===2)if(n.type==="node"&&n.picked)this.debug("Right click on node - context menu territory");else{if(this._bgGestureExternal)return;this.enterRotateMode()}}handleMouseMove(e,t,r){switch(this.currentMode){case"potential-drag":return this.handlePotentialDragMove(t,r);case"drag-node":return this.handleDragNodeMove(t,r);case"path-select":return this.pathSelectHandler?.move(t,r),!0;case"edge-create":return this.edgeCreateHandler?.move(t,r),!0;case"pan":case"rotate":return!1;case"idle":return this.isEventOverCanvas(e)?(this.hoverHandler.onMouseMove(t,r),!1):(this.hoverHandler.onMouseLeave(),!1);default:return!1}}handleMouseUp(e,t,r){switch(this.debug(`MouseUp, mode was: ${this.currentMode}`),this.hoverEmphasis?.onMouseUp(),this.currentMode){case"potential-drag":this.dragHandler.onMouseUp();break;case"drag-node":this.dragHandler.onMouseUp();break;case"path-select":this.pathSelectHandler?.end();break;case"edge-create":this.edgeCreateHandler?.end();break;case"pan":case"rotate":break}this.resetState()}handleMouseLeave(){this.debug(`MouseLeave, mode was: ${this.currentMode}`),this.currentMode==="drag-node"||this.currentMode==="potential-drag"?this.dragHandler.onMouseUp():this.currentMode==="path-select"&&this.pathSelectHandler?.cancel(),this.currentMode==="edge-create"&&this.edgeCreateHandler?.cancel(),this.hoverHandler.onMouseLeave(),this.resetState()}enterPotentialDragMode(e,t,r){this.currentMode="potential-drag",this.pickedNodeIdOnDown=e.nodeId,this.graphControlWasEnabled=this.graphControl.enabled,this.graphControl.enabled=!1,this.dragHandler.onMouseDown(e.nodeId,t,r),this.debug(`Entered potential-drag mode for node: ${e.nodeId}`)}enterPanMode(){if(this.config.globeMode){this.enterRotateMode();return}this.currentMode="pan",this.dragHandlerWasEnabled=this.dragHandler.enabled,this.dragHandler.enabled=!1,this.debug("Entered pan mode")}enterPathSelectMode(e,t,r){this.currentMode="path-select",this.graphControlWasEnabled=this.graphControl.enabled,this.dragHandlerWasEnabled=this.dragHandler.enabled,this.graphControl.enabled=!1,this.dragHandler.enabled=!1,this.pathSelectHandler.start(e,t,r),this.debug(`Entered path-select mode (${r})`)}enterRotateMode(){this.currentMode="rotate",this.dragHandlerWasEnabled=this.dragHandler.enabled,this.dragHandler.enabled=!1,this.debug("Entered rotate mode")}handlePotentialDragMove(e,t){if(!this.mouseDownPosition)return!1;let r=e-this.mouseDownPosition.x,n=t-this.mouseDownPosition.y,i=Math.sqrt(r*r+n*n);return i>=this.config.dragThreshold&&(this.modKeyOnDown&&this.edgeCreateHandler&&this.pickedNodeIdOnDown?(this.currentMode="edge-create",this.dragHandler.cancelDrag(),this.edgeCreateHandler.start(this.pickedNodeIdOnDown,e,t),this.debug(`Crossed threshold \u2192 edge-create mode for node: ${this.pickedNodeIdOnDown}`)):(this.currentMode="drag-node",this.debug(`Crossed drag threshold (${i.toFixed(1)}px) \u2192 drag-node mode`))),this.currentMode==="potential-drag"||this.currentMode==="drag-node"?this.dragHandler.onMouseMove(e,t):!0}handleDragNodeMove(e,t){return this.dragHandler.onMouseMove(e,t)}resetState(){this.currentMode==="potential-drag"||this.currentMode==="drag-node"?this.graphControl.enabled=this.graphControlWasEnabled:this.currentMode==="pan"||this.currentMode==="rotate"?this.dragHandler.enabled=this.dragHandlerWasEnabled:this.currentMode==="path-select"?(this.graphControl.enabled=this.graphControlWasEnabled,this.dragHandler.enabled=this.dragHandlerWasEnabled):this.currentMode==="edge-create"&&(this.graphControl.enabled=this.graphControlWasEnabled),this.modKeyOnDown=!1,this.pickedNodeIdOnDown=null,this.currentMode="idle",this.mouseDownPosition=null,this.pickedOnDown=null,this.debug("Reset to idle state")}isEventOverCanvas(e){let t=this.dragHandler.getRendererElement?.();return t?e.target===t:!0}debug(e){this.config.debug&&console.log(`[InteractionCoordinator] ${e}`)}forceReset(){(this.currentMode==="drag-node"||this.currentMode==="potential-drag")&&this.dragHandler.cancelDrag(),this.currentMode==="edge-create"&&this.edgeCreateHandler?.cancel(),this.resetState()}isActive(){return this.currentMode!=="idle"}testGroupHit(e,t){if(!this.store?._groups)return null;let r=this.dragHandler.getRendererElement?.();if(!r)return null;let n=e/r.clientWidth*2-1,i=-(t/r.clientHeight)*2+1,o=this.dragHandler.getCamera?.();if(!o)return null;this.raycaster.setFromCamera(new Fr.Vector2(n,i),o);let s=new Fr.Plane(new Fr.Vector3(0,0,1),0),d=new Fr.Vector3;if(!this.raycaster.ray.intersectPlane(s,d))return null;let u=this.dragHandler.getCloudScene?.();return u&&(u.updateMatrixWorld(!0),u.worldToLocal(d)),this.groupHitTest.setGroups(this.store.groups),this.groupHitTest.testPoint(d.x,d.y,d.z)}};import*as qh from"three";var xc={selectRadius:20,minSampleDistance:5,pathStyle:{color:"#61dafb",width:2,opacity:.8}},wd=class{constructor(e,t,r,n,i={}){this.canvas=null;this.ctx2d=null;this._active=!1;this.pathPoints=[];this.selectionMode="replace";this.cloudScene=null;this.store=e,this.selection=t,this.camera=r,this.container=n,this.config={selectRadius:i.selectRadius??xc.selectRadius,minSampleDistance:i.minSampleDistance??xc.minSampleDistance,pathStyle:{...xc.pathStyle,...i.pathStyle}}}setCloudScene(e){this.cloudScene=e}setCamera(e){this.camera=e}get active(){return this._active}start(e,t,r){this._active=!0,this.selectionMode=r,this.pathPoints=[{x:e,y:t}],this.createOverlay(),this.drawPath()}move(e,t){if(!this._active)return;let r=this.pathPoints[this.pathPoints.length-1],n=e-r.x,i=t-r.y;Math.sqrt(n*n+i*i)>=this.config.minSampleDistance&&(this.pathPoints.push({x:e,y:t}),this.drawPath())}end(){if(!this._active)return;this._active=!1;let e=this.findNodesInLasso();e.length>0?this.selection.selectNodes(e,this.selectionMode):this.selectionMode==="replace"&&this.selection.clearSelection(),this.pathPoints=[],this.removeOverlay()}cancel(){this._active=!1,this.pathPoints=[],this.removeOverlay()}dispose(){this.cancel()}findNodesInLasso(){let e=this.store.positionProvider;if(!e)return[];let t=e.getPositions();if(!t)return[];if(this.pathPoints.length<2)return[];let r=this.store.data.nodes,n=[],i=this.container.getBoundingClientRect(),o=i.width/2,s=i.height/2;this.camera.updateMatrixWorld(),this.cloudScene&&this.cloudScene.updateMatrixWorld();let d=this.pathPoints,l=this.config.selectRadius,u=l*l,c=new qh.Vector3;for(let h=0;h<r.length;h++){if(this.store.nodeState?.hidden[h]===1)continue;c.set(t[h*3],t[h*3+1],t[h*3+2]),this.cloudScene&&c.applyMatrix4(this.cloudScene.matrixWorld),c.project(this.camera);let p=(c.x+1)*o,f=(-c.y+1)*s;if(d.length>=3&&this.pointInPolygon(p,f,d)){n.push(r[h].id);continue}for(let m of d){let g=p-m.x,y=f-m.y;if(g*g+y*y<=u){n.push(r[h].id);break}}}return n}pointInPolygon(e,t,r){let n=!1,i=r.length;for(let o=0,s=i-1;o<i;s=o++){let d=r[o].x,l=r[o].y,u=r[s].x,c=r[s].y;l>t!=c>t&&e<(u-d)*(t-l)/(c-l)+d&&(n=!n)}return n}createOverlay(){if(this.canvas)return;let e=document.createElement("canvas"),t=this.container.getBoundingClientRect();e.width=t.width*(window.devicePixelRatio||1),e.height=t.height*(window.devicePixelRatio||1),e.style.cssText=`
262
+ position: absolute;
263
+ top: 0; left: 0;
264
+ width: ${t.width}px;
265
+ height: ${t.height}px;
266
+ pointer-events: none;
267
+ z-index: 10;
268
+ `,this.container.appendChild(e),this.canvas=e;let r=e.getContext("2d");r&&(r.scale(window.devicePixelRatio||1,window.devicePixelRatio||1),this.ctx2d=r)}removeOverlay(){this.canvas&&(this.canvas.remove(),this.canvas=null,this.ctx2d=null)}drawPath(){let e=this.ctx2d;if(!e||!this.canvas)return;let{width:t,opacity:r}=this.config.pathStyle,n=this.selectionMode==="remove"?"#ff4444":this.selectionMode==="add"?"#44ff88":this.config.pathStyle.color,i=window.devicePixelRatio||1;if(e.clearRect(0,0,this.canvas.width/i,this.canvas.height/i),this.pathPoints.length<2)return;let o=this.pathPoints[0],s=this.pathPoints[this.pathPoints.length-1];e.beginPath(),e.moveTo(o.x,o.y);for(let d=1;d<this.pathPoints.length;d++)e.lineTo(this.pathPoints[d].x,this.pathPoints[d].y);e.closePath(),e.fillStyle=n,e.globalAlpha=r*.1,e.fill(),e.beginPath(),e.moveTo(o.x,o.y);for(let d=1;d<this.pathPoints.length;d++)e.lineTo(this.pathPoints[d].x,this.pathPoints[d].y);e.strokeStyle=n,e.lineWidth=t,e.globalAlpha=r,e.lineCap="round",e.lineJoin="round",e.setLineDash([]),e.stroke(),e.beginPath(),e.moveTo(s.x,s.y),e.lineTo(o.x,o.y),e.strokeStyle=n,e.lineWidth=1,e.globalAlpha=r*.5,e.setLineDash([4,4]),e.stroke(),e.setLineDash([]),e.beginPath(),e.arc(o.x,o.y,4,0,Math.PI*2),e.fillStyle=n,e.globalAlpha=r,e.fill(),e.globalAlpha=1}};function Td(a,e){if(!e.hasFonts())return null;let t=a.nodeCount;if(t===0)return null;let r=new Float32Array(t*4).fill(-1),n=a.data.nodes;if(a.iconNames.size===0)return r;for(let i=0;i<n.length;i++){let o=a.getNodeIconName(n[i].id);if(!o)continue;let s=e.ensureIcon(o);s&&(r[i*4]=s.u0,r[i*4+1]=s.v0,r[i*4+2]=s.u1,r[i*4+3]=s.v1)}return r}function Kh(a,e){let{store:t,nodeRenderer:r,edgeRenderer:n,picker:i,iconAtlasManager:o}=a,s=t.applyDelta(e);if(o&&r){let l=Td(t,o);l&&r.updateIconUVs(l),r.setIconSdfAtlas(o.getTexture()),o.isDirty()&&r.setIconSdfAtlas(o.getTexture())}let d=null;if(r&&(r.update(),d=r.getLastConsumedDirtyFlags()),n&&n.update(d??void 0),i&&r){let l=r.getGeometry();l&&i.setupNodePicking(l)}if(i&&n){let l=n.getMesh();l&&i.setupEdgePicking(l.geometry,l.material)}return t.markTransactionResolved(),s}var xi=class xi{constructor(e,t,r,n,i={}){this.graphControl=null;this.coordinator=null;this.shortcuts=null;this.pathSelect=null;this.edgeCreate=null;this._autoRotateRafId=null;this._requestRender=null;this._suppressNextClick=!1;this._pressAt=null;this._lastClickWasDrag=!1;this._txCtx=null;this._modKeyHeld=!1;this.onEdgeCreateCallbacks=[];this.isMouseDown=!1;this.mouseDownPosition=null;this._disposed=!1;this._rightDownPosition=null;this._rightDragDistance=0;this._edgeCreatePending=!1;this._edgeCreateSourceNodeId=null;this.onClickCallbacks=[];this.onDblClickCallbacks=[];this.onContextMenuCallbacks=[];this.renderer=e,this.camera=t,this.store=r,this.container=n,this.picker=new Ps(e,t,r,i),this.selection=new yd(r),this.drag=new vd(e,t,r,this.selection,i.drag),this.hover=new bd(r,this.picker,i.hover),this.hover.onChange(()=>this.updateCursor()),i.cloudScene&&(this.graphControl=new vi(t,i.cloudScene,n,i.graphControl),this.coordinator=new Cd(this.picker,this.drag,this.graphControl,this.selection,this.hover,i.coordinator),this.coordinator.setStore(r)),this.pathSelect=new wd(r,this.selection,t,n,i.pathSelect),this.edgeCreate=new Rd(r,this.selection,this.picker,t,n,i.edgeCreate),this.edgeCreate.onComplete=o=>{this.emitEdgeCreate(o)},this.coordinator&&(this.pathSelect&&this.coordinator.setPathSelectHandler(this.pathSelect),this.coordinator.setEdgeCreateHandler(this.edgeCreate)),i.shortcuts!==!1&&(this.shortcuts=new xd(typeof i.shortcuts=="object"?i.shortcuts:{}),this.shortcuts.registerAll(jh),this.wireBuiltinShortcuts()),this.boundMouseDown=this.handleMouseDown.bind(this),this.boundMouseMove=this.handleMouseMove.bind(this),this.boundMouseUp=this.handleMouseUp.bind(this),this.boundMouseLeave=this.handleMouseLeave.bind(this),this.boundClick=this.handleClick.bind(this),this.boundDblClick=this.handleDblClick.bind(this),this.boundContextMenu=this.handleContextMenu.bind(this),this.boundKeyDown=this.handleKeyDown.bind(this),this.boundKeyUp=this.handleKeyUp.bind(this),this.attachListeners()}getRenderer(){return this.renderer}setupNodePicking(e){this.picker.setupNodePicking(e)}syncNodePickingDrawRange(e){this.picker.syncNodeDrawRange(e)}setupEdgePicking(e,t){this.picker.setupEdgePicking(e,t)}addSelfLoopPickingMesh(e){this.picker.addSelfLoopPickingMesh(e)}updatePositionTexture(e,t,r){this.picker.updatePositionTexture(e,t,r)}syncTransforms(e,t){this.picker.syncTransforms(e,t)}setCloudScene(e){this.drag.setCloudScene(e),this.picker.setCloudScene(e),this.pathSelect?.setCloudScene(e),this.edgeCreate?.setCloudScene(e)}setCamera(e){this.camera=e,this.picker.setCamera(e),this.drag.setCamera(e),this.edgeCreate?.setCamera(e)}pick(e,t){return this.picker.pick(e,t)}setGraphControl(e){this.graphControl=e,this.wireNavigationShortcuts(e)}setRequestRender(e){this._requestRender=e,this.edgeCreate&&(this.edgeCreate.requestRender=e)}requestRender(){this._requestRender?.()}setTransactionContext(e){this._txCtx={store:this.store,...e}}setGlobeMode(e){this.coordinator?.setGlobeMode(e)}get lastClickWasDrag(){return this._lastClickWasDrag}onClick(e){return this.onClickCallbacks.push(e),()=>{let t=this.onClickCallbacks.indexOf(e);t>=0&&this.onClickCallbacks.splice(t,1)}}onDblClick(e){return this.onDblClickCallbacks.push(e),()=>{let t=this.onDblClickCallbacks.indexOf(e);t>=0&&this.onDblClickCallbacks.splice(t,1)}}onContextMenu(e){return this.onContextMenuCallbacks.push(e),()=>{let t=this.onContextMenuCallbacks.indexOf(e);t>=0&&this.onContextMenuCallbacks.splice(t,1)}}onEdgeCreate(e){return this.onEdgeCreateCallbacks.push(e),()=>{let t=this.onEdgeCreateCallbacks.indexOf(e);t>=0&&this.onEdgeCreateCallbacks.splice(t,1)}}emitEdgeCreate(e){for(let t of this.onEdgeCreateCallbacks)try{t(e)}catch(r){console.error("InteractionManager.emitEdgeCreate callback error:",r)}}handleMouseDown(e){this._suppressNextClick=!1,e.button===0&&(this._pressAt={x:e.clientX,y:e.clientY});let{x:t,y:r}=this.getMousePosition(e);if(e.button===2&&(this._rightDownPosition={x:e.clientX,y:e.clientY},this._rightDragDistance=0),this.coordinator){this.coordinator.handleMouseDown(e,t,r),e.button===0&&(this.isMouseDown=!0,this.mouseDownPosition={x:t,y:r});return}if(e.button!==0)return;if(this.isMouseDown=!0,this.mouseDownPosition={x:t,y:r},e.shiftKey&&this.pathSelect&&!this.picker.pick(t,r).picked){let o=e.ctrlKey||e.metaKey?"add":e.altKey?"remove":"replace";this.graphControl&&(this.graphControl.enabled=!1),this.pathSelect.start(t,r,o);return}let n=this.picker.pick(t,r);if(n.type==="node"&&n.picked){let i=n.nodeId;if((e.ctrlKey||e.metaKey)&&this.edgeCreate){console.log("[InteractionManager] edge-create pending on node:",i),this._edgeCreatePending=!0,this._edgeCreateSourceNodeId=i,this.graphControl&&(this.graphControl.enabled=!1);return}if(this.store.hasGroupData()){let o=this.store.getGroupForNode(i),s=this.store.getGroupManager().getDragMode();if(o&&s==="group"){let d=this.store.getGroupMembers(o.id);this.selection.selectNodes(d,"replace"),this.drag.activeGroupId=o.id}}this.drag.onMouseDown(i,t,r)}else if(this.store.hasGroupData()){let i=this.testGroupHitFallback(t,r);if(i){let o=this.store.getGroupMembers(i);this.selection.selectNodes(o,"replace"),this.graphControl&&(this.graphControl.enabled=!1),this.drag.onGroupDragStart(i,t,r)}}}testGroupHitFallback(e,t){let r=this.store.groups;if(!r)return null;let n=this.renderer.domElement,i=e/n.clientWidth*2-1,o=-(t/n.clientHeight)*2+1,s=new qt.Raycaster;s.setFromCamera(new qt.Vector2(i,o),this.drag.getCamera());let d=this.drag.getCloudScene(),l;if(d){d.updateMatrixWorld(!0);let f=new qt.Vector3(0,0,0).applyMatrix4(d.matrixWorld),m=new qt.Vector3(0,0,1).transformDirection(d.matrixWorld);l=new qt.Plane().setFromNormalAndCoplanarPoint(m,f)}else l=new qt.Plane(new qt.Vector3(0,0,1),0);let u=new qt.Vector3;if(!s.ray.intersectPlane(l,u))return null;d&&d.worldToLocal(u);let h=null,p=1/0;for(let[f,m]of r){if(m.collapsed)continue;let g=u.x-m.center.x,y=u.y-m.center.y,v=u.z-m.center.z;Math.sqrt(g*g+y*y+v*v)<=m.radius&&m.radius<p&&(h=f,p=m.radius)}return h}handleMouseMove(e){let{x:t,y:r}=this.getMousePosition(e);if(this._rightDownPosition){let n=e.clientX-this._rightDownPosition.x,i=e.clientY-this._rightDownPosition.y;this._rightDragDistance=Math.sqrt(n*n+i*i)}if(this.coordinator){this.coordinator.handleMouseMove(e,t,r);return}if(this.edgeCreate?.active){this.edgeCreate.move(t,r);return}if(this._edgeCreatePending&&this.mouseDownPosition&&this.edgeCreate){let n=t-this.mouseDownPosition.x,i=r-this.mouseDownPosition.y;if(Math.sqrt(n*n+i*i)>=3){this.edgeCreate.start(this._edgeCreateSourceNodeId,t,r),this._edgeCreatePending=!1;return}return}if(this.pathSelect?.active){this.pathSelect.move(t,r);return}this.isMouseDown&&this.drag.onMouseMove(t,r)||this.drag.isDragging||(e.target===this.renderer.domElement?this.hover.onMouseMove(t,r):this.hover.onMouseLeave())}handleMouseUp(e){let{x:t,y:r}=this.getMousePosition(e);if(e.button===2){let n=this._rightDragDistance>xi.RIGHT_CLICK_THRESHOLD;this._rightDownPosition=null,this._rightDragDistance=0,n||this.fireContextMenu(t,r,e);return}if(this.coordinator){let n=this.coordinator.getMode();this.coordinator.handleMouseUp(e,t,r),e.button===0&&(this.isMouseDown=!1,this.mouseDownPosition=null),(n==="drag-node"||n==="path-select"||n==="edge-create")&&(this._suppressNextClick=!0),this.updateCursor(),this._requestRender?.();return}e.button===0&&(this.edgeCreate?.active?(this.edgeCreate.end(),this.graphControl&&(this.graphControl.enabled=!0),this._suppressNextClick=!0,this._requestRender?.()):this._edgeCreatePending?(this._edgeCreatePending=!1,this._edgeCreateSourceNodeId=null,this.graphControl&&(this.graphControl.enabled=!0)):this.pathSelect?.active?(this.pathSelect.end(),this.graphControl&&(this.graphControl.enabled=!0),this._suppressNextClick=!0,this._requestRender?.()):(this.drag.onMouseUp(),this.graphControl&&!this.graphControl.enabled&&(this.graphControl.enabled=!0)),this.isMouseDown=!1,this.mouseDownPosition=null)}handleMouseLeave(e){if(this._rightDownPosition=null,this._rightDragDistance=0,this.coordinator){this.coordinator.handleMouseLeave(),this.isMouseDown=!1,this.mouseDownPosition=null,this.updateCursor();return}this.hover.onMouseLeave(),this.edgeCreate?.active&&(this.edgeCreate.cancel(),this.graphControl&&(this.graphControl.enabled=!0)),this._edgeCreatePending&&(this._edgeCreatePending=!1,this._edgeCreateSourceNodeId=null,this.graphControl&&(this.graphControl.enabled=!0)),this.pathSelect?.active&&(this.pathSelect.cancel(),this.graphControl&&(this.graphControl.enabled=!0)),this.isMouseDown&&(this.drag.onMouseUp(),this.isMouseDown=!1,this.mouseDownPosition=null)}handleClick(e){if(e.target!==this.renderer.domElement)return;let t=this._pressAt;if(this._pressAt=null,this._lastClickWasDrag=!!t&&Math.hypot(e.clientX-t.x,e.clientY-t.y)>xi.CLICK_MOVE_TOLERANCE,this._suppressNextClick){this._suppressNextClick=!1;return}if(this.drag.isDragging)return;let{x:r,y:n}=this.getMousePosition(e),i=this.picker.pick(r,n),o={ctrlKey:e.ctrlKey,altKey:e.altKey,shiftKey:e.shiftKey,metaKey:e.metaKey};i.type==="node"&&i.picked?this.selection.handleNodeClick(i.nodeId,o):i.type==="edge"&&i.picked?this.selection.handleEdgeClick(i.edgeId,o):this.selection.handleBackgroundClick(),this._requestRender?.();for(let s of this.onClickCallbacks)try{s(i,e)}catch(d){console.error("InteractionManager.onClick callback error:",d)}}handleDblClick(e){if(e.target!==this.renderer.domElement)return;let{x:t,y:r}=this.getMousePosition(e),n=this.picker.pick(t,r);if(n.type==="node"&&n.nodeId){let i=this.store.index.getNodeIndex(n.nodeId);i!==void 0&&this.store.nodeState?.pinned[i]===1&&(this.store.unpinNodes([n.nodeId]),this._requestRender?.())}for(let i of this.onDblClickCallbacks)try{i(n,e)}catch(o){console.error("InteractionManager.onDblClick callback error:",o)}}handleContextMenu(e){e.preventDefault()}fireContextMenu(e,t,r){let n=this.picker.pick(e,t);for(let i of this.onContextMenuCallbacks)try{i(n,r)}catch(o){console.error("InteractionManager.onContextMenu callback error:",o)}}handleKeyDown(e){(e.key==="Control"||e.key==="Meta")&&(this._modKeyHeld=!0,this.updateCursor()),e.shiftKey&&(e.metaKey||e.ctrlKey)&&e.key==="P"&&(this.picker.debugPicking=!this.picker.debugPicking,console.log(`[Picker] debug picking: ${this.picker.debugPicking?"ON":"OFF"}`),this._requestRender?.())}handleKeyUp(e){(e.key==="Control"||e.key==="Meta")&&(this._modKeyHeld=!1,this.updateCursor())}updateCursor(){this.container.style.cursor=""}getMousePosition(e){let t=this.container.getBoundingClientRect();return{x:e.clientX-t.left,y:e.clientY-t.top}}attachListeners(){this.container.addEventListener("mousedown",this.boundMouseDown),this.container.addEventListener("mousemove",this.boundMouseMove),this.container.addEventListener("mouseup",this.boundMouseUp),this.container.addEventListener("mouseleave",this.boundMouseLeave),this.container.addEventListener("click",this.boundClick),this.container.addEventListener("dblclick",this.boundDblClick),this.container.addEventListener("contextmenu",this.boundContextMenu),document.addEventListener("keydown",this.boundKeyDown),document.addEventListener("keyup",this.boundKeyUp)}detachListeners(){this.container.removeEventListener("mousedown",this.boundMouseDown),this.container.removeEventListener("mousemove",this.boundMouseMove),this.container.removeEventListener("mouseup",this.boundMouseUp),this.container.removeEventListener("mouseleave",this.boundMouseLeave),this.container.removeEventListener("click",this.boundClick),this.container.removeEventListener("dblclick",this.boundDblClick),this.container.removeEventListener("contextmenu",this.boundContextMenu),document.removeEventListener("keydown",this.boundKeyDown),document.removeEventListener("keyup",this.boundKeyUp)}dispose(){this._disposed||(this._disposed=!0,this.stopAutoRotate(),this.detachListeners(),this.picker.dispose(),this.selection.dispose(),this.drag.dispose(),this.hover.dispose(),this.graphControl?.dispose(),this.shortcuts?.dispose(),this.pathSelect?.dispose(),this.edgeCreate?.dispose(),this.onClickCallbacks=[],this.onDblClickCallbacks=[],this.onContextMenuCallbacks=[],this.onEdgeCreateCallbacks=[])}withRender(e){return()=>{let t=this.store.version;e(),this.store.version===t&&this.store.notifyChange(),this._requestRender?.()}}wireBuiltinShortcuts(){let e=this.shortcuts;if(!e)return;let t=this.selection,r=this.store;e.setHandler("sel.selectAll",this.withRender(()=>t.selectAllNodes())),e.setHandler("sel.deselectAll",this.withRender(()=>t.clearSelection())),e.setHandler("sel.invertSelection",this.withRender(()=>t.invertNodeSelection())),e.setHandler("sel.selectOrphans",this.withRender(()=>t.selectOrphanNodes()));let n=()=>{let i=t.selectedNodeIds,o=r.getSelectedNodeIds(),s=i.length>0&&o.length>0?[...new Set([...i,...o])]:i.length>0?i:o,d=t.selectedEdgeIds,l=[];if(r.edgeState){for(let h=0;h<r.edgeState.selected.length;h++)if(r.edgeState.selected[h]>0){let p=r.index.edgeIndexToId[h];p&&l.push(p)}}let u=d.length>0&&l.length>0?[...new Set([...d,...l])]:d.length>0?d:l;if(s.length===0&&u.length===0)return;t.clearSelection({syncStore:!1});let c={};s.length>0&&(c.removedNodeIds=s),u.length>0&&(c.removedEdgeIds=u),(c.removedNodeIds||c.removedEdgeIds)&&(this._txCtx?Kh(this._txCtx,c):r.applyDelta(c))};e.setHandler("edit.delete",this.withRender(n)),e.setHandler("edit.deleteAlt",this.withRender(n)),e.setHandler("edit.pinToggle",this.withRender(()=>{let i=t.selectedNodeIds;if(i.length===0)return;let o=r.index.getNodeIndex(i[0]);if(o===void 0)return;r.nodeState?.pinned[o]===1?r.unpinNodes(i):r.pinNodes(i)})),this.graphControl&&this.wireNavigationShortcuts(this.graphControl)}wireNavigationShortcuts(e){let t=this.shortcuts;if(!t)return;let r=.02,n=.15,i=.1;t.setHandler("nav.panUp",this.withRender(()=>e.pan(0,r))),t.setHandler("nav.panDown",this.withRender(()=>e.pan(0,-r))),t.setHandler("nav.panLeft",this.withRender(()=>e.pan(-r,0))),t.setHandler("nav.panRight",this.withRender(()=>e.pan(r,0))),t.setHandler("nav.zoomIn",this.withRender(()=>e.setZoom(e.getZoom()+n))),t.setHandler("nav.zoomOut",this.withRender(()=>e.setZoom(e.getZoom()-n))),t.setHandler("nav.resetPosition",this.withRender(()=>e.reset())),t.setHandler("nav.rotateLeft",this.withRender(()=>e.rotate(-i,0))),t.setHandler("nav.rotateRight",this.withRender(()=>e.rotate(i,0))),t.setHandler("nav.resetRotation",this.withRender(()=>e.resetRotation(!0)));let o=.008;t.setHandler("nav.turntableY",()=>{this.isAutoRotating?this.stopAutoRotate():this.startAutoRotate(o)})}startAutoRotate(e){if(this._autoRotateRafId!==null)return;let t=this.graphControl;if(!t)return;let r=()=>{t.rotate(e,0),this._requestRender?.(),this._autoRotateRafId=requestAnimationFrame(r)};this._autoRotateRafId=requestAnimationFrame(r)}stopAutoRotate(){this._autoRotateRafId!==null&&(cancelAnimationFrame(this._autoRotateRafId),this._autoRotateRafId=null)}get isAutoRotating(){return this._autoRotateRafId!==null}};xi.RIGHT_CLICK_THRESHOLD=4,xi.CLICK_MOVE_TOLERANCE=4;var Md=xi;import*as zr from"three";import $h from"@mapbox/tiny-sdf";var Zh=96,Yh=12,Xh=24,Qh=.25,Id=class{constructor(){this.fonts=new Map;this._fontsVersion=0;this.iconCache=new Map;this.textureSize=1024;this.shelfX=0;this.shelfY=0;this.shelfHeight=0;this.dirty=!1;this.textureData=new Uint8Array(this.textureSize*this.textureSize),this.atlas=this.createTexture(this.textureData,this.textureSize)}async loadFont(e,t){let r=e.fontFamily,n=e.fontWeight??"normal";try{let l=await new FontFace(r,`url(${e.url})`,{weight:n}).load();document.fonts.add(l)}catch(d){console.warn(`[IconAtlasManager] Failed to load font "${e.name}" from ${e.url}:`,d);return}let i=new $h({fontSize:Zh,buffer:Yh,radius:Xh,cutoff:Qh,fontFamily:'"'+r+'"',fontWeight:n,fontStyle:"normal"}),s={config:{...e,glyphMap:this.normalizeGlyphMap(e.glyphMap)},sdf:i};if(t?.categories)if(s.categories={},Array.isArray(t.categories))for(let d of t.categories)s.categories[d.id]={label:d.id,icons:[...d.icons]};else for(let[d,l]of Object.entries(t.categories))s.categories[d]={label:l.label,icons:[...l.icons]};this.fonts.set(e.name,s),this._fontsVersion++}registerFont(e,t){let r=e.fontWeight??"normal",n=new $h({fontSize:Zh,buffer:Yh,radius:Xh,cutoff:Qh,fontFamily:'"'+e.fontFamily+'"',fontWeight:r,fontStyle:"normal"}),i={...e,url:e.url??""},s={config:{...i,glyphMap:this.normalizeGlyphMap(i.glyphMap)},sdf:n};if(t?.categories)if(s.categories={},Array.isArray(t.categories))for(let d of t.categories)s.categories[d.id]={label:d.id,icons:[...d.icons]};else for(let[d,l]of Object.entries(t.categories))s.categories[d]={label:l.label,icons:[...l.icons]};this.fonts.set(e.name,s),this._fontsVersion++}ensureIcon(e){let t=this.iconCache.get(e);if(t)return t;let r=null,n=e,i=e.indexOf(":");i>0&&(r=e.substring(0,i),n=e.substring(i+1));let o=null,s=null;if(r){let w=this.fonts.get(r);if(!w)return null;o=w.config.glyphMap[n]??null,s=w}else{for(let[,w]of this.fonts)if(w.config.glyphMap[n]){o=w.config.glyphMap[n],s=w;break}!o&&n.length===1&&this.fonts.size>0&&(o=n,s=this.fonts.values().next().value)}if(!o||!s)return null;let d;try{if(d=s.sdf.draw(o),!isFinite(d.width)||!isFinite(d.height)||d.width<=0||d.height<=0)return null}catch{return null}let l=128,u=d.height,c=-1,h=d.width,p=-1;for(let w=0;w<d.height;w++){let T=w*d.width;for(let I=0;I<d.width;I++)d.data[T+I]>=l&&(w<u&&(u=w),w>c&&(c=w),I<h&&(h=I),I>p&&(p=I))}let f=c>=0&&p>=0,m=6,g,y,v;if(f){let w=p-h+1,T=c-u+1;g=Math.max(w,T)+m*2;let I=(u+c)/2,R=(h+p)/2,S=g/2;y=Math.round(S-R),v=Math.round(S-I)}else g=Math.max(d.width,d.height),y=Math.floor((g-d.width)/2),v=Math.floor((g-d.height)/2);let b=this.allocateRegion(g,g);for(let w=0;w<d.height;w++){let T=w*d.width,I=w+v;if(!(I<0||I>=g))for(let R=0;R<d.width;R++){let S=R+y;if(S<0||S>=g)continue;let P=(b.y+I)*this.textureSize+(b.x+S);P<this.textureData.length&&(this.textureData[P]=d.data[T+R])}}this.atlas.needsUpdate=!0;let x={u0:b.x/this.textureSize,v0:b.y/this.textureSize,u1:(b.x+g)/this.textureSize,v1:(b.y+g)/this.textureSize,fontFamily:s.config.fontFamily,unicode:o};return this.iconCache.set(e,x),x}getTexture(){return this.atlas}isDirty(){let e=this.dirty;return this.dirty=!1,e}get fontsVersion(){return this._fontsVersion}hasFonts(){return this.fonts.size>0}getAllIconNames(){let e=[];for(let[t,r]of this.fonts)for(let n of Object.keys(r.config.glyphMap))e.push(`${t}:${n}`);return e}getIconRenderInfo(e){let t=null,r=e,n=e.indexOf(":");if(n>0&&(t=e.substring(0,n),r=e.substring(n+1)),t){let i=this.fonts.get(t);if(!i)return null;let o=i.config.glyphMap[r];return o?{fontFamily:i.config.fontFamily,fontWeight:i.config.fontWeight??"normal",unicode:o}:null}for(let[,i]of this.fonts){let o=i.config.glyphMap[r];if(o)return{fontFamily:i.config.fontFamily,fontWeight:i.config.fontWeight??"normal",unicode:o}}return null}getIconCategories(){let e=[];for(let[t,r]of this.fonts)r.categories&&e.push({prefix:t,categories:r.categories});return e}dispose(){this.atlas.dispose(),this.iconCache.clear(),this.fonts.clear()}normalizeGlyphMap(e){let t={};for(let[r,n]of Object.entries(e))t[r]=typeof n=="number"?String.fromCodePoint(n):n;return t}createTexture(e,t){let r=new zr.DataTexture(e,t,t,zr.RedFormat,zr.UnsignedByteType);return r.minFilter=zr.LinearFilter,r.magFilter=zr.LinearFilter,r.generateMipmaps=!1,r.needsUpdate=!0,r}allocateRegion(e,t){this.shelfX+e>this.textureSize&&(this.shelfY+=this.shelfHeight,this.shelfX=0,this.shelfHeight=0),this.shelfY+t>this.textureSize&&this.textureSize<4096&&this.expandTexture();let r={x:this.shelfX,y:this.shelfY};return this.shelfX+=e,this.shelfHeight=Math.max(this.shelfHeight,t),r}expandTexture(){let e=this.textureSize,t=Math.min(e*2,4096),r=new Uint8Array(t*t);for(let i=0;i<e;i++)r.set(this.textureData.subarray(i*e,i*e+e),i*t);let n=e/t;for(let i of this.iconCache.values())i.u0*=n,i.v0*=n,i.u1*=n,i.v1*=n;this.textureData=r,this.textureSize=t,this.atlas.dispose(),this.atlas=this.createTexture(this.textureData,this.textureSize),this.dirty=!0}};import*as Br from"three";var Pd=class{constructor(){this.textureSize=1024;this.cellSize=128;this.cache=new Map;this.shelfX=0;this.shelfY=0;this.shelfHeight=0;this._isDirty=!1;this.textureData=new Uint8Array(this.textureSize*this.textureSize*4),this.atlas=this.createTexture(this.textureData,this.textureSize),this.canvas=document.createElement("canvas"),this.canvas.width=this.cellSize,this.canvas.height=this.cellSize,this.ctx=this.canvas.getContext("2d")}async setImage(e,t){let r=this.cache.get(e);if(r&&r.url===t)return r;let n=await this.loadImage(t);if(!n)return null;this.drawImageToCanvas(n);let i=this.ctx.getImageData(0,0,this.cellSize,this.cellSize),o=this.allocateRegion(this.cellSize,this.cellSize);for(let d=0;d<this.cellSize;d++)for(let l=0;l<this.cellSize;l++){let u=(d*this.cellSize+l)*4,c=((o.y+d)*this.textureSize+(o.x+l))*4;this.textureData[c]=i.data[u],this.textureData[c+1]=i.data[u+1],this.textureData[c+2]=i.data[u+2],this.textureData[c+3]=i.data[u+3]}this.atlas.needsUpdate=!0;let s={u0:o.x/this.textureSize,v0:o.y/this.textureSize,u1:(o.x+this.cellSize)/this.textureSize,v1:(o.y+this.cellSize)/this.textureSize,url:t};return this.cache.set(e,s),s}getImageUVs(e){return this.cache.get(e)||null}getTexture(){return this.atlas}isDirty(){let e=this._isDirty;return this._isDirty=!1,e}dispose(){this.atlas.dispose(),this.cache.clear()}loadImage(e){return new Promise(t=>{let r=new Image;r.crossOrigin="anonymous",r.onload=()=>t(r),r.onerror=()=>{console.warn("[ImageAtlasManager] Failed to load: "+e),t(null)},r.src=e})}drawImageToCanvas(e){let t=this.cellSize;this.ctx.clearRect(0,0,t,t);let r=Math.max(t/e.width,t/e.height),n=e.width*r,i=e.height*r,o=(t-n)/2,s=(t-i)/2;this.ctx.drawImage(e,o,s,n,i)}createTexture(e,t){let r=new Br.DataTexture(e,t,t,Br.RGBAFormat,Br.UnsignedByteType);return r.minFilter=Br.LinearFilter,r.magFilter=Br.LinearFilter,r.generateMipmaps=!1,r.needsUpdate=!0,r}allocateRegion(e,t){this.shelfX+e>this.textureSize&&(this.shelfY+=this.shelfHeight,this.shelfX=0,this.shelfHeight=0),this.shelfY+t>this.textureSize&&this.textureSize<4096&&this.expandTexture();let r={x:this.shelfX,y:this.shelfY};return this.shelfX+=e,this.shelfHeight=Math.max(this.shelfHeight,t),r}expandTexture(){let e=this.textureSize,t=Math.min(e*2,4096),r=new Uint8Array(t*t*4);for(let i=0;i<e;i++)r.set(this.textureData.subarray(i*e*4,(i*e+e)*4),i*t*4);let n=e/t;for(let i of this.cache.values())i.u0*=n,i.v0*=n,i.u1*=n,i.v1*=n;this.textureData=r,this.textureSize=t,this.atlas.dispose(),this.atlas=this.createTexture(this.textureData,this.textureSize),this._isDirty=!0}};import He,{useState as rn,useEffect as ke,useRef as be,useCallback as Xm,useSyncExternalStore as Qm}from"react";import*as ot from"three";var Ad=class{constructor(e){this.deps=e;this.seq=0}report(e,t){this.seq+=1;let r={reportId:`fault-${this.seq}`,faultKind:e,sanitizedReason:e,occurredAt:this.deps.now(),resultingPathId:t.resultingPathId,causedFallback:t.causedFallback},n=null;try{n=this.deps.getEvents()}catch{n=null}if(n)try{n.emit("renderFault",r)}catch{}return r}};function Jh(){return typeof navigator<"u"&&!!navigator.gpu}var rm="__kinevizWebGPURenderPath";function ep(){try{return globalThis[rm]===!0}catch{return!1}}var _d=class{constructor(e){this.deps=e;this.hostEnabled=!1;this.device={isAvailable:!1,readiness:"ready"};this.renderer="absent";this.disabledBy=null;this.faultCounters={total:0,lostCount:0,compileFailedCount:0,lastOccurredAt:null,permanentlyFellBack:!1,failedEngineShaderCount:0,failedHostShaderLayerIndices:[]}}setHostEnabled(e){this.hostEnabled=e}setDeviceAvailability(e){this.device={isAvailable:e.isAvailable,readiness:e.readiness}}setRendererReadiness(e){this.renderer=e}describe(){let e=this.readDebug(),t=this.hostEnabled||e,n=this.readCapable()&&this.device.isAvailable,i=this.disabledBy!==null,o=t&&n&&!i&&this.device.readiness==="ready"&&this.renderer==="ready",s=!o&&t&&!i&&this.renderer!=="unavailable"&&(this.device.readiness==="preparing"||n&&this.renderer!=="ready");return{pathId:o?"webgpu":"webgl",isAvailable:n,isEnabledByHost:this.hostEnabled,isEnabledByDebugFlag:e,isPermanentlyDisabled:i,disableReason:this.disabledBy,disableSource:this.disabledBy,readiness:s?"preparing":"ready"}}reportFault(e,t={origin:"engine"}){let r=this.describe().pathId;this.disabledBy===null&&(this.disabledBy=e),this.faultCounters.total+=1,this.faultCounters.lastOccurredAt=this.deps.now(),this.faultCounters.permanentlyFellBack=!0,e==="device-lost"?this.faultCounters.lostCount+=1:(this.faultCounters.compileFailedCount+=1,t.origin==="host"?this.faultCounters.failedHostShaderLayerIndices.push(t.layerIndex):this.faultCounters.failedEngineShaderCount+=1);try{this.deps.onFault(e,{resultingPathId:"webgl",causedFallback:r==="webgpu"})}catch{}}counters(){return{...this.faultCounters,failedHostShaderLayerIndices:[...this.faultCounters.failedHostShaderLayerIndices]}}readDebug(){try{return this.deps.readDebugFlag()===!0}catch{return!1}}readCapable(){try{return this.deps.isCapable()===!0}catch{return!1}}};var tp=0,rp=0,Dd=class{constructor(e){this.deps=e;this.pending=null;this.handle=null;this.disposed=!1;this.bufferIds=new WeakMap;this.current=null}ensureDevice(e){return this.disposed?Promise.reject(new Error("SharedGpuResources disposed")):this.handle&&!this.handle.isLost?(this.noteConsumer(e),Promise.resolve(this.toBundle(this.handle))):this.pending?(this.pending.then(()=>this.noteConsumer(e),()=>{}),this.pending):this.safeCapable()?(this.deps.onAvailability({isAvailable:!1,readiness:"preparing"}),this.pending=this.deps.acquire().then(t=>{if(this.pending=null,this.disposed)throw this.destroyDevice(t.device),this.deps.onAvailability({isAvailable:!1,readiness:"ready"}),new Error("SharedGpuResources disposed during acquisition");return tp+=1,this.handle={deviceId:`gpu-${tp}`,device:t.device,adapter:t.adapter,limits:t.limits,features:new Set(t.features),isLost:!1,lostReason:null,createdAt:this.deps.now(),sharedWith:[e]},this.watchLost(this.handle),this.deps.onAvailability({isAvailable:!0,readiness:"ready"}),t},t=>{throw this.pending=null,this.deps.onAvailability({isAvailable:!1,readiness:"ready"}),t instanceof Error?t:new Error("WebGPU device acquisition failed")}),this.pending):(this.deps.onAvailability({isAvailable:!1,readiness:"ready"}),Promise.reject(new Error("WebGPU is not available in this environment")))}getDeviceHandle(){return this.handle}notePositionsWritten(e){if(!e.positionBuffer){this.current=null;return}let t=e.dimensions??3;if(this.current&&this.current.buffer===e.positionBuffer){this.current.nodeCount=e.nodeCount,this.current.dimensions=t,this.current.generation+=1;return}this.bufferIds.has(e.positionBuffer)||(rp+=1,this.bufferIds.set(e.positionBuffer,`posbuf-${rp}`)),this.current={buffer:e.positionBuffer,nodeCount:e.nodeCount,generation:1,dimensions:t}}getPositionSource(){return!this.current||!this.handle||this.handle.isLost?null:{buffer:this.current.buffer,nodeCount:this.current.nodeCount,dimensions:this.current.dimensions,generation:this.current.generation,device:this.handle.device}}describePositionBuffer(){return!this.current||!this.handle||this.handle.isLost?null:{bufferId:this.bufferIds.get(this.current.buffer),nodeCount:this.current.nodeCount,strideBytes:16,generation:this.current.generation,device:this.handle.deviceId}}dispose(){this.disposed||(this.disposed=!0,this.current=null,this.handle&&!this.handle.isLost&&(this.handle.isLost=!0,this.handle.lostReason="destroyed",this.destroyDevice(this.handle.device)))}destroyDevice(e){try{e.destroy()}catch{}}watchLost(e){let t;try{t=e.device.lost}catch{return}!t||typeof t.then!="function"||t.then(r=>{if(e.isLost=!0,e.lostReason=r&&r.reason==="destroyed"?"destroyed":"unknown",this.current=null,this.disposed&&e.lostReason==="destroyed"){this.deps.onAvailability({isAvailable:!1,readiness:"ready"});return}try{this.deps.onDeviceLost()}catch{}this.deps.onAvailability({isAvailable:!1,readiness:"ready"})},()=>{})}noteConsumer(e){this.handle&&!this.handle.sharedWith.includes(e)&&this.handle.sharedWith.push(e)}toBundle(e){return{adapter:e.adapter,device:e.device,features:e.features,limits:e.limits}}safeCapable(){try{return this.deps.isCapable()===!0}catch{return!1}}};function Ec(a){let e=a.now??(()=>typeof performance<"u"?performance.now():Date.now()),t=a.isCapable??Jh,r=new Ad({getEvents:a.getEvents,now:e}),n=new _d({isCapable:t,readDebugFlag:a.readDebugFlag??ep,now:e,onFault:(d,l)=>{r.report(d,l)}}),i=new Dd({acquire:a.acquire??(async()=>{let{acquireWebGPUDevice:d}=await import("./webgpu-SY2OB4QP.mjs");return d({preferHighPerformance:!0})}),isCapable:t,onAvailability:d=>n.setDeviceAvailability(d),onDeviceLost:()=>n.reportFault("device-lost"),now:e});fl(()=>n.counters());let o={webgl:no("webgl"),webgpu:no("webgpu")},s=!1;return{selector:n,shared:i,channel:r,describe(){return n.describe()},activePathId(){return n.describe().pathId},activeBackend(){let d=o[n.describe().pathId];return d.supportsPrimitives?d:o.webgl},setHostEnabled(d){s=d,n.setHostEnabled(d),d&&i.ensureDevice("render").catch(()=>{})},isHostEnabled(){return s},dispose(){fl(null),i.dispose()}}}var nm=16,Nd=class{constructor(e,t={}){this.intervalId=null;this.disposed=!1;this.snapshotVersion=0;this.dim=3;this.structureDirty=!1;this._positionsStride3=null;this._positionVersion=0;this._repackVersion=-1;this._lastRepackSrc=null;this._repackCount=0;this._nodeIds=[];this._known=new Set;this._pinned=new Set;this.mode="cpu";this.settings=t,this.dim=e.dimensions===2?2:3,this.engine=new Vl("internal-d3",t),this.engine.init(e,t),this.adoptSnapshot(e);let r=[],n=[],i=this;this.graph={renderNeedsUpdate:!1,get layoutNodes(){return r},set layoutNodes(o){r=o,i.structureDirty=!0},get layoutEdges(){return n},set layoutEdges(o){n=o,i.structureDirty=!0}}}adoptSnapshot(e){this._nodeIds=e.nodes.map(t=>t.id),this._known=new Set(this._nodeIds),this._pinned=new Set(e.nodes.filter(t=>t.pinned).map(t=>t.id))}rebuildSnapshotFromGraph(){let e=this.graph.layoutNodes,t=this.graph.layoutEdges;return{version:++this.snapshotVersion,dimensions:this.dim,nodes:e.map((r,n)=>({id:r.id,index:n,position:{x:r.position.x,y:r.position.y,z:r.position.z},pinned:r.pinned??!1})),edges:t.map((r,n)=>({id:r.id,index:n,source:r.sourceId,target:r.targetId}))}}getPositionTexture(){return null}getTextureSize(){return 0}getSpaceSize(){return 100}tick(){}transitionDimensions(e,t){this.dim=e,this.structureDirty=!0}getDimensions(){return this.dim}start(){if(!this.disposed){if(this.structureDirty&&this.graph.layoutNodes.length>0){this.structureDirty=!1;let e=this.rebuildSnapshotFromGraph();this.engine.init(e,this.settings),this.adoptSnapshot(e),this._positionVersion++}this.engine.start(),this.intervalId===null&&(this.intervalId=setInterval(()=>{if(this.disposed)return;this.engine.tick().didChangePositions&&(this._positionVersion++,this.graph.renderNeedsUpdate=!0)},nm))}}stop(){this.intervalId!==null&&(clearInterval(this.intervalId),this.intervalId=null),this.disposed||this.engine.stop()}getPositions(){let t=this.engine.getReadback().positions;if(!t)return null;let r=t.length/4|0,n=r*3;if(this._repackVersion===this._positionVersion&&this._lastRepackSrc===t&&this._positionsStride3!==null&&this._positionsStride3.length===n)return this._positionsStride3;(!this._positionsStride3||this._positionsStride3.length!==n)&&(this._positionsStride3=new Float32Array(n));let i=this._positionsStride3;for(let o=0;o<r;o++)i[o*3]=t[o*4],i[o*3+1]=t[o*4+1],i[o*3+2]=t[o*4+2];return this._repackVersion=this._positionVersion,this._lastRepackSrc=t,this._repackCount++,i}updatePosition(e,t,r,n=0){if(this.disposed)return;let i=this._nodeIds[e];i!==void 0&&(this.engine.setNodePosition(i,{x:t,y:r,z:n}),this._pinned.add(i),this._positionVersion++,this.graph.renderNeedsUpdate=!0,this.start())}writePositions(e){if(this.disposed)return[];let t=[],r=[];for(let[n,i]of e)this._known.has(n)&&(this.engine.setNodePosition(n,{x:i[0],y:i[1],z:i[2]}),this._pinned.has(n)||r.push(n),t.push(n));return r.length>0&&this.engine.unpinNodes(r),t.length>0&&(this._positionVersion++,this.graph.renderNeedsUpdate=!0),t}pinNodes(e){if(this.disposed)return;let t=!1;for(let r of e)this._known.has(r.id)&&(this.engine.setNodePosition(r.id,{x:r.position.x,y:r.position.y,z:r.position.z}),this._pinned.add(r.id),t=!0);t&&(this._positionVersion++,this.graph.renderNeedsUpdate=!0)}unpinNodes(e){if(this.disposed)return;let t=e.filter(r=>this._known.has(r));if(t.length!==0){this.engine.unpinNodes(t);for(let r of t)this._pinned.delete(r);this.intervalId!==null&&this.engine.start()}}markNeedsUpdate(){this.graph.renderNeedsUpdate=!0}get needsUpdate(){return this.graph.renderNeedsUpdate}clearNeedsUpdate(){this.graph.renderNeedsUpdate=!1}get isFinish(){return this.intervalId===null}destroy(){this.disposed=!0,this.intervalId!==null&&(clearInterval(this.intervalId),this.intervalId=null),this.engine.dispose()}};function np(){let a=!1,e=null;return{publish(t,r){if(a){try{t.destroy()}catch{}return!1}return e=t,r(),!0},cancel(){a=!0;let t=e;return e=null,t},get cancelled(){return a}}}import{useRef as im}from"react";function om(a,e){if(Object.is(a,e))return!0;if(!ip(a)||!ip(e)||Array.isArray(a)!==Array.isArray(e))return!1;let t=Object.keys(a),r=Object.keys(e);if(t.length!==r.length)return!1;for(let n of t){if(!Object.prototype.hasOwnProperty.call(e,n))return!1;let i=a[n],o=e[n];if(!Object.is(i,o)&&!(Array.isArray(i)&&Array.isArray(o)&&i.length===o.length&&i.every((s,d)=>Object.is(s,o[d]))))return!1}return!0}function ip(a){if(a===null||typeof a!="object")return!1;if(Array.isArray(a))return!0;let e=Object.getPrototypeOf(a);return e===Object.prototype||e===null}function Eo(a){let e=im(a);return om(e.current,a)||(e.current=a),e.current}import{useEffect as Ro,useMemo as dm,useRef as lm}from"react";import*as Ke from"three";var op=`precision highp float;
269
+
270
+ // TinySDF atlas texture
271
+ uniform sampler2D uSdfAtlas;
272
+
273
+ // Varyings from vertex shader
274
+ varying vec2 vUv;
275
+ varying vec4 vUvRect;
276
+ varying vec3 vBgRgb;
277
+ varying vec3 vFgRgb;
278
+ varying float vGroupRole;
279
+ varying vec2 vSizePx; // background pill CSS px dimensions (from badge.vert.glsl)
280
+
281
+ void main() {
282
+ if (vGroupRole < 0.5) {
283
+ // Background quad \u2014 pill/circle SDF in height-normalised space.
284
+ //
285
+ // Transform vUv from [0,1]\xB2 into height-normalised coords:
286
+ // uvNorm.x \u2208 [-aspect/2, +aspect/2], uvNorm.y \u2208 [-0.5, +0.5]
287
+ // Corner radius = 0.5 (= half height), which gives:
288
+ // aspect = 1 \u2192 perfect circle (badgeWidth clamped to \u2265 badgeHeight above)
289
+ // aspect > 1 \u2192 pill with semicircle ends
290
+ float aspect = max(vSizePx.x / max(vSizePx.y, 0.001), 1.0);
291
+ vec2 uvNorm = (vUv - 0.5) * vec2(aspect, 1.0);
292
+ float cornerR = 0.5;
293
+ // Inner box: straight portion along x, no straight portion along y
294
+ vec2 q = abs(uvNorm) - vec2(aspect * 0.5 - cornerR, 0.0);
295
+ float pillDist = min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - cornerR;
296
+ float fw = fwidth(pillDist);
297
+ // Outer edge (full pill) and inner fill edge (shrunk by border width).
298
+ // borderW = 1.5 CSS px expressed in height-normalised units.
299
+ float borderW = 1.5 / vSizePx.y;
300
+ float fillAlpha = 1.0 - smoothstep(-fw, fw, pillDist + borderW);
301
+ float outerAlpha = 1.0 - smoothstep(-fw, fw, pillDist);
302
+ // Border colour: blend bg 75% / fg 25% \u2192 subtle darker outline.
303
+ vec3 borderRgb = mix(vBgRgb, vFgRgb, 0.25);
304
+ vec3 outColor = mix(borderRgb, vBgRgb, fillAlpha);
305
+ gl_FragColor = vec4(outColor, outerAlpha);
306
+ } else {
307
+ // Glyph quad \u2014 sample SDF atlas, foreground colour only (no background).
308
+ // Flip UV Y: the quad's uv.y=0 is at the bottom vertex, but TinySDF stores
309
+ // glyph row-0 (visual top) at low v-values in the atlas (DataTexture flipY=false).
310
+ // Without the flip the glyph renders upside-down.
311
+ // SDF_EDGE = 1.0 - TinySDF cutoff (0.25) = 0.75. Using 0.5 renders blurry/thin.
312
+ const float SDF_EDGE = 0.75;
313
+ vec2 atlasUv = mix(vUvRect.xy, vUvRect.zw, vec2(vUv.x, 1.0 - vUv.y));
314
+ float sdf = texture2D(uSdfAtlas, atlasUv).r;
315
+ float fw = fwidth(sdf);
316
+ float fgAlpha = smoothstep(SDF_EDGE - fw, SDF_EDGE + fw, sdf);
317
+ gl_FragColor = vec4(vFgRgb, fgAlpha);
318
+ }
319
+ if (gl_FragColor.a < 0.01) discard;
320
+ }
321
+ `;var sm=256,am=1.5,kd=class{constructor(e,t={}){this.instanceCount=0;this.geometry=null;this.material=null;this.mesh=null;this.scene=e,this.capacity=t.initialCapacity??sm}init(){this.createGeometry(),this.createMaterial(),this.createMesh()}createGeometry(){this.geometry=new Ke.InstancedBufferGeometry;let e=new Float32Array([-.5,-.5,0,.5,-.5,0,.5,.5,0,-.5,.5,0]),t=new Float32Array([0,0,1,0,1,1,0,1]);this.geometry.setAttribute("position",new Ke.BufferAttribute(e,3)),this.geometry.setAttribute("uv",new Ke.BufferAttribute(t,2)),this.geometry.setIndex(new Ke.BufferAttribute(new Uint16Array([0,1,2,0,2,3]),1)),this.allocateInstanceBuffers(this.capacity),this.geometry.instanceCount=0}allocateInstanceBuffers(e){if(!this.geometry)throw new Error("allocateInstanceBuffers called before geometry init");this.capacity=e,this.parentNodeIndexArr=new Float32Array(e),this.anchorOffsetPxArr=new Float32Array(e*2),this.sizePxArr=new Float32Array(e*2),this.uvRectArr=new Float32Array(e*4),this.bgRgbArr=new Float32Array(e*3),this.fgRgbArr=new Float32Array(e*3),this.roleArr=new Float32Array(e),this.glyphOffsetPxArr=new Float32Array(e*2),this.glyphSizePxArr=new Float32Array(e*2),this.geometry.setAttribute("aParentNodeIndex",new Ke.InstancedBufferAttribute(this.parentNodeIndexArr,1)),this.geometry.setAttribute("aAnchorOffsetPx",new Ke.InstancedBufferAttribute(this.anchorOffsetPxArr,2)),this.geometry.setAttribute("aSizePx",new Ke.InstancedBufferAttribute(this.sizePxArr,2)),this.geometry.setAttribute("aUvRect",new Ke.InstancedBufferAttribute(this.uvRectArr,4)),this.geometry.setAttribute("aBgRgb",new Ke.InstancedBufferAttribute(this.bgRgbArr,3)),this.geometry.setAttribute("aFgRgb",new Ke.InstancedBufferAttribute(this.fgRgbArr,3)),this.geometry.setAttribute("aGroupRole",new Ke.InstancedBufferAttribute(this.roleArr,1)),this.geometry.setAttribute("aGlyphOffsetPx",new Ke.InstancedBufferAttribute(this.glyphOffsetPxArr,2)),this.geometry.setAttribute("aGlyphSizePx",new Ke.InstancedBufferAttribute(this.glyphSizePxArr,2))}createMaterial(){this.material=new Ke.ShaderMaterial({vertexShader:Nu,fragmentShader:op,uniforms:{positionTexture:{value:null},textureSize:{value:512},uViewportPx:{value:new Ke.Vector2(1,1)},uSdfAtlas:{value:null},mapMode:{value:0},mapDamping:{value:1},mapMaxGrowth:{value:4}},transparent:!0,depthWrite:!1})}createMesh(){if(!this.geometry||!this.material)throw new Error("createMesh called before geometry/material init");this.mesh=new Ke.Mesh(this.geometry,this.material),this.mesh.frustumCulled=!1,this.mesh.renderOrder=2,this.scene.add(this.mesh)}ensureCapacity(e){if(e<=this.capacity)return;let t=this.capacity;for(;t<e;)t=Math.ceil(t*am);this.allocateInstanceBuffers(t)}setInstances(e){this.ensureCapacity(e.length);for(let t=0;t<e.length;t++){let r=e[t];this.parentNodeIndexArr[t]=r.parentNodeIndex,this.anchorOffsetPxArr[t*2]=r.anchorOffsetPx[0],this.anchorOffsetPxArr[t*2+1]=r.anchorOffsetPx[1],this.sizePxArr[t*2]=r.sizePx[0],this.sizePxArr[t*2+1]=r.sizePx[1],this.uvRectArr[t*4]=r.uvRect[0],this.uvRectArr[t*4+1]=r.uvRect[1],this.uvRectArr[t*4+2]=r.uvRect[2],this.uvRectArr[t*4+3]=r.uvRect[3],this.bgRgbArr[t*3]=r.bgRgb[0],this.bgRgbArr[t*3+1]=r.bgRgb[1],this.bgRgbArr[t*3+2]=r.bgRgb[2],this.fgRgbArr[t*3]=r.fgRgb[0],this.fgRgbArr[t*3+1]=r.fgRgb[1],this.fgRgbArr[t*3+2]=r.fgRgb[2],this.roleArr[t]=r.role,this.glyphOffsetPxArr[t*2]=r.glyphOffsetPx[0],this.glyphOffsetPxArr[t*2+1]=r.glyphOffsetPx[1],this.glyphSizePxArr[t*2]=r.glyphSizePx[0],this.glyphSizePxArr[t*2+1]=r.glyphSizePx[1]}if(this.instanceCount=e.length,this.geometry){this.geometry.instanceCount=this.instanceCount;let t=["aParentNodeIndex","aAnchorOffsetPx","aSizePx","aUvRect","aBgRgb","aFgRgb","aGroupRole","aGlyphOffsetPx","aGlyphSizePx"];for(let r of t){let n=this.geometry.getAttribute(r);n&&(n.needsUpdate=!0)}}}setPositionTexture(e,t){this.material&&(this.material.uniforms.positionTexture.value=e,this.material.uniforms.textureSize.value=t)}setSdfAtlas(e){this.material&&(this.material.uniforms.uSdfAtlas.value=e)}setMapMode(e,t){this.material&&(this.material.uniforms.mapMode.value=e?1:0,this.material.uniforms.mapDamping.value=t)}setMapMaxGrowth(e){if(!this.material)return;let t=e===1/0?-1:e;this.material.uniforms.mapMaxGrowth.value=t}setViewport(e,t){this.material&&this.material.uniforms.uViewportPx.value.set(e,t)}getCapacity(){return this.capacity}getInstanceCount(){return this.instanceCount}getGeometry(){if(!this.geometry)throw new Error("Geometry not initialised \u2014 call init() first");return this.geometry}getMesh(){return this.mesh}dispose(){this.mesh&&(this.scene.remove(this.mesh),this.mesh=null),this.geometry&&(this.geometry.dispose(),this.geometry=null),this.material&&(this.material.dispose(),this.material=null)}};function sp(a,e){if(!a)return e;let t=a.startsWith("#")?a.slice(1):a,r,n,i;if(t.length===3)r=parseInt(t[0]+t[0],16),n=parseInt(t[1]+t[1],16),i=parseInt(t[2]+t[2],16);else if(t.length===6)r=parseInt(t.slice(0,2),16),n=parseInt(t.slice(2,4),16),i=parseInt(t.slice(4,6),16);else return e;return isNaN(r)||isNaN(n)||isNaN(i)?e:[r/255,n/255,i/255]}var cm=[.95,.95,.95],um=[0,0,0],ap=3,hm=4,dp=8,pm=.7;function gm(a,e,t,r){let n=(e.text??"").slice(0,hm),i=t.getFontSize(),o=dp/i,s=n===""?[]:Array.from(n).map(y=>t.ensureGlyph(y)),d=s.reduce((y,v)=>y+v.glyphAdvance*o,0),l=dp+ap*2,u=Math.max(d+ap*2,l),c=sp(e.bg,cm),h=sp(e.fg,um),p=r===void 0?$i[e.anchor]:ss(e.anchor,r,[u/2,l/2],pm),f={parentNodeIndex:a,anchorOffsetPx:p,sizePx:[u,l],uvRect:[0,0,0,0],bgRgb:c,fgRgb:h,role:0,glyphOffsetPx:[0,0],glyphSizePx:[0,0]},m=[],g=-d/2;for(let y of s){let v=y.glyphWidth*o,b=y.width*o,x=y.height*o;m.push({parentNodeIndex:a,anchorOffsetPx:p,sizePx:[0,0],uvRect:[y.u0,y.v0,y.u1,y.v1],bgRgb:c,fgRgb:h,role:1,glyphOffsetPx:[g+v/2,0],glyphSizePx:[b,x]}),g+=y.glyphAdvance*o}return[f,...m]}function fm(a,e){let t=a.nodeState,r="";for(let n of e){let i=a.index.getNodeIndex(n);i!==void 0&&(r+=`${i}:${t?.effectiveSizes[i]??""}:${t?.hidden[i]??0};`)}return r}function lp(){let{store:a,cloudScene:e,container:t,invalidate:r,registerFrameCallback:n,getNodePositionTexture:i,registerMapModeCallback:o,registerMapMaxGrowthCallback:s,isMapMode:d,mapDamping:l}=dt(),{glyphAtlasManager:u}=Dr(),c=lm(null),h=Kr(Qo),p=Kr(Jo),f=dm(()=>fm(a,a.listBadges().map(m=>m.nodeId)),[a,h,p]);return Ro(()=>()=>{c.current&&(c.current.dispose(),c.current=null)},[]),Ro(()=>(o("badge-cloud",(g,y,v)=>{c.current?.setMapMode(g,v??.3)}),()=>o("badge-cloud",null)),[o]),Ro(()=>(s("badge-cloud",g=>{c.current?.setMapMaxGrowth(g)}),()=>s("badge-cloud",null)),[s]),Ro(()=>(n("badge-cloud",()=>{let m=c.current;if(!m)return;let g=i();g&&m.setPositionTexture(g.texture,g.textureSize)}),()=>n("badge-cloud",null)),[n,i]),Ro(()=>{if(!a.hasBadgeData()){c.current&&(c.current.dispose(),c.current=null,r());return}if(!c.current){let b=new kd(e);b.init(),t&&b.setViewport(t.clientWidth,t.clientHeight),d&&b.setMapMode(!0,l??.3);let x=i();x&&b.setPositionTexture(x.texture,x.textureSize),c.current=b}let g=c.current;u&&g.setSdfAtlas(u.getTexture());let y=a.listBadges(),v=[];for(let{nodeId:b,spec:x}of y){let w=a.index.getNodeIndex(b);if(w!==void 0&&!((a.nodeState?.hidden[w]??0)>.5)&&u){let T=(a.nodeState?.effectiveSizes[w]??a.defaultNodeSize)*os;v.push(...gm(w,x,u,T))}}g.setInstances(v),u?.isDirty()&&g.setSdfAtlas(u.getTexture()),r()},[h,f,a,e,t,r,u]),null}import{useEffect as Co,useMemo as vm,useRef as bm}from"react";import*as $e from"three";var cp=`precision highp float;
322
+
323
+ // TinySDF atlas texture
324
+ uniform sampler2D uSdfAtlas;
325
+
326
+ // Varyings from vertex shader
327
+ varying vec2 vUv;
328
+ varying vec4 vUvRect;
329
+ varying vec3 vBgRgb;
330
+ varying vec3 vFgRgb;
331
+ varying float vGroupRole;
332
+ varying vec2 vSizePx; // background pill CSS px dimensions (from tag.vert.glsl)
333
+
334
+ void main() {
335
+ if (vGroupRole < 0.5) {
336
+ // Background quad \u2014 pill/circle SDF in height-normalised space.
337
+ // Same formula as badge.frag.glsl: cornerR = 0.5 \u2192 circle when aspect=1,
338
+ // pill with semicircle ends when aspect > 1.
339
+ float aspect = max(vSizePx.x / max(vSizePx.y, 0.001), 1.0);
340
+ vec2 uvNorm = (vUv - 0.5) * vec2(aspect, 1.0);
341
+ float cornerR = 0.5;
342
+ vec2 q = abs(uvNorm) - vec2(aspect * 0.5 - cornerR, 0.0);
343
+ float pillDist = min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - cornerR;
344
+ float fw = fwidth(pillDist);
345
+ // Outer edge (full pill) and inner fill edge (shrunk by border width).
346
+ // borderW = 1.5 CSS px expressed in height-normalised units.
347
+ float borderW = 1.5 / vSizePx.y;
348
+ float fillAlpha = 1.0 - smoothstep(-fw, fw, pillDist + borderW);
349
+ float outerAlpha = 1.0 - smoothstep(-fw, fw, pillDist);
350
+ // Border colour: blend bg 75% / fg 25% \u2192 subtle darker outline.
351
+ vec3 borderRgb = mix(vBgRgb, vFgRgb, 0.25);
352
+ vec3 outColor = mix(borderRgb, vBgRgb, fillAlpha);
353
+ gl_FragColor = vec4(outColor, outerAlpha);
354
+ } else {
355
+ // Glyph quad \u2014 sample SDF atlas, foreground colour only (no background).
356
+ // Flip UV Y: the quad's uv.y=0 is at the bottom vertex, but TinySDF stores
357
+ // glyph row-0 (visual top) at low v-values in the atlas (DataTexture flipY=false).
358
+ // Without the flip the glyph renders upside-down.
359
+ // SDF_EDGE = 1.0 - TinySDF cutoff (0.25) = 0.75. Using 0.5 renders blurry/thin.
360
+ const float SDF_EDGE = 0.75;
361
+ vec2 atlasUv = mix(vUvRect.xy, vUvRect.zw, vec2(vUv.x, 1.0 - vUv.y));
362
+ float sdf = texture2D(uSdfAtlas, atlasUv).r;
363
+ float fw = fwidth(sdf);
364
+ float fgAlpha = smoothstep(SDF_EDGE - fw, SDF_EDGE + fw, sdf);
365
+ gl_FragColor = vec4(vFgRgb, fgAlpha);
366
+ }
367
+ if (gl_FragColor.a < 0.01) discard;
368
+ }
369
+ `;var mm=256,ym=1.5,Gd=class{constructor(e,t={}){this.instanceCount=0;this.geometry=null;this.material=null;this.mesh=null;this.scene=e,this.capacity=t.initialCapacity??mm}init(){this.createGeometry(),this.createMaterial(),this.createMesh()}createGeometry(){this.geometry=new $e.InstancedBufferGeometry;let e=new Float32Array([-.5,-.5,0,.5,-.5,0,.5,.5,0,-.5,.5,0]),t=new Float32Array([0,0,1,0,1,1,0,1]);this.geometry.setAttribute("position",new $e.BufferAttribute(e,3)),this.geometry.setAttribute("uv",new $e.BufferAttribute(t,2)),this.geometry.setIndex(new $e.BufferAttribute(new Uint16Array([0,1,2,0,2,3]),1)),this.allocateInstanceBuffers(this.capacity),this.geometry.instanceCount=0}allocateInstanceBuffers(e){if(!this.geometry)throw new Error("allocateInstanceBuffers called before geometry init");this.capacity=e,this.parentNodeIndexArr=new Float32Array(e),this.anchorOffsetPxArr=new Float32Array(e*2),this.sizePxArr=new Float32Array(e*2),this.uvRectArr=new Float32Array(e*4),this.bgRgbArr=new Float32Array(e*3),this.fgRgbArr=new Float32Array(e*3),this.roleArr=new Float32Array(e),this.glyphOffsetPxArr=new Float32Array(e*2),this.glyphSizePxArr=new Float32Array(e*2),this.geometry.setAttribute("aParentNodeIndex",new $e.InstancedBufferAttribute(this.parentNodeIndexArr,1)),this.geometry.setAttribute("aAnchorOffsetPx",new $e.InstancedBufferAttribute(this.anchorOffsetPxArr,2)),this.geometry.setAttribute("aSizePx",new $e.InstancedBufferAttribute(this.sizePxArr,2)),this.geometry.setAttribute("aUvRect",new $e.InstancedBufferAttribute(this.uvRectArr,4)),this.geometry.setAttribute("aBgRgb",new $e.InstancedBufferAttribute(this.bgRgbArr,3)),this.geometry.setAttribute("aFgRgb",new $e.InstancedBufferAttribute(this.fgRgbArr,3)),this.geometry.setAttribute("aGroupRole",new $e.InstancedBufferAttribute(this.roleArr,1)),this.geometry.setAttribute("aGlyphOffsetPx",new $e.InstancedBufferAttribute(this.glyphOffsetPxArr,2)),this.geometry.setAttribute("aGlyphSizePx",new $e.InstancedBufferAttribute(this.glyphSizePxArr,2))}createMaterial(){this.material=new $e.ShaderMaterial({vertexShader:ku,fragmentShader:cp,uniforms:{positionTexture:{value:null},textureSize:{value:512},uViewportPx:{value:new $e.Vector2(1,1)},uSdfAtlas:{value:null},mapMode:{value:0},mapDamping:{value:1},mapMaxGrowth:{value:4}},transparent:!0,depthWrite:!1,depthTest:!1})}createMesh(){if(!this.geometry||!this.material)throw new Error("createMesh called before geometry/material init");this.mesh=new $e.Mesh(this.geometry,this.material),this.mesh.frustumCulled=!1,this.mesh.renderOrder=3,this.scene.add(this.mesh)}ensureCapacity(e){if(e<=this.capacity)return;let t=this.capacity;for(;t<e;)t=Math.ceil(t*ym);this.allocateInstanceBuffers(t)}setInstances(e){this.ensureCapacity(e.length);for(let t=0;t<e.length;t++){let r=e[t];this.parentNodeIndexArr[t]=r.parentNodeIndex,this.anchorOffsetPxArr[t*2]=r.anchorOffsetPx[0],this.anchorOffsetPxArr[t*2+1]=r.anchorOffsetPx[1],this.sizePxArr[t*2]=r.sizePx[0],this.sizePxArr[t*2+1]=r.sizePx[1],this.uvRectArr[t*4]=r.uvRect[0],this.uvRectArr[t*4+1]=r.uvRect[1],this.uvRectArr[t*4+2]=r.uvRect[2],this.uvRectArr[t*4+3]=r.uvRect[3],this.bgRgbArr[t*3]=r.bgRgb[0],this.bgRgbArr[t*3+1]=r.bgRgb[1],this.bgRgbArr[t*3+2]=r.bgRgb[2],this.fgRgbArr[t*3]=r.fgRgb[0],this.fgRgbArr[t*3+1]=r.fgRgb[1],this.fgRgbArr[t*3+2]=r.fgRgb[2],this.roleArr[t]=r.role,this.glyphOffsetPxArr[t*2]=r.glyphOffsetPx[0],this.glyphOffsetPxArr[t*2+1]=r.glyphOffsetPx[1],this.glyphSizePxArr[t*2]=r.glyphSizePx[0],this.glyphSizePxArr[t*2+1]=r.glyphSizePx[1]}if(this.instanceCount=e.length,this.geometry){let t=this.geometry;t.instanceCount=this.instanceCount;let r=1/0;for(let i in t.attributes){let o=t.attributes[i];if(!o.isInstancedBufferAttribute)continue;let d=(o.meshPerAttribute??1)*o.count;d<r&&(r=d)}r!==1/0&&(t._maxInstanceCount=r);let n=["aParentNodeIndex","aAnchorOffsetPx","aSizePx","aUvRect","aBgRgb","aFgRgb","aGroupRole","aGlyphOffsetPx","aGlyphSizePx"];for(let i of n){let o=this.geometry.getAttribute(i);o&&(o.needsUpdate=!0)}}}setPositionTexture(e,t){this.material&&(this.material.uniforms.positionTexture.value=e,this.material.uniforms.textureSize.value=t)}setSdfAtlas(e){this.material&&(this.material.uniforms.uSdfAtlas.value=e)}setMapMode(e,t){this.material&&(this.material.uniforms.mapMode.value=e?1:0,this.material.uniforms.mapDamping.value=t)}setMapMaxGrowth(e){if(!this.material)return;let t=e===1/0?-1:e;this.material.uniforms.mapMaxGrowth.value=t}setViewport(e,t){this.material&&this.material.uniforms.uViewportPx.value.set(e,t)}getCapacity(){return this.capacity}getInstanceCount(){return this.instanceCount}getGeometry(){if(!this.geometry)throw new Error("Geometry not initialised \u2014 call init() first");return this.geometry}getMesh(){return this.mesh}dispose(){this.mesh&&(this.scene.remove(this.mesh),this.mesh=null),this.geometry&&(this.geometry.dispose(),this.geometry=null),this.material&&(this.material.dispose(),this.material=null)}};function up(a,e){if(!a)return e;let t=a.startsWith("#")?a.slice(1):a,r,n,i;if(t.length===3)r=parseInt(t[0]+t[0],16),n=parseInt(t[1]+t[1],16),i=parseInt(t[2]+t[2],16);else if(t.length===6)r=parseInt(t.slice(0,2),16),n=parseInt(t.slice(2,4),16),i=parseInt(t.slice(4,6),16);else return e;return isNaN(r)||isNaN(n)||isNaN(i)?e:[r/255,n/255,i/255]}var Sm=[.95,.95,.95],xm=[0,0,0],Em=3,hp=9,Rm=[6,32],Cm=2;function wm(a,e,t,r){let n=t.ensureGlyph("\u2026"),i=n.glyphAdvance*r,o=[...a],s=o.map(l=>t.ensureGlyph(l)),d=s.reduce((l,u)=>l+u.glyphAdvance*r,0);for(;o.length>0&&d+i>e;)o.pop(),s=o.map(l=>t.ensureGlyph(l)),d=s.reduce((l,u)=>l+u.glyphAdvance*r,0);return s.push(n),d+=i,{entries:s,totalAdvancePx:d}}function Tm(a,e,t,r){let n=t.getFontSize(),[i,o]=Rm,s=e.fontSizePx,d=typeof s=="number"&&Number.isFinite(s)?Math.min(o,Math.max(i,s)):hp,l=Em*d/hp,u=d/n,c=e.maxWidthPx!=null?e.maxWidthPx-l*2:1/0,h=Array.from(e.text??""),p=h.map(S=>t.ensureGlyph(S)),f=p.reduce((S,P)=>S+P.glyphAdvance*u,0),m,g;f>c?{entries:m,totalAdvancePx:g}=wm(h,c,t,u):(m=p,g=f);let y=d+l*2,v=Math.max(g+l*2,y),b=up(e.bg,Sm),x=up(e.fg,xm),w=r===void 0?$i[e.anchor]:ss(e.anchor,r,[v/2,y/2],1,Cm),T={parentNodeIndex:a,anchorOffsetPx:w,sizePx:[v,y],uvRect:[0,0,0,0],bgRgb:b,fgRgb:x,role:0,glyphOffsetPx:[0,0],glyphSizePx:[0,0]},I=[],R=-g/2;for(let S of m){let P=S.glyphWidth*u,D=S.width*u,E=S.height*u;I.push({parentNodeIndex:a,anchorOffsetPx:w,sizePx:[0,0],uvRect:[S.u0,S.v0,S.u1,S.v1],bgRgb:b,fgRgb:x,role:1,glyphOffsetPx:[R+P/2,0],glyphSizePx:[D,E]}),R+=S.glyphAdvance*u}return[T,...I]}function Mm(a,e){let t=a.nodeState,r="";for(let n of e){let i=a.index.getNodeIndex(n);i!==void 0&&(r+=`${i}:${t?.effectiveSizes[i]??""}:${t?.hidden[i]??0};`)}return r}function pp(){let{store:a,cloudScene:e,container:t,invalidate:r,registerFrameCallback:n,getNodePositionTexture:i,registerMapModeCallback:o,registerMapMaxGrowthCallback:s}=dt(),{glyphAtlasManager:d}=Dr(),l=bm(null),u=Kr(Qo),c=Kr(Jo),h=vm(()=>Mm(a,a.listTags().flatMap(p=>[...p.nodeIds])),[a,u,c]);return Co(()=>()=>{l.current&&(l.current.dispose(),l.current=null)},[]),Co(()=>(o("tag-cloud",(f,m,g)=>{l.current?.setMapMode(f,g??.3)}),()=>o("tag-cloud",null)),[o]),Co(()=>(s("tag-cloud",f=>{l.current?.setMapMaxGrowth(f)}),()=>s("tag-cloud",null)),[s]),Co(()=>(n("tag-cloud",()=>{let p=l.current;if(!p)return;let f=i();f&&p.setPositionTexture(f.texture,f.textureSize)}),()=>n("tag-cloud",null)),[n,i]),Co(()=>{if(!a.hasTagData()){l.current&&(l.current.dispose(),l.current=null,r());return}if(!l.current){let v=new Gd(e);v.init(),t&&v.setViewport(t.clientWidth,t.clientHeight);let b=i();b&&v.setPositionTexture(b.texture,b.textureSize),l.current=v}let f=l.current;d&&f.setSdfAtlas(d.getTexture());let m=i();m&&f.setPositionTexture(m.texture,m.textureSize);let g=a.listTags(),y=[];for(let{spec:v,nodeIds:b}of g)for(let x of b){let w=a.index.getNodeIndex(x);if(w!==void 0&&!((a.nodeState?.hidden[w]??0)>.5)&&d){let T=(a.nodeState?.effectiveSizes[w]??a.defaultNodeSize)*os;y.push(...Tm(w,v,d,T))}}f.setInstances(y),d?.isDirty()&&f.setSdfAtlas(d.getTexture()),r()},[u,h,a,e,t,r,d]),null}import{useEffect as Im,useRef as gp}from"react";function fp(){let a=ul(),e=dt(),{store:t,cloudScene:r,camera:n,renderer:i,invalidate:o,registerMapModeCallback:s}=e,{iconAtlasManager:d}=Dr(),l=_r(),u=zi(),c=gp(l);c.current=l;let h=gp(u);return h.current=u,Im(()=>{let p={cloudScene:r,camera:n,getRenderer:()=>i,store:t,invalidate:o,registerMapModeCallback:s,iconAtlasManager:d,isMapMode:()=>c.current,mapSphereRadius:()=>h.current,mapNodeSizing:()=>au(e),getHitTest:()=>e.interaction?.picker??null};return a.layers._wireHost(p),()=>a.layers._wireHost(null)},[a,t,r,n,i]),null}var Ei="hoverDimAnim",Pm={duration:200,dimOpacity:.15,glowEnabled:!0,glowStrength:0,haloStrength:1},mp=1;function Am(a){return a<.5?4*a*a*a:1-Math.pow(-2*a+2,3)/2}var Hd=class{constructor(e){this.deps=e;this._state="Idle";this._progress=0;this._keep=null;this._config={...Pm};this._suppressed=!1;this._lastTickTs=0;this._externalKeep=null;this._externalDimActive=!1;this._onFrame=()=>{let e=typeof performance<"u"?performance.now():Date.now(),t=this._lastTickTs===0?16:Math.max(0,e-this._lastTickTs);this._lastTickTs=e,this.deps.setHoverTimeUniform(Math.floor(e)%524288),this._tickWithDt(t)}}get state(){return this._state}get progress(){return this._progress}_singletonKeepSet(e){return e==null?null:e.kind==="node"?{nodes:new Set([e.index]),edges:new Set}:{nodes:new Set,edges:new Set([e.index])}}_wantsHover(){return this._config.glowEnabled!==!1}_applyKeepSet(e,t){let r=typeof performance<"u"?performance.now():Date.now();this.deps.setHoverTimeUniform(Math.floor(r)%524288);let n=this._config.glowEnabled===!1?0:this._config.glowStrength??1,i=this._config.glowEnabled===!1?0:this._config.haloStrength??1,o=this._externalDimActive;if(t==null){this.deps.clearAllHoverDimBits(),this.deps.clearAllEmphasisGlow(),this._keep=null;return}if(e==null){if(o){for(let s=0;s<this.deps.nodeCount;s++)t.nodes.has(s)||this.deps.setNodeHoverDimBit(s,1);for(let s=0;s<this.deps.edgeCount;s++)t.edges.has(s)||this.deps.setEdgeHoverDimBit(s,1)}for(let s of t.nodes)this.deps.setNodeHalo(s,i);for(let s of t.edges)this.deps.setEdgeTubeGlow(s,n);this._keep=t;return}for(let s of e.nodes)t.nodes.has(s)||(o&&this.deps.setNodeHoverDimBit(s,1),this.deps.setNodeHalo(s,0));for(let s of t.nodes)e.nodes.has(s)||(o&&this.deps.setNodeHoverDimBit(s,0),this.deps.setNodeHalo(s,i));for(let s of e.edges)t.edges.has(s)||(o&&this.deps.setEdgeHoverDimBit(s,1),this.deps.setEdgeTubeGlow(s,0));for(let s of t.edges)e.edges.has(s)||(o&&this.deps.setEdgeHoverDimBit(s,0),this.deps.setEdgeTubeGlow(s,n));this._keep=t}setConfig(e){e.duration!=null&&(this._config.duration=Math.max(1,Math.min(2e3,e.duration)),this.deps.setHoverDurationUniform(this._config.duration),this.deps.requestRender()),e.dimOpacity!=null&&(this._config.dimOpacity=Math.max(0,Math.min(1,e.dimOpacity)),this.deps.setHoverDimOpacityUniform(this._config.dimOpacity),this.deps.requestRender()),e.glowStrength!=null&&(this._config.glowStrength=Math.max(0,e.glowStrength)),e.haloStrength!=null&&(this._config.haloStrength=Math.max(0,e.haloStrength)),e.glowEnabled!=null&&(this._config.glowEnabled=e.glowEnabled,e.glowEnabled||(this.deps.clearAllEmphasisGlow(),this.deps.requestRender()),this._reconcile())}_reconcile(){this._wantsHover()?this._state==="Disabled"&&(this._state="Idle"):this._enterDisabled()}isGlowEnabled(){return this._config.glowEnabled!==!1}getConfig(){return{...this._config}}onHoverEnter(e){if(!this._wantsHover()||this._state==="Disabled"||this._state==="Suppressed"||this._externalKeep)return;let t=this._singletonKeepSet(e);this._applyKeepSet(this._keep,t),this._goRampingUp(),this.deps.requestRender()}onHoverMove(e){if(!this._wantsHover()||this._state==="Disabled"||this._state==="Suppressed"||this._externalKeep)return;if(this._state==="Idle")return this.onHoverEnter(e);let t=this._singletonKeepSet(e);this._applyKeepSet(this._keep,t),this.deps.requestRender()}onHoverLeave(){this._state==="Disabled"||this._state==="Suppressed"||this._externalKeep||(this._applyKeepSet(this._keep,null),this._goRampingDown())}setExternalKeepSet(e,t){let r=new Set;for(let o of e){let s=this.deps.getNodeIndex(o);s!=null&&r.add(s)}let n=new Set;for(let o of t){let s=this.deps.getEdgeIndex(o);s!=null&&n.add(s)}let i={nodes:r,edges:n};this._externalDimActive||(this._externalDimActive=!0,this.deps.setHoverProgressUniform(1)),this._applyKeepSet(this._externalKeep??this._keep,i),this._externalKeep=i,this._keep=i,this._goRampingUp(),this.deps.requestRender()}clearExternalKeepSet(){this._externalKeep&&(this._applyKeepSet(this._externalKeep,null),this._externalKeep=null,this._externalDimActive=!1,this._goRampingDown(),this.deps.requestRender())}onMouseDown(e){e===0&&this._state!=="Disabled"&&(this._suppressed=!0,this._state="Suppressed",this._progress=0,this.deps.setHoverProgressUniform(0),this.deps.requestRender(),this.deps.clearAllHoverDimBits(),this._keep=null,this.deps.unregisterFrameCallback(Ei))}onMouseUp(){this._state==="Suppressed"&&(this._suppressed=!1,this._state="Idle")}_enterDisabled(){this._state="Disabled",this._progress=0,this.deps.setHoverProgressUniform(0),this.deps.requestRender(),this.deps.clearAllHoverDimBits(),this.deps.clearAllEmphasisGlow(),this._keep=null,this.deps.unregisterFrameCallback(Ei)}_goRampingUp(){if(this._config.duration<=mp){this._state="Steady",this._progress=1,this.deps.setHoverProgressUniform(1),this.deps.requestRender(),this.deps.unregisterFrameCallback(Ei);return}if(this._state="RampingUp",this._progress>=1){this._state="Steady";return}this._lastTickTs=0,this.deps.registerFrameCallback(Ei,this._onFrame)}_goRampingDown(){if(this._config.duration<=mp){this._enterIdle();return}if(this._state="RampingDown",this._progress<=0){this._enterIdle();return}this._lastTickTs=0,this.deps.registerFrameCallback(Ei,this._onFrame)}_enterIdle(){this._state="Idle",this._progress=0,this.deps.setHoverProgressUniform(0),this.deps.requestRender(),this.deps.clearAllHoverDimBits(),this._keep=null,this.deps.unregisterFrameCallback(Ei)}_tickWithDt(e){this._state==="RampingUp"&&(this._progress=Math.min(1,this._progress+e/this._config.duration)),this._state==="RampingDown"&&(this._progress=Math.max(0,this._progress-e/this._config.duration));let t=Am(this._progress);this.deps.setHoverProgressUniform(t),this.deps.requestRender(),this._state==="RampingUp"&&this._progress>=1&&(this._state="Steady"),this._state==="RampingDown"&&this._progress<=0&&this._enterIdle()}};var Fd=Object.freeze({pathId:"webgl",isAvailable:!1,isEnabledByHost:!1,isEnabledByDebugFlag:!1,isPermanentlyDisabled:!1,disableReason:null,disableSource:null,readiness:"ready"}),wo=class{constructor(e){this.nodeRenderer=null;this.edgeRenderer=null;this.interaction=null;this.layoutProvider=null;this.iconAtlasManager=null;this.nodeTextCloud=null;this.edgeTextCloud=null;this.frameCallbacks=new Map;this.lastStoreVersion=-1;this._needsRender=!1;this._positionsVersion=0;this.pendingStructureChange=!1;this._extraFrames=0;this.hasLayoutController=!1;this.cloudScene=null;this.host=null;this.hostFrameCallbacks=null;this.pickerDebugActive=!1;this.targets={webgl:null,webgpu:null};this.pathSource=()=>Fd;this.activePathId="webgl";this.scheduler=null;this.rafId=null;this.running=!1;this.frameCounter=0;this.lastFrameState=null;this.perfT0=NaN;this.boundFrame=()=>this.runFrame();this.store=e.store,this.now=e.now??(()=>typeof performance<"u"?performance.now():Date.now()),this.hoverEmphasis=new Hd({queries:{getNeighbors:t=>this.store.queries.getNeighbors(t),getEdge:t=>this.store.queries.getEdge(t)},getNodeIndex:t=>this.store.index.getNodeIndex(t),getEdgeIndex:t=>this.store.index.getEdgeIndex(t),setNodeHoverDimBit:(t,r)=>{this.nodeRenderer?.setHoverDimBit(t,r);let n=this.store.index.getNodeId(t);n!=null&&this.nodeTextCloud?.setHoverDimById(n,r)},setEdgeHoverDimBit:(t,r)=>{this.edgeRenderer?.setHoverDimBit(t,r);let n=this.store.index.getEdgeId(t);n!=null&&this.edgeTextCloud?.setHoverDimById(n,r)},clearAllHoverDimBits:()=>{this.nodeRenderer?.clearAllHoverDimBits(),this.edgeRenderer?.clearAllHoverDimBits(),this.nodeTextCloud?.clearAllHoverDim(),this.edgeTextCloud?.clearAllHoverDim()},setEdgeTubeGlow:(t,r)=>{this.edgeRenderer?.setTubeGlow(t,r)},setNodeHalo:(t,r)=>{this.nodeRenderer?.setHalo(t,r)},clearAllEmphasisGlow:()=>{this.edgeRenderer?.clearAllEmphasisGlow(),this.nodeRenderer?.clearAllEmphasisHalo()},setHoverProgressUniform:t=>{this.nodeRenderer?.setHoverUniform("u_hoverProgress",t),this.edgeRenderer?.setHoverUniform("u_hoverProgress",t),this.nodeTextCloud?.setHoverUniform("u_hoverProgress",t),this.edgeTextCloud?.setHoverUniform("u_hoverProgress",t)},setHoverDimOpacityUniform:t=>{this.nodeRenderer?.setHoverUniform("u_hoverDimOpacity",t),this.edgeRenderer?.setHoverUniform("u_hoverDimOpacity",t),this.nodeTextCloud?.setHoverUniform("u_hoverDimOpacity",t),this.edgeTextCloud?.setHoverUniform("u_hoverDimOpacity",t)},setHoverTimeUniform:t=>{this.nodeRenderer?.setHoverUniform("u_hoverTime",t),this.edgeRenderer?.setHoverUniform("u_hoverTime",t),this.nodeTextCloud?.setHoverUniform("u_hoverTime",t),this.edgeTextCloud?.setHoverUniform("u_hoverTime",t)},setHoverDurationUniform:t=>{this.nodeRenderer?.setHoverUniform("u_hoverDuration",t),this.edgeRenderer?.setHoverUniform("u_hoverDuration",t),this.nodeTextCloud?.setHoverUniform("u_hoverDuration",t),this.edgeTextCloud?.setHoverUniform("u_hoverDuration",t)},registerFrameCallback:(t,r)=>this.registerFrameCallback(t,r),unregisterFrameCallback:t=>this.registerFrameCallback(t,null),requestRender:()=>this.invalidate(),get nodeCount(){return e.store.nodeCount},get edgeCount(){return e.store.edgeCount}})}get positionsVersion(){return this._positionsVersion}setNodeRenderer(e){this.nodeRenderer=e}setEdgeRenderer(e){this.edgeRenderer=e}setInteraction(e){this.interaction=e}setLayoutProvider(e){this.layoutProvider=e}setIconAtlasManager(e){this.iconAtlasManager=e}setNodeTextCloud(e){this.nodeTextCloud=e}setEdgeTextCloud(e){this.edgeTextCloud=e}setCloudScene(e){this.cloudScene=e}setHasLayoutController(e){this.hasLayoutController=e}markStructureChanged(){this.pendingStructureChange=!0,this._needsRender=!0}invalidate(){this._needsRender=!0}setHost(e){this.host=e}setHostFrameCallbacks(e){this.hostFrameCallbacks=e}setPickerDebugActive(e){this.pickerDebugActive=e}setPaintTargets(e){this.targets={webgl:e.webgl,webgpu:e.webgpu}}setRenderPathSource(e){this.pathSource=e??(()=>Fd)}getActivePathId(){return this.activePathId}getPaintTarget(e){return this.targets[e]}lastFrame(){return this.lastFrameState}start(e){this.running||(this.scheduler=e,this.running=!0,this.rafId=e.request(this.boundFrame))}stop(){this.running=!1,this.rafId!==null&&this.scheduler&&this.scheduler.cancel(this.rafId),this.rafId=null,this.scheduler=null}resizeTargets(e,t){this.targets.webgl?.setSize(e,t),this.targets.webgpu?.setSize(e,t)}setTargetsPixelRatio(e){this.targets.webgl?.setPixelRatio(e),this.targets.webgpu?.setPixelRatio(e)}setTargetsClearColor(e,t){this.targets.webgl?.setClearColor(e,t),this.targets.webgpu?.setClearColor(e,t)}registerFrameCallback(e,t,r){t?this.frameCallbacks.set(e,{cb:t,requiresPath:r?.requiresPath}):this.frameCallbacks.delete(e)}runFrameCallbacks(){if(this.frameCallbacks.size!==0)for(let e of[...this.frameCallbacks.keys()]){let t=this.frameCallbacks.get(e);t&&(t.requiresPath&&t.requiresPath!==this.activePathId||t.cb())}}update(){if(this.checkDirtySources(),!this._needsRender)return{rendered:!1,structureChanged:!1};this.perfT0=gu();let e=this.store,t=this.nodeRenderer,r=this.edgeRenderer,n=this.interaction,i=this.layoutProvider,o=this.pendingStructureChange||e.updateStrategy.hasDirty("structure");if(o&&(this.pendingStructureChange=!1),o&&t&&this.resolveIcons(e,t),t&&r){let l=t.config?.fixedSize??0;r.setFixedSize(l)}i&&i.mode==="gpu"?this.updateGPUMode(t,r,n,i):this.updateCPUMode(t,r,n,i),o&&this.host?.afterStructureChange(),(o||i?.needsUpdate||e.positionProvider?.needsUpdate)&&(this._positionsVersion+=1),i&&i.needsUpdate&&i.clearNeedsUpdate&&i.clearNeedsUpdate();let s=e.positionProvider;s&&s.needsUpdate&&s.clearNeedsUpdate(),this.host?.beforeFrameCallbacks();let d=!1;if(this.hostFrameCallbacks)for(let l of this.hostFrameCallbacks.values())l()===!0&&(d=!0);return this.runFrameCallbacks(),this.pickerDebugActive?this._needsRender=!0:this.hasLayoutController?this._needsRender=!1:this._extraFrames>0?(this._extraFrames--,this._needsRender=!0):this._needsRender=!1,d&&(this._needsRender=!0),this.host?.afterSettle(),{rendered:!0,structureChanged:o}}runFrame(){this.rafId=null,this.frameCounter+=1;try{pu();let e=this.readPath();this.orchestratePath(e),this.host?.syncDeps();let t=this.update(),r=null;t.rendered&&(r=this.nodeRenderer?.getLastConsumedDirtyFlags()??null,this.paint(),this.host?.afterPaint()),this.lastFrameState={frameId:this.frameCounter,timestamp:this.now(),activePathId:this.activePathId,needsRender:t.rendered,consumedDirtyFlags:r}}finally{this.running&&this.scheduler&&(this.rafId=this.scheduler.request(this.boundFrame))}}readPath(){try{return this.pathSource()}catch{return Fd}}orchestratePath(e){let t=this.targets.webgpu;if(t){let n=e.isEnabledByHost||e.isEnabledByDebugFlag;e.isPermanentlyDisabled?(t.state==="preparing"||t.state==="ready")&&t.retire():n&&t.state==="absent"&&t.prepare()}let r=e.pathId==="webgpu"&&t!==null&&t.isReady()?"webgpu":"webgl";r!==this.activePathId&&(this.activePathId=r,this.targets.webgl?.setVisible(r==="webgl"),t?.setVisible(r==="webgpu"),gl(r),this._needsRender=!0)}resolvePaintTarget(){let e=this.targets.webgpu;return this.activePathId==="webgpu"&&e&&e.isReady()?e:this.targets.webgl}paint(){let e=this.resolvePaintTarget();e?.render(),fu(this.perfT0),mu(e?.getDrawCallSource()??null),bu()}checkDirtySources(){let e=this.store;if(this.host)try{this.host.collectDirty()&&(this._needsRender=!0)}catch{}e.version!==this.lastStoreVersion&&(this.lastStoreVersion=e.version,this._needsRender=!0,this._extraFrames=3),this.layoutProvider&&this.layoutProvider.needsUpdate&&(this._needsRender=!0);let t=e.positionProvider;t&&t.needsUpdate&&(this._needsRender=!0)}resolveIcons(e,t){if(e.isResolvedByTransaction())return;let n=this.iconAtlasManager;if(!n||!n.hasFonts())return;t.setIconSdfAtlas(n.getTexture());let i=Td(e,n),o=!1;i&&(t.updateIconUVs(i),o=!0),n.isDirty()&&t.setIconSdfAtlas(n.getTexture()),o&&e.markTransactionResolved()}updateGPUMode(e,t,r,n){if(e&&(e.setPositionProvider(n),e.update(),e.getLastConsumedDirtyFlags()?.has("structure")&&(e.forceUpdateAllAttributes(),r))){let s=e.getMesh();s?.geometry&&(r.setupNodePicking(s.geometry),r.syncTransforms(this.cloudScene))}let i=e?.getLastConsumedDirtyFlags()??void 0;if(t){let o=n.getPositionTexture(),s=n.getTextureSize(),d=n.getSpaceSize();o&&s>0&&t.setSharedPositionTexture(o,s,d),t.update(i),this.syncEdgePickerAfterStructureChange(t,r,i)}if(r){let o=n.getPositionTexture(),s=n.getTextureSize(),d=n.getSpaceSize();o&&s>0&&r.updatePositionTexture(o,s,d)}}updateCPUMode(e,t,r,n){let i=this.store.positionProvider??n;if(e&&i&&i.mode==="cpu"&&e.setPositionProvider(i),e&&(e.update(),e.getLastConsumedDirtyFlags()?.has("structure")&&(e.forceUpdateAllAttributes(),r))){let d=e.getMesh();d?.geometry&&(r.setupNodePicking(d.geometry),r.syncTransforms(this.cloudScene))}let o=e?.getLastConsumedDirtyFlags()??void 0;if(e&&t){let s=e.getCpuPositionTextureInfo();s&&t.setSharedPositionTexture(s.texture,s.textureSize,s.spaceSize)}if(t&&(t.update(o),this.syncEdgePickerAfterStructureChange(t,r,o)),r&&e){let s=e.getCpuPositionTextureInfo();s&&r.updatePositionTexture(s.texture,s.textureSize,s.spaceSize)}}syncEdgePickerAfterStructureChange(e,t,r){if(!(r?.has("structure")||r?.has("edgeStructure"))||!t)return;let i=e.getMesh();i?.geometry&&i.material&&(t.setupEdgePicking(i.geometry,i.material),t.syncTransforms(this.cloudScene))}dispose(){this.stop(),this.lastFrameState=null,this.frameCounter=0,this.host=null,this.hostFrameCallbacks=null,this.frameCallbacks.clear(),this.targets={webgl:null,webgpu:null},this.pathSource=()=>Fd,this.activePathId="webgl",gl("webgl"),this.pickerDebugActive=!1,this.nodeRenderer=null,this.edgeRenderer=null,this.interaction=null,this.layoutProvider=null,this.iconAtlasManager=null,this.nodeTextCloud=null,this.edgeTextCloud=null,this.cloudScene=null,this.hasLayoutController=!1}};import*as br from"three";import{useEffect as yp,useRef as _m}from"react";function zd(a){return{shift:a.shiftKey,ctrl:a.ctrlKey,meta:a.metaKey,alt:a.altKey}}function Dm(a,e){return[a.clientX-e.left,a.clientY-e.top]}function Nm(a,e,t=new br.Vector3){return a.ray.intersectPlane(e,t)?[t.x,t.y,t.z]:[0,0,0]}function vp(a,e,t,r){return{nodeId:a.nodeId,originalEvent:e,canvasPos:t,worldPos:r,modifiers:zd(e)}}function bp(a,e,t,r){return{edgeId:a.edgeId,originalEvent:e,canvasPos:t,worldPos:r,modifiers:zd(e)}}function km(a,e,t,r){return{originalEvent:e,canvasPos:t,worldPos:r,modifiers:zd(e)}}function Rc(a,e,t,r,n){let i=a.nodeIds[0]??"",o=[n[0]-r[0],n[1]-r[1],n[2]-r[2]];return{nodeId:i,originalEvent:e,canvasPos:t,worldPos:n,modifiers:zd(e),startWorld:r,deltaWorld:o,draggedNodeIds:a.nodeIds.slice()}}function Gm(a){return{raycaster:new br.Raycaster,plane:new br.Plane(new br.Vector3(0,0,1),0),out:new br.Vector3,camera:a}}function Sp(a,e,t){let r=e[0]/t.width*2-1,n=-(e[1]/t.height)*2+1;return a.raycaster.setFromCamera(new br.Vector2(r,n),a.camera),Nm(a.raycaster,a.plane,a.out)}function Cc(a,e,t,r,n,i){let o=n.getBoundingClientRect(),s=Dm(t,o),d=Sp(r,s,o);e.type==="node"?(a==="click"?i.onNodeClick:a==="dblclick"?i.onNodeDoubleClick:i.onNodeContextMenu)?.(vp(e,t,s,d)):e.type==="edge"?(a==="click"?i.onEdgeClick:a==="dblclick"?i.onEdgeDoubleClick:i.onEdgeContextMenu)?.(bp(e,t,s,d)):(a==="click"?i.onBackgroundClick:a==="dblclick"?void 0:i.onBackgroundContextMenu)?.(km(e,t,s,d))}function Hm(a){let e=_m(a);return yp(()=>{e.current=a},[a]),e}function xp(a,e){let t=Hm(e);yp(()=>{if(!a?.interaction||!a?.camera||!a?.renderer)return;let r=a.interaction,n=a.camera,i=a.renderer.domElement,o=Gm(n),s=r.onClick((y,v)=>{Cc("click",y,v,o,i,t.current)}),d=r.onDblClick((y,v)=>{Cc("dblclick",y,v,o,i,t.current)}),l=r.onContextMenu((y,v)=>{Cc("contextmenu",y,v,o,i,t.current)}),u=r.hover.onChange(y=>{let v=i.getBoundingClientRect(),b=[y.screenPosition.x,y.screenPosition.y],x=Sp(o,b,v),w=new MouseEvent("mousemove",{clientX:y.screenPosition.x+v.left,clientY:y.screenPosition.y+v.top});y.previous.type==="node"&&y.current.type!=="node"&&t.current.onNodeHover?.(null),y.current.type==="node"&&y.current.id&&t.current.onNodeHover?.(vp({type:"node",index:-1,nodeId:y.current.id,node:null,picked:!0,screenPosition:y.screenPosition,ndcPosition:{x:0,y:0}},w,b,x)),y.previous.type==="edge"&&y.current.type!=="edge"&&t.current.onEdgeHover?.(null),y.current.type==="edge"&&y.current.id&&t.current.onEdgeHover?.(bp({type:"edge",index:-1,edgeId:y.current.id,edge:null,picked:!0,screenPosition:y.screenPosition,ndcPosition:{x:0,y:0}},w,b,x))}),c=[0,0,0],h=new MouseEvent("mousedown"),p=y=>{h=y};i.addEventListener("mousedown",p,!0),i.addEventListener("mousemove",p,!0),i.addEventListener("mouseup",p,!0);let f=r.drag.onDragStart(y=>{let v=[y.screenPosition.x,y.screenPosition.y];c=[y.startPosition.x,y.startPosition.y,y.startPosition.z],t.current.onNodeDragStart?.(Rc(y,h,v,c,c))}),m=r.drag.onDragMove(y=>{let v=[y.screenPosition.x,y.screenPosition.y],b=[y.currentPosition.x,y.currentPosition.y,y.currentPosition.z];t.current.onNodeDrag?.(Rc(y,h,v,c,b))}),g=r.drag.onDragEnd(y=>{let v=[y.finalPosition.x,y.finalPosition.y,y.finalPosition.z];t.current.onNodeDragEnd?.(Rc(y,h,[0,0],c,v))});return()=>{s(),d(),l(),u(),f(),m(),g(),i.removeEventListener("mousedown",p,!0),i.removeEventListener("mousemove",p,!0),i.removeEventListener("mouseup",p,!0)}},[a])}import{useEffect as Ep,useRef as Um}from"react";function Fm(a){return{source:"algorithm",recovered:!1,algo:a.algo,jobId:a.jobId}}function zm(a){return{type:a.type,reason:"converged",durationMs:a.duration}}function Bm(a){return{algo:a.algo,jobId:a.jobId,nodeCount:a.nodeCount,edgeCount:a.edgeCount}}function Om(a){return{algo:a.algo,jobId:a.jobId,durationMs:a.duration}}function Lm(a){return{algo:a.algo,jobId:a.jobId,error:a.error}}function Vm(a){return{algo:a.algo,jobId:a.jobId,progress:a.pct/100}}function Wm(a){let e=Um(a);return Ep(()=>{e.current=a},[a]),e}function Rp(a,e){let t=Wm(e);Ep(()=>{if(!a)return;let r=[];return r.push(a.events.on("destroy",()=>t.current.onDestroy?.())),r.push(a.events.on("algorithm:error",n=>{t.current.onAlgorithmError?.(Lm(n)),t.current.onError?.(n.error,Fm(n))})),r.push(a.events.on("graph:deltaApplied",n=>t.current.onDelta?.(n.delta,n.result))),r.push(a.events.on("layout:start",n=>t.current.onLayoutStart?.(n))),r.push(a.events.on("layout:end",n=>t.current.onLayoutEnd?.(zm(n)))),r.push(a.events.on("layout:tick",n=>t.current.onLayoutProgress?.(n))),r.push(a.events.on("algorithm:start",n=>t.current.onAlgorithmStart?.(Bm(n)))),r.push(a.events.on("algorithm:end",n=>t.current.onAlgorithmEnd?.(Om(n)))),r.push(a.events.on("algorithm:progress",n=>t.current.onAlgorithmProgress?.(Vm(n)))),r.push(a.events.on("history:changed",n=>t.current.onHistoryChange?.(n))),r.push(a.events.on("style:changed",n=>t.current.onStyleChange?.(n))),()=>{for(let n of r)n()}},[a])}import{useEffect as Le,useRef as pt,useState as jm}from"react";var Cp=new Set;function Ri(a,e,t){let r=e!==void 0,[n,i]=jm(t),o=pt(r);return Le(()=>{(typeof globalThis<"u"&&globalThis.process?.env?.NODE_ENV)!=="production"&&o.current!==r&&(Cp.has(`${a}-mode-switch`)||(Cp.add(`${a}-mode-switch`),console.warn(`[render-engine] \`${a}\` switched between controlled and uncontrolled mode. This is usually a bug; pick one and stick with it.`)),o.current=r)},[r,a]),{value:r?e:n,isControlled:r,setUncontrolled:i}}function wp(a,e,t,r){let{value:n,isControlled:i,setUncontrolled:o}=Ri("selection",e,t??{nodes:[],edges:[]}),s=pt(null);Le(()=>{if(!a||!i)return;let l=s.current;l&&l.nodes.length===n.nodes.length&&l.edges.length===n.edges.length&&l.nodes.every((u,c)=>u===n.nodes[c])&&l.edges.every((u,c)=>u===n.edges[c])||(s.current=n,(async()=>(await a.selection.clear(),n.nodes.length>0&&await a.selection.selectNodes(n.nodes,"replace"),n.edges.length>0&&await a.selection.selectEdges(n.edges,"replace")))())},[a,i,n]);let d=pt(r);Le(()=>{d.current=r},[r]),Le(()=>a?a.events.on("selection:changed",u=>{if(i&&u.source==="api")return;let c={nodes:u.nodeIds,edges:u.edgeIds},h=i?e:{nodes:[],edges:[]};d.current?.(c,h),i||o(c)}):void 0,[a,i])}function Tp(a,e,t,r){let{value:n,isControlled:i,setUncontrolled:o}=Ri("hidden",e,t??{nodes:[],edges:[]}),s=async c=>{if(!a)return;let h=new Set(a.store.getHiddenNodeIds()),p=new Set(c.nodes),f=[...p].filter(g=>!h.has(g)),m=[...h].filter(g=>!p.has(g));m.length>0&&await a.nodes.show(m),f.length>0&&await a.nodes.hide(f)},d=pt(!1);Le(()=>{if(!a||i||d.current||(d.current=!0,n.nodes.length===0))return;let c=new Set(a.store.getHiddenNodeIds()),h=n.nodes.filter(p=>!c.has(p));h.length>0&&a.nodes.hide(h)},[a]);let l=pt(null);Le(()=>{if(!a||!i)return;let c=l.current;c&&c.nodes.length===n.nodes.length&&c.nodes.every((h,p)=>h===n.nodes[p])||(l.current=n,s(n))},[a,i,n]);let u=pt(r);Le(()=>{u.current=r},[r]),Le(()=>a?a.events.on("visibility:changed",h=>{let p={nodes:a.store.getHiddenNodeIds(),edges:[]};if(i&&p.nodes.length===n.nodes.length&&p.nodes.every((m,g)=>m===n.nodes[g]))return;let f=i?e:{nodes:[],edges:[]};u.current?.(p,f),i||o(p)}):void 0,[a,i,n])}function Mp(a,e,t,r){let{value:n,isControlled:i,setUncontrolled:o}=Ri("is3D",e,t),s=pt(!1);Le(()=>{if(!a||i||s.current)return;s.current=!0;let l=n?3:2;a.getDimensions()!==l&&a.setDimensions(l)},[a]),Le(()=>{if(!a||!i)return;let l=n?3:2;a.getDimensions()!==l&&a.setDimensions(l)},[a,i,n]);let d=pt(r);Le(()=>{d.current=r},[r]),Le(()=>a?a.events.on("view:changed",u=>{if(u.mode===void 0)return;let c=u.mode==="3D";if(i&&c===n)return;let h=i?e:!c;d.current?.(c,h),i||o(c)}):void 0,[a,i,n])}function Ip(a,e,t,r){let{value:n,isControlled:i,setUncontrolled:o}=Ri("theme",e,t??"dark"),s=pt(!1);Le(()=>{!a||i||s.current||(s.current=!0,a.renderer.setTheme(n))},[a]),Le(()=>{!a||!i||a.renderer.setTheme(n)},[a,i,n]);let d=pt(r);Le(()=>{d.current=r},[r]),Le(()=>a?a.events.on("view:changed",u=>{if(u.theme===void 0)return;let c=u.theme;if(i&&typeof n=="string"&&c===n)return;let h=i?typeof e=="string"?e:"dark":typeof n=="string"?n:"dark";d.current?.(c,h),i||o(c)}):void 0,[a,i,n])}function wc(a,e){return a===e?!0:!(!a||!e||a.cameraZ!==e.cameraZ||a.position[0]!==e.position[0]||a.position[1]!==e.position[1]||a.position[2]!==e.position[2]||!!a.rotation!=!!e.rotation||a.rotation&&e.rotation&&(a.rotation.x!==e.rotation.x||a.rotation.y!==e.rotation.y||a.rotation.z!==e.rotation.z))}function Pp(a,e,t,r){let{value:n,isControlled:i,setUncontrolled:o}=Ri("viewState",e,t??{position:[0,0,-15],cameraZ:.001}),s=t!==void 0,d=pt(!1);Le(()=>{!a||i||d.current||s&&(d.current=!0,a.camera.setViewState(n))},[a]);let l=pt(null);Le(()=>{!a||!i||wc(l.current,n)||(l.current=n,a.camera.setViewState(n))},[a,i,n]);let u=pt(r);Le(()=>{u.current=r},[r]);let c=!!r;Le(()=>{if(!a||!c)return;let h=0,p=a.camera.getViewState(),f=()=>{let m=a.camera.getViewState();m&&p&&!wc(m,p)?(i&&wc(m,l.current)||(u.current?.(m,p),i||o(m)),p=m):m&&!p&&(p=m),h=requestAnimationFrame(f)};return h=requestAnimationFrame(f),()=>cancelAnimationFrame(h)},[a,c,i])}function Ap(a,e,t,r){let{value:n,isControlled:i,setUncontrolled:o}=Ri("pinned",e,t??{nodes:[],edges:[]}),s=async c=>{if(!a)return;let h=new Set(a.store.getPinnedNodeIds()),p=new Set(c.nodes),f=[...p].filter(g=>!h.has(g)),m=[...h].filter(g=>!p.has(g));m.length>0&&await a.nodes.unpin(m),f.length>0&&await a.nodes.pin(f)},d=pt(!1);Le(()=>{!a||i||d.current||(d.current=!0,s(n))},[a]);let l=pt(null);Le(()=>{if(!a||!i)return;let c=l.current;c&&c.nodes.length===n.nodes.length&&c.nodes.every((h,p)=>h===n.nodes[p])||(l.current=n,s(n))},[a,i,n]);let u=pt(r);Le(()=>{u.current=r},[r]),Le(()=>a?a.events.on("pin:changed",h=>{let p={nodes:h.nodeIds,edges:[]};if(i&&p.nodes.length===n.nodes.length&&p.nodes.every((m,g)=>m===n.nodes[g]))return;let f=i?e:{nodes:[],edges:[]};u.current?.(p,f),i||o(p)}):void 0,[a,i,n])}function _p(a,e,t){let r=e!==void 0,n=pt(null);Le(()=>{if(!a||!r)return;let o=e??null;n.current=o,a.hover.set(o)},[a,r,e]);let i=pt(t);Le(()=>{i.current=t},[t]),Le(()=>{if(!a)return;let o={current:null};return a.interaction.hover.onChange(d=>{let l=d.current?.id&&(d.current.type==="node"||d.current.type==="edge")?{kind:d.current.type,id:d.current.id}:null;if(r){let c=n.current;if(((p,f)=>!p&&!f||p&&f&&p.kind===f.kind&&p.id===f.id)(l,c))return}let u=o.current;o.current=l,i.current?.(l,u)})},[a,r])}import Dp from"react";var Or=new Set;function qm(a,e,t,r,n){if(t===void 0&&r===void 0)return n;if(t!==void 0&&r!==void 0&&t!==r){let i=`${a}-vs-${e}`;(typeof globalThis<"u"&&globalThis.process?.env?.NODE_ENV)!=="production"&&!Or.has(i)&&(Or.add(i),console.warn(`[render-engine] Both \`${a}\` and deprecated \`${e}\` props were set with different values. \`${a}\` (=${JSON.stringify(t)}) wins. Remove \`${e}\` to clear this warning.`))}return t!==void 0?t:r}function Tc(a,e){return qm("drag","enableDrag",a,e,!0)}function Mc(a,e){return a==="d3"?"d3":a==="webgl"?"webgl":a==="webgpu"?e?"webgpu":((typeof globalThis<"u"&&globalThis.process?.env?.NODE_ENV)!=="production"&&(Or.has("webgpu-fallback")||(Or.add("webgpu-fallback"),console.warn('[render-engine] forceLayout.engine="webgpu" requested but navigator.gpu is not available. Falling back to "d3" (CPU).'))),"d3"):a==="auto"&&e?"webgpu":"d3"}function Ic(a,e,t){if(typeof a=="object"&&a!==null){if(t&&(typeof globalThis<"u"&&globalThis.process?.env?.NODE_ENV)!=="production"){let r="controls-vs-controlConfig";Or.has(r)||(Or.add(r),console.warn("[render-engine] Both `controls` (object) and deprecated `controlConfig` were set. `controls` wins. Remove `controlConfig` to clear this warning."))}return{enabled:!0,config:a}}if(a!==void 0){if(e!==void 0&&e!==a&&(typeof globalThis<"u"&&globalThis.process?.env?.NODE_ENV)!=="production"){let r="controls-vs-enableControl";Or.has(r)||(Or.add(r),console.warn("[render-engine] Both `controls` and deprecated `enableControl` were set with different values. `controls` wins. Remove `enableControl` to clear this warning."))}return{enabled:a,config:a?t:void 0}}return{enabled:e,config:t}}function Ci(a){if(a!==void 0)return a===!1?!1:a===!0?{}:a}function Pc(a,e){return a!==void 0?a:e?"spherical":"planar"}function Bd(a){let e=!1;return Dp.Children.forEach(a,t=>{if(!Dp.isValidElement(t))return;let r=Ct("flatMap"),n=Ct("globeMap");(r&&t.type===r||n&&t.type===n)&&(e=!0)}),e}import*as Np from"three";function kp(a){let{cloudScene:e,storeRef:t,needsRenderRef:r,renderRuntimeRef:n,nodeRendererRef:i,edgeRendererRef:o,childNodeRendererRef:s,childEdgeRendererRef:d,layoutControllerRef:l,layoutAdapterRef:u,interactionRef:c,iconAtlasManagerRef:h,apiInstanceRef:p,pendingStructureChangeRef:f,forceWasFinishedRef:m,forceStartPositionsRef:g,geoSettleSigRef:y,frameCallbacksRef:v,beforePaintCallbacksRef:b}=a,x=n.current;if(!x)throw new Error("createRenderLoop: RenderRuntime must be created before the render loop");let w=()=>{let R=l.current;return u.current||(R&&"mode"in R?R:null)},T={syncDeps(){let R=i.current||s.current,S=o.current||d.current;x.setNodeRenderer(R),x.setEdgeRenderer(S),x.setInteraction(c.current),x.setLayoutProvider(w()),x.setIconAtlasManager(h.current),x.setCloudScene(e),x.setHasLayoutController(!!l.current),x.setPickerDebugActive(!!c.current?.picker?.debugPicking),f.current&&(f.current=!1,x.markStructureChanged())},collectDirty(){let R=!1,S=p.current?.animations.manager;S&&S.hasActiveEffects&&(S.tick(performance.now()),R=!0);let P=p.current?.animationManager;P&&P.hasActiveTweens&&(P.tick(performance.now()),R=!0);let D=b?.current;if(D)for(let N of D.values())N()&&(R=!0);let E=l.current,M=w();if(E?.tick?.(),E&&E.graph?.renderNeedsUpdate&&(R=!0,u.current?.invalidateMirror?.()),E&&"isFinish"in E&&p.current){let N=!!E.isFinish,A=m.current;if(A!==void 0&&A&&!N){let C=t.current,F=C.positionProvider;if(F){E.readBackPositions&&E.readBackPositions(),M&&typeof M.syncFromLayout=="function"&&M.syncFromLayout();let G=F.getPositions();if(G){let L=new Map;for(let V of C.data.nodes){let B=C.index.nodeIdToIndex.get(V.id);B!==void 0&&L.set(V.id,[G[B*3],G[B*3+1],G[B*3+2]])}g.current=L}}}else if(A!==void 0&&!A&&N){let C=g.current;if(C&&C.size>0){let F=t.current,G=F.positionProvider;if(G){E.readBackPositions&&E.readBackPositions(),M&&typeof M.syncFromLayout=="function"&&M.syncFromLayout();let L=G.getPositions();if(L){let V=new Map;for(let[oe]of C){let Q=F.index.nodeIdToIndex.get(oe);Q!==void 0&&V.set(oe,[L[Q*3],L[Q*3+1],L[Q*3+2]])}let B=new en(F,C,V),K=p.current.history;K.execute(B),K.flush()}}g.current=null}}m.current=N}return r.current&&(r.current=!1,R=!0),R},afterStructureChange(){let R=t.current,S=l.current;if(S?.graph){let P=R.data.nodes,D=R.data.edges,E=R.getAllPositions(),M=new Map;for(let A of S.graph.layoutNodes||[])M.set(A.id,{x:A.position.x,y:A.position.y,z:A.position.z,pinned:A.pinned});S.graph.layoutNodes=P.map(A=>{let C=E.get(A.id),F=C?void 0:M.get(A.id),G=C?C[0]:F?F.x:Math.random()*2-1,L=C?C[1]:F?F.y:Math.random()*2-1,V=C?C[2]:F?F.z:0;return{id:A.id,position:new Np.Vector3(G,L,V),pinned:R.isPinned(A.id),isPositionDirty:!1}}),S.graph.layoutEdges=D.map(A=>({id:A.id,sourceId:A.source,targetId:A.target})),u.current?.onStructureResynced?.(),S.start?.(),y.current=""}},beforeFrameCallbacks(){let R=t.current;{let S=l.current;S&&S.graph&&(S.graph.renderNeedsUpdate=!1)}{let S=p.current?.map;if(!S?.isEnabled?.())y.current="";else{let P=S.getMode(),D=R.data.nodes.length,E=R.positionProvider?.getPositions?.(),M=!!E&&E.length>=D*3&&D>0&&(E[0]!==0||E[1]!==0||E[2]!==0),N=`${D}|${P}`;M&&P&&N!==y.current&&(y.current=N,S.reassertGeoLayout(P))}}},afterPaint(){c.current?.picker?.debugPicking&&c.current.picker.renderDebugToScreen()},afterSettle(){r.current=!1}};x.setHostFrameCallbacks(v.current),x.setHost(T);let I={request:R=>requestAnimationFrame(R),cancel:R=>cancelAnimationFrame(R)};return{start(){x.start(I)},stop(){x.stop()}}}function Gp(a){let{apiInstanceRef:e,storeRef:t,interactionRef:r,renderRuntimeRef:n,needsRenderRef:i,apiOptions:o,is3DProp:s,defaultDim:d,resolvedTheme:l,is3D:u}=a;if(!e.current&&t.current){let c=s===!1?2:s===!0?3:d===2?2:3;e.current=new gd(t.current,r.current??null,{...o,initialDimensions:c,hoverEmphasis:()=>n.current?.hoverEmphasis??null}),e.current.animations.manager.setInvalidateCallback(()=>{i.current=!0}),e.current.animationManager.setInvalidateCallback(()=>{i.current=!0});let h=l.isDark?"dark":"light";e.current.renderer.setTheme(h),e.current.map.wireIs3D(u)}return e.current}function Hp(a,e,t,r,n){a.current&&(a.current.wireInteraction(t),e.current.positionProvider&&a.current.wireLayoutRuntime(e.current.positionProvider),a.current.map.wireScene(r,n),a.current.debug.wireScene(n))}import*as Fp from"three";function zp(a){let{container:e,containerProp:t,style:r,antialias:n,pixelRatio:i,effectiveBackground:o,effectiveCameraZ:s,sceneRef:d,cameraRef:l,storeRef:u,cloudSceneRef:c,rendererRef:h}=a,p=new Fp.WebGLRenderer({antialias:n,alpha:!0,preserveDrawingBuffer:!0});p.setSize(e.clientWidth,e.clientHeight),p.setPixelRatio(i??window.devicePixelRatio),p.setClearColor(o,1),p.autoClear=!0,window.__THREE_SCENE__=d.current,window.__THREE_RENDERER__=p,window.__THREE_CAMERA__=l.current,window.__GRAPH_STORE__=u.current;let f=d.current,m=l.current,g=u.current;(!e.style.position||e.style.position==="static")&&(e.style.position="relative"),t==null&&r!=null&&(r.background!=null||r.backgroundColor!=null)||(e.style.backgroundColor="#"+o.toString(16).padStart(6,"0"));let v=p.domElement;v.style.position="absolute",v.style.top="0",v.style.left="0",v.style.width="100%",v.style.height="100%",e.appendChild(v),h.current=p;let b=c.current;b.name="cloudScene",d.current.add(b);let x=l.current;return x.aspect=e.clientWidth/e.clientHeight,x.position.z=s,x.updateProjectionMatrix(),{renderer:p,cloudScene:b,camera:x,dispose:T=>{p.dispose(),e.removeChild(p.domElement);let I=window;I.__THREE_SCENE__===f&&delete I.__THREE_SCENE__,I.__THREE_RENDERER__===p&&delete I.__THREE_RENDERER__,I.__THREE_CAMERA__===m&&delete I.__THREE_CAMERA__,I.__GRAPH_STORE__===g&&delete I.__GRAPH_STORE__,I.__INTERACTION__===T&&delete I.__INTERACTION__}}}import*as Op from"three";var Od=class{constructor(e,t={}){this._store=e;this._config=t;this._state={active:!1,nodeIds:[],categories:[],selectedCategory:null,loading:!1};this._listeners=new Set;this._api=null;this._flowsApi=null}setEngineApi(e){this._api=e,this._flowsApi=e.flows}setFlowsApi(e){this._flowsApi=e}get state(){return this._state}get isActive(){return this._state.active}onChange(e){return this._listeners.add(e),()=>this._listeners.delete(e)}_notify(){for(let e of this._listeners)try{e()}catch(t){console.error("[ChangeCategoryFlow] listener error:",t)}}async start(e){if(!this._flowsApi?.hasCallback("onResolveCategories")){console.warn("[ChangeCategoryFlow] onResolveCategories callback not registered; cannot start");return}if(e.nodeIds.length!==0){this._state.active&&this.cancel(),this._state={active:!0,nodeIds:[...e.nodeIds],categories:[],selectedCategory:null,loading:!0},this._notify();try{let t=await this._flowsApi.callbacks.onResolveCategories();this._state={...this._state,categories:t,loading:!1},this._notify()}catch(t){console.error("[ChangeCategoryFlow] failed to load categories:",t),this.cancel()}}}selectCategory(e){this._state.active&&(this._state={...this._state,selectedCategory:e},this._notify())}async confirm(){if(!this._state.active||!this._state.selectedCategory)return;if(!this._api){console.warn("[ChangeCategoryFlow] engine api not set; cannot execute command");return}let{nodeIds:e,selectedCategory:t}=this._state;this._api.history.beginTransaction(`Change Category to ${t}`);try{for(let r of e)this._api.history.execute(new Fs(this._store,r,t))}finally{this._api.history.endTransaction()}this.cancel()}cancel(){this._state={active:!1,nodeIds:[],categories:[],selectedCategory:null,loading:!1},this._notify()}dispose(){this.cancel(),this._listeners.clear()}};function Bp(a){let e=()=>{if(a.target.state!=="ready")return null;let t=a.getSize();return t.width<=0||t.height<=0?null:t};return{pathId:"webgpu",orientation:"top-left",canReadSync:!1,getTargetSize:e,readSync(){return null},async readAsync(t,r){if(t==="edge"&&!a.target.hasEdgePicking?.())return null;let n=e();if(!n)return null;let i=Ts(r,n);if(!i)return null;let o=es(),s=await a.target.readPickPixels(i,n,t==="edge"?"edge":"node");return ts("picking",o),s?{data:rs(s,{width:i.width,height:i.height,bytesPerPixel:4,bytesPerRow:Su(i.width,4),orientation:"top-left"}),width:i.width,height:i.height}:null},dispose(){}}}function Lp(a){let{renderer:e,camera:t,cloudScene:r,container:n,effectiveControlConfig:i,effectiveEnableControl:o,is3DProp:s,enableDragEffective:d,apiInstanceRef:l,needsRenderRef:u,controlRef:c,storeRef:h,interactionRef:p,renderRuntimeRef:f,changeCategoryFlowRef:m,contextMenuManagerRef:g,cameraRef:y,nodeRendererRef:v,edgeRendererRef:b,webgpuTarget:x,pixelRatio:w,setCreatePanelAllowedRels:T,setEdgeCreateResult:I}=a,R=new vi(t,r,n,{...i,onPitchDelta:D=>{let E=l.current;E&&E.map.setPitch(E.map.getPitch()+D)}});R.setCanvas(e.domElement),R.onChange(()=>{u.current=!0}),c.current=R,R.setPivotProvider?.(()=>{let D=h.current,E=D.getSelectedNodeIds();if(E.length===0)return null;let M=D.positionProvider?.getPositions();if(!M)return null;let N=0,A=0,C=0,F=0;for(let G of E){let L=D.index.getNodeIndex(G);L!==void 0&&(N+=M[L*3],A+=M[L*3+1],C+=M[L*3+2],F++)}return F===0?null:{x:N/F,y:A/F,z:C/F}}),R.setEnablePan(o),R.setEnableZoom(o),R.setEnableRotate(o&&s),s||R.resetRotation(!1);let S=null;if(d){S=new Md(e,t,h.current,n,{drag:{enabled:!0,pinAfterDrag:!0}}),S.setCloudScene(r),R&&S.setGraphControl(R),S.setRequestRender(()=>{u.current=!0}),S.edgeCreate?.setRenderer(e),S.onEdgeCreate(M=>{T(void 0),I(M)});let D=new Od(h.current);if(l.current&&D.setEngineApi(l.current),m.current=D,S.onContextMenu((M,N)=>{let A=h.current,C=S.selection;if(M.type==="node"&&M.picked){let G=M.nodeId;C.isNodeSelected(G)||(C.handleNodeClick(G,{ctrlKey:!1,altKey:!1,shiftKey:!1}),u.current=!0)}else if(M.type==="edge"&&M.picked){let G=M.edgeId;C.isEdgeSelected(G)||(C.handleEdgeClick(G,{ctrlKey:!1,altKey:!1,shiftKey:!1}),u.current=!0)}let F=g.current;if(F){let G=M.ndcPosition,L=y.current,V=new Op.Vector3(G.x,G.y,.5).unproject(L),B={x:V.x,y:V.y,z:V.z},K=l.current,oe=(()=>{if(!K)return;let Q=K.map?.getMode?.();return Q==="spherical"?"globe":Q==="planar"?"map":K.renderer?.getMode?.()==="3D"?"3d":"2d"})();F.show({type:M.type,nodeId:M.type==="node"?M.nodeId:void 0,edgeId:M.type==="edge"?M.edgeId:void 0,selectedNodeIds:Array.from(C.selectedNodeIds),selectedEdgeIds:Array.from(C.selectedEdgeIds),screenPosition:M.screenPosition,store:A,engine:K??void 0,interaction:S??void 0,worldPos:B,mode:oe})}}),R){let M=e.domElement,N=C=>{if(C.button!==0)return;let F=n.getBoundingClientRect(),G=C.clientX-F.left,L=C.clientY-F.top,V=S.pick(G,L);(V.type==="node"||V.type==="edge")&&V.picked&&(R.enabled=!1)},A=()=>{R.enabled=!0};M.addEventListener("mousedown",N,{capture:!0}),M.addEventListener("mouseup",A,{capture:!0}),M.addEventListener("mouseleave",A,{capture:!0}),S._captureMouseDown=N,S._captureMouseUp=A,S._captureCanvas=M}let E=M=>{let N=h.current.positionProvider;if(!N)return;let A=v.current;if(A?.cpuPositionTexture){let C=N.getPositions();if(C){let F=A.cpuPositionTexture.image.data;for(let G of M)F[G*4]=C[G*3],F[G*4+1]=C[G*3+1],F[G*4+2]=C[G*3+2];A.cpuPositionTexture.needsUpdate=!0,u.current=!0}return}u.current=!0};if(S.drag.setOnPositionsWritten(E),S.edgeCreate?.attachOverlay(r),R?.onChange(()=>{let M=b.current?.getMesh()??void 0;S.syncTransforms(r,M),S.setCamera(t)}),R?.onChange(()=>{S.syncTransforms(r,b.current?.getMesh()??void 0)}),R?.onChange(()=>{S.syncTransforms(r)}),p.current=S,window.__INTERACTION__=S,f.current?.hoverEmphasis&&(S.hover.setHoverEmphasis(f.current.hoverEmphasis),S.coordinator?.setHoverEmphasis(f.current.hoverEmphasis)),x){let M=w??window.devicePixelRatio;S.picker.setPickingBackend("webgpu",Bp({target:x,getSize:()=>({width:Math.round(n.clientWidth*M),height:Math.round(n.clientHeight*M)})}))}S.picker.setActivePathId(()=>f.current?.getActivePathId()??"webgl"),Hp(l,h,S,r,t)}return{control:R,interaction:S,disposeInteraction:()=>{if(S?._captureCanvas){let D=S._captureCanvas;D.removeEventListener("mousedown",S._captureMouseDown,{capture:!0}),D.removeEventListener("mouseup",S._captureMouseUp,{capture:!0}),D.removeEventListener("mouseleave",S._captureMouseUp,{capture:!0})}m.current?.dispose(),m.current=null,S?.dispose(),p.current=null,l.current&&l.current.wireInteraction(null)}}}function Vp(a){let{storeRef:e,layoutControllerRef:t,pendingStructureChangeRef:r,needsRenderRef:n,renderRuntimeRef:i}=a;if(e.current.positionProvider)!t.current&&!e.current.onStructureChange&&(e.current.onStructureChange=()=>{r.current=!0,n.current=!0,i.current?.markStructureChanged()});else{let o=Math.max(e.current.nodeCount,64),s=new mn(o),d=e.current;s.setIndexBridge({getNodeIndex:l=>d.index.getNodeIndex(l),getNodeCount:()=>d.nodeCount,get structureEpoch(){return d.structureEpoch}}),e.current.setPositionProvider(s),e.current.onStructureChange=()=>{let l=e.current.positionProvider;if(l&&l instanceof mn){let u=e.current.nodeCount,c=l.getPositions().length/3;u>c&&l.resize(u*2)}r.current=!0,n.current=!0,i.current?.markStructureChanged()}}}function Up(a){let{renderer:e,camera:t,cloudScene:r,container:n,control:i,interaction:o,viewState:s,storeRef:d,sceneRef:l,apiInstanceRef:u,needsRenderRef:c,renderRuntimeRef:h,nodeRendererRef:p,edgeRendererRef:f,childNodeRendererRef:m,childEdgeRendererRef:g,layoutControllerRef:y,frameCallbacksRef:v,mapModeCallbacksRef:b,mapMaxGrowthCallbacksRef:x,mapDampingRef:w,mapSphereRadiusRef:T,setIsMapMode:I,setIs3DState:R,getRenderBackend:S,getActiveRenderPathId:P}=a;return{_viewState:s,store:d.current,scene:l.current,cloudScene:r,renderer:e,camera:t,control:i,interaction:o,api:u.current,container:n,get renderBackend(){return S()},get activeRenderPathId(){return P()},invalidate:()=>{c.current=!0,h.current?.invalidate()},registerNodeRenderer:E=>{m.current=E,h.current?.setNodeRenderer(E)},registerEdgeRenderer:E=>{g.current=E,h.current?.setEdgeRenderer(E)},registerTextCloud:(E,M)=>{E==="node"?h.current?.setNodeTextCloud(M):h.current?.setEdgeTextCloud(M)},registerFrameCallback:(E,M)=>{M?v.current.set(E,M):v.current.delete(E)},getNodePositionTexture:()=>{let E=d.current.positionProvider;if(E?.mode==="gpu"){let A=E.getPositionTexture();return A?{texture:A,textureSize:E.getTextureSize()}:null}let N=(p.current||m.current)?.getCpuPositionTextureInfo()??null;return N?{texture:N.texture,textureSize:N.textureSize}:null},registerMapModeCallback:(E,M)=>{M?b.current.set(E,M):b.current.delete(E)},get isMapMode(){return s.getSnapshot().isMapMode},get mapDamping(){return s.getSnapshot().mapDamping},get mapSphereRadius(){return s.getSnapshot().mapSphereRadius},get iconAtlasManager(){return s.getSnapshot().iconAtlasManager},get imageAtlasManager(){return s.getSnapshot().imageAtlasManager},get glyphAtlasManager(){return s.getSnapshot().glyphAtlasManager},get theme(){return s.getSnapshot().theme},get textScale(){return s.getSnapshot().textScale},get edgeTextScale(){return s.getSnapshot().edgeTextScale},get layoutController(){return s.getSnapshot().layoutController},get layoutPositionProvider(){return s.getSnapshot().layoutPositionProvider},setMapMode:(E,M,N)=>{let A=p.current||m.current,C=f.current||g.current;A?.setMapMode(E,M,N),n&&(A?.setResolution(n.clientWidth,n.clientHeight),C?.setResolution(n.clientWidth,n.clientHeight)),C?.setMapMode(E,M,N),C?.setSphereRadius(M??0),o?.picker?.setMapMode(E,M,N),i?.setMapMode(E),o&&!E&&(o.drag.enabled=!0),b.current.forEach(F=>F(E,M,N)),w.current=N??.3,T.current=E&&M?M:0,s.patch({mapDamping:N??.3,mapSphereRadius:E&&M?M:0}),I(E)},setMapMaxGrowth:E=>{let M=p.current||m.current,N=f.current||g.current;M?.setMapMaxGrowth?.(E),N?.setMapMaxGrowth?.(E),o?.picker?.setMapMaxGrowth?.(E),x.current.forEach(A=>A(E))},setMaxScreenFraction:E=>{let M=p.current||m.current,N=f.current||g.current;M?.setMaxScreenFraction?.(E),N?.setMaxScreenFraction?.(E),o?.picker?.setMaxScreenFraction?.(E)},setNodeSizeScale:E=>{d.current.setGlobalNodeSizeScale(E);let M=p.current||m.current,N=f.current||g.current;M?.setNodeSizeScale?.(E),N?.setNodeSizeScale?.(E),o?.picker?.setNodeSizeScale?.(E),c.current=!0,h.current?.invalidate()},registerMapMaxGrowthCallback:(E,M)=>{M?x.current.set(E,M):x.current.delete(E)},setMapDamping:E=>{let M=p.current||m.current,N=f.current||g.current;if(M){let A=M.material;A?.uniforms?.mapDamping&&(A.uniforms.mapDamping.value=E)}if(N){let A=N.material;A?.uniforms?.mapDamping&&(A.uniforms.mapDamping.value=E);let C=N.arrowMaterial;C?.uniforms?.mapDamping&&(C.uniforms.mapDamping.value=E)}b.current.forEach(A=>A(s.getSnapshot().isMapMode,T.current,E)),w.current=E,s.patch({mapDamping:E}),c.current=!0},get is3D(){return s.getSnapshot().is3D},get effectiveMapProjection(){return s.getSnapshot().effectiveMapProjection},setIs3D:E=>{R(E),i&&(i.setEnableRotate(E),E||i.resetRotation(!0,400));let M=E?3:2,N=u.current;if(N&&typeof N.setDimensions=="function")N.setDimensions(M);else{let C=y.current;C&&typeof C.transitionDimensions=="function"&&(typeof C.getDimensions!="function"||C.getDimensions()!==M)&&C.transitionDimensions(M)}let A=f.current||g.current;A&&typeof A.set3DMode=="function"&&A.set3DMode(E)}}}function Wp(a){let{container:e,renderer:t,camera:r,sceneRef:n,needsRenderRef:i,nodeRendererRef:o,edgeRendererRef:s,childNodeRendererRef:d,childEdgeRendererRef:l,renderRuntimeRef:u}=a,c=0,h=0,p=()=>{let m=e.clientWidth,g=e.clientHeight;if(m===0||g===0||m===c&&g===h)return;if(c=m,h=g,t.setSize(m,g),u.current?.resizeTargets(m,g),r.aspect=m/g,r.updateProjectionMatrix(),(o.current||d.current)?.setResolution(m,g),(s.current||l.current)?.setResolution(m,g),i.current=!0,n.current&&r)try{t.render(n.current,r)}catch{}},f=new ResizeObserver(p);return f.observe(e),{dispose:()=>{f.disconnect()}}}function jp(a){return{pathId:"webgl",isReady:()=>!0,render(){a.renderer.render(a.getScene(),a.camera)},getDrawCallSource:()=>a.renderer,setVisible(){},setSize(){},setPixelRatio(){},setClearColor(){},dispose(){}}}import*as Vd from"three";function qp(){return import("three/webgpu").then(a=>a)}function Kp(){return import("three/tsl").then(a=>a)}import*as gt from"three";function Ld(a){let e=a,{vec2:t,float:r,select:n,length:i,max:o,min:s,abs:d,dot:l,clamp:u,sign:c,floor:h,mod:p,Fn:f,Loop:m,If:g}=e,y=(P,D)=>{let E=d(P).sub(D);return i(o(E,0)).add(s(o(E.x,E.y),0))},v=P=>{let D=t(.809016994375,-.587785252292),E=t(-.809016994375,-.587785252292),M=t(d(P.x),P.y);M=M.sub(D.mul(o(l(D,M),0).mul(2))),M=M.sub(E.mul(o(l(E,M),0).mul(2))),M=t(d(M.x),M.y.sub(.5));let N=t(D.y.negate(),D.x).mul(.5).sub(t(0,1)),A=u(l(M,N).div(l(N,N)),0,.5);return i(M.sub(N.mul(A))).mul(c(M.y.mul(N.x).sub(M.x.mul(N.y))))},b=P=>{let D=d(P),E=P.x.mul(-.894427191).add(P.y.mul(.4472135955)).sub(.2236067977),M=P.x.mul(.894427191).add(P.y.mul(.4472135955)).sub(.2236067977);return{circle:i(P).sub(.5),box:y(P,t(.5,.5)),round:y(P,t(.32,.32)).sub(.18),diamond:d(P.x).add(d(P.y)).sub(.5).mul(.70710678118),triangle:o(o(E,M),P.y.negate().sub(.5)),hexagon:o(D.y,D.x.mul(.86602540378).add(D.y.mul(.5))).sub(.43301270189),star:v(P)}},x=(P,D)=>{let E=b(D);return n(P.lessThan(.5),E.circle,n(P.lessThan(1.5),E.box,n(P.lessThan(2.5),E.round,n(P.lessThan(3.5),E.diamond,n(P.lessThan(4.5),E.triangle,n(P.lessThan(5.5),E.hexagon,n(P.lessThan(6.5),E.star,E.circle)))))))},w=(P,D)=>{let E=b(D),M=d(i(D).sub(.4)).sub(.1);return n(P.lessThan(.5),E.circle,n(P.lessThan(1.5),E.box,n(P.lessThan(2.5),E.round,n(P.lessThan(3.5),E.diamond,n(P.lessThan(4.5),E.triangle,n(P.lessThan(5.5),E.hexagon,n(P.lessThan(6.5),E.star,n(P.lessThan(7.5),M,E.circle))))))))},T=P=>p(P,16),I=P=>{let D=h(P.div(16));return n(D.greaterThan(.5),D.div(1024),r(1))},R=P=>T(P).lessThan(.5).and(d(I(P).sub(1)).lessThan(1e-4)),S=f(([P,D,E])=>{let M=h(T(P).add(.5)).toVar(),N=I(P),A=t(E.x,E.y.mul(N)).toVar(),C=r(0).toVar(),F=r(.7072).div(i(A)).toVar();return m(14,()=>{let G=C.add(F).mul(.5).toVar();g(x(M,A.mul(G)).lessThan(0),()=>{C.assign(G)}).Else(()=>{F.assign(G)})}),D.mul(.5).mul(C.add(F)).mul(2)});return{isPlain:R,clippedDiameter(P,D,E){return n(R(P),D,S(P,D,E))},fillDistance(P,D){return n(P.lessThan(.5),i(D),r(.5).add(w(h(P.add(.5)),D)))}}}function Km(){let a=new Float32Array([-.5,-.5,.5,-.5,.5,.5,-.5,.5]),e=new Float32Array(8);for(let t=0;t<4;t++)e[t*2]=a[t*2]+.5,e[t*2+1]=.5-a[t*2+1];return{corner:a,uv:e,index:[0,1,2,0,2,3]}}function $p(a){let{tsl:e,three:t}=a,r=Km(),n=new gt.InstancedBufferGeometry;n.setAttribute("position",new gt.Float32BufferAttribute(new Float32Array(12),3)),n.setAttribute("corner",new gt.Float32BufferAttribute(r.corner,2)),n.setAttribute("uv",new gt.Float32BufferAttribute(r.uv,2)),n.setIndex(r.index),n.instanceCount=0;let i=e.uniform(a.getNodeSizeScale()),o=e.uniform(new gt.Vector2(1,1)),s=Ld(e),d=e.uniform(1),l=e.attribute("iPos","vec4"),u=e.vec3(l.x,l.y,l.z.mul(d)),c=e.attribute("iSize","float"),h=e.attribute("corner","vec2"),p=e.modelViewMatrix.mul(e.vec4(u,1)),f=e.max(p.z.negate(),e.float(.001)),m=e.clamp(c.mul(i).mul(e.float(50).div(f)),1.5,4096),g=e.cameraProjectionMatrix.mul(p),y=e.attribute("iAspect","float"),v=e.select(y.greaterThan(0),y,e.float(1)),b=e.vec2(h.x,h.y.div(v)).mul(m).div(o).mul(2).mul(g.w),x=e.vec4(g.xy.add(b),g.z,g.w),w=e.uv().sub(.5),T=s.fillDistance(e.attribute("iShape","float"),e.vec2(w.x,w.y.negate())),I=e.smoothstep(.5,.48,T),R=new t.MeshBasicNodeMaterial;R.vertexNode=x,R.colorNode=e.attribute("iColor","vec3"),R.opacityNode=I,R.transparent=!0,R.depthWrite=!1,R.depthTest=!0;let S=new t.MeshBasicNodeMaterial;S.vertexNode=x,S.colorNode=e.attribute("iPickColor","vec3"),S.opacityNode=I,S.alphaTest=.5,S.transparent=!1,S.depthWrite=!0;let P=new gt.Mesh(n,R),D=new gt.Mesh(n,S);P.frustumCulled=!1,D.frustumCulled=!1;let E=null,M=!1,N=3,A=(oe,Q)=>{let $=E.array;for(let z=0;z<Q;z++)$[z*4]=oe[z*3],$[z*4+1]=oe[z*3+1],$[z*4+2]=oe[z*3+2]},C=null,F=-1,G=NaN,L=NaN,V=!1,B=(oe,Q,$)=>{let z=oe.nodeState;M=!1,E=new gt.InstancedBufferAttribute(new Float32Array(Math.max(1,$)*4),4),A(Q,$),n.setAttribute("iPos",E),z&&(n.setAttribute("iColor",new gt.InstancedBufferAttribute(z.colors,3)),n.setAttribute("iSize",new gt.InstancedBufferAttribute(z.effectiveSizes,1)),n.setAttribute("iShape",new gt.InstancedBufferAttribute(z.shapeIds,1)),n.setAttribute("iAspect",new gt.InstancedBufferAttribute(z.aspects,1)));let W=new Float32Array($*3);for(let te=0;te<$;te++){let[Ne,Pe,Ve]=ti(te,"node");W[te*3]=Ne,W[te*3+1]=Pe,W[te*3+2]=Ve}n.setAttribute("iPickColor",new gt.InstancedBufferAttribute(W,3)),n.instanceCount=$,delete n._maxInstanceCount,C=Q,F=$},K=(oe,Q)=>{if(M=!1,!oe||!E||oe.source.nodeCount<Q)return!1;let $=oe.bufferOf(E);return!$||$.size<Q*16?!1:(oe.encoder.copyBufferToBuffer(oe.source.buffer,0,$,0,Q*16),M=!0,N=oe.source.dimensions,!0)};return{displayObject:P,pickObject:D,sync(oe){if(V)return!1;let Q=a.getStore();if(!Q)return!1;let $=a.getPositions();if(!$)return!1;let z=Math.min(Q.nodeCount,Math.floor($.length/3));if(z<=0)return n.instanceCount=0,C=null,F=0,!1;let W=Q.nodeState,te=et=>n.getAttribute(et)?.array,Ne=!!W&&(te("iColor")!==W.colors||te("iSize")!==W.effectiveSizes||te("iShape")!==W.shapeIds||te("iAspect")!==W.aspects),Pe=a.getPositionsVersion?.()??NaN,Ve=a.getStyleVersion?.()??NaN;if($!==C||z!==F||Ne)B(Q,$,z);else if(Pe!==G&&!K(oe,z)&&(A($,z),E.needsUpdate=!0),Ve!==L)for(let et of["iColor","iSize","iShape","iAspect"]){let Bt=n.getAttribute(et);Bt&&(Bt.needsUpdate=!0)}G=Pe,L=Ve,d.value=M&&N===2?0:1;let Oe=a.getCloudTransform();for(let et of[P,D])Oe?(et.position.copy(Oe.position),et.quaternion.copy(Oe.quaternion),et.scale.copy(Oe.scale)):(et.position.set(0,0,0),et.quaternion.identity(),et.scale.set(1,1,1));i.value=a.getNodeSizeScale();let st=a.getResolution();return o.value.set(Math.max(1,st.width),Math.max(1,st.height)),M},dispose(){V||(V=!0,P.removeFromParent(),D.removeFromParent(),n.dispose(),R.dispose(),S.dispose())}}}import*as J from"three";function Zp(a){let e=a.tsl,{attribute:t,uniform:r,texture:n,vec2:i,vec3:o,vec4:s,float:d,select:l,normalize:u,cross:c,dot:h,length:p,mix:f,clamp:m,min:g,max:y,abs:v,cos:b,sin:x,smoothstep:w,fwidth:T,varying:I,Discard:R,Fn:S,floor:P,cameraProjectionMatrix:D,modelViewMatrix:E,positionLocal:M}=e,N=r(new J.Vector2(1,1)),A=r(a.getLineWidth()*.05),C=r(a.getArrowsEnabled()?1:0),F=r(a.getDefaultEdgeShape()),G=r(a.getFixedSize()?1:0),L=0,V=null,B=null,K=n(new J.DataTexture(new Float32Array(4),1,1,J.RGBAFormat,J.FloatType)),oe=r(1),Q=NaN,$=null,z=j=>Math.ceil(Math.ceil(Math.sqrt(Math.max(1,j)))/16)*16,W=r(1),te=!1,Ne=j=>{let U=z(j);V&&U===L||(V?.dispose(),L=U,B=new Float32Array(U*U*4),V=new J.DataTexture(B,U,U,J.RGBAFormat,J.FloatType),V.minFilter=J.NearestFilter,V.magFilter=J.NearestFilter,V.generateMipmaps=!1,V.needsUpdate=!0,K.value=V,oe.value=U)},Pe=3,Ve=(j,U)=>{if(!j||!V||U<=0||j.source.nodeCount<U)return!1;let ge=j.textureOf(V);if(!ge)return!1;let ce=L*16,X=Math.floor(U/L),Me=U-X*L;return X>0&&j.encoder.copyBufferToTexture({buffer:j.source.buffer,offset:0,bytesPerRow:ce,rowsPerImage:X},{texture:ge},{width:L,height:X,depthOrArrayLayers:1}),Me>0&&j.encoder.copyBufferToTexture({buffer:j.source.buffer,offset:X*ce,bytesPerRow:ce,rowsPerImage:1},{texture:ge,origin:{x:0,y:X,z:0}},{width:Me,height:1,depthOrArrayLayers:1}),Pe=j.source.dimensions,!0},Oe=t("iA","vec4"),st=t("iB","vec4"),et=t("iC","vec4"),Bt=t("iD","vec4"),Lr=t("side","float"),Wd=t("along","float"),Mo=Oe.x,Io=Oe.y,Po=Oe.z,Mi=Oe.w,Ao=st.xyz,_o=st.w,Dn=et.xyz,Nn=j=>{let U=P(j.div(oe)),ge=j.sub(U.mul(oe)),ce=K.sample(i(ge.add(.5),U.add(.5)).div(oe)).level(0);return o(ce.x,ce.y,ce.z.mul(W))},Do=N.x.div(N.y),Ii=j=>i(j.x.div(j.w).mul(Do),j.y.div(j.w)),Pi=(j,U,ge,ce)=>{let X=d(1).sub(ce);return j.mul(X.mul(X)).add(U.mul(X.mul(ce).mul(2))).add(ge.mul(ce.mul(ce)))},No=Ld(a.tsl),ko=(j,U,ge,ce,X,Me)=>{let Ge=D.mul(E.mul(s(j,1))),Ae=D.mul(E.mul(s(U,1))),Ce=Ae.xy.div(Ae.w).sub(Ge.xy.div(Ge.w)).mul(N).mul(.5),re=p(Ce),ue=l(re.greaterThan(1e-4),Ce.div(re),i(1,0));return{srcPixDiam:No.clippedDiameter(X,ge,ue),tgtPixDiam:No.clippedDiameter(Me,ce,ue.negate())}},Go=j=>{let U=Nn(Mo),ge=Nn(Io),ce=ge.sub(U),X=p(ce),Me=l(X.greaterThan(1e-9),ce.div(X),o(0,1,0)),Ge=Dn.x,Ae=Dn.y,Ce=v(E.mul(s(U,1)).z),re=v(E.mul(s(ge,1)).z),ue=D.element(1).y,le=g(Bt.x.mul(50).div(Ce),4096),Te=g(Bt.y.mul(50).div(re),4096),{srcPixDiam:xe,tgtPixDiam:fe}=ko(U,ge,le,Te,Bt.z,Bt.w),Dt=xe.mul(Ce).div(ue.mul(N.y)).mul(.96),Et=fe.mul(re).div(ue.mul(N.y)).mul(.96),Zt=Dt.add(Et),Yt=l(Zt.greaterThan(X.mul(.9)),X.mul(.9).div(Zt),d(1));Dt=Dt.mul(Yt),Et=Et.mul(Yt);let sn=Te.mul(re).div(ue.mul(N.y)).mul(.96).mul(Yt),Ur=l(C.greaterThan(.5),l(G.greaterThan(.5),sn.mul(4*.035*4),d(4*.035*.3)),d(0)),It=l(Dn.z.greaterThanEqual(0),Dn.z,F),or=U.add(Me.mul(Dt)),ut=ge.sub(Me.mul(Et)),ft=l(It.greaterThan(.5).and(It.lessThan(1.5)).and(v(Ge).lessThan(.001)),d(.15),Ge),zn=ut.sub(or),Xt=It.lessThan(2.5).and(It.greaterThan(.5).or(v(ft).greaterThan(.001))),an=l(v(Me.z).lessThan(.99),o(0,0,1),o(1,0,0)),sr=u(c(Me,an)),rt=b(Ae),Bn=x(Ae),Vt=sr.mul(rt).add(c(Me,sr).mul(Bn)).add(Me.mul(h(Me,sr)).mul(d(1).sub(rt))),Rr=l(v(Ae).greaterThan(.001),Vt,sr),Ye=or.add(ut).mul(.5).add(Rr.mul(ft.mul(X))),dn=p(zn),On=l(Xt,p(ut.sub(Ye)).mul(2),dn),ln=l(On.greaterThan(.001),m(d(1).sub(Ur.div(On)),.001,1),d(1)),Wr=Wd.mul(ln),ar=d(.85),Di=Pi(or,Ye,ut,ar),Ut=jr=>{let jo=l(jr.greaterThan(ar),f(Di,ut,jr.sub(ar).div(d(1).sub(ar))),Pi(or,Ye,ut,jr));return l(Xt,jo,f(or,ut,jr))},cn=D.mul(E),dr=jr=>cn.mul(s(Ut(jr),1)),Ln=y(d(0),Wr.sub(.01)),lr=g(ln,Wr.add(.01)),Cr=dr(Wr),Qt=Ii(Cr),wr=Ii(dr(Ln)),Tr=Ii(dr(lr)),Vn=j?y(Po.mul(A).mul(2),.03):Po.mul(A).add(l(_o.greaterThan(.5),A.mul(2),d(0))),vt=Cr.w,cr=l(G.greaterThan(.5),vt.mul(Vn).mul(1.8*.15),Vn.mul(1.8*.16)),Un=d(.25).mul(cr).mul(N.y).div(y(vt,1e-6)),Wn=y(Un,d(.5)),Xe=m(Un.div(Wn),0,1),Ue=Wn.mul(4).mul(vt).div(N.y),Qe=1e-6,Ni=p(Tr.sub(Qt)).lessThan(Qe),Mr=p(wr.sub(Qt)).lessThan(Qe),k=l(Ni,u(Qt.sub(wr)),l(Mr,u(Tr.sub(Qt)),u(u(Qt.sub(wr)).add(u(Tr.sub(Qt)))))),Zd=i(k.y.negate().div(Do),k.x).mul(d(.5).mul(Ue)),Yd=Cr.xy.add(Zd.mul(Lr)),Wo=s(Yd,Cr.z,Cr.w),ki=Mo.equal(Io);return{position:l(ki,s(2,2,2,1),Wo),coreEdge:Xe}},Ho=Go(!1),jd=Go(!0),qd=Ho.position,Fo=I(Ho.coreEdge,"vCoreEdge"),Kd=S(()=>{R(Mi.lessThan(.01));let j=T(Lr),U=d(1).sub(w(Fo.sub(j),Fo.add(j),v(Lr))),ge=Mi.mul(Mi).mul(U),ce=Ao.mul(1.2).add(o(0,.2,.5).mul(.3)),X=l(_o.greaterThan(.5),ce,Ao).mul(ge);return R(ge.lessThan(.01)),s(X,ge)}),lt=new a.three.MeshBasicNodeMaterial;lt.vertexNode=qd,lt.fragmentNode=Kd(),lt.transparent=!0,lt.depthWrite=!1,lt.depthTest=!0,lt.side=J.DoubleSide,lt.forceSinglePass=!0,lt.premultipliedAlpha=!1,lt.blending=J.CustomBlending,lt.blendEquation=J.AddEquation,lt.blendSrc=J.OneFactor,lt.blendDst=J.OneMinusSrcAlphaFactor,lt.blendSrcAlpha=J.OneFactor,lt.blendDstAlpha=J.OneMinusSrcAlphaFactor;let Ai=new J.InstancedBufferGeometry;Ai.setAttribute("position",new J.Float32BufferAttribute(new Float32Array(9),3)),Ai.instanceCount=0;let zo=(j,U,ge,ce=16)=>{let X=new J.InstancedBufferGeometry,Me=null,Ge=null,Ae=null,Ce="";return{own:X,sync(re){if(re!==Me){Me=re,X.setIndex(re.index);for(let fe of j){let Dt=re.getAttribute(fe);Dt&&X.setAttribute(fe,Dt)}Ae=null,Ce=""}let ue=re.getAttribute(U[0]);if(!ue){X.instanceCount=0;return}let le=ue.array.length/ue.itemSize;(!Ae||!Ge||Ge.length<le*ce)&&(Ge=new Float32Array(le*ce),Ae=new J.InstancedInterleavedBuffer(Ge,ce,1),X.setAttribute("iA",new J.InterleavedBufferAttribute(Ae,4,0)),X.setAttribute("iB",new J.InterleavedBufferAttribute(Ae,4,4)),X.setAttribute("iC",new J.InterleavedBufferAttribute(Ae,4,8)),X.setAttribute("iD",new J.InterleavedBufferAttribute(Ae,4,12)),ce>=20&&X.setAttribute("iE",new J.InterleavedBufferAttribute(Ae,4,16)),Ce="");let Te=Math.min(Number.isFinite(re.instanceCount)?re.instanceCount:le,le),xe=`${Te}|`;for(let fe of U)xe+=re.getAttribute(fe).version+",";xe!==Ce&&(Ce=xe,ge(re,Ge,Te),Ae.needsUpdate=!0),X.instanceCount=Te}}},at=(j,U)=>j.getAttribute(U).array,xr={explicit:!1,defaultShaped:!1,defaultBent:!1},Er=zo(["position","side","along"],["sourceIndex","targetIndex","edgeWidth","edgeOpacity","edgeColor","edgeSelected","controlOffset","nodeSizes"],(j,U,ge)=>{let ce=at(j,"sourceIndex"),X=at(j,"targetIndex"),Me=at(j,"edgeWidth"),Ge=at(j,"edgeOpacity"),Ae=at(j,"edgeColor"),Ce=at(j,"edgeSelected"),re=at(j,"controlOffset"),ue=at(j,"nodeSizes");xr={explicit:!1,defaultShaped:!1,defaultBent:!1};for(let le=0;le<ge;le++){let Te=re[le*3],xe=re[le*3+2];xe>=0?xe<2.5&&(xe>.5||Math.abs(Te)>.001)&&(xr.explicit=!0):(xr.defaultShaped=!0,Math.abs(Te)>.001&&(xr.defaultBent=!0));let fe=le*16;U[fe]=ce[le],U[fe+1]=X[le],U[fe+2]=Me[le],U[fe+3]=Ge[le],U[fe+4]=Ae[le*3],U[fe+5]=Ae[le*3+1],U[fe+6]=Ae[le*3+2],U[fe+7]=Ce[le],U[fe+8]=re[le*3],U[fe+9]=re[le*3+1],U[fe+10]=re[le*3+2],U[fe+11]=0,U[fe+12]=ue[le*4],U[fe+13]=ue[le*4+1],U[fe+14]=ue[le*4+2],U[fe+15]=ue[le*4+3]}}),nn=zo(["position"],["sourceIndex","targetIndex","arrowColor","arrowOpacity","arrowScale","targetSize","sourceSize","controlOffset","edgeSelected"],(j,U,ge)=>{let ce=at(j,"sourceIndex"),X=at(j,"targetIndex"),Me=at(j,"arrowColor"),Ge=at(j,"arrowOpacity"),Ae=at(j,"arrowScale"),Ce=at(j,"targetSize"),re=at(j,"sourceSize"),ue=at(j,"controlOffset"),le=at(j,"edgeSelected");for(let Te=0;Te<ge;Te++){let xe=Te*20;U[xe]=ce[Te],U[xe+1]=X[Te],U[xe+2]=Ge[Te],U[xe+3]=le[Te],U[xe+4]=Me[Te*3],U[xe+5]=Me[Te*3+1],U[xe+6]=Me[Te*3+2],U[xe+7]=ue[Te*3],U[xe+8]=Ae[Te*3],U[xe+9]=Ae[Te*3+1],U[xe+10]=Ae[Te*3+2],U[xe+11]=ue[Te*3+1],U[xe+12]=Ce[Te*2],U[xe+13]=re[Te*2],U[xe+14]=ue[Te*3+2],U[xe+15]=0,U[xe+16]=Ce[Te*2+1],U[xe+17]=re[Te*2+1],U[xe+18]=0,U[xe+19]=0}},20),Vr=Er.own,kn=new J.Mesh(Vr,lt),Bo={position:new J.Float32BufferAttribute(new Float32Array(12),3),side:new J.Float32BufferAttribute([-1,1,-1,1],1),along:new J.Float32BufferAttribute([0,0,1,1],1),index:new J.Uint16BufferAttribute([0,1,2,1,3,2],1)},$d=j=>{Er.sync(j);let U=a.getDefaultEdgeShape(),ge=xr.explicit||xr.defaultShaped&&U<2.5&&(U>.5||xr.defaultBent),ce=ge?j.index:Bo.index;if(Vr.index!==ce){Vr.setIndex(ce);for(let X of["position","side","along"]){let Me=ge?j.getAttribute(X):Bo[X];Me&&Vr.setAttribute(X,Me)}}},$t=t("iA","vec4"),_i=t("iB","vec4"),Oo=t("iC","vec4"),Gn=t("iD","vec4"),Lo=t("iE","vec4"),Hn=()=>{let j=Nn($t.x),U=Nn($t.y),ge=U.sub(j),ce=p(ge),X=l(ce.greaterThan(1e-9),ge.div(ce),o(0,1,0)),Me=v(E.mul(s(j,1)).z),Ge=v(E.mul(s(U,1)).z),Ae=D.element(1).y,Ce=(Xe,Ue)=>Xe.mul(Ue).div(Ae.mul(N.y)).mul(.96),re=g(Gn.y.mul(50).div(Me),4096),ue=g(Gn.x.mul(50).div(Ge),4096),{srcPixDiam:le,tgtPixDiam:Te}=ko(j,U,re,ue,Lo.y,Lo.x),xe=Ce(le,Me),fe=Ce(Te,Ge),Dt=xe.add(fe),Et=l(Dt.greaterThan(ce.mul(.9)),ce.mul(.9).div(Dt),d(1));xe=xe.mul(Et),fe=fe.mul(Et);let Zt=Ce(ue,Ge).mul(Et),Yt=_i.w,sn=Oo.w,Ur=l(Gn.z.greaterThanEqual(0),Gn.z,F),It=l(Ur.greaterThan(.5).and(Ur.lessThan(1.5)).and(v(Yt).lessThan(.001)),d(.15),Yt),or=Ur.lessThan(2.5).and(Ur.greaterThan(.5).or(v(It).greaterThan(.001))),ut=j.add(X.mul(xe)),ft=U.sub(X.mul(fe)),zn=l(v(X.z).lessThan(.99),o(0,0,1),o(1,0,0)),Xt=u(c(X,zn)),an=b(sn),sr=x(sn),rt=Xt.mul(an).add(c(X,Xt).mul(sr)).add(X.mul(h(X,Xt)).mul(d(1).sub(an))),Bn=l(v(sn).greaterThan(.001),rt,Xt),Vt=ut.add(ft).mul(.5).add(Bn.mul(It.mul(ce))),Rr=Pi(ut,Vt,ft,d(.85)),Ye=l(or,u(ft.sub(Rr)),X),dn=l(or,ft,U.sub(X.mul(fe))),On=u(o(Ye.z,0,Ye.x.negate())),ln=Ye.y.clamp(-1,1).acos().mul(.5),Wr=s(On.mul(x(ln)),b(ln)),ar=l(Ye.y.greaterThan(.99999),s(0,0,0,1),l(Ye.y.lessThan(-.99999),s(1,0,0,0),Wr)),Di=$t.w.greaterThan(.5),Ut=Oo.xyz.mul(l(Di,o(3,1,3),o(1,1,1))),cn=Ut.x.mul(Zt).mul(18),dr=Ut.y.mul(Zt).mul(4),Ln=Ut.z.mul(Zt).mul(18),lr=dr.mul(2.2),Cr=o(g(cn,lr),dr,g(Ln,lr)),Qt=Zt.mul(.216),wr=Zt.mul(.14),Tr=o(y(Ut.x,Qt),y(Ut.y.mul(.3),wr),y(Ut.z,Qt)),Vn=l(G.greaterThan(.5),Cr,Tr),vt=M.mul(Vn),Un=vt.add(c(ar.xyz,c(ar.xyz,vt).add(vt.mul(ar.w))).mul(2)).add(dn),Wn=D.mul(E).mul(s(Un,1));return l($t.x.equal($t.y),s(2,2,2,1),Wn)},Vo=S(()=>{let j=_i.xyz.mul(1.2).add(o(0,.2,.5).mul(.3)),U=l($t.w.greaterThan(.5),j,_i.xyz);return R($t.z.lessThan(.01)),s(U.mul($t.z),$t.z)}),ct=new a.three.MeshBasicNodeMaterial;ct.vertexNode=Hn(),ct.fragmentNode=Vo(),ct.transparent=!0,ct.depthWrite=!1,ct.depthTest=!0,ct.side=J.DoubleSide,ct.forceSinglePass=!0,ct.premultipliedAlpha=!1,ct.blending=J.CustomBlending,ct.blendEquation=J.AddEquation,ct.blendSrc=J.OneFactor,ct.blendDst=J.OneMinusSrcAlphaFactor,ct.blendSrcAlpha=J.OneFactor,ct.blendDstAlpha=J.OneMinusSrcAlphaFactor;let Fn=new J.Mesh(nn.own,ct);Fn.frustumCulled=!1,Fn.renderOrder=0;let Ot=new a.three.MeshBasicNodeMaterial;Ot.vertexNode=jd.position,Ot.fragmentNode=s(t("iPick","vec3"),1),Ot.transparent=!1,Ot.depthWrite=!1,Ot.depthTest=!1,Ot.blending=J.NoBlending,Ot.side=J.DoubleSide;let Lt=new J.InstancedBufferGeometry,_t=new J.Mesh(Lt,Ot);_t.frustumCulled=!1;let on=new J.Group;on.add(_t);let tt=null,Uo=()=>{let j=Er.own.getAttribute("iA");if(!j){Lt.instanceCount=0;return}if(Lt.getAttribute("iA")!==j||Lt.index!==Er.own.index){Lt.setIndex(Er.own.index);for(let ge of["position","side","along","iA","iB","iC","iD"]){let ce=Er.own.getAttribute(ge);ce&&Lt.setAttribute(ge,ce)}}let U=j.data.array.length/16|0;if(!tt||tt.length<U*3){tt=new Float32Array(U*3);for(let ge=0;ge<U;ge++){let[ce,X,Me]=ti(ge,"edge");tt[ge*3]=ce,tt[ge*3+1]=X,tt[ge*3+2]=Me}Lt.setAttribute("iPick",new J.InstancedBufferAttribute(tt,3))}Lt.instanceCount=Er.own.instanceCount},nr=new J.Group;nr.add(kn),nr.add(Fn),kn.frustumCulled=!1,kn.renderOrder=-1;let ir=!1;return{displayObject:nr,pickObject:on,sync(j){if(ir)return!1;let U=!1,ge=a.getGeometry();ge?$d(ge):Vr.instanceCount=0,Uo();let ce=a.getArrowGeometry?.()??null;ce&&a.getArrowsEnabled()?nn.sync(ce):nn.own.instanceCount=0,Fn.visible=nn.own.instanceCount>0;let X=a.getPositions(),Me=a.getPositionsVersion?.()??NaN;if(X&&(Me!==Q||X!==$||z(Math.floor(X.length/3))!==L)){Q=Me,$=X;let Ce=Math.floor(X.length/3);if(Ne(Ce),Ve(j,Ce))U=!0;else{let re=B;for(let ue=0;ue<Ce;ue++)re[ue*4]=X[ue*3],re[ue*4+1]=X[ue*3+1],re[ue*4+2]=X[ue*3+2],re[ue*4+3]=1;V.needsUpdate=!0}}else U=te;W.value=U&&Pe===2?0:1;let Ge=a.getCloudTransform();if(Ge)for(let Ce of[nr,on])Ce.position.copy(Ge.position),Ce.quaternion.copy(Ge.quaternion),Ce.scale.copy(Ge.scale);else for(let Ce of[nr,on])Ce.position.set(0,0,0),Ce.quaternion.identity(),Ce.scale.set(1,1,1);let Ae=a.getResolution();return N.value.set(Math.max(1,Ae.width),Math.max(1,Ae.height)),A.value=a.getLineWidth()*.05,C.value=a.getArrowsEnabled()?1:0,F.value=a.getDefaultEdgeShape(),G.value=a.getFixedSize()?1:0,te=U,U},dispose(){ir||(ir=!0,nr.removeFromParent(),on.removeFromParent(),Ot.dispose(),Lt.dispose(),lt.dispose(),ct.dispose(),nn.own.dispose(),Ai.dispose(),Vr.dispose(),V?.dispose())}}}function $m(a){a.style.position="absolute",a.style.top="0",a.style.left="0",a.style.width="100%",a.style.height="100%",a.style.pointerEvents="none",a.style.display="none"}function Yp(a){let e=a.loadModule??qp,t=new Vd.Scene,r=new Vd.Scene,n=new Vd.Scene,i="absent",o=null,s=null,d=!1,l={width:a.size.width,height:a.size.height},u=a.pixelRatio,c=a.clearColor,h=1,p=null,f=0,m=NaN,g=null,y=-1,v=C=>{if(!a.getPositionsVersion)return;let F=a.getPositionsVersion(),G=C?.buffer??null,L=C?.generation??-1;F===m&&G===g&&L===y||(m=F,g=G,y=L,f+=1)},b=a.getPositionsVersion?()=>f:void 0,x=null,w=null,T=C=>{try{a.onReadiness(C)}catch{}},I=C=>{C.parentNode&&C.parentNode.removeChild(C)},R=(C,F)=>{try{C.dispose()}catch{}I(F)},S=()=>{i==="preparing"&&(i="unavailable",T("unavailable"))},P=async()=>{let[C,F]=await Promise.all([e(),a.ensureDevice()]);if(i!=="preparing")return;w=C,w.ColorManagement.enabled=!1;let G=document.createElement("canvas");$m(G);let L=new w.WebGPURenderer({canvas:G,device:F.device,antialias:a.antialias,alpha:!0,forceWebGL:!1});L.setPixelRatio(u),L.setSize(l.width,l.height,!1),L.setClearColor(c,h);try{await L.init()}catch(B){throw I(G),B}if(i!=="preparing"){R(L,G);return}if(L.backend?.isWebGPUBackend!==!0){R(L,G),S();return}if(a.getStore&&a.getPositions){let B;try{B=await(a.loadTSL??Kp)()}catch(oe){throw R(L,G),oe}if(i!=="preparing"){R(L,G);return}p=$p({three:w,tsl:B,getStore:a.getStore,getPositions:a.getPositions,getPositionsVersion:b,getStyleVersion:a.getStyleVersion,getCloudTransform:a.getCloudTransform??(()=>null),getNodeSizeScale:a.getNodeSizeScale??(()=>1),getResolution:()=>l}),t.add(p.displayObject),r.add(p.pickObject),p.displayObject.renderOrder=1;let K=a.getEdgeSource;K&&(x=Zp({three:w,tsl:B,getGeometry:()=>K()?.geometry??null,getArrowGeometry:()=>K()?.arrowGeometry??null,getPositions:a.getPositions??(()=>null),getPositionsVersion:b,getResolution:()=>l,getLineWidth:()=>K()?.lineWidth??1,getArrowsEnabled:()=>K()?.arrowsEnabled??!1,getDefaultEdgeShape:()=>K()?.defaultEdgeShape??0,getFixedSize:()=>K()?.fixedSize??!1,getCloudTransform:a.getCloudTransform??(()=>null)}),t.add(x.displayObject),n.add(x.pickObject))}let V=a.stackAbove;V&&V.parentNode===a.container?a.container.insertBefore(G,V.nextSibling):a.container.appendChild(G),G.style.display=d?"":"none",o=L,s=G,i="ready",T("ready")},D=!1,E=(C,F)=>{let G=C.backend,L=G.device;if(!F||!L||F.device!==L||!G.get)return null;let V=G.get.bind(G);return{source:F,encoder:L.createCommandEncoder(),bufferOf:B=>V(B)?.buffer,textureOf:B=>V(B)?.texture}},M=null,A={pathId:"webgpu",scene:t,pickScene:r,edgePickScene:n,hasEdgePicking:()=>x!==null,usesGpuPositions:()=>i==="ready"&&D,get state(){return i},isReady:()=>i==="ready",render(){if(i!=="ready"||!o)return;let C=a.getGpuPositions?.()??null;v(C);let F=E(o,C),G=p?.sync(F)??!1,L=x?.sync(F)??!1;F&&o.backend.device.queue.submit([F.encoder.finish()]),D=G&&(x===null||L),o.render(t,a.camera)},readPickPixels:async(C,F,G="node")=>{if(i!=="ready"||!o||!w)return null;let L=Math.max(1,Math.round(F.width)),V=Math.max(1,Math.round(F.height));M?(M.width!==L||M.height!==V)&&M.setSize(L,V):M=new w.RenderTarget(L,V,{depthBuffer:!0,samples:0}),v(a.getGpuPositions?.()??null),p?.sync(),x?.sync();try{return o.setRenderTarget(M),o.setClearColor(0,0),o.render(G==="edge"?n:r,a.camera),o.setRenderTarget(null),o.setClearColor(c,h),await o.readRenderTargetPixelsAsync(M,C.x,C.y,C.width,C.height)}catch{try{o.setRenderTarget(null),o.setClearColor(c,h)}catch{}return null}},getDrawCallSource(){return i==="ready"&&o?o:null},setVisible(C){d=C,C||(D=!1),s&&(s.style.display=C?"":"none")},setSize(C,F){if(l={width:C,height:F},i==="ready"&&o){o.setSize(C,F,!1);try{o.render(t,a.camera)}catch{}}},setPixelRatio(C){u=C,i==="ready"&&o&&o.setPixelRatio(C)},setClearColor(C,F){c=C,h=F,i==="ready"&&o&&o.setClearColor(C,F)},prepare(){i==="absent"&&(i="preparing",T("preparing"),P().catch(()=>S()))},retire(){if(i==="retired")return;let C=i;i="retired",p?.dispose(),p=null,x?.dispose(),x=null,t.clear(),r.clear(),n.clear(),M?.dispose(),M=null,o&&s&&(R(o,s),o=null,s=null),C!=="absent"&&T("absent")},dispose(){A.retire()}};return A}import{useEffect as zt,useRef as Ym}from"react";var Zm="data:font/woff2;base64,d09GMgABAAAAAAIUAA8AAAAABBgAAAHCAAEEWgAAAAAAAAAAAAAAAAAAAAAAAAAAGhYbEBwaBmAAVAgEEQgKglSCHgE2AiQDDgsOAAQgBQYHIBvLAiCG4Hm7/6pzu8dEvwEQfYTz/oArZRAiKYMYTra7bcvTrihAe8EEM84oTwLuLpjzaAAw0F0kzkIpXxJoCUhCaCQJNNdSayB3Ousqju+pOakpgDyJGzQiVsZBLDlfdVU3Z0kaZQC0BQCofr/nj+8TSEAAoK8RSMjQUSbQUW4uWmoqyb/f8+OqX6b98u4f35cl/eU+d/V6vvv73Wd2HiQAQLtYiChLCTQGLdEUy3AMkGO0JCQhRJ43zVp3ata8RdYiVVpkzT9r+OzKJ9WPLx9qUam0KFL1oeYtLz8S2xoe3VcxTWVjzIiNsSkaHr3yMMW2YuPwTS2jVWVbofrxxk8/jWhXXCzq2h6ccHD0xpev2b9/VzrOqautuaXPo6dOaXdHu5oo2l30yiOPTKx9su/yjss69r2z9uGJwx8+Wtuqf/f+rWofOap8RO6buvp8eE6m/POVorrlxE3rOgg0t1TB02HMzGea5P4Z/3TjRl9/miU4nHEj+NY4/kXifCDyrVOufHXfrjYzrzZtlsDn9909Bb4b/sGb5f/lfylShqYSCBJIoDIQ5oIi0U6hMEJhrkDjuFNXkBACc40G0FgGlGeMFw==",Xp={name:"gl-markers",url:Zm,fontFamily:"GLMarkers",glyphMap:{plane:58681,file:57933,shield:59872,dot:57441,arrow:58824}};function Qp(a){let{contextValue:e,viewState:t,resolvedTheme:r,textScaleProp:n,edgeTextScaleProp:i,isMapMode:o,mapDampingRef:s,mapSphereRadiusRef:d,apiInstanceRef:l,clickDim:u,restoreOnBackgroundClick:c,is3DProp:h,is3D:p,setIs3DState:f,controlRef:m,layoutControllerRef:g,edgeRendererRef:y,childEdgeRendererRef:v,defaultDim:b,effectiveEnableControl:x,effectiveMapProjection:w,iconFonts:T,iconAtlasManagerRef:I,needsRenderRef:R,imageAtlasManagerRef:S,glyphAtlasManagerRef:P}=a;zt(()=>{t.patch({theme:r})},[r]),zt(()=>{t.patch({textScale:n,edgeTextScale:i})},[n,i]),zt(()=>{t.patch({isMapMode:o,mapDamping:s.current,mapSphereRadius:d.current})},[o]),zt(()=>{l.current?.emphasis.setClickDimEnabled(!!u)},[u,e]),zt(()=>{l.current?.emphasis.setRestoreOnBackgroundClick(c!==!1)},[c,e]),zt(()=>{if(h===p)return;f(h);let E=m.current;E&&(E.setEnableRotate(h),h||E.resetRotation(!0,400));let M=h?3:2,N=l.current;if(N&&typeof N.setDimensions=="function")N.setDimensions(M);else{let C=g.current;C&&typeof C.transitionDimensions=="function"&&(typeof C.getDimensions!="function"||C.getDimensions()!==M)&&C.transitionDimensions(M)}let A=y.current||v.current;A&&typeof A.set3DMode=="function"&&A.set3DMode(h)},[h]);let D=Ym(!1);zt(()=>{D.current||h===void 0&&b!==void 0&&l.current&&(D.current=!0,l.current.setDimensions(b))},[]),zt(()=>{let E=m.current;E&&(E.setEnablePan(x),E.setEnableZoom(x),E.setEnableRotate(x&&h))},[x,h]),zt(()=>{t.patch({is3D:p,effectiveMapProjection:w})},[p,w]),zt(()=>{l.current&&l.current.map.wireIs3D(p)},[p]),zt(()=>{let E=new Id;I.current=E;let M=[Xp,...T??[]];return Promise.all(M.map(N=>{let A=N;return E.loadFont(N,A.categories?{categories:A.categories}:void 0)})).then(()=>{t.patch({iconAtlasManager:E}),R.current=!0}),()=>{E.dispose(),t.patch({iconAtlasManager:null}),I.current=null}},[T]),zt(()=>{let E=new Pd;return S.current=E,t.patch({imageAtlasManager:E}),()=>{E.dispose(),t.patch({imageAtlasManager:null}),S.current=null}},[]),zt(()=>{let E=new ri;return P.current=E,t.patch({glyphAtlasManager:E}),()=>{E.dispose(),t.patch({glyphAtlasManager:null}),P.current=null}},[])}var Ud=class{constructor(e){this._listeners=new Set;this.getSnapshot=()=>this._snapshot;this.subscribe=e=>(this._listeners.add(e),()=>{this._listeners.delete(e)});this._snapshot={...e}}patch(e){let t=Object.keys(e),r=!1;for(let n of t)if(!Object.is(e[n],this._snapshot[n])){r=!0;break}if(r){this._snapshot={...this._snapshot,...e};for(let n of this._listeners)try{n()}catch(i){console.error("[ViewStateStore] listener threw:",i)}}}};import{Fragment as ny,jsx as Ze,jsxs as _c}from"react/jsx-runtime";var Jp=new WeakSet,eg=["wheel","pointerdown","touchstart"],Jm=10,ey=.15,ty=1.2,tg=!1,Ac=no("webgl");function ry({container:a,className:e,style:t,backgroundColor:r=0,antialias:n=!0,pixelRatio:i,children:o,store:s,controls:d,enableControl:l,drag:u,enableDrag:c,controlConfig:h,cameraZ:p,initialPosition:f,onReady:m,apiRef:g,apiOptions:y,nodeCloud:v,edgeCloud:b,node:x,edge:w,caption:T,edgeCaption:I,data:R,enableWebGPURenderPath:S=!1,minimap:P,map:D,toolbar:E=!1,legend:M,locale:N,layoutController:A,forceLayout:C,autoFit:F,autoStartLayout:G=!0,iconFonts:L,theme:V,mapProvider:B,textScale:K=.6,edgeTextScale:oe=.6,is3D:Q=!0,defaultDim:$,mapProjection:z,onThemeChange:W,onViewChange:te,clickDim:Ne=!1,restoreOnBackgroundClick:Pe=!0,onNodeClick:Ve,onNodeDoubleClick:Oe,onEdgeClick:st,onEdgeDoubleClick:et,onBackgroundClick:Bt,onNodeContextMenu:Lr,onEdgeContextMenu:Wd,onBackgroundContextMenu:Mo,onNodeHover:Io,onEdgeHover:Po,onNodeDragStart:Mi,onNodeDrag:Ao,onNodeDragEnd:_o,onDestroy:Dn,onError:Nn,onDelta:Do,onLayoutStart:Ii,onLayoutEnd:Pi,onLayoutProgress:No,onAlgorithmStart:ko,onAlgorithmEnd:Go,onAlgorithmError:Ho,onAlgorithmProgress:jd,onHistoryChange:qd,onStyleChange:Fo,selection:Kd,defaultSelection:lt,onSelectionChange:Ai,hidden:zo,defaultHidden:at,onVisibilityChange:xr,defaultIs3D:Er,onIs3DChange:nn,defaultTheme:Vr,defaultViewState:kn,viewState:Bo,onViewStateChange:$d,hoveredId:$t,onHoverChange:_i,pinned:Oo,defaultPinned:Gn,onPinnedChange:Lo}){let Hn=P??!0,Vo=Tc(u,c),ct=Er??($!==void 0?$===3:!0),Fn=kn??(p!==void 0||f!==void 0?{position:f??[0,0,-15],cameraZ:p??.001}:void 0),[Ot,Lt]=rn(!0),[_t,on]=rn(null),tt=He.useMemo(()=>{if(typeof V=="object"&&V!==null)return V;if(_t)return Mn[_t];if(typeof V=="string")return Mn[V]||Mn.dark;let _=(r>>16&255)/255,H=(r>>8&255)/255,ne=(r&255)/255,Z=.299*_+.587*H+.114*ne;return{background:r,isDark:Z<.5}},[V,r,_t]),Uo=He.useMemo(()=>{if(typeof V=="object"&&V!==null)return tt.isDark?"dark":"light";if(_t)return _t;if(typeof V=="string"){if(V in Mn)return V;console.warn(`[render-engine] Unknown theme key "${V}". tokens.css only ships blocks for: ${Object.keys(Mn).join(", ")}. Falling back to dark/light by background luminance.`)}return tt.isDark?"dark":"light"},[V,_t,tt.isDark]),nr=He.useMemo(()=>typeof B=="string"&&B.length>0?B:_t?uo[_t]:typeof V=="string"&&V in uo?uo[V]:typeof V=="object"&&V!==null?V.isDark?"esriDarkGray":"esriLightGray":"esriDarkGray",[B,V,_t]),ir=V||_t?tt.background:r,[j,U]=He.useState(null),ge=be(a??null),ce=be(null),X=be(new ot.Scene),Me=be(new ot.PerspectiveCamera(42,1,1e-4,2e4)),Ge=be(new ot.Group),Ae=be(null),Ce=be(null),re=be(null),ue=be(null),le=be(null),Te=be(null),xe=be(null),fe=be(null);fe.current===null&&(fe.current=Ec({getEvents:()=>re.current?.events??null}));let Dt=be(S);Dt.current=S;let Et=be(null);ke(()=>(fe.current===null&&(fe.current=Ec({getEvents:()=>re.current?.events??null}),fe.current.setHostEnabled(Dt.current)),()=>{Et.current?.dispose(),Et.current=null,fe.current?.dispose(),fe.current=null}),[]),ke(()=>(Qe.current===null&&(Qe.current=new wo({store:Xe.current})),()=>{Qe.current?.dispose(),Qe.current=null}),[]);let Zt=be(new Map),Yt=be(new Map),sn=be(new Map),Ur=be(new Map),[It,or]=He.useState(!1),ut=be(.3),ft=be(0),zn=He.useRef(!1),Xt=He.useMemo(()=>p??(D?6:3),[p,D]),[an,sr]=He.useMemo(()=>{let{enabled:_,config:H}=Ic(d,l,h);return[_??!(D&&Q===!0),H]},[d,l,h,D,Q]);He.useEffect(()=>{typeof B=="string"&&B.length>0&&!zn.current&&(zn.current=!0,console.warn("[GraphCanvas] mapProvider is deprecated. Use map={{ tileProvider: '"+B+"' }} instead."))},[B]);let[rt,Bn]=He.useState(Q),[Vt,Rr]=He.useState(null),[Ye,dn]=He.useState(null),[On,ln]=He.useState(new Set),Wr=He.useRef(new Map),ar=He.useCallback(_=>{Wr.current=_},[]),Di=He.useCallback(()=>Wr.current,[]),Ut=He.useRef(null),[cn,dr]=He.useState(null),Ln=He.useMemo(()=>Pc(z,rt),[z,rt]),lr=be(null),Cr=be(null),Qt=be(null),wr=be(0),Tr=be(!1),Vn=be(""),vt=be(null),cr=be(A),Un=be(void 0),Wn=be(null),Xe=be(s??new fs),Ue=be(!1),Qe=be(null);Qe.current||(Qe.current=new wo({store:Xe.current}));let Ni=be(null);Ni.current||(Ni.current=new Ud({isMapMode:It,mapDamping:ut.current,mapSphereRadius:ft.current,is3D:rt,effectiveMapProjection:Ln,theme:tt,textScale:K,edgeTextScale:oe,iconAtlasManager:null,imageAtlasManager:null,glyphAtlasManager:null,layoutController:void 0,layoutPositionProvider:void 0}));let Mr=Ni.current;Qm(Mr.subscribe,()=>Mr.getSnapshot().iconAtlasManager,()=>Mr.getSnapshot().iconAtlasManager);let[k,Zd]=rn(null);xp(k,{onNodeClick:Ve,onNodeDoubleClick:Oe,onEdgeClick:st,onEdgeDoubleClick:et,onBackgroundClick:Bt,onNodeContextMenu:Lr,onEdgeContextMenu:Wd,onBackgroundContextMenu:Mo,onNodeHover:Io,onEdgeHover:Po,onNodeDragStart:Mi,onNodeDrag:Ao,onNodeDragEnd:_o}),Rp(k?.api??null,{onDestroy:Dn,onError:Nn,onDelta:Do,onLayoutStart:Ii,onLayoutEnd:Pi,onLayoutProgress:No,onAlgorithmStart:ko,onAlgorithmEnd:Go,onAlgorithmError:Ho,onAlgorithmProgress:jd,onHistoryChange:qd,onStyleChange:Fo}),wp(k?.api??null,Kd,lt,Ai),Tp(k?.api??null,zo,at,xr),Mp(k?.api??null,Q,ct,nn),Ip(k?.api??null,V,Vr,W),Pp(k?.api??null,Bo,Fn,$d),Ap(k?.api??null,Oo,Gn,Lo);let Yd=He.useMemo(()=>!k?.api||!k?.interaction?null:{hover:k.api.hover,interaction:{hover:k.interaction.hover}},[k?.api,k?.interaction]);_p(Yd,$t,_i);let[Wo,ki]=rn(null),[jr,jo]=rn(void 0),[hy,Hc]=rn(0);ke(()=>{let _=s??Xe.current,H=_.subscribeIconVersionChanged(()=>{Hc(_.iconVersion)});return Hc(_.iconVersion),H},[s]);let Fc=be(null),Gi=be(null),jn=be(null),qo=be(null),un=be(null),Ko=be(null),[Xd,Qd]=rn(null),zc=A??Xd??void 0;ke(()=>{cr.current=zc},[zc]),ke(()=>{s&&(Xe.current=s)},[s]),ke(()=>{R&&Xe.current.setData(R)},[R]);let Hi=He.Children.count(o)>0,Jd=Eo(v),el=Eo(b),Bc=Eo(x),Oc=Eo(w),ur=He.useMemo(()=>{if(Hi)return Jd;let _=Ci(Bc);return _?{useCircle:_.shape!=="square",fixedSize:_.fixedSize??0,hidePin:_.showPin===!1,hideRing:_.showRing===!1,iconMode:_.iconMode??1,maxNodes:_.maxNodes,lightMode:!tt.isDark,nodeSizeScale:_.nodeScale,defaultNodeSize:_.defaultSize}:Jd??!0},[Hi,Bc,Jd,tt.isDark]),Fi=He.useMemo(()=>{if(Hi)return el;let _=Ci(Oc);return _?_.visible===!1?void 0:{lineWidthScale:_.lineWidth??1,showArrows:_.showArrows??!1,arrowScale:_.arrowScale??1,maxEdges:_.maxEdges,useCurve:_.curved,dashArray:_.dashed?.5:void 0,dashRatio:_.dashed?.5:void 0,edgeShape:_.edgeShape,radialAxis:_.radialAxis}:el??!0},[Hi,Oc,el]),Se=He.useMemo(()=>{if(!D)return null;let _=D===!0?{}:D,H=_.tileProvider??(typeof B=="string"&&B.length>0?B:void 0);return{..._,tileProvider:H}},[D,B]),Lc=He.useMemo(()=>typeof D=="object"&&D?.maxNodeGrowth!==void 0?D.maxNodeGrowth:4,[D]);He.useEffect(()=>{if(!Se||!k)return;let _=.3,H=rt?Se.globeRadius??5:0;k.setMapMode(!0,H,_),re.current?.debug.setSphereRadius(H);let ne=re.current;if(ne?.map){let Z=rt?"spherical":"planar",q=Se.tileProvider;ne.map.isEnabled()?ne.map.getMode()!==Z&&ne.map.transition(Z):ne.map.enableMap({mode:Z,...typeof q=="string"&&q.length>0?{provider:q}:{},...Se.mapSize!==void 0?{mapSize:Se.mapSize}:{},...Se.globeRadius!==void 0?{globeRadius:Se.globeRadius}:{}})}},[Se,rt,k]),He.useEffect(()=>{if(!Se){Rr(null);return}if(Bd(o)){console.warn("[GraphCanvas] map prop is set, but children already contain a FlatLayer/GlobeLayer. Internal auto-mount skipped. Remove the child layer or remove the map prop."),Rr(null);return}let _=rt?"globe":"flat";Vt&&Vt!==_&&(Ut.current=re.current?.map.beginLayerSwap()??null),Rr(_)},[Se,rt,o,Vt]),He.useEffect(()=>{let _=re.current;if(!_||!k)return;let H=5,ne=10,Z=_.events.on("map:enabled",({mode:se,provider:ee})=>{if(Se!==null||Bd(o))return;let Y=se==="spherical"?H:0;k.setMapMode(!0,Y,.3),dr({tileProvider:ee,globeRadius:se==="spherical"?H:void 0,mapSize:ne}),Rr(se==="spherical"?"globe":"flat")}),q=_.events.on("map:disabled",()=>{Se===null&&(Bd(o)||(k.setMapMode(!1,0,1),Rr(null),dr(null)))}),ae=_.events.on("map:providerChanged",({provider:se})=>{Se===null&&dr(ee=>ee&&{...ee,tileProvider:se})});return()=>{Z(),q(),ae()}},[k,Se,o]);let[$o,sg]=rn(null);He.useEffect(()=>{let _=re.current;if(!_||!k)return;let H=()=>{let Z=_.style.getCaptionConfig();sg(Z?{config:Z,scale:_.style.getCaptionScale()}:null)};H();let ne=_.events.on("style:changed",H);return()=>{ne()}},[k]),He.useEffect(()=>{if(!Se)return;let _=Se.geoLayout;if(_===!1)return;let H=re.current;if(!H||!k)return;let ne=typeof _=="object"&&_!==null?_:{},Z=rt?"spherical":"planar",q=Se.mapSize??10,ae=Se.globeRadius??5,se=Z==="planar"&&ne.nonGeoStrategy==="egoRing",ee=!1,Y=Z==="planar"?new Zn(q):null;function pe(){let je=H.store.data.nodes;if(je.length===0)return null;let Rt=["lat","latitude"],_e=["lng","lon","long","longitude"],ve=null,Je=null,ye=ne.geoMapping;if(ye&&typeof ye=="object"){let mt=Array.isArray(ye.lat)?ye.lat[0]:ye.lat,$n=Array.isArray(ye.lng)?ye.lng[0]:ye.lng;ve=mt,Je=$n}else e:for(let mt of je){let $n=mt.properties??{},qr=Object.keys($n),hr=qr.map(Nt=>Nt.toLowerCase());for(let Nt of Rt){let yt=hr.indexOf(Nt);if(yt>=0&&Number.isFinite(Number($n[qr[yt]]))){ve=qr[yt];break}}for(let Nt of _e){let yt=hr.indexOf(Nt);if(yt>=0&&Number.isFinite(Number($n[qr[yt]]))){Je=qr[yt];break}}if(ve&&Je)break e}let nt=new Float32Array(je.length*3),Ie=0,bt=-1/0,Pr=1/0,Ar=-1/0,al=1/0;for(let mt=0;mt<je.length;mt++){let qr=je[mt].properties??{},hr=ve?Number(qr[ve]):NaN,Nt=Je?Number(qr[Je]):NaN;if(Number.isFinite(hr)&&Number.isFinite(Nt)){if(Y){let yt=Y.latLngToWorld(hr,Nt);nt[mt*3]=yt.x,nt[mt*3+1]=yt.y,nt[mt*3+2]=0}else{let yt=Li(hr,Nt,ae);nt[mt*3]=yt.x,nt[mt*3+1]=yt.y,nt[mt*3+2]=yt.z}Ie++,hr>bt&&(bt=hr),hr<Pr&&(Pr=hr),Nt>Ar&&(Ar=Nt),Nt<al&&(al=Nt)}else{let yt=mt+1,Jc=Math.sin(yt*127.1+311.7)*43758.5453,eu=Math.sin(yt*269.5+183.3)*43758.5453,tu=.3+(Jc-Math.floor(Jc))*.4,ru=(eu-Math.floor(eu))*Math.PI*2;nt[mt*3]=Math.cos(ru)*tu,nt[mt*3+1]=Math.sin(ru)*tu,nt[mt*3+2]=0}}let yg=Ie>0&&Number.isFinite(bt)?{north:bt,south:Pr,east:Ar,west:al}:null;return{positions:nt,geoCount:Ie,bbox:yg}}function me(){let we=pe();if(!we)return;let je=H.map.applyGeoLayout({mode:Z,mapSize:q,globeRadius:ae,...ne.geoMapping?{geoMapping:ne.geoMapping}:{},...se?{pinAutoPlaced:!1}:{}});dn(se?{geoIds:je.geoNodeIds,nonGeoIds:je.nonGeoNodeIds,edges:H.store.data.edges.map(ve=>({source:ve.source,target:ve.target}))}:null);let Rt=le.current??xe.current,_e=Rt&&typeof Rt.getEdgeClassifier=="function"?Rt.getEdgeClassifier():null;if(_e){_e.setBaseCurvature(0);let ve=Rt.reclassifyEdges;typeof ve=="function"&&ve.call(Rt)}if(k?.invalidate(),!ee&&we.bbox&&Se.autoFit!==!1){ee=!0;let ve=.01,Je=we.bbox.north-we.bbox.south,ye=we.bbox.east-we.bbox.west,{north:nt,south:Ie,east:bt,west:Pr}=we.bbox;if(Je<ve){let Ar=(nt+Ie)/2;nt=Ar+ve/2,Ie=Ar-ve/2}if(ye<ve){let Ar=(bt+Pr)/2;bt=Ar+ve/2,Pr=Ar-ve/2}Z==="planar"?H.map.flyToBounds({north:nt,south:Ie,east:bt,west:Pr},{padding:0,duration:400}):H.map.flyToBounds({north:nt,south:Ie,east:bt,west:Pr},{padding:0,duration:400,mode:"spherical"})}}let he=!1;function Fe(){he||(he=!0,requestAnimationFrame(()=>{he=!1,me()}))}return H.events.on("nodes:added",Fe),H.events.on("graph:dataReset",Fe),se&&H.events.on("edges:added",Fe),me(),()=>{H.events.off("nodes:added",Fe),H.events.off("graph:dataReset",Fe),se&&H.events.off("edges:added",Fe),dn(null)}},[Se,rt,k]),ke(()=>{fe.current?.setHostEnabled(S)},[S]),ke(()=>{let _=a??j;if(!_)return;let{renderer:H,cloudScene:ne,camera:Z,dispose:q}=zp({container:_,containerProp:a,style:t,antialias:n,pixelRatio:i,effectiveBackground:ir,effectiveCameraZ:Xt,sceneRef:X,cameraRef:Me,storeRef:Xe,cloudSceneRef:Ge,rendererRef:ce}),ae=Qe.current,se=fe.current,ee=jp({renderer:H,camera:Z,getScene:()=>X.current}),Y=se?Yp({container:_,stackAbove:H.domElement,camera:Z,ensureDevice:()=>se.shared.ensureDevice("render"),onReadiness:ye=>se.selector.setRendererReadiness(ye),antialias:n,pixelRatio:i??window.devicePixelRatio,clearColor:ir,size:{width:_.clientWidth,height:_.clientHeight},getStore:()=>Xe.current,getPositions:()=>Xe.current.positionProvider?.getPositions()??null,getGpuPositions:()=>se.shared.getPositionSource(),getPositionsVersion:()=>ae.positionsVersion,getStyleVersion:()=>Xe.current.changes.versionOf(O.All&~O.Position),getCloudTransform:()=>Ge.current,getEdgeSource:()=>{let ye=le.current;return!ye?.getGeometry||!ye.getRenderParams?null:{geometry:ye.getGeometry(),arrowGeometry:ye.getArrowGeometry?.()??null,...ye.getRenderParams()}}}):null;Et.current=Y,ae.setPaintTargets({webgl:ee,webgpu:Y});let pe=-1;Y&&se&&Yt.current.set("gpuPositions",()=>{if(!Y.usesGpuPositions())return!1;let ye=se.shared.getPositionSource()?.generation??-1;return ye===pe?!1:(pe=ye,!0)}),ae.setRenderPathSource(se?()=>se.describe():null);let{control:me,interaction:he,disposeInteraction:Fe}=Lp({renderer:H,camera:Z,cloudScene:ne,container:_,effectiveControlConfig:sr,effectiveEnableControl:an,is3DProp:Q,enableDragEffective:Vo,apiInstanceRef:re,needsRenderRef:Ue,controlRef:Ae,storeRef:Xe,interactionRef:Ce,renderRuntimeRef:Qe,changeCategoryFlowRef:Fc,contextMenuManagerRef:Gi,cameraRef:Me,nodeRendererRef:ue,edgeRendererRef:le,webgpuTarget:Y,pixelRatio:i,setCreatePanelAllowedRels:jo,setEdgeCreateResult:ki}),we=f??[0,0,-2],je=sr?.zoomMax??Xt-2e-4,Rt=Math.min(we[2],je-2e-4);if(ne.position.set(we[0],we[1],Rt),he){let ye=le.current?.getMesh()??void 0;he.syncTransforms(ne,ye),he.setCamera(Z)}Vp({storeRef:Xe,layoutControllerRef:cr,pendingStructureChangeRef:Tr,needsRenderRef:Ue,renderRuntimeRef:Qe});let _e=Up({renderer:H,camera:Z,cloudScene:ne,container:_,control:me,interaction:he,viewState:Mr,storeRef:Xe,sceneRef:X,apiInstanceRef:re,needsRenderRef:Ue,renderRuntimeRef:Qe,nodeRendererRef:ue,edgeRendererRef:le,childNodeRendererRef:Te,childEdgeRendererRef:xe,layoutControllerRef:cr,frameCallbacksRef:Zt,mapModeCallbacksRef:sn,mapMaxGrowthCallbacksRef:Ur,mapDampingRef:ut,mapSphereRadiusRef:ft,setIsMapMode:or,setIs3DState:Bn,getRenderBackend:()=>fe.current?.activeBackend()??Ac,getActiveRenderPathId:()=>Qe.current?.getActivePathId()??"webgl"});Zd(_e),m?.(_e);let ve=kp({cloudScene:ne,storeRef:Xe,needsRenderRef:Ue,renderRuntimeRef:Qe,nodeRendererRef:ue,edgeRendererRef:le,childNodeRendererRef:Te,childEdgeRendererRef:xe,layoutControllerRef:cr,layoutAdapterRef:vt,interactionRef:Ce,iconAtlasManagerRef:lr,apiInstanceRef:re,pendingStructureChangeRef:Tr,forceWasFinishedRef:Un,forceStartPositionsRef:Wn,geoSettleSigRef:Vn,frameCallbacksRef:Zt,beforePaintCallbacksRef:Yt});ve.start();let{dispose:Je}=Wp({container:_,renderer:H,camera:Z,sceneRef:X,needsRenderRef:Ue,nodeRendererRef:ue,edgeRendererRef:le,childNodeRendererRef:Te,childEdgeRendererRef:xe,renderRuntimeRef:Qe});return()=>{Je(),ve.stop(),ue.current?.dispose(),le.current?.dispose(),ue.current=null,le.current=null,cr.current?.stop?.(),Fe(),Qe.current?.setPaintTargets({webgl:null,webgpu:null}),Qe.current?.setRenderPathSource(null),Yt.current.delete("gpuPositions"),Y?.dispose(),Et.current===Y&&(Et.current=null),me?.dispose(),q(he)}},[a,j,r,n,i,Vo,sr,Xt,m]),ke(()=>{let _=a??j;if(_)return _.setAttribute("data-gxr-theme",Uo),()=>{_.removeAttribute("data-gxr-theme")}},[a,j,Uo]),He.useEffect(()=>{(typeof globalThis<"u"&&globalThis.process?.env?.NODE_ENV)!=="production"&&a!=null&&(t!=null||e!=null)&&console.warn("[@kineviz/gl] `style` / `className` props are ignored when `container` is provided. Style the external container directly.")},[a,t,e]),ke(()=>{let _=ce.current;_&&(_.setClearColor(ir,1),Qe.current?.setTargetsClearColor(ir,1),Ue.current=!0);let H=a??j,ne=a==null&&t!=null&&(t.background!=null||t.backgroundColor!=null);H&&!ne&&(H.style.backgroundColor="#"+ir.toString(16).padStart(6,"0"))},[ir,a,j,t]),Qp({contextValue:k,viewState:Mr,resolvedTheme:tt,textScaleProp:K,edgeTextScaleProp:oe,isMapMode:It,mapDampingRef:ut,mapSphereRadiusRef:ft,apiInstanceRef:re,clickDim:Ne,restoreOnBackgroundClick:Pe,is3DProp:Q,is3D:rt,setIs3DState:Bn,controlRef:Ae,layoutControllerRef:cr,edgeRendererRef:le,childEdgeRendererRef:xe,defaultDim:$,effectiveEnableControl:an,effectiveMapProjection:Ln,iconFonts:L,iconAtlasManagerRef:lr,needsRenderRef:Ue,imageAtlasManagerRef:Cr,glyphAtlasManagerRef:Qt});let ag=typeof C=="object"&&C!==null?JSON.stringify(C):C,Vc=be(C);Vc.current=C,ke(()=>{let _=Vc.current;if(!k||!_||A){if(un.current){try{un.current.destroy()}catch{}un.current=null,Ko.current=null,Qd(null)}return}let H=k.renderer;if(!H)return;let ne=typeof _=="object"?_:{},Z={...gc,...ne},q=typeof _=="object"?_.engine:void 0,ae=typeof navigator<"u"&&"gpu"in navigator,se=Mc(q,ae),ee=Q?3:2,Y=k.store.data.nodes,pe=k.store.data.edges,me={version:0,dimensions:ee,nodes:Y.map((_e,ve)=>({id:_e.id,index:ve,position:{x:Math.random()*2-1,y:Math.random()*2-1,z:0},pinned:!1})),edges:pe.map((_e,ve)=>({id:_e.id,index:ve,source:_e.source,target:_e.target}))},he=np(),Fe=(_e,ve)=>he.publish(_e,()=>{un.current=_e,Ko.current=ve,Qd(ve)}),we=()=>{let _e=new Nd(me,Z);Fe(_e,_e)};return se==="webgl"&&ee===3?(tg||(tg=!0,console.warn('[kineviz.gl] forceLayout engine "webgl" is 2D only; this 3D canvas uses "d3".')),we()):se==="webgl"?(async()=>{let{WebGLForceLayoutController:_e}=await import("./WebGLForceLayoutController-P6NPZ7WK.mjs");if(he.cancelled)return;let ve=new _e({config:ne}),Je=k.store;if(G&&Je.nodeCount>0){let ye=Je.getAllPositions();ve.graph.layoutNodes=Je.data.nodes.map(Ie=>{let bt=ye.get(Ie.id);return{id:Ie.id,position:bt?new ot.Vector3(bt[0],bt[1],bt[2]):new ot.Vector3,pinned:Je.isPinned(Ie.id),isPositionDirty:!1}}),ve.graph.layoutEdges=Je.data.edges.map(Ie=>({id:Ie.id,sourceId:Ie.source,targetId:Ie.target})),ve.start(),Jp.add(ve);let nt=Je.positionProvider;nt instanceof mn&&nt.setAllPositions(ve.getPositions().slice())}Fe(ve,ve)&&ve.ready().catch(ye=>{he.cancelled||(console.warn('[kineviz.gl] forceLayout: the WebGL layout engine is unavailable; falling back to "d3".',ye),ve.destroy(),we())})})().catch(_e=>{he.cancelled||(console.warn('[kineviz.gl] forceLayout: the WebGL layout engine is unavailable; falling back to "d3".',_e),we())}):se==="webgpu"?(async()=>{let{WebGPUForceLayoutController:_e}=await import("./webgpu-SY2OB4QP.mjs");if(he.cancelled)return;let ve={nodes:[],edges:[],layoutNodes:[],layoutEdges:[]},Je=fe.current,ye=new _e(ve,H,{device:Je?Je.shared.ensureDevice("layout"):void 0,onTick:Je?Ie=>Je.shared.notePositionsWritten(Ie):void 0});ye.setReadbackTimingSink?.(Ie=>{yu(Ie)}),ye.config(()=>Z),ye.transitionDimensions(ee);let nt={mode:"cpu",get sharedArray(){return ye.sharedArray},getPositionTexture:()=>null,getTextureSize:()=>0,getSpaceSize:()=>ye.getSpaceSize(),tick:()=>{ye.setReadbackInterval(Et.current?.usesGpuPositions()?Jm:null)},start:()=>{ye.startLayout()},stop:()=>{ye.stopLayout()},get graph(){return ye.graph},pinNodes:Ie=>{ye.pinNodes?.(Ie)},unpinNodes:Ie=>{ye.unpinNodes?.(Ie)},get needsUpdate(){return!ye.isFinish},clearNeedsUpdate:()=>{},transitionDimensions:(Ie,bt)=>{ye.transitionDimensions?.call(ye,Ie,bt)},getDimensions:()=>{let Ie=ye.getDimensions;return Ie?Ie.call(ye):3}};Y.length>0&&(ve.layoutNodes=Y.map(Ie=>({id:Ie.id,position:new ot.Vector3(Math.random()*2-1,Math.random()*2-1,0),pinned:!1,isPositionDirty:!1})),ve.layoutEdges=pe.map(Ie=>({id:Ie.id,sourceId:Ie.source,targetId:Ie.target}))),Fe(ye,nt)})().catch(_e=>{he.cancelled||(console.warn('[kineviz.gl] forceLayout: the WebGPU layout engine is unavailable; falling back to "d3".',_e),we())}):we(),()=>{let _e=he.cancel();if(_e){try{_e.destroy()}catch{}un.current===_e&&(un.current=null,Ko.current=null,Qd(null))}}},[k,ag,A]),ke(()=>{let _=A??Xd??null;if(!k||!_){vt.current=null;return}let H=k.store,ne={getNodeIndex:ee=>H.index.getNodeIndex(ee),getNodeCount:()=>H.nodeCount,get structureEpoch(){return H.structureEpoch}},Z,q=_,ae=q.graph?.layoutNodes&&typeof q.pinNodes=="function";if(q.mode==="gpu"&&ae)Z=new Yi(q,{bridge:ne});else if(q.mode==="cpu"&&ae&&q.sharedArray){let ee=new us(q);ee.setIndexBridge(ne),Z=ee}else"mode"in _?Z=_:Z=new Yi(q,{bridge:ne});vt.current=Z,un.current===_&&(Ko.current=_),k.store.setPositionProvider(Z),Mr.patch({layoutController:_,layoutPositionProvider:Z}),re.current&&re.current.wireLayoutRuntime(Z),re.current&&re.current.wireLayoutController(_);let se={pinNodes(ee){if(ee.length===0||!_.pinNodes)return;let Y=Z.getPositions?.();if(!Y)return;let pe=[];for(let me of ee){let he=k.store.index.getNodeIndex(me);he!==void 0&&pe.push({id:me,position:{x:Y[he*3]??0,y:Y[he*3+1]??0,z:Y[he*3+2]??0},pinned:!0})}pe.length>0&&_.pinNodes(pe)},unpinNodes(ee){ee.length>0&&_.unpinNodes&&_.unpinNodes(ee)}};return k.store.setLayoutRuntime(se),k.store.onStructureChange=()=>{Tr.current=!0,Ue.current=!0,Qe.current?.markStructureChanged()},k.store.nodeCount>0&&k.store.onStructureChange(),G&&!Jp.delete(_)&&_.start?.(),k.invalidate(),()=>{vt.current=null,k.store.onStructureChange=null,Mr.patch({layoutController:void 0,layoutPositionProvider:void 0}),k.store.setLayoutRuntime(null),re.current&&re.current.wireLayoutRuntime(null),re.current?.wireLayoutController(null)}},[k,A,Xd,G]);let Uc=F??(!A&&typeof C=="object"&&C.engine==="webgl"&&kn===void 0&&f===void 0);ke(()=>{if(!k||!Uc)return;let _=Yt.current,H=k.container,ne=!0,Z=()=>{_.delete("autoFit");for(let q of eg)H?.removeEventListener(q,Z,!0)};for(let q of eg)H?.addEventListener(q,Z,{capture:!0,passive:!0});return _.set("autoFit",()=>{let q=re.current?.camera;if(!q)return!1;let ae=cr.current?.isFinish===!0,se=q.fitStep(ne||ae?1:ey,{scale:ty});return se&&(ne=!1),ae&&!ne&&Z(),se}),k.invalidate(),Z},[k,Uc]),ke(()=>{if(!k||!ur)return;let _=typeof ur=="object"?ur:{},{positionProvider:H,iconAtlas:ne,iconColumns:Z,pinTexture:q,avatarTexture:ae,defaultNodeSize:se,...ee}=_;se!==void 0&&(k.store.defaultNodeSize=se);let Y=(fe.current?.activeBackend()??Ac).createNodeRenderer(k.cloudScene,k.store,{useCircle:!0,lightMode:!tt.isDark,...ee});if(Y.init(),ue.current=Y,k.container&&Y.setResolution(k.container.clientWidth,k.container.clientHeight),It&&Y.setMapMode(!0,ft.current,ut.current),H?Y.setPositionProvider(H):vt.current?Y.setPositionProvider(vt.current):k.store.positionProvider&&Y.setPositionProvider(k.store.positionProvider),ne&&Z&&Y.setIconAtlas(ne,Z),q&&Y.setPinTexture(q),ae&&Y.setAvatarTexture(ae),k.interaction&&Y.getMesh()){let pe=Y.getMesh();if(pe&&pe.geometry){k.interaction.setupNodePicking(pe.geometry),k.interaction.syncTransforms(Ge.current),ee.nodeSizeScale!==void 0&&k.interaction.picker?.setNodeSizeScale(ee.nodeSizeScale),k.interaction.picker?.setMinPixelSize(Y.config.minPixelSize);let me=k.store.positionProvider;me?.mode==="gpu"&&k.interaction.updatePositionTexture(me.getPositionTexture(),me.getTextureSize(),me.getSpaceSize())}}return k.invalidate(),()=>{Y.dispose(),ue.current=null}},[k,ur]),ke(()=>{It&&(ue.current?.setMapMode(!0,ft.current,ut.current),le.current?.setMapMode(!0,ft.current,ut.current),le.current?.setSphereRadius(ft.current),k?.invalidate())},[It,k,ur,Fi]),ke(()=>{if(typeof ur=="object"&&ur.lightMode!==void 0)return;let _=ue.current;_&&(_.setOptions({lightMode:!tt.isDark}),k?.invalidate())},[k,ur,tt.isDark]),ke(()=>{let _=ue.current;if(!k?.interaction||!_)return;let H=_.getMesh();!H||!H.geometry||(k.interaction.setupNodePicking(H.geometry),k.interaction.syncTransforms(Ge.current),k.interaction.picker?.setMinPixelSize(_.config.minPixelSize))},[k?.interaction]),ke(()=>{let _=ue.current,H=lr.current;if(!_||!k)return;if(!H||!H.hasFonts()){_.setIconSdfAtlas(null);return}let ne=k.store,Z=ne.iconVersion,q=H.fontsVersion,ae=_;if(ae.__lastIconVersion===Z&&ae.__lastFontsVersion===q)return;ae.__lastIconVersion=Z,ae.__lastFontsVersion=q,_.setIconSdfAtlas(H.getTexture());let se=ne.nodeCount,ee=ne.data.nodes,Y=new Float32Array(se*4).fill(-1);for(let pe=0;ne.iconNames.size>0&&pe<ee.length;pe++){let me=ne.getNodeIconName(ee[pe].id);if(!me)continue;let he=H.ensureIcon(me);he&&(Y[pe*4]=he.u0,Y[pe*4+1]=he.v0,Y[pe*4+2]=he.u1,Y[pe*4+3]=he.v1)}_.updateIconUVs(Y),H.isDirty()&&_.setIconSdfAtlas(H.getTexture()),k.invalidate()}),ke(()=>{let _=++wr.current,H=!1,ne=ue.current,Z=k?.imageAtlasManager;if(!ne||!k||!Z)return()=>{H=!0};let q=k.store;if(q.imageUrls.size===0)return ne.setImageAtlas(null),()=>{H=!0};let se=q.data.nodes,ee=[];for(let Y=0;Y<se.length;Y++){let pe=q.getNodeImageUrl(se[Y].id);pe&&ee.push(Z.setImage(se[Y].id,pe).then(()=>{}))}return Promise.all(ee).then(()=>{if(H||_!==wr.current)return;let Y=ue.current;if(!Y)return;let pe=k.store,me=pe.data.nodes,he=pe.nodeCount,Fe=new Float32Array(he*4).fill(-1);for(let we=0;we<me.length;we++){let je=Z.getImageUVs(me[we].id);je&&(Fe[we*4]=je.u0,Fe[we*4+1]=je.v0,Fe[we*4+2]=je.u1,Fe[we*4+3]=je.v1)}Y.updateImageUVs(Fe),Y.setImageAtlas(Z.getTexture()),k.invalidate()}).catch(Y=>{H||_!==wr.current||console.warn("Failed to sync internal node image atlas:",Y)}),()=>{H=!0}}),ke(()=>{if(!k||!Fi)return;let _=typeof Fi=="object"?Fi:{},{positionProvider:H,lineWidthScale:ne=1,showArrows:Z=!1,arrowScale:q,sizeAttenuation:ae,dashArray:se,dashOffset:ee,dashRatio:Y,...pe}=_,me=(fe.current?.activeBackend()??Ac).createEdgeRenderer(k.cloudScene,k.store,{lineWidth:ne,...pe});if(me.init(),le.current=me,It&&(me.setMapMode(!0,ft.current,ut.current),me.setSphereRadius(ft.current)),H?me.setPositionProvider(H):vt.current?me.setPositionProvider(vt.current):k.store.positionProvider&&me.setPositionProvider(k.store.positionProvider),me.setShowArrows(Z),k.container&&me.setResolution(k.container.clientWidth,k.container.clientHeight),k.interaction){let he=me.getMesh();he&&he.geometry&&he.material&&(k.interaction.setupEdgePicking(he.geometry,he.material),k.interaction.syncTransforms(Ge.current,he));let Fe=me.createSelfLoopPickingMesh(we=>{let je=ph.encodeId(we,"edge");return[(je>>16&255)/255,(je>>8&255)/255,(je&255)/255]});Fe&&k.interaction.addSelfLoopPickingMesh(Fe)}return k.invalidate(),()=>{me.dispose(),le.current=null}},[k,Fi]);let hn=typeof ur=="object"?ur.nodeSizeScale:void 0;ke(()=>{hn!==void 0&&(k?.store.setGlobalNodeSizeScale(hn),le.current?.setNodeSizeScale(hn),k?.invalidate())},[hn,k]),ke(()=>{let _=le.current;if(!k?.interaction||!_)return;let H=_.getMesh();H&&H.geometry&&H.material instanceof ot.ShaderMaterial&&(k.interaction.setupEdgePicking(H.geometry,H.material),k.interaction.syncTransforms(k.cloudScene,H))},[k?.interaction]),ke(()=>{let _=Ce.current;if(!_)return;let H=ue.current||Te.current,ne=le.current||xe.current;_.setTransactionContext({nodeRenderer:H??null,edgeRenderer:ne??null,picker:_.picker??null,iconAtlasManager:lr.current??null})},[k?.interaction,L]),ke(()=>{let _=re.current;if(!_)return;let H=ne=>{if(ne.key!=="Delete"&&ne.key!=="Backspace")return;let Z=ne.target;if(Z){let se=Z.tagName;if(se==="INPUT"||se==="TEXTAREA"||se==="SELECT"||Z.isContentEditable)return}if(!_.selection.hasSelection())return;ne.preventDefault();let q=_.selection.getSelectedNodeIds(),ae=_.selection.getSelectedEdgeIds();ae.length>0&&_.edges.remove(ae),q.length>0&&_.nodes.remove(q),Ue.current=!0};return document.addEventListener("keydown",H),()=>document.removeEventListener("keydown",H)},[k]),ke(()=>{ge.current=a??null},[a]);let dg=Xm(()=>{ki(null),Ue.current=!0},[]);Gp({apiInstanceRef:re,storeRef:Xe,interactionRef:Ce,renderRuntimeRef:Qe,needsRenderRef:Ue,apiOptions:y,is3DProp:Q,defaultDim:$,resolvedTheme:tt,is3D:rt});let Ee=re.current,Wc=be(!1);if(Ee&&Ce.current?.shortcuts&&!Wc.current){let _=Ce.current.shortcuts,H=Ee.history;_.setHandler("data.undo",()=>{H.undo(),Ue.current=!0}),_.setHandler("data.redo",()=>{H.redo(),Ue.current=!0}),_.setHandler("data.redoAlt",()=>{H.redo(),Ue.current=!0});let ne=Ce.current,Z=ne.selection,q=Xe.current,ae=()=>{if(!Z.hasSelection)return;let ee=Z.selectedNodeIds,Y=Z.selectedEdgeIds;Z.clearSelection({syncStore:!1});let pe=new Set(ee),me=Y.filter(he=>{let Fe=q.index.edgeIdToIndex.get(he);if(Fe===void 0)return!1;let we=q.data.edges[Fe];return we&&!pe.has(we.source)&&!pe.has(we.target)});me.length>0&&Ee.edges.remove(me),ee.length>0&&Ee.nodes.remove(ee)};_.setHandler("edit.delete",ae),_.setHandler("edit.deleteAlt",ae),_.setHandler("edit.pinToggle",()=>{let ee=Z.selectedNodeIds;if(ee.length===0)return;let Y=q.index.getNodeIndex(ee[0]);if(Y===void 0)return;q.nodeState?.pinned[Y]===1?Ee.nodes.unpin(ee):Ee.nodes.pin(ee)});let se=ne.drag;if(se){let ee=null;se.onDragStart(Y=>{let pe=q.positionProvider?.getPositions();if(pe){ee=new Map;for(let me of Y.nodeIds){let he=q.index.nodeIdToIndex.get(me);he!==void 0&&ee.set(me,[pe[he*3],pe[he*3+1],pe[he*3+2]])}}}),se.onDragEnd(Y=>{if(!ee||ee.size===0)return;let pe=q.positionProvider?.getPositions();if(!pe){ee=null;return}let me=new Map;for(let Fe of Y.nodeIds){let we=q.index.nodeIdToIndex.get(Fe);we!==void 0&&me.set(Fe,[pe[we*3],pe[we*3+1],pe[we*3+2]])}let he=new en(q,ee,me);Ee.history.execute(he),Ee.history.flush(),ee=null})}Wc.current=!0}if(jn.current||(jn.current=new Ns),Ee&&!qo.current&&(qo.current=Ee.cards.manager),Ee&&!Gi.current){let _=Ee.ui.contextMenu.manager;Gi.current=_;let H=Xe.current,Z=Ce.current?.selection;_.registerItems(Th({pinToggle:q=>{let ae=q.selectedNodeIds;if(ae.length===0)return;let se=H.index.getNodeIndex(ae[0]);if(se===void 0)return;H.nodeState?.pinned[se]===1?Ee.nodes.unpin(ae):Ee.nodes.pin(ae),Ue.current=!0},deleteSelected:q=>{let ae=q.selectedEdgeIds,se=q.selectedNodeIds;Z?.clearSelection();let ee={};se.length>0&&(ee.removedNodeIds=se),ae.length>0&&(ee.removedEdgeIds=ae),(ee.removedNodeIds||ee.removedEdgeIds)&&H.applyDelta(ee),Ue.current=!0},hideSelected:q=>{let ae=q.selectedNodeIds;ae.length>0&&Ee.nodes.hide(ae),Z?.clearSelection(),Ue.current=!0},showHidden:()=>{Ee.nodes.showAll(),Ue.current=!0},hasHiddenItems:()=>{if(!H.nodeState)return!1;for(let q=0;q<H.data.nodes.length;q++)if(H.nodeState.hidden[q]===1)return!0;return!1},fitToScreen:()=>{Ae.current?.reset(),Ue.current=!0},showNodeInfo:q=>{q.nodeId&&jn.current?.show(q.nodeId,q.screenPosition)},createNodeHere:q=>{let ae=ge.current,se=Me.current,ee=Ge.current;if(!ae)return;let Y=ae.getBoundingClientRect(),pe=q.screenPosition.x-Y.left,me=q.screenPosition.y-Y.top,he=pe/ae.clientWidth*2-1,Fe=-(me/ae.clientHeight)*2+1,we=new ot.Raycaster;we.setFromCamera(new ot.Vector2(he,Fe),se);let je=new ot.Plane(new ot.Vector3(0,0,1),-ee.position.z),Rt=new ot.Vector3;we.ray.intersectPlane(je,Rt),ee.worldToLocal(Rt);let _e={x:Rt.x,y:Rt.y,z:0},ve={sourceNodeIds:[],targetNodeId:null,dropScreenPosition:q.screenPosition,dropWorldPosition:_e};jo(void 0),ki(ve)},changeCategory:q=>{if(q.selectedNodeIds.length===0)return;let ae=Fc.current;ae&&(re.current&&!ae._api&&ae.setEngineApi(re.current),ae.start({nodeIds:[...q.selectedNodeIds]}))},createEdgeFrom:q=>{console.warn("[createEdgeFrom fallback] EdgeCreateHandler not available via ctx.interaction")}}))}ke(()=>(g&&Ee&&(g.current=Ee),()=>{g&&(g.current=null)}),[Ee,g]),ke(()=>{Ee&&Ee.renderer.wireRenderPath({setHostEnabled:_=>fe.current?.setHostEnabled(_),isHostEnabled:()=>fe.current?.isHostEnabled()??!1})},[Ee]),ke(()=>{Ee&&Ee.events.emit("ready",{})},[Ee]),ke(()=>Ee?.map?(Ee.map.setProvider(nr),Ee.events.on("map:enabled",H=>{Ee.map.setProvider(nr)})):void 0,[Ee,nr]);let jc=be(te);if(ke(()=>{jc.current=te},[te]),ke(()=>{if(!Ee)return;Lt(Ee.renderer.isMinimapVisible()),Ee.map.wireMapDamping(H=>{k?.setMapDamping(H)}),Ee.map.setMaxNodeGrowth(Lc),Ee.map.wireMapMaxGrowth(H=>{k?.setMapMaxGrowth(H)}),Ee.renderer.wireMaxScreenFraction(H=>{k?.setMaxScreenFraction(H)}),hn!==void 0&&Ee.renderer.setNodeSizeScale(hn),Ee.renderer.wireNodeSizeScale(H=>{k?.setNodeSizeScale(H)});let _=Ee.events.on("view:changed",H=>{H.minimapVisible!==void 0&&Lt(H.minimapVisible),H.theme!==void 0&&on(H.theme),H.mode!==void 0&&k?.setIs3D(H.mode==="3D"),jc.current?.(H)});return()=>{_()}},[Ee,k,Lc,hn]),ke(()=>()=>{re.current?.dispose(),jn.current?.dispose()},[]),!k)return a==null?Ze(Yo.Provider,{value:Ee,children:_c(dl.Provider,{value:k,children:[Ze("div",{ref:U,className:e,style:{width:"100%",height:"100%",position:"relative",...t}}),null]})}):null;let lg=Se&&Se.geoLayout!==!1,qc=Se?.autoFit??!lg,Kc=Se?.tileProvider??cn?.tileProvider,cg=Se?.mapSize??cn?.mapSize,ug=Se?.globeRadius??cn?.globeRadius,tl=Ct("flatMap"),rl=Ct("globeMap"),nl=Ct("geoEgoRing"),$c=Ct("egoCollapse"),il=Ct("minimap"),ol=Ct("toolbar"),sl=Ct("legend"),Zc=Ct("cards"),Yc=Ct("nodeInfo"),Xc=Ct("quickCreate"),Qc=Ct("contextMenu");Vt&&!(Vt==="flat"?tl:rl)&&Yn(Vt==="flat"?"flatMap":"globeMap","The map layer"),P&&!il&&Yn("minimap","The minimap"),E!==!1&&!ol&&Yn("toolbar","The toolbar"),M&&!sl&&Yn("legend","The legend");let hg=Vt==="flat"&&tl?Ze(tl,{tileProvider:Kc,tileUrl:Se?.tileUrl,tileUrl2x:Se?.tileUrl2x,mapSize:cg,minLevel:Se?.minLevel,maxLevel:Se?.maxLevel,autoFit:qc,visible:Se?.visible,swapTokenRef:Ut}):Vt==="globe"&&rl?Ze(rl,{tileProvider:Kc,tileUrl:Se?.tileUrl,tileUrl2x:Se?.tileUrl2x,radius:ug,minAltitude:Se?.minAltitude,minLevel:Se?.minLevel,maxLevel:Se?.maxLevel,mercatorProjection:Se?.mercatorProjection,autoFit:qc,visible:Se?.visible,swapTokenRef:Ut}):null,pg=typeof Se?.geoLayout=="object"&&Se.geoLayout?Se.geoLayout.ringGapPx??50:50,qn=typeof Se?.geoLayout=="object"?Se.geoLayout?.collapse:void 0;Ye&&!rt&&Ye.nonGeoIds.length>0&&!nl&&Yn("geoEgoRing","The ego-ring layout of non-geo nodes");let gg=Ye&&!rt&&Ye.nonGeoIds.length>0&&nl?Ze(nl,{geoIds:Ye.geoIds,nonGeoIds:Ye.nonGeoIds,edges:Ye.edges,ringGapPx:pg,expandedAnchors:qn?On:void 0,neighbourCap:qn?.neighbourCap,maxViewportFraction:qn?.maxViewportFraction,onFitMetrics:qn?.expandZoom==="auto"?ar:void 0}):null,fg=Ye&&!rt&&qn&&$c?Ze($c,{geoIds:Ye.geoIds,nonGeoIds:Ye.nonGeoIds,edges:Ye.edges,config:qn,onExpandedChange:ln,getFitMetrics:Di}):null,Zo=Ci(T)||null,Kn=Ci(I),Ir=Zo||$o?{...Zo??{},...$o?{property:$o.config.property??Zo?.property,scale:(Zo?.scale??1)*$o.scale,visible:!0}:{}}:null,mg=!Hi&&_c(ny,{children:[Ir&&Ir.visible!==!1&&Ze(Eh,{position:Ir.position??"right",radialCenter:Ir.radialCenter,scale:Ir.scale??1,maxLength:Ir.maxLength??50,property:Ir.property,properties:Ir.properties,autoCaption:Ir.autoCaption??!0}),Kn&&Kn.visible!==!1?Ze(hc,{showRelationshipName:Kn.showRelationshipName??!1,property:Kn.property,scale:Kn.scale??.9,maxLength:Kn.maxLength??50}):Ze(hc,{})]});return Ze(Yo.Provider,{value:Ee,children:_c(dl.Provider,{value:k,children:[a==null&&Ze("div",{ref:U,className:e,style:{width:"100%",height:"100%",position:"relative",...t}}),o,Ze(fp,{}),mg,hg,gg,fg,Ze(wh,{}),Ze(lp,{}),Ze(pp,{}),Wo&&k?.store&&Xc&&Ze(Xc,{result:Wo,store:k.store,container:k.container||void 0,allowedRelationships:jr,onDone:dg,onCreated:()=>{Ue.current=!0}}),Gi.current&&Qc&&Ze(Qc,{manager:Gi.current,container:k.container}),jn.current&&k?.store&&Yc&&Ze(Yc,{manager:jn.current,store:k.store,container:k.container,locale:N}),qo.current&&k?.store&&Zc&&Ze(Zc,{manager:qo.current,store:k.store,container:k.container}),Hn&&Ot&&il&&Ze(il,{...typeof Hn=="object"?Hn:{}}),E!==!1&&ol&&Ze(ol,{config:E===!0?!0:E,locale:N}),M&&sl&&Ze(sl,{store:Xe.current,api:re.current,visible:typeof M=="object"?M.visible:!0,locale:N,minimapVisible:!!(Hn&&Ot),iconAtlasManager:lr.current})]})})}var WT=ry;import{useEffect as Kt,useRef as rg}from"react";import*as To from"three";var iy="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAC5klEQVR4Xu2b8VUUQQzG81WgdCAdSAVIBWoFSgViBUAF0oFSgVqBWAF0IB2IFYSXezsy7vN8yWySOdyZvzO3k98mmcm3c6CVD6zcfxoARgQEE2Dmt0T0gYieGh91R0TvAXwyzjOZh6cAM18T0XPTqh6MbwAcNM5VTcsAwKqVbDECELrG0B8Xn5j5iogOGyF8B/Cica5qWgYAyf0LInqjWtGD0SURnQCQWhA2wgGUlU/F8KPSk9cAvihtF5mlAZjSQVUPovO+JjYALIofw2RmlmL2TTnlCIAUz/CRFgHM/IqIPis9+v9qADOfEdGpEsA5ALEPH5kRIFX9pdKjrwAkYsJHJgDLkTj8CFzIZgJQbYG/FxZ8BE4FwMzPiOiHMZ73Adwa55jNUyLAuAUWJ1K2wiwAlh2gAEjZCbIASDP0zhiflwBETAkdWQBaWuLwVljIZgH42SKJAdgLff0ZAJhZ9AAB0DL2Hr0e0LgDpO0E4Slg7AHmURK+E4QCYGZRg6UFtkriBYTIYXIeuGnJH82cMADMLJ3fyQLnawgXAM41Dllt3AFMb120v9ZvAdt8kCg49o4GVwBTxZeQ93a+QBEIkhJuSrE3AHE+VMcnoisAR9ZQ32bvBmDhdmf1x61R8gRgUXysDs/t3RQjTwAWxWcpgFsA+0t/xLUXYGaT4rN08V4fTzwjQCrzk6WOKef/AtB6uPrjEZ4ApHfXfvtT+rnVTM4DLhcn3ABYPZqnjFdIW9fRE0CdMm4h/ZgA1CpRivrzNzg9I2AAqK7OrDICpIqXazMpCvCupUD9rSBc+QlvhqzVdyaVDQBZ9wHmL6rnLlDfGHFrb62R2BNAfWdoAMi6FLVLKSC6oWgIMg68xU5tKnRLAVlgaYh6NUKugoiWeG03AEwq0pojYHMHCIDcIeoyeteAzXXY6P8E/IvsANAl7qaHTv8mWXUEyOWpu159wC5sg5sL0asF0DP9yrO7FsEBYAcIrD4C7gEk5hBQowJRiwAAAABJRU5ErkJggg==",Dc=null;function Nc(){if(Dc)return Dc;let a=new To.TextureLoader().load(iy);return a.minFilter=To.LinearFilter,a.magFilter=To.LinearFilter,Dc=a,a}function tM({positionProvider:a,iconAtlas:e,iconColumns:t,pinTexture:r,avatarTexture:n,useCircle:i=!0,iconMode:o=1,iconDisplayMode:s=0,hidePin:d=!1,hideRing:l=!1,lightMode:u,theme:c,fixedSize:h=0,nodeSizeScale:p,minPixelSize:f,primitive:m,defaultNodeSize:g,maxNodes:y,onReady:v}){let{store:b,cloudScene:x,invalidate:w,container:T,registerNodeRenderer:I,interaction:R,renderBackend:S}=dt(),P=gn(),D=_r(),E=pn(),M=zi(),{iconAtlasManager:N,imageAtlasManager:A}=Dr(),C=rg(null),F=rg(0),G=fn(),L=ll();Kt(()=>{g!==void 0&&(b.defaultNodeSize=g);let B=S.createNodeRenderer(x,b,{maxNodes:y,useCircle:i,iconColumns:t,iconMode:o,iconDisplayMode:s,hidePin:d,hideRing:l,lightMode:c?c==="light":u!==void 0?u:!P.isDark,fixedSize:h,nodeSizeScale:p,minPixelSize:f,primitive:m});if(B.init(),C.current=B,T&&B.setResolution(T.clientWidth,T.clientHeight),a?B.setPositionProvider(a):b.positionProvider&&B.setPositionProvider(b.positionProvider),e&&t&&B.setIconAtlas(e,t),B.setPinTexture(r??Nc()),n&&B.setAvatarTexture(n),I(B),R){let K=B.getMesh();K&&K.geometry&&(R.setupNodePicking(K.geometry),R.syncTransforms(x))}return v?.(B),w(),()=>{I(null),B.dispose(),C.current=null}},[x,b,m]),Kt(()=>{C.current?.setMapMode(D,M,E),w()},[D,E,M,x,b,w]),Kt(()=>{let B=C.current;if(!R||!B)return;let K=B.getMesh();K&&K.geometry&&(R.setupNodePicking(K.geometry),R.syncTransforms(x),R.picker?.setMapMode(D,M,E),p!==void 0&&R.picker?.setNodeSizeScale(p),R.picker?.setMinPixelSize(B.config.minPixelSize))},[R,x,D,E,M,p,m]),Kt(()=>{C.current&&a&&(C.current.setPositionProvider(a),w())},[a,w]),Kt(()=>{C.current&&e&&t&&(C.current.setIconAtlas(e,t),w())},[e,t,w]),Kt(()=>{C.current&&(C.current.setPinTexture(r??Nc()),w())},[r,w]),Kt(()=>{C.current&&n&&(C.current.setAvatarTexture(n),w())},[n,w]);let V=c?c==="light":u!==void 0?u:!P.isDark;return Kt(()=>{C.current&&(C.current.setOptions({useCircle:i,iconMode:o,iconDisplayMode:s,hidePin:d,hideRing:l,lightMode:V,fixedSize:h}),w())},[i,o,s,d,l,V,h,w]),Kt(()=>{let B=C.current;B&&(B.setMinPixelSize(f??Number.NaN),R?.picker?.setMinPixelSize(B.config.minPixelSize),w())},[f,w,R]),Kt(()=>{C.current&&p!==void 0&&(C.current.setNodeSizeScale(p),R?.picker?.setNodeSizeScale(p),w())},[p,w,R]),Kt(()=>{let B=C.current;if(!B||!N||!N.hasFonts()){B&&B.setIconSdfAtlas(null);return}B.setIconSdfAtlas(N.getTexture());let K=b.nodeCount,oe=b.nodeState?.iconUVs,Q;oe&&oe.length>=K*4?Q=oe.slice(0,K*4):Q=new Float32Array(K*4).fill(-1);let $=b.data.nodes;b.iconNames.size===0&&Q.fill(-1);for(let z=0;b.iconNames.size>0&&z<$.length;z++){let W=b.getNodeIconName($[z].id);if(!W){Q[z*4]=-1,Q[z*4+1]=-1,Q[z*4+2]=-1,Q[z*4+3]=-1;continue}let te=N.ensureIcon(W);te&&(Q[z*4]=te.u0,Q[z*4+1]=te.v0,Q[z*4+2]=te.u1,Q[z*4+3]=te.v1)}B.updateIconUVs(Q),N.isDirty()&&B.setIconSdfAtlas(N.getTexture()),w()},[L,N,b,w]),Kt(()=>{let B=++F.current,K=!1,oe=C.current;if(!oe||!A)return()=>{K=!0};if(b.imageUrls.size===0)return oe.setImageAtlas(null),()=>{K=!0};let $=b.data.nodes,z=[];for(let W=0;W<$.length;W++){let te=b.getNodeImageUrl($[W].id);te&&z.push(A.setImage($[W].id,te).then(()=>{}))}return Promise.all(z).then(()=>{if(K||B!==F.current)return;let W=C.current;if(!W)return;let te=b.nodeCount,Ne=b.data.nodes,Pe=new Float32Array(te*4).fill(-1);for(let Ve=0;Ve<Ne.length;Ve++){let Oe=A.getImageUVs(Ne[Ve].id);Oe&&(Pe[Ve*4]=Oe.u0,Pe[Ve*4+1]=Oe.v0,Pe[Ve*4+2]=Oe.u1,Pe[Ve*4+3]=Oe.v1)}W.updateImageUVs(Pe),W.setImageAtlas(A.getTexture()),A.isDirty()&&W.setImageAtlas(A.getTexture()),w()}).catch(W=>{K||B!==F.current||console.warn("Failed to sync node image atlas:",W)}),()=>{K=!0}},[G,A,b,w]),null}import*as kc from"three";import{useEffect as Sr,useRef as oy}from"react";function oM({positionProvider:a,maxEdges:e,lineWidthScale:t=1,sizeAttenuation:r=!1,showArrows:n=!1,arrowScale:i=1,nodeSizeScale:o,dashArray:s,dashOffset:d,dashRatio:l,edgeShape:u,radialAxis:c,onReady:h}){let{store:p,cloudScene:f,invalidate:m,container:g,registerEdgeRenderer:y,interaction:v,renderBackend:b}=dt(),x=oy(null);return Sr(()=>{let w={maxEdges:e,lineWidth:t,hideArrows:!n,nodeSizeScale:o,edgeShape:u,radialAxis:c},T=b.createEdgeRenderer(f,p,w);if(T.init(),x.current=T,a?T.setPositionProvider(a):p.positionProvider&&T.setPositionProvider(p.positionProvider),g&&T.setResolution(g.clientWidth,g.clientHeight),y(T),v){let I=T.getMesh();I&&I.geometry&&I.material instanceof kc.ShaderMaterial&&(v.setupEdgePicking(I.geometry,I.material),v.syncTransforms(f,I))}return h?.(T),m(),()=>{y(null),T.dispose(),x.current=null}},[f,p]),Sr(()=>{let w=x.current;if(!v||!w)return;let T=w.getMesh();T&&T.geometry&&T.material instanceof kc.ShaderMaterial&&(v.setupEdgePicking(T.geometry,T.material),v.syncTransforms(f,T))},[v,f]),Sr(()=>{x.current&&a&&(x.current.setPositionProvider(a),m())},[a,m]),Sr(()=>{x.current&&(x.current.setLineWidthScale(t),m())},[t,m]),Sr(()=>{x.current&&(x.current.setShowArrows(n),m())},[n,m]),Sr(()=>{x.current&&o!==void 0&&(x.current.setNodeSizeScale(o),m())},[o,m]),Sr(()=>{x.current&&(s!==void 0||d!==void 0||l!==void 0)&&(x.current.setDashPattern(!0,s,d,l),m())},[s,d,l,m]),Sr(()=>{x.current&&u&&(x.current.setEdgeShape(u),m())},[u,m]),Sr(()=>{x.current&&c&&(x.current.setRadialAxis(c),m())},[c,m]),Sr(()=>{if(!g||!x.current)return;let w=()=>{x.current&&g&&(x.current.setResolution(g.clientWidth,g.clientHeight),m())},T=new ResizeObserver(w);return T.observe(g),()=>{T.disconnect()}},[g,m]),null}function dM(){let{invalidate:a}=dt();return a}import*as Re from"three";function sy(a){let e=a.labelExtent??"auto";return e==="none"?null:e==="auto"?a.hideBuiltinNode||(a.hitArea??"none")!=="none"?[1,1]:null:[Math.max(0,e[0]),Math.max(0,e[1])]}var Ti={1:"float",2:"vec2",3:"vec3",4:"vec4"},wi=a=>a.charAt(0).toUpperCase()+a.slice(1),ng=`uniform float uMapMode;
370
+ uniform float uMapDamping;
371
+ uniform float uMapMaxGrowth;`,ig=`
372
+ vec4 mv = modelViewMatrix * vec4(aCenter, 1.0);
373
+ float viewDepth = max(-mv.z, 0.001);
374
+ float scale = 50.0 / viewDepth;
375
+ if (uMapMode > 0.5) {
376
+ scale = 5.0 * kvMapGrowth(pow(10.0 / viewDepth, uMapDamping), uMapMaxGrowth);
377
+ }
378
+ float px = clamp(aSize * scale * uSizeFactor, 1.5, 4096.0);
379
+ vec4 clip = projectionMatrix * mv;
380
+ vec2 offset = corner * px / uResolution * 2.0 * clip.w;
381
+ gl_Position = clip + vec4(offset, 0.0, 0.0);`,og=`
382
+ vec3 world = aCenter + vec3(corner * aSize * uSizeFactor, 0.0);
383
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(world, 1.0);`;function ay(a){if(typeof a=="number")return"float";if(a instanceof Re.Color)return"vec3";if(a instanceof Re.Vector2)return"vec2";if(a instanceof Re.Vector3)return"vec3";if(a instanceof Re.Vector4)return"vec4";if(a instanceof Re.Texture)return"sampler2D";if(Array.isArray(a)&&a.length>=2&&a.length<=4)return Ti[a.length];throw new Error(`[createNodeShaderLayer] unsupported uniform value: ${JSON.stringify(a)}`)}function dy(a){let e=a.followDim!==!1,t=a.animate===!0,r=a.attributes??[],n=r.map(c=>`attribute ${Ti[c.size]} ${c.name};`).join(`
384
+ `),i=r.map(c=>`varying ${Ti[c.size]} v${wi(c.name)};`).join(`
385
+ `),o=r.map(c=>` v${wi(c.name)} = ${c.name};`).join(`
386
+ `),s=(a.sizing??"screen")==="world"?og:ig,d=["precision highp float;","attribute vec3 aCenter;","attribute float aSize;",e?"attribute float aDim;":"",n,"uniform vec2 uResolution;","uniform float uSizeFactor;",ng,ml,"varying vec2 vUv;",e?"varying float vDim;":"",i,"void main() {"," vec2 corner = position.xy;"," vUv = corner + 0.5;",e?" vDim = aDim;":"",o,s,"}"].filter(Boolean).join(`
387
+ `),l=[t?"uniform float uTime;":"","uniform vec2 uResolution;",...Object.entries(a.uniforms??{}).map(([c,h])=>`uniform ${ay(h)} ${c};`)].filter(Boolean).join(`
388
+ `),u=["precision highp float;","varying vec2 vUv;",e?"varying float vDim;":"",i,l,a.fragmentShader].filter(Boolean).join(`
389
+ `);return{vertex:d,fragment:u}}function ly(a){let e=(a.sizing??"screen")==="world"?og:ig,t=a.hitArea==="shape"?a.hitMask:void 0;if(a.hitArea==="shape"&&!t)throw new Error('[createNodeShaderLayer] hitArea: "shape" needs a `hitMask`.');let r=t?`${t.prelude??""}
390
+ ${t.sdf}`:"",n=(a.attributes??[]).filter(d=>new RegExp(`\\bv${wi(d.name)}\\b`).test(r)),i=["precision highp float;","attribute vec3 aCenter;","attribute float aSize;","attribute vec3 aId;",...n.map(d=>`attribute ${Ti[d.size]} ${d.name};`),"uniform vec2 uResolution;","uniform float uSizeFactor;",ng,ml,"varying vec2 vUv;","varying vec3 vId;",...n.map(d=>`varying ${Ti[d.size]} v${wi(d.name)};`),"void main() {"," vec2 corner = position.xy;"," vUv = corner + 0.5;"," vId = aId;",...n.map(d=>` v${wi(d.name)} = ${d.name};`),e,"}"].join(`
391
+ `),o=t?` vec2 q = vUv - vec2(0.5);
392
+ if ((${t.sdf}) > 0.0) discard;`:a.hitArea==="circle"?" if (length(vUv - vec2(0.5)) > 0.5) discard;":"",s=["precision highp float;","varying vec2 vUv;","varying vec3 vId;",...n.map(d=>`varying ${Ti[d.size]} v${wi(d.name)};`),t?.prelude??"","void main() {",o," gl_FragColor = vec4(vId, 1.0);","}"].filter(Boolean).join(`
393
+ `);return{vertex:i,fragment:s}}var cy=[[-.5,.5],[.5,.5],[.5,-.5],[-.5,-.5]];function uy(a){if(Array.isArray(a)){if(a.length===2)return{value:new Re.Vector2(a[0],a[1])};if(a.length===3)return{value:new Re.Vector3(a[0],a[1],a[2])};if(a.length===4)return{value:new Re.Vector4(a[0],a[1],a[2],a[3])}}return{value:a}}var Gc=class{constructor(e){this.mesh=null;this.geom=null;this.mat=null;this.ctx=null;this.aCenter=null;this.aSize=null;this.aDim=null;this.userArrays=new Map;this.hitMesh=null;this.hitMat=null;this.hitTest=null;this.aId=null;this.slots=[];this.suppressedIds=[];this.lastNodeCount=-1;this.lastEpoch=-1;this.t=0;this.warnedOverflow=!1;this.lastLabelVersion=-1;this.spec=e,this.followDim=e.followDim!==!1,this.sizeFactor=e.sizeFactor??1,this.capacity=Math.max(e.maxNodes??256,1),this.labelQuad=sy(e)}reportLabelExtents(e){let t=this.labelQuad;if(!t)return;let r=e.store;if(r.version===this.lastLabelVersion)return;this.lastLabelVersion=r.version;let n=r.data.nodes,i=r.nodeState?.effectiveSizes??null,o=this.spec.size,s=this.spec.sizing==="world",d=new Map;for(let l of this.slots){let u=n[l];if(!u)continue;let c=i?i[l]:8,h=o?o(u,l):c;if(s){let p=.5*this.sizeFactor*h;d.set(u.id,{x:t[0]*p,y:t[1]*p,unit:"world"})}else{let p=this.sizeFactor*(c>0?h/c:1);d.set(u.id,{x:t[0]*p,y:t[1]*p,unit:"node"})}}r.setNodeLabelExtents?.(this,d)}mount(e){this.ctx=e;let t=this.capacity*4,r=new Re.BufferGeometry,n=new Float32Array(t*3);for(let u=0;u<t;u++){let c=cy[u%4];n[u*3]=c[0],n[u*3+1]=c[1],n[u*3+2]=0}r.setAttribute("position",new Re.Float32BufferAttribute(n,3));let i=(u,c)=>{let h=new Re.BufferAttribute(u,c);return h.setUsage(Re.DynamicDrawUsage),h};this.aCenter=new Float32Array(t*3),this.aSize=new Float32Array(t),r.setAttribute("aCenter",i(this.aCenter,3)),r.setAttribute("aSize",i(this.aSize,1)),this.followDim&&(this.aDim=new Float32Array(t).fill(1),r.setAttribute("aDim",i(this.aDim,1)));for(let u of this.spec.attributes??[]){let c=new Float32Array(t*u.size);this.userArrays.set(u.name,c),r.setAttribute(u.name,i(c,u.size))}let o=new Uint16Array(this.capacity*6);for(let u=0;u<this.capacity;u++){let c=u*4,h=u*6;o[h]=c,o[h+1]=c+1,o[h+2]=c+2,o[h+3]=c,o[h+4]=c+2,o[h+5]=c+3}r.setIndex(new Re.BufferAttribute(o,1)),r.setDrawRange(0,0);let{vertex:s,fragment:d}=dy(this.spec),l={uResolution:{value:new Re.Vector2(1,1)},uSizeFactor:{value:this.sizeFactor},uMapMode:{value:0},uMapDamping:{value:.3},uMapMaxGrowth:{value:4}};this.spec.animate&&(l.uTime={value:0});for(let[u,c]of Object.entries(this.spec.uniforms??{}))l[u]=uy(c);this.mat=new Re.ShaderMaterial({vertexShader:s,fragmentShader:d,uniforms:l,transparent:!0,depthTest:!1,depthWrite:!1,side:Re.DoubleSide,blending:this.spec.blending==="normal"?Re.NormalBlending:Re.AdditiveBlending}),this.geom=r,this.mesh=new Re.Mesh(r,this.mat),this.mesh.frustumCulled=!1,this.mesh.renderOrder=e.renderOrder(this.spec.band??"overlay",this.spec.bandOffset??0),e.cloudScene.add(this.mesh),this.mountHitMesh(e,r,t)}mountHitMesh(e,t,r){if((this.spec.hitArea??"none")==="none")return;let i=e.getHitTest?.()??null;if(!i)return;this.aId=new Float32Array(r*3);let o=new Re.BufferAttribute(this.aId,3);o.setUsage(Re.DynamicDrawUsage),t.setAttribute("aId",o);let s=ly(this.spec);this.hitMat=new Re.ShaderMaterial({vertexShader:s.vertex,fragmentShader:s.fragment,uniforms:{uResolution:this.mat.uniforms.uResolution,uSizeFactor:this.mat.uniforms.uSizeFactor,uMapMode:this.mat.uniforms.uMapMode,uMapDamping:this.mat.uniforms.uMapDamping,uMapMaxGrowth:this.mat.uniforms.uMapMaxGrowth},transparent:!0,depthTest:!1,depthWrite:!1,blending:Re.NoBlending,side:Re.DoubleSide}),this.hitMesh=new Re.Mesh(t,this.hitMat),this.hitMesh.frustumCulled=!1,this.hitMesh.renderOrder=1e3,i.addNodeHitMesh(this.hitMesh),this.hitTest=i}update(e){if(this.mat)for(let[t,r]of Object.entries(e)){let n=this.mat.uniforms[t];n&&(r instanceof Re.Color&&n.value instanceof Re.Color?n.value.copy(r):Array.isArray(r)&&n.value?.fromArray?n.value.fromArray(r):n.value=r)}}dispose(){this.labelQuad&&this.ctx&&this.ctx.store.setNodeLabelExtents?.(this,null),this.suppressedIds.length&&this.ctx&&(this.ctx.store.setNodeFillSuppressed(this.suppressedIds,!1),this.suppressedIds=[]),this.hitMesh&&this.hitTest&&this.hitTest.removeNodeHitMesh(this.hitMesh),this.mesh&&this.mesh.parent?.remove(this.mesh),this.geom?.dispose(),this.mat?.dispose(),this.hitMat?.dispose(),this.mesh=null,this.geom=null,this.mat=null,this.ctx=null,this.hitMesh=null,this.hitMat=null,this.hitTest=null,this.aId=null,this.aCenter=this.aSize=this.aDim=null,this.userArrays.clear()}refreshMembership(e){let t=e.store,r=t.nodeCount,n=this.spec.filter,i=t.structureEpoch;if(!n&&r===this.lastNodeCount&&i===this.lastEpoch)return!1;let o=t.data.nodes,s=[],d=Math.min(r,this.capacity);for(let c=0;c<d;c++)(!n||n(o[c],c))&&s.push(c);r>this.capacity&&!this.warnedOverflow&&(this.warnedOverflow=!0,console.warn(`[createNodeShaderLayer] ${r} nodes exceeds capacity ${this.capacity}; ${r-this.capacity} dropped. Pass { maxNodes } to raise it.`));let u=i!==this.lastEpoch||s.length!==this.slots.length||s.some((c,h)=>c!==this.slots[h]);if(this.lastNodeCount=r,this.lastEpoch=i,!u)return!1;this.slots=s;for(let c of this.spec.attributes??[]){if(c.dynamic)continue;this.writeAttr(c,e);let h=this.geom?.getAttribute(c.name);h&&(h.needsUpdate=!0)}if(this.aId&&this.hitTest){let c=this.aId;for(let p=0;p<this.slots.length;p++){let[f,m,g]=this.hitTest.encodeNodeId(this.slots[p]);for(let y=0;y<4;y++){let v=(p*4+y)*3;c[v]=f,c[v+1]=m,c[v+2]=g}}let h=this.geom?.getAttribute("aId");h&&(h.needsUpdate=!0)}if(this.spec.hideBuiltinNode){let c=this.slots.map(h=>t.index.getNodeId(h)).filter(h=>!!h);this.suppressedIds.length&&t.setNodeFillSuppressed(this.suppressedIds,!1),t.setNodeFillSuppressed(c,!0),this.suppressedIds=c}return!0}writeAttr(e,t){let r=this.userArrays.get(e.name);if(!r)return;let n=t.store.data.nodes;for(let i=0;i<this.slots.length;i++){let o=this.slots[i],s=e.value(n[o],o),d=Array.isArray(s)?s:[s];for(let l=0;l<4;l++){let u=(i*4+l)*e.size;for(let c=0;c<e.size;c++)r[u+c]=d[c]??0}}}syncMapSizing(e){let t=this.mat.uniforms;t.uMapMode.value=e.isMapMode?1:0;let r=e.getMapNodeSizing?.();t.uMapDamping.value=r?r.damping:.3,t.uMapMaxGrowth.value=r?r.maxGrowth===1/0?-1:r.maxGrowth:4}frame(e,t){if(!this.geom||!this.mat||!this.aCenter||!this.aSize)return!1;let r=t.store,n=r.positionProvider?.getPositions();if(!n)return this.spec.animate===!0;!this.hitMesh&&(this.spec.hitArea??"none")!=="none"&&(this.mountHitMesh(t,this.geom,this.capacity*4),this.hitMesh&&(this.lastNodeCount=-1,this.lastEpoch=-1)),this.syncMapSizing(t);let i=this.refreshMembership(t);i&&(this.lastLabelVersion=-1),this.reportLabelExtents(t);let o=r.nodeState?.effectiveSizes??null,s=r.nodeState?.opacities??null,d=this.spec.size,l=r.data.nodes,u=this.aCenter,c=this.aSize,h=this.aDim;for(let m=0;m<this.slots.length;m++){let g=this.slots[m],y=n[g*3],v=n[g*3+1],b=n[g*3+2],x=d?d(l[g],g):o?o[g]:8,w=s?s[g]:1;for(let T=0;T<4;T++){let I=m*4+T;u[I*3]=y,u[I*3+1]=v,u[I*3+2]=b,c[I]=x,h&&(h[I]=w)}}this.geom.getAttribute("aCenter").needsUpdate=!0,this.geom.getAttribute("aSize").needsUpdate=!0,h&&(this.geom.getAttribute("aDim").needsUpdate=!0);for(let m of this.spec.attributes??[])m.dynamic&&(this.writeAttr(m,t),this.geom.getAttribute(m.name).needsUpdate=!0);this.geom.setDrawRange(0,this.slots.length*6);let p=t.getDrawingBufferSize(),f=typeof window<"u"&&window.devicePixelRatio||1;return this.mat.uniforms.uResolution.value.set(p.width/f,p.height/f),this.spec.animate&&(this.t+=e,this.mat.uniforms.uTime.value=this.t),this.spec.animate===!0||i}};function uM(a){return new Gc(a)}export{vg as a,gy as b,jl as c,ql as d,my as e,ns as f,xg as g,wy as h,Ty as i,Ki as j,is as k,Hy as l,$i as m,os as n,ss as o,as as p,ds as q,ls as r,Uu as s,Zi as t,cs as u,ju as v,Yi as w,mn as x,us as y,Xn as z,fs as A,$r as B,Gg as C,Ji as D,ic as E,to as F,eh as G,En as H,no as I,ih as J,Ps as K,ph as L,ni as M,vh as N,io as O,aS as P,Eh as Q,lo as R,mS as S,hc as T,wh as U,Ns as V,Th as W,en as X,di as Y,Mn as Z,uo as _,gc as $,Ls as aa,Vs as ba,In as ca,Us as da,Ws as ea,js as fa,qs as ga,Ks as ha,Sf as ia,$s as ja,Ys as ka,ea as la,ua as ma,ma as na,ya as oa,Ra as pa,vo as qa,pi as ra,vr as sa,gi as ta,fi as ua,eE as va,Nh as wa,Ma as xa,Ia as ya,Pa as za,Aa,_a as Ba,Da as Ca,Na as Da,ka as Ea,Ga as Fa,Fa as Ga,za as Ha,Ba as Ia,mi as Ja,La as Ka,Va as La,Ua as Ma,Wa as Na,ja as Oa,qa as Pa,Ka as Qa,$a as Ra,Za as Sa,Xa as Ta,Ja as Ua,ed as Va,Df as Wa,Nf as Xa,Hh as Ya,bo as Za,td as _a,rd as $a,nd as ab,id as bb,od as cb,ad as db,dd as eb,ld as fb,cd as gb,gd as hb,vi as ib,yd as jb,vd as kb,bi as lb,bd as mb,Sd as nb,xd as ob,Rd as pb,jh as qb,Md as rb,Id as sb,Pd as tb,ry as ub,WT as vb,tM as wb,oM as xb,dM as yb,ay as zb,dy as Ab,uM as Bb};
394
+ //# sourceMappingURL=chunk-4PNV55G2.mjs.map