semiotic 3.8.4 → 3.8.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/CLAUDE.md +6 -3
  2. package/README.md +44 -38
  3. package/ai/componentMetadata.cjs +1 -1
  4. package/ai/dist/mcp-server.js +4 -2
  5. package/ai/examples.md +167 -0
  6. package/ai/schema.json +1004 -1
  7. package/ai/surface-manifest.json +6 -4
  8. package/ai/system-prompt.md +1 -1
  9. package/dist/chunk-chartContainerDataAudit-74TLKIP6.module.min.js +2 -0
  10. package/dist/{chunk-chunk-LQBSXO7K.module.min.js → chunk-chunk-4AANPFOX.module.min.js} +1 -1
  11. package/dist/{chunk-chunk-N6VKKF3A.module.min.js → chunk-chunk-5I3UZV4Q.module.min.js} +1 -1
  12. package/dist/chunk-chunk-74CCPVXB.module.min.js +1 -0
  13. package/dist/{chunk-chunk-6TPGFL7M.module.min.js → chunk-chunk-BANTPINB.module.min.js} +1 -1
  14. package/dist/chunk-chunk-CKMD5NV3.module.min.js +2 -0
  15. package/dist/chunk-chunk-CO5KQMGH.module.min.js +1 -0
  16. package/dist/{chunk-chunk-BFHUYEOS.module.min.js → chunk-chunk-CWQ5YIHX.module.min.js} +1 -1
  17. package/dist/chunk-chunk-E6TXX6MI.module.min.js +1 -0
  18. package/dist/{chunk-chunk-JDXT6ORT.module.min.js → chunk-chunk-I36PJ4OC.module.min.js} +1 -1
  19. package/dist/chunk-chunk-K3DMEW22.module.min.js +1 -0
  20. package/dist/chunk-chunk-KT2VAZMZ.module.min.js +1 -0
  21. package/dist/{chunk-chunk-AQPQN2HH.module.min.js → chunk-chunk-L6EA5V3G.module.min.js} +1 -1
  22. package/dist/{chunk-chunk-FBGHXL72.module.min.js → chunk-chunk-LJLS6DY7.module.min.js} +1 -1
  23. package/dist/chunk-chunk-LJPCLYSC.module.min.js +2 -0
  24. package/dist/{chunk-chunk-7RYBCTK5.module.min.js → chunk-chunk-N5DDKCCF.module.min.js} +1 -1
  25. package/dist/chunk-chunk-NLO44TOS.module.min.js +2 -0
  26. package/dist/{chunk-chunk-F5V4UIE6.module.min.js → chunk-chunk-PZJ2SBLL.module.min.js} +1 -1
  27. package/dist/chunk-chunk-QUJ6TTLY.module.min.js +1 -0
  28. package/dist/chunk-chunk-RBIDBUT4.module.min.js +2 -0
  29. package/dist/chunk-chunk-RFLAG356.module.min.js +1 -0
  30. package/dist/{chunk-chunk-7KZJUTKP.module.min.js → chunk-chunk-RPU4IZAV.module.min.js} +1 -1
  31. package/dist/{chunk-chunk-PLIDPQNG.module.min.js → chunk-chunk-SKMBCFIL.module.min.js} +1 -1
  32. package/dist/{chunk-chunk-SR4ZXOWR.module.min.js → chunk-chunk-TAE7W424.module.min.js} +1 -1
  33. package/dist/{chunk-chunk-KQ546MKE.module.min.js → chunk-chunk-TMWIZL3K.module.min.js} +1 -1
  34. package/dist/chunk-chunk-TUBMTZMU.module.min.js +2 -0
  35. package/dist/chunk-chunk-UFFEXJQY.module.min.js +1 -0
  36. package/dist/chunk-chunk-XSCHTS4D.module.min.js +2 -0
  37. package/dist/{chunk-chunk-F7WFPD4O.module.min.js → chunk-chunk-XXWSHGPL.module.min.js} +1 -1
  38. package/dist/chunk-chunk-ZXIXAPRE.module.min.js +2 -0
  39. package/dist/components/ChartContainer.d.ts +10 -0
  40. package/dist/components/ai/chartCapabilities.d.ts +2 -1
  41. package/dist/components/ai/chartCapabilityTypes.d.ts +14 -0
  42. package/dist/components/chartContainerDataAudit.d.ts +10 -0
  43. package/dist/components/charts/geo/DistanceCartogram.d.ts +29 -3
  44. package/dist/components/charts/index.d.ts +1 -0
  45. package/dist/components/charts/network/ForceDirectedGraph.d.ts +36 -1
  46. package/dist/components/charts/physics/CrucibleChart.capability.d.ts +8 -0
  47. package/dist/components/charts/physics/CrucibleChart.d.ts +63 -0
  48. package/dist/components/charts/physics/crucibleBodyRenderers.d.ts +27 -0
  49. package/dist/components/charts/physics/crucibleChartProps.d.ts +90 -0
  50. package/dist/components/charts/physics/crucibleChrome.d.ts +47 -0
  51. package/dist/components/charts/physics/crucibleController.d.ts +59 -0
  52. package/dist/components/charts/physics/crucibleEffects.d.ts +30 -0
  53. package/dist/components/charts/physics/cruciblePhysics.d.ts +54 -0
  54. package/dist/components/charts/physics/crucibleProgram.d.ts +38 -0
  55. package/dist/components/charts/physics/crucibleTypes.d.ts +415 -0
  56. package/dist/components/charts/shared/chartSpecCore.d.ts +8 -0
  57. package/dist/components/charts/shared/crucibleWireSchema.d.ts +5 -0
  58. package/dist/components/charts/shared/diagnoseTypes.d.ts +10 -0
  59. package/dist/components/charts/shared/knownChartComponents.d.ts +1 -1
  60. package/dist/components/data/auditData.d.ts +51 -0
  61. package/dist/components/data/dataAuditPresentation.d.ts +18 -0
  62. package/dist/components/data/dataAuditSources.d.ts +9 -0
  63. package/dist/components/data/numericContracts.d.ts +59 -0
  64. package/dist/components/data/numericFieldProfiler.d.ts +23 -0
  65. package/dist/components/recipes/netEnsembleLayout.d.ts +167 -0
  66. package/dist/components/recipes/netEnsembleOverlays.d.ts +20 -0
  67. package/dist/components/recipes/wordTrails.d.ts +156 -0
  68. package/dist/components/recipes/wordTrailsProgressiveReveal.d.ts +42 -0
  69. package/dist/components/semiotic-ai-core.d.ts +3 -0
  70. package/dist/components/semiotic-ai-data-audit.d.ts +4 -0
  71. package/dist/components/semiotic-ai.d.ts +7 -5
  72. package/dist/components/semiotic-physics.d.ts +1 -0
  73. package/dist/components/semiotic-recipes-core.d.ts +4 -0
  74. package/dist/components/semiotic-utils-core.d.ts +3 -0
  75. package/dist/components/semiotic.d.ts +1 -1
  76. package/dist/components/server/renderEvidence.d.ts +27 -0
  77. package/dist/components/server/serverChartConfigs.d.ts +1 -0
  78. package/dist/components/server/serverChartConfigsPhysics.d.ts +9 -0
  79. package/dist/components/server/staticAnnotations.d.ts +12 -0
  80. package/dist/components/stream/GeoPipelineStore.d.ts +1 -0
  81. package/dist/components/stream/GeoSVGOverlay.d.ts +7 -0
  82. package/dist/components/stream/geoCartogram.d.ts +7 -0
  83. package/dist/components/stream/geoTypes.d.ts +17 -2
  84. package/dist/components/stream/networkFrameHandleTypes.d.ts +4 -0
  85. package/dist/components/stream/physics/PhysicsSettledSVG.d.ts +8 -0
  86. package/dist/components/useChartContainerDataAudit.d.ts +7 -0
  87. package/dist/geo.min.js +1 -1
  88. package/dist/geo.module.min.js +1 -1
  89. package/dist/network.min.js +1 -1
  90. package/dist/network.module.min.js +1 -1
  91. package/dist/ordinal.module.min.js +1 -1
  92. package/dist/physics.min.js +1 -1
  93. package/dist/physics.module.min.js +1 -1
  94. package/dist/realtime.min.js +1 -1
  95. package/dist/realtime.module.min.js +1 -1
  96. package/dist/semiotic-ai-core.d.ts +3 -0
  97. package/dist/semiotic-ai-core.min.js +1 -1
  98. package/dist/semiotic-ai-core.module.min.js +1 -1
  99. package/dist/semiotic-ai.d.ts +7 -5
  100. package/dist/semiotic-ai.min.js +1 -1
  101. package/dist/semiotic-ai.module.min.js +1 -1
  102. package/dist/semiotic-experimental.min.js +1 -1
  103. package/dist/semiotic-experimental.module.min.js +1 -1
  104. package/dist/semiotic-physics.d.ts +1 -0
  105. package/dist/semiotic-realtime-core.min.js +1 -1
  106. package/dist/semiotic-realtime-core.module.min.js +1 -1
  107. package/dist/semiotic-recipes-core.d.ts +4 -0
  108. package/dist/semiotic-recipes-core.min.js +1 -1
  109. package/dist/semiotic-recipes-core.module.min.js +1 -1
  110. package/dist/semiotic-recipes.min.js +1 -1
  111. package/dist/semiotic-recipes.module.min.js +1 -1
  112. package/dist/semiotic-server-edge.min.js +1 -1
  113. package/dist/semiotic-server-edge.module.min.js +1 -1
  114. package/dist/semiotic-server-node.min.js +1 -1
  115. package/dist/semiotic-server-node.module.min.js +1 -1
  116. package/dist/semiotic-utils-core.d.ts +3 -0
  117. package/dist/semiotic-utils-core.min.js +1 -1
  118. package/dist/semiotic-utils-core.module.min.js +1 -1
  119. package/dist/semiotic-utils.min.js +1 -1
  120. package/dist/semiotic-utils.module.min.js +1 -1
  121. package/dist/semiotic.d.ts +1 -1
  122. package/dist/semiotic.min.js +1 -1
  123. package/dist/semiotic.module.min.js +1 -1
  124. package/dist/server.min.js +1 -1
  125. package/dist/server.module.min.js +1 -1
  126. package/dist/xy.module.min.js +1 -1
  127. package/package.json +2 -2
  128. package/dist/chunk-chunk-3ILKBVVQ.module.min.js +0 -1
  129. package/dist/chunk-chunk-ASKSE5F5.module.min.js +0 -1
  130. package/dist/chunk-chunk-B3DRZPBK.module.min.js +0 -2
  131. package/dist/chunk-chunk-FP44FHFO.module.min.js +0 -2
  132. package/dist/chunk-chunk-HKXUAEPJ.module.min.js +0 -2
  133. package/dist/chunk-chunk-ICEXPNDC.module.min.js +0 -2
  134. package/dist/chunk-chunk-JMVEIZXP.module.min.js +0 -1
  135. package/dist/chunk-chunk-KHCOJMGK.module.min.js +0 -1
  136. package/dist/chunk-chunk-MFHF4J2Z.module.min.js +0 -1
  137. package/dist/chunk-chunk-NKZ75IM5.module.min.js +0 -2
  138. package/dist/chunk-chunk-QGZGZI4X.module.min.js +0 -1
  139. package/dist/chunk-chunk-RP7WTID5.module.min.js +0 -1
  140. package/dist/chunk-chunk-S7KLNUO6.module.min.js +0 -1
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- var e,t=Object.create,n=Object.defineProperty,i=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,o=Object.getPrototypeOf,s=Object.prototype.hasOwnProperty,a=(e,t,o,a)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of r(t))s.call(e,c)||c===o||n(e,c,{get:()=>t[c],enumerable:!(a=i(t,c))||a.enumerable});return e},c=(e,i,r)=>(r=null!=e?t(o(e)):{},a(!i&&e&&e.__esModule?r:n(r,"default",{value:e,enumerable:!0}),e)),l={};((e,t)=>{for(var i in t)n(e,i,{get:t[i],enumerable:!0})})(l,{BuiltInPhysicsEngineAdapter:()=>Mi,ChainReactionChart:()=>Gd,CollisionSwarmChart:()=>fc,EventDropChart:()=>Za,GaltonBoardChart:()=>Ua,GauntletChart:()=>bl,GuantletChart:()=>vl,PhysicalFlowChart:()=>$l,PhysicsCustomChart:()=>dc,PhysicsPileChart:()=>tc,PhysicsPipelineStore:()=>br,PhysicsSVGOverlay:()=>zn,PhysicsSedimentAccumulator:()=>Ti,ProcessFlowChart:()=>Yl,StreamPhysicsFrame:()=>es,absorbRegion:()=>Zs,aggregateRegionCounts:()=>Ns,arrivalReplay:()=>xd,bodiesToAnnotationAnchors:()=>qn,bodyGroupSpec:()=>ea,buildCollisionSwarmPhysics:()=>As,buildEventDropPhysics:()=>Ms,buildGaltonBoardPhysics:()=>vs,buildPhysicalFlowPhysics:()=>Ts,buildPhysicsAnnotationContext:()=>On,buildPhysicsPile:()=>Is,buildProcessFlowPhysics:()=>ia,calculateBlockerAmplification:()=>Dd,capacitatedRegion:()=>Ks,chargeGateRegion:()=>_s,collidersFromScales:()=>fd,comparePhysicsTrace:()=>rd,compileDependencyMachine:()=>jd,compileMotionEncoding:()=>xc,compilePhysicsEncoding:()=>Mc,composePhysicsControllers:()=>Lr,composeStyleRules:()=>as,createCapacityQueueController:()=>Tr,createDefaultPhysicsEngineAdapter:()=>Si,createDependencyGateController:()=>Fr,createLogicalJoin:()=>Cd,createPhysicsEncodingLayout:()=>Sc,createPortalController:()=>Yr,createProcessJourneyLedger:()=>sd,createServiceLevelController:()=>Or,createServiceResourcePoolController:()=>Wr,default:()=>Xd,deriveMotionVector:()=>kc,evaluatePhysicsBodyBudget:()=>Wi,forceFieldRegion:()=>Js,galtonPegs:()=>md,groupCompletionRows:()=>Ws,hatchFillId:()=>ie,hatchPatternDef:()=>oe,isHatchFill:()=>te,makeRuleValueResolver:()=>ns,matchesThreshold:()=>rs,membraneRegion:()=>Xs,normalizePhysicsAnnotations:()=>Fn,opacityFromAge:()=>vc,physicsProcessBoundaryColliders:()=>jc,physicsProcessGroupSemanticItems:()=>Rc,physicsProcessRegionSemanticItem:()=>Ac,physicsProcessStageSemanticItems:()=>Cc,physicsReferenceEnvelope:()=>Jl,planGauntletPropertyWork:()=>Jc,portalRegion:()=>Qs,pressureFieldRegion:()=>Us,processChrome:()=>zl,processJourneyRows:()=>cd,processLaneWalls:()=>ta,processStageLayout:()=>Ys,processStageRegions:()=>Gs,processVolumePolygons:()=>Fs,regionCountsToProjectionRows:()=>Es,replaceGauntletNegative:()=>el,replayStateTransitions:()=>Pd,resolveMotionAccessor:()=>gc,resolveMotionAge:()=>bc,resolveMotionVector:()=>wc,resolveStyleRules:()=>ss,resolveSvgFill:()=>se,routeDependencyTracks:()=>Ad,routeSurfaceRegion:()=>Vs,ruleMatches:()=>os,sedimentBake:()=>gd,sedimentHeightfield:()=>Ni,spawnFromTokens:()=>yd,stageTargetInVolume:()=>Os,updateProcessJourney:()=>ad}),module.exports=(e=l,a(n({},"__esModule",{value:!0}),e));var d=require("react"),u=c(require("react")),h=require("react"),p=c(require("react")),f=require("react"),m=require("react"),y=require("react/jsx-runtime");function g(e){let t=null;const n=()=>(t||(t=(0,m.createContext)(null)),t),i=x(e);return[function({children:t,initialState:i}){const r=(0,m.useRef)(i),o=(0,m.useMemo)(()=>x(e,r.current),[]),s=n();return(0,y.jsx)(s.Provider,{value:o,children:t})},(e,t)=>{const r=n(),o=(0,m.useContext)(r)??i,s=(0,m.useRef)(e);s.current=e;const a=(0,m.useRef)({hasValue:!1,value:void 0}),c=(0,m.useCallback)(()=>{const e=s.current(o.getState()),n=a.current;return n.hasValue&&t&&t(n.value,e)?n.value:(a.current={hasValue:!0,value:e},e)},[o,t]),l=(0,m.useCallback)(()=>s.current(o.getState()),[o]);return(0,m.useSyncExternalStore)(o.subscribe,c,l)}]}function x(e,t){const n=new Set;let i={...e(function(e){const t=e(i);if(function(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!0;return!1}(t)){i={...i,...t};for(const e of n)e()}}),...t??{}};return{getState:()=>i,subscribe:function(e){return n.add(e),()=>{n.delete(e)}}}}function b(e){if(!e.accessibility)return e;let t=e;if(e.accessibility.colorBlindSafe&&(t={...t,colors:{...t.colors,categorical:v}}),e.accessibility.highContrast){const e="dark"===t.mode;t={...t,colors:{...t.colors,text:e?"#ffffff":"#000000",textSecondary:e?"#cccccc":"#333333",grid:e?"#666666":"#999999",border:e?"#888888":"#000000"}}}return t}var v=["#0072B2","#E69F00","#009E73","#CC79A7","#56B4E9","#D55E00","#F0E442","#000000"],w={mode:"light",colors:{primary:"#00a2ce",secondary:"#6c757d",categorical:["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],sequential:"blues",diverging:"RdBu",background:"transparent",surface:"#ffffff",text:"#333",textSecondary:"#666",grid:"#e0e0e0",border:"#ccc",selection:"#00a2ce",selectionOpacity:.15,success:"#2ca02c",danger:"#d62728",warning:"#f0ad4e",error:"#b4181b",info:"#00a2ce"},typography:{fontFamily:"sans-serif",titleSize:16,labelSize:12,tickSize:12}},k={mode:"dark",colors:{primary:"#4fc3f7",secondary:"#90a4ae",categorical:["#4fc3f7","#ffb74d","#81c784","#ef5350","#ba68c8","#a1887f","#f06292","#90a4ae","#dce775","#4dd0e1"],sequential:"blues",diverging:"RdBu",background:"#1a1a2e",surface:"#252540",text:"#e0e0e0",textSecondary:"#aaa",grid:"#333",border:"#555",selection:"#4fc3f7",selectionOpacity:.15,success:"#81c784",danger:"#ef5350",warning:"#ffb74d",error:"#d84848",info:"#4fc3f7"},typography:{fontFamily:"sans-serif",titleSize:16,labelSize:12,tickSize:12}},M={mode:"light",colors:{primary:"#0000cc",secondary:"#333333",categorical:v,sequential:"blues",diverging:"RdBu",background:"#ffffff",surface:"#ffffff",text:"#000000",textSecondary:"#333333",grid:"#999999",border:"#000000",focus:"#0000cc",selection:"#0000cc",selectionOpacity:.1,success:"#006400",danger:"#cc0000",warning:"#b15a00",error:"#8b0000",info:"#0000cc"},typography:{fontFamily:"system-ui, sans-serif",titleSize:18,labelSize:14,tickSize:12},tooltip:{background:"#000000",text:"#ffffff",borderRadius:"4px",fontSize:"14px",shadow:"0 2px 8px rgba(0, 0, 0, 0.3)"},borderRadius:"4px"};function S(e,t){if("light"===t)return w;if("dark"===t)return k;if("high-contrast"===t)return M;if("string"==typeof t)return void 0!==console&&console.warn(`[ThemeStore] Unknown theme preset "${t}". Keeping current theme.`),e;if(t.mode&&"auto"!==t.mode){const e="dark"===t.mode?k:w;return b({...e,...t,colors:{...e.colors,...t.colors||{}},typography:{...e.typography,...t.typography||{}}})}return b({...e,...t,colors:{...e.colors,...t.colors||{}},typography:{...e.typography,...t.typography||{}}})}var[I,j]=g(e=>({theme:w,setTheme(t){e(e=>({theme:S(e.theme,t)}))}})),A=require("react");var C=require("react"),R=new WeakMap,P=0,D=!1,$=null,B=null;function T(e,t){if(!t)return t;const n=function(e){const t=e.trim();if(!t.startsWith("var(")||!t.endsWith(")"))return null;const n=t.slice(4,-1),i=n.indexOf(",");if(-1===i){const e=n.trim();return e.startsWith("--")?{name:e}:null}const r=n.slice(0,i).trim(),o=n.slice(i+1).trim();return r.startsWith("--")?{name:r,fallback:o||void 0}:null}(t);if(!n)return t;const i=()=>n.fallback?T(e,n.fallback):t,r=e.canvas;if(!r)return i();!function(){if(D)return;if("undefined"==typeof window||"undefined"==typeof document)return;D=!0;const e=()=>{P++};if("undefined"!=typeof MutationObserver&&document.documentElement&&new MutationObserver(e).observe(document.documentElement,{attributes:!0,attributeFilter:["class","style","data-theme","data-semiotic-theme"],subtree:!0}),"function"==typeof window.matchMedia)try{$=window.matchMedia("(prefers-color-scheme: dark)"),B=e,"function"==typeof $.addEventListener?$.addEventListener("change",B):"function"==typeof $.addListener&&$.addListener(B)}catch{}}();let o=R.get(r);o&&o.version===P||(o={version:P,map:new Map},R.set(r,o));const s=o.map.get(t);if(void 0!==s)return s;const a=getComputedStyle(r).getPropertyValue(n.name).trim()||i()||t;return o.map.set(t,a),a}var N=()=>"undefined"!=typeof performance?performance.now():Date.now();function E(e,t){const n=e();return Number.isFinite(n)?n:t}var W=class{constructor(e={}){this.randomSource=Math.random,this.subscribers=new Set,this.now=()=>this.advance(),this.random=()=>this.randomSource(),this.clock=e.clock??N,this.lastWallTime=E(this.clock,0),this.logicalTime=this.lastWallTime,this.pausedValue=!0===e.paused,this.visibleValue=!1!==e.visible,this.setRandomSource(e.random,e.seed)}get isActive(){return!this.pausedValue&&this.visibleValue}get paused(){return this.pausedValue}get seed(){return this.seedValue}get visible(){return this.visibleValue}configure(e){this.setClock(e.clock),this.setRandomSource(e.random,e.seed)}setPaused(e){this.pausedValue!==e&&(this.advance(),this.pausedValue=e,this.emit())}setVisible(e){this.visibleValue!==e&&(this.advance(),this.visibleValue=e,this.emit())}snapshot(){return{now:this.now(),paused:this.pausedValue,seed:this.seedValue,visible:this.visibleValue}}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}advance(){const e=E(this.clock,this.lastWallTime),t=Math.max(0,e-this.lastWallTime);return this.lastWallTime=e,this.isActive&&(this.logicalTime+=t),this.logicalTime}emit(){for(const e of this.subscribers)e()}setClock(e){const t=e??N;t!==this.clock&&(this.advance(),this.clock=t,this.lastWallTime=E(t,this.lastWallTime))}setRandomSource(e,t){const n=function(e){return"number"==typeof e&&Number.isFinite(e)?Math.trunc(e):void 0}(t);e===this.randomInput&&n===this.seedValue||(this.randomInput=e,this.seedValue=n,this.randomSource=e??(void 0===n?Math.random:function(e){let t=e>>>0;return()=>{t+=1831565813;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(n)))}},q="undefined"==typeof window?f.useEffect:f.useLayoutEffect,O={requestAnimationFrame:e=>("undefined"==typeof window?globalThis:window).requestAnimationFrame(e),cancelAnimationFrame:e=>("undefined"==typeof window?globalThis:window).cancelAnimationFrame(e)};function F(e,t,n){return"function"==typeof e?e({size:t,margin:n}):e}function z(e){const t=function(){const[e,t]=(0,A.useState)(()=>!("undefined"==typeof window||!window.matchMedia)&&window.matchMedia("(prefers-reduced-motion: reduce)").matches);return(0,A.useEffect)(()=>{if("undefined"==typeof window||!window.matchMedia)return;const e=window.matchMedia("(prefers-reduced-motion: reduce)");return t(e.matches),function(e,t){if("function"==typeof e.addEventListener)return e.addEventListener("change",t),()=>e.removeEventListener("change",t);const n=e;return n.addListener(t),()=>n.removeListener(t)}(e,e=>t(e.matches))},[]),e}(),n=(0,f.useRef)(t);n.current=t;const[i,r]=function(e,t,n){const i=(0,C.useRef)(null),[r,o]=(0,C.useState)(null);return(0,C.useEffect)(()=>{if(!t&&!n)return;const e=i.current;if(!e)return;const r=new ResizeObserver(e=>{for(const t of e){const{width:e,height:n}=t.contentRect;o(t=>t&&t.w===e&&t.h===n?t:{w:e,h:n})}});return r.observe(e),()=>r.disconnect()},[t,n]),[i,[t&&r?r.w:e[0],n&&r?r.h:e[1]]]}(e.sizeProp,e.responsiveWidth,e.responsiveHeight),o=!!e.title,s=!!e.legend&&"top"===e.legendPosition,a=(0,f.useMemo)(()=>function(e,t,n=!1){const i=n?t?58:34:t?36:0;return i>e.top?{...e,top:i}:e}({...e.marginDefault,...e.userMargin},o,s),[e.marginDefault,e.userMargin,o,s]),c=r[0]-a.left-a.right,l=r[1]-a.top-a.bottom,d=F(e.foregroundGraphics,r,a),u=F(e.backgroundGraphics,r,a),h=j(e=>e.theme),{transition:m,introEnabled:y}=function(e,t){if(!1===e)return{transition:void 0,introEnabled:!1};const n="undefined"!=typeof window&&window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;return{transition:e?!0===e?{duration:300}:{duration:e.duration??300,easing:"linear"===e.easing?"linear":"ease-out"}:t,introEnabled:!(n||!e||!0!==e&&!1===e.intro)}}(e.animate,e.transitionProp),g="semiotic-table-"+p.useId(),x=(0,f.useRef)(null);if(!x.current){const t=!e.suspendWhenHidden||"undefined"==typeof document||!document.hidden;x.current=new W({clock:e.clock,random:e.random,seed:e.seed,paused:e.paused,visible:t})}const b=x.current;b.configure({clock:e.clock,random:e.random,seed:e.seed});const v=(0,f.useRef)(null),w=(0,f.useRef)(e.frameScheduler??O);w.current=e.frameScheduler??O;const k=(0,f.useRef)(null),M=(0,f.useRef)(!1),S=(0,f.useRef)(()=>{}),I=(0,f.useCallback)(()=>{if(null!==v.current||M.current)return;const e=w.current;let t=!1,n=!1;const i=e.requestAnimationFrame(()=>{t=!0;const e=!n;e&&(M.current=!0),v.current=null,k.current=null;try{S.current()}finally{e&&(M.current=!1)}});n=!0,t||(v.current=i,k.current=e)},[]),R=(0,f.useCallback)(()=>{null!==v.current&&((k.current??w.current).cancelAnimationFrame(v.current),v.current=null,k.current=null)},[]);q(()=>{b.setPaused(!0===e.paused)},[b,e.paused]),(0,f.useEffect)(()=>{if(!e.suspendWhenHidden||"undefined"==typeof document)return void b.setVisible(!0);const t=()=>b.setVisible(!document.hidden);return t(),document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)},[b,e.suspendWhenHidden]),(0,f.useEffect)(()=>()=>{R()},[R]);const D=(0,f.useRef)(()=>{}),$=(0,f.useRef)(()=>{}),B=(0,f.useRef)(null),T=(0,f.useRef)(null),N=(0,f.useRef)(null),E=(0,f.useCallback)(()=>{const e=B.current;B.current=null,e&&D.current(e)},[]),z=(0,f.useCallback)(e=>{if(B.current={clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType},null===T.current){const e=w.current;let t=!1;const n=e.requestAnimationFrame(()=>{t=!0,T.current=null,N.current=null,E()});t||(T.current=n,N.current=e)}},[E]),L=(0,f.useCallback)(()=>{B.current=null,null!==T.current&&((N.current??w.current).cancelAnimationFrame(T.current),T.current=null,N.current=null),$.current()},[]);(0,f.useEffect)(()=>()=>{B.current=null,null!==T.current&&((N.current??w.current).cancelAnimationFrame(T.current),T.current=null,N.current=null)},[]);const Y=e.themeDirtyRef;return q(()=>{Y&&(P++,Y.current=!0,I())},[h,I,Y]),{reducedMotion:t,reducedMotionRef:n,responsiveRef:i,size:r,margin:a,adjustedWidth:c,adjustedHeight:l,resolvedForeground:d,resolvedBackground:u,currentTheme:h,transition:m,introEnabled:y,tableId:g,frameRuntime:b,rafRef:v,renderFnRef:S,scheduleRender:I,cancelRender:R,hoverHandlerRef:D,hoverLeaveRef:$,onPointerMove:z,onPointerLeave:L}}var L=require("react"),Y="undefined"!=typeof window?L.useLayoutEffect:L.useEffect,H=()=>()=>{},G=()=>!1,X=()=>!0,_=require("react"),V=require("react/jsx-runtime");function U({children:e,size:t,margin:n,overflowVisible:i=!1}){return e?(0,V.jsx)("svg",{style:{position:"absolute",left:0,top:0,width:t[0],height:t[1],pointerEvents:"none",overflow:i?"visible":void 0},children:(0,V.jsx)("g",{transform:`translate(${n.left},${n.top})`,children:e})}):null}var K=c(require("react")),Q=require("d3-shape");function Z(e){return{type:"hatch",background:e.background,stroke:e.stroke,lineWidth:e.lineWidth,spacing:e.spacing,angle:e.angle}}var J=null;var ee=require("react/jsx-runtime");function te(e){return"object"==typeof e&&null!==e&&"hatch"===e.type}function ne(e){return["hatch",e.background??"transparent",e.stroke??"#000",e.lineWidth??1.5,e.spacing??6,e.angle??45,e.lineOpacity??1].join("|")}function ie(e,t){let n=2166136261;const i=ne(t);for(let e=0;i.length>e;e++)n^=i.charCodeAt(e),n=Math.imul(n,16777619);return`${e}-hatch-${(n>>>0).toString(36)}`}var re=new Map;function oe(e,t){const{background:n="transparent",stroke:i="#000",lineWidth:r=1.5,spacing:o=6,angle:s=45,lineOpacity:a=1}=e,c=Math.max(8,Math.ceil(2*o));return(0,ee.jsxs)("pattern",{id:t,width:c,height:c,patternUnits:"userSpaceOnUse",patternTransform:0!==s?`rotate(${s})`:void 0,children:[n&&"transparent"!==n&&(0,ee.jsx)("rect",{width:c,height:c,fill:n}),(0,ee.jsx)("line",{x1:0,y1:0,x2:0,y2:c,stroke:i,strokeWidth:r,strokeOpacity:a}),(0,ee.jsx)("line",{x1:o,y1:0,x2:o,y2:c,stroke:i,strokeWidth:r,strokeOpacity:a})]},t)}function se(e,t,n="#4e79a7"){if(te(e)){const n=ie(t,e);return{fill:`url(#${n})`,def:oe(e,n)}}return e&&"string"==typeof e?{fill:e}:{fill:n}}var ae=require("d3-shape");function ce(e){switch(e){case"monotoneX":return ae.curveMonotoneX;case"monotoneY":return ae.curveMonotoneY;case"cardinal":return ae.curveCardinal;case"catmullRom":return ae.curveCatmullRom;case"step":return ae.curveStep;case"stepBefore":return ae.curveStepBefore;case"stepAfter":return ae.curveStepAfter;case"basis":return ae.curveBasis;case"natural":return ae.curveNatural;default:return null}}function le(e,t,n){if(null==t)return n;if(te(t)){const i=function(e,t){const n="undefined"!=typeof window&&window.devicePixelRatio||1,i=`${ne(e)}@${n}`,r=re.get(i);if(void 0!==r)return r;const o=function(e={},t){const{background:n="transparent",stroke:i="#000",lineWidth:r=1.5,spacing:o=6,angle:s=45}=e,a={background:n,stroke:i,lineWidth:r,spacing:o,angle:s},c=Math.max(8,Math.ceil(2*o));let l;try{l=function(e){return"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,e):(J||(J=document.createElement("canvas")),J.width=e,J.height=e,J)}(c)}catch{return Z(a)}const d=l.getContext("2d");if(!d)return Z(a);n&&"transparent"!==n?(d.fillStyle=n,d.fillRect(0,0,c,c)):d.clearRect(0,0,c,c),d.strokeStyle=i,d.lineWidth=r,d.lineCap="square";const u=s*Math.PI/180;if(45===s||-45===s){const e=s>0?1:-1;for(let t=-c;2*c>=t;t+=o)d.beginPath(),d.moveTo(t,0),d.lineTo(t+e*c,c),d.stroke()}else{d.save(),d.translate(c/2,c/2),d.rotate(u);const e=2*c;for(let t=-e;e>=t;t+=o)d.beginPath(),d.moveTo(-e,t),d.lineTo(e,t),d.stroke();d.restore()}return(t||d).createPattern(l,"repeat")}({background:e.background,stroke:e.stroke,lineWidth:e.lineWidth,spacing:e.spacing,angle:e.angle},t),s=te(o)?null:o;return re.set(i,s),s}(t,e);return i||t.background&&T(e,t.background)||n}return"string"!=typeof t?t:T(e,t)||n}var de=[40,40],ue=[.5,.5];function he(e,t,n,i){if("none"!==e)return"color"===e||null==e?t??i:"accent"===e?n:e}var pe=require("d3-shape"),fe={circle:pe.symbolCircle,square:pe.symbolSquare,triangle:pe.symbolTriangle,diamond:pe.symbolDiamond,star:pe.symbolStar,cross:pe.symbolCross,wye:pe.symbolWye};var me=require("react/jsx-runtime");function ye(e,t="#4e79a7"){return te(e)?e.background&&"transparent"!==e.background?e.background:t:e&&"string"==typeof e?e:t}function ge(e){const t=e.replace(/[^A-Za-z0-9_-]/g,"_");return!t||/^\d/.test(t)?"s_"+t:t}function xe(e){const t=e.filter(e=>Number.isFinite(e.offset)).map(e=>({offset:Math.max(0,Math.min(1,e.offset)),color:e.color}));return 2>t.length?null:t.map((e,t)=>(0,me.jsx)("stop",{offset:e.offset,stopColor:e.color},t))}var be=require("react/jsx-runtime");function ve(e,t,n){if(!e||2>t.length)return null;const i=xe(e.colorStops);return i?(0,be.jsx)("linearGradient",{id:n,gradientUnits:"userSpaceOnUse",x1:t[0][0],y1:0,x2:t[t.length-1][0],y2:0,children:i}):null}function we(e,t,n){switch(e.type){case"line":{const i=e;if(0===i.path.length)return null;const r=ce(i.curve),o=r?(0,Q.line)().x(([e])=>e).y(([,e])=>e).curve(r)(i.path)??"":"M"+i.path.map(([e,t])=>`${e},${t}`).join("L"),s=ge(`${n?n+"-":""}line-${t}-stroke-gradient`),a=ve(i.strokeGradient,i.path,s);return(0,be.jsxs)(K.Fragment,{children:[a&&(0,be.jsx)("defs",{children:a}),(0,be.jsx)("path",{d:o,fill:"none",stroke:a?`url(#${s})`:i.style.stroke||"#4e79a7",strokeWidth:i.style.strokeWidth||2,strokeDasharray:i.style.strokeDasharray,opacity:i.style.opacity})]},"line-"+t)}case"area":{const i=e;if(0===i.topPath.length)return null;const r=ce(i.curve),o=!r||2>i.topPath.length||2>i.bottomPath.length?`M${i.topPath.map(([e,t])=>`${e},${t}`).join("L")}L${[...i.bottomPath].reverse().map(([e,t])=>`${e},${t}`).join("L")}Z`:(0,Q.area)().x(([e])=>e).y0((e,t)=>i.bottomPath[t][1]).y1(([,e])=>e).curve(r)(i.topPath)??"",s=`${n?n+"-":""}area-${t}-hatch`,a=te(i.style.fill)?oe(i.style.fill,s):void 0,c=ge(`${n?n+"-":""}area-${t}-gradient`),l=function(e,t){const n=e.fillGradient;if(!n||"object"!=typeof n)return null;let i=1/0;for(const[,t]of e.topPath)i=Math.min(i,t);let r=-1/0;for(const[,t]of e.bottomPath)r=Math.max(r,t);if(!Number.isFinite(i)||!Number.isFinite(r))return null;const o=[];if("colorStops"in n){const e=xe(n.colorStops);if(!e)return null;o.push(...e)}else{if(!Number.isFinite(n.topOpacity)||!Number.isFinite(n.bottomOpacity))return null;o.push((0,be.jsx)("stop",{offset:0,stopColor:ye(e.style.fill),stopOpacity:Math.max(0,Math.min(1,n.topOpacity))},"0")),o.push((0,be.jsx)("stop",{offset:1,stopColor:ye(e.style.fill),stopOpacity:Math.max(0,Math.min(1,n.bottomOpacity))},"1"))}return(0,be.jsx)("linearGradient",{id:t,gradientUnits:"userSpaceOnUse",x1:0,y1:i,x2:0,y2:r,children:o})}(i,c),d=l?`url(#${c})`:a?`url(#${s})`:ye(i.style.fill),u=l?void 0:i.style.fillOpacity??i.style.opacity??.7,h=r?(0,Q.line)().x(([e])=>e).y(([,e])=>e).curve(r)(i.topPath)??"":"M"+i.topPath.map(([e,t])=>`${e},${t}`).join("L"),p=ge(`${n?n+"-":""}area-${t}-stroke-gradient`),f=ve(i.strokeGradient,i.topPath,p),m=i.style.stroke&&"none"!==i.style.stroke?(0,be.jsx)("path",{d:h,fill:"none",stroke:f?`url(#${p})`:ye(i.style.stroke),strokeWidth:i.style.strokeWidth||2,opacity:i.style.opacity}):null;if(i.clipRect){const e=`${n?n+"-":""}area-clip-${t}`;return(0,be.jsxs)("g",{children:[(0,be.jsxs)("defs",{children:[l,!l&&a,f,(0,be.jsx)("clipPath",{id:e,children:(0,be.jsx)("rect",{x:i.clipRect.x,y:i.clipRect.y,width:i.clipRect.width,height:i.clipRect.height})})]}),(0,be.jsxs)("g",{clipPath:`url(#${e})`,children:[(0,be.jsx)("path",{d:o,fill:d,fillOpacity:u,opacity:l?i.style.opacity:void 0,stroke:"none"}),m]})]},"area-"+t)}return(0,be.jsxs)(K.Fragment,{children:[(l||a||f)&&(0,be.jsxs)("defs",{children:[l,!l&&a,f]}),(0,be.jsx)("path",{d:o,fill:d,fillOpacity:u,opacity:l?i.style.opacity:void 0,stroke:"none"}),m]},"area-"+t)}case"point":{const i=e,r=`${n?n+"-":""}point-${t}-hatch`,o=te(i.style.fill)?oe(i.style.fill,r):void 0;return(0,be.jsxs)(K.Fragment,{children:[o&&(0,be.jsx)("defs",{children:o}),(0,be.jsx)("circle",{cx:i.x,cy:i.y,r:i.r,fill:o?`url(#${r})`:ye(i.style.fill),opacity:i.style.opacity??i.style.fillOpacity??.8,stroke:i.style.stroke,strokeWidth:i.style.strokeWidth})]},"point-"+t)}case"symbol":return function(e,t){const n=function(e,t,n){if(n)return n;const i=e??"circle";return"chevron"===i?function(e){const t=1.5*function(e){return Math.sqrt(Math.max(1,e)/Math.PI)}(e),n=.92*t;return`M0,${-t}L${n},${(.78*t).toFixed(3)}L0,${(.28*t).toFixed(3)}L${-n},${(.78*t).toFixed(3)}Z`}(t):(0,pe.symbol)(fe[i]??pe.symbolCircle,Math.max(1,t))()??""}(e.symbolType,e.size,e.path);return(0,me.jsx)("path",{d:n,transform:e.rotation?`translate(${e.x},${e.y}) rotate(${180*e.rotation/Math.PI})`:`translate(${e.x},${e.y})`,fill:e.style.fill?ye(e.style.fill):"none",fillOpacity:e.style.fillOpacity,opacity:e.style.opacity,stroke:e.style.stroke,strokeWidth:e.style.strokeWidth},"symbol-"+t)}(e,t);case"glyph":return function(e,t,n,i){const r=e.glyph;if(!r?.parts?.length||0>=e.size)return null;const o=function(e,t){const[n,i]=e.viewBox??de,[r,o]=e.anchor??ue,s=i>0?i:1,a=Math.max(0,t)/s,c=(n>0?n:s)*a,l=s*a;return{width:c,height:l,scale:a,offsetX:-r*c,offsetY:-o*l}}(r,e.size);if(0>=o.scale)return null;const s=`translate(${t},${n})${e.rotation?` rotate(${180*e.rotation/Math.PI})`:""} translate(${o.offsetX},${o.offsetY}) scale(${o.scale})`,a=e.color??("string"==typeof e.style.fill?e.style.fill:void 0),c=function(e,t,n=0,i="horizontal"){const[r,o]=e.viewBox??de,s=Math.min(1,Math.max(0,n)),a=Math.min(1,Math.max(0,t));return a>s?s>0||1>a?"vertical"===i?{x:0,y:o*(1-a),width:r,height:o*(a-s)}:{x:r*s,y:0,width:r*(a-s),height:o}:null:{x:0,y:0,width:0,height:0}}(r,e.fraction??1,e.fractionStart??0,e.fractionDirection??"horizontal"),l=c?ge(i+"-clip"):void 0,d=(e.style.opacity??1)*(e._decayOpacity??1)*(e.style.fillOpacity??1),u=t=>r.parts.map((n,i)=>{const r=t?"none"===n.fill?void 0:t:he(n.fill,a,e.accent),o=t?n.stroke&&"none"!==n.stroke?t:void 0:he(n.stroke??"none",a,e.accent);return r||o?(0,me.jsx)("path",{d:n.d,fill:r??"none",stroke:o,strokeWidth:o?n.strokeWidth??1:void 0,strokeLinecap:n.strokeLinecap,strokeLinejoin:n.strokeLinejoin,opacity:n.opacity},i):null});return(0,me.jsxs)("g",{transform:s,opacity:1===d?void 0:d,children:[c&&l&&(0,me.jsx)("clipPath",{id:l,children:(0,me.jsx)("rect",{x:c.x,y:c.y,width:c.width,height:c.height})}),c&&e.ghostColor?(0,me.jsx)("g",{children:u(e.ghostColor)}):null,c&&l?(0,me.jsx)("g",{clipPath:`url(#${l})`,children:u()}):u()]},i)}(e,e.x,e.y,`${n??""}glyph-${e.pointId??t}`);case"rect":{const i=e,r=`${n?n+"-":""}xyrect-${t}-hatch`,o=te(i.style.fill)?oe(i.style.fill,r):void 0;return(0,be.jsxs)(K.Fragment,{children:[o&&(0,be.jsx)("defs",{children:o}),(0,be.jsx)("rect",{x:i.x,y:i.y,width:i.w,height:i.h,fill:o?`url(#${r})`:ye(i.style.fill),opacity:i.style.opacity,stroke:i.style.stroke,strokeWidth:i.style.strokeWidth})]},"rect-"+t)}case"heatcell":{const n=e;if(n.showValues&&null!=n.value&&n.w>=20&&n.h>=20){const e=n.valueFormat?n.valueFormat(n.value):Number.isInteger(n.value)?n.value+"":100>Math.abs(n.value)?1>Math.abs(n.value)?n.value.toPrecision(3):n.value.toFixed(1):n.value.toFixed(0),[i,r,o]=function(e){if(e.startsWith("#")){let t=e.slice(1);if(3===t.length&&(t=t[0]+t[0]+t[1]+t[1]+t[2]+t[2]),6===t.length)return[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16)]}const t=e.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);return t?[+t[1],+t[2],+t[3]]:[128,128,128]}(n.fill),s=.299*i+.587*r+.114*o>128?"#000":"#fff",a=Math.max(10,Math.min(16,.3*Math.min(n.w,n.h)));return(0,be.jsxs)("g",{children:[(0,be.jsx)("rect",{x:n.x,y:n.y,width:n.w,height:n.h,fill:n.fill,stroke:n.style?.stroke,strokeWidth:n.style?.strokeWidth}),(0,be.jsx)("text",{x:n.x+n.w/2,y:n.y+n.h/2,textAnchor:"middle",dominantBaseline:"middle",fill:s,fontSize:a+"px",children:e})]},"heatcell-"+t)}return(0,be.jsx)("rect",{x:n.x,y:n.y,width:n.w,height:n.h,fill:n.fill,stroke:n.style?.stroke,strokeWidth:n.style?.strokeWidth},"heatcell-"+t)}case"candlestick":{const n=e;if(n.isRange){const e=n.dotRadius??Math.max(2,n.bodyWidth/2);return(0,be.jsxs)("g",{children:[(0,be.jsx)("line",{x1:n.x,y1:n.highY,x2:n.x,y2:n.lowY,stroke:n.wickColor,strokeWidth:n.wickWidth}),(0,be.jsx)("circle",{cx:n.x,cy:n.highY,r:e,fill:n.wickColor}),(0,be.jsx)("circle",{cx:n.x,cy:n.lowY,r:e,fill:n.wickColor})]},"candle-"+t)}const i=Math.min(n.openY,n.closeY),r=Math.max(Math.abs(n.openY-n.closeY),1),o=n.isUp?n.upColor:n.downColor;return(0,be.jsxs)("g",{children:[(0,be.jsx)("line",{x1:n.x,y1:n.highY,x2:n.x,y2:n.lowY,stroke:n.wickColor,strokeWidth:n.wickWidth}),(0,be.jsx)("rect",{x:n.x-n.bodyWidth/2,y:i,width:n.bodyWidth,height:r,fill:o,stroke:o,strokeWidth:1})]},"candle-"+t)}default:return null}}var ke="undefined"==typeof window||"undefined"==typeof document;var Me=c(require("react")),Se=["name","label","title"],Ie=["type","kind","category","group","class","status","role","shape"],je=["value","amount","total","count","weight","score"],Ae=new Set(["x","y","z","x0","x1","y0","y1","r","cx","cy","radius","layer","row","rowindex","col","column","depth","index","order","sankeywidth","coincidentpoints","sourcelinks","targetlinks","parent","children","fx","fy","vx","vy"]);function Ce(e,t){for(const n of t){const t=e.find(e=>e.lower===n);if(t)return t}}var Re=require("react/jsx-runtime"),Pe={background:"var(--semiotic-tooltip-bg, rgba(0, 0, 0, 0.85))",color:"var(--semiotic-tooltip-text, white)",padding:"8px 12px",borderRadius:"var(--semiotic-tooltip-radius, 6px)",fontSize:"var(--semiotic-tooltip-font-size, 14px)",fontFamily:"var(--semiotic-font-family, inherit)",lineHeight:"1.5",boxShadow:"var(--semiotic-tooltip-shadow, 0 2px 8px rgba(0, 0, 0, 0.15))",pointerEvents:"none",maxWidth:"300px",wordWrap:"break-word"};function De(e,t){return"function"==typeof t?t(e):e[t]}function $e(e,t){if(t)return t(e);if(null==e)return"";if("number"==typeof e){if(!Number.isFinite(e))return e+"";const t=Number.isInteger(e)?e:parseFloat(e.toPrecision(6));return Math.abs(t)>9999?t.toLocaleString():t+""}return e instanceof Date?e.toLocaleDateString():"object"==typeof e&&null!==e?void 0!==e.id?e.id+"":void 0!==e.name?e.name+"":JSON.stringify(e):e+""}function Be(e={}){const{fields:t,title:n,format:i,style:r={},className:o=""}=e;return e=>{if(!e||"object"!=typeof e)return null;let s;const a=[];if(n){const t=De(e,n);s=$e(t,i)}if(t&&t.length>0)t.forEach(t=>{let n,r,o;"string"==typeof t?(n=t,r=t,o=i):(n=t.label,r=t.accessor||t.key||"",o=t.format||i);const s=De(e,r);a.push({label:n,value:$e(s,o)})});else if(!n){const t=["value","y","name","id","label"];for(const n of t)if(void 0!==e[n]){s=$e(e[n],i);break}if(!s){const t=Object.keys(e).filter(e=>!e.startsWith("_"));t.length>0&&(s=$e(e[t[0]],i))}}const c={...Pe,...r};return(0,Re.jsxs)("div",{className:("semiotic-tooltip "+o).trim(),style:c,children:[s&&(0,Re.jsx)("div",{style:{fontWeight:a.length>0?"bold":"normal"},children:s}),a.map((e,t)=>(0,Re.jsxs)("div",{style:{marginTop:0===t&&s?"4px":0},children:[e.label&&(0,Re.jsxs)("span",{children:[e.label,": "]}),e.value]},t))]})}}function Te(e){if(!0!==e){if("function"==typeof e){const t=e;return e=>{let n=Array.isArray(i=!0===e?.__semioticHoverData||e&&void 0!==e.data&&"number"==typeof e.x&&"number"==typeof e.y&&e&&("node"===e.type||"edge"===e.type||void 0!==e.nodeOrEdge||void 0!==e.allSeries||void 0!==e.stats||void 0!==e.__chartType)?e.data??{}:e)?i[0]:i;var i;if(!n)return null;if(("node"===e?.nodeOrEdge&&"number"==typeof n?.x0&&"number"==typeof n?.x1||"edge"===e?.nodeOrEdge&&"number"==typeof n?.sankeyWidth)&&n.data&&"object"==typeof n.data&&(n=n.data),!n)return null;const r=t(n);return null==r?null:(0,Re.jsx)("div",{className:"semiotic-tooltip",style:Pe,children:r})}}return!1!==e&&void 0!==e&&("object"==typeof e&&null!==e&&("fields"in e||"title"in e)?Be(e):"multi"===e?("undefined"!=typeof process&&"production"!==process.env?.NODE_ENV&&console.warn('[semiotic] tooltip="multi" reached normalizeTooltip — prefer charts that set tooltipMode (LineChart, AreaChart, StackedAreaChart, DifferenceChart). Rendering MultiLineTooltip content as a fallback.'),function(e={}){const{fields:t=[],title:n,format:i,style:r={},className:o="",showLabels:s=!0,separator:a=": "}=e;return e=>{if(!e||"object"!=typeof e)return null;const c=[];if(n){const t=De(e,n);c.push({value:$e(t,i)})}if(t&&Array.isArray(t)&&t.length>0)t.forEach(t=>{let n,r,o;"string"==typeof t?(n=t,r=t,o=i):(n=t.label,r=t.accessor||t.key||"",o=t.format||i);const a=$e(De(e,r),o);c.push({label:s?n:void 0,value:a})});else{const t=function(e,t={}){if(!e||"object"!=typeof e)return{entries:[]};const n=t.maxEntries??6,i=!1!==t.skipPositional,r=[];for(const[t,n]of Object.entries(e)){if(t.startsWith("_"))continue;if("data"===t)continue;if(i&&Ae.has(t.toLowerCase()))continue;if(null==n)continue;const e=typeof n;("string"===e||"number"===e||"boolean"===e||n instanceof Date)&&r.push({key:t,lower:t.toLowerCase(),value:n})}if(0===r.length)return{entries:[]};let o=r.findIndex(e=>Se.includes(e.lower));const s=o>=0;0>o&&(o=r.findIndex(e=>"id"===e.lower)),0>o&&(o=r.findIndex(e=>"string"==typeof e.value));const a=0>o?void 0:r[o];let c=r.filter((e,t)=>t!==o);s&&(c=c.filter(e=>"id"!==e.lower));const l=Ce(c,Ie),d=Ce(c,je),u=new Set(Ie),h=new Set(je),p=[];l&&p.push({key:l.key,value:l.value}),d&&p.push({key:d.key,value:d.value});for(const e of c){if(p.length>=n)break;e!==l&&e!==d&&(u.has(e.lower)||h.has(e.lower)||p.push({key:e.key,value:e.value}))}return{titleKey:a?.key,title:a?.value,entries:p}}(e,{skipPositional:!1});null!=t.title&&c.push({label:void 0,value:$e(t.title,i),bold:!0}),t.entries.forEach(e=>{c.push({label:s?e.key:void 0,value:$e(e.value,i)})})}const l={...Pe,...r};return Array.isArray(c)&&0!==c.length?(0,Re.jsx)("div",{className:("semiotic-tooltip semiotic-tooltip-multiline "+o).trim(),style:l,children:c.map((e,t)=>(0,Re.jsxs)("div",{style:{marginBottom:c.length-1>t?"4px":0,fontWeight:e.bold?"bold":void 0},children:[e.label&&(0,Re.jsxs)("strong",{children:[e.label,a]}),e.value]},t))}):null}}()):Be())}}var Ne=require("react/jsx-runtime");function Ee({x:e,y:t,containerWidth:n,containerHeight:i,margin:r,children:o,className:s="stream-frame-tooltip",zIndex:a=1}){const c=Number.isFinite(e)&&Number.isFinite(t),l=Me.useRef(null),[d,u]=Me.useState(null);Me.useLayoutEffect(()=>{const e=l.current;if(!e)return;const t=()=>{const t=e.getBoundingClientRect();Number.isFinite(t.width)&&Number.isFinite(t.height)&&u(e=>e&&.5>Math.abs(e.width-t.width)&&.5>Math.abs(e.height-t.height)?e:{width:t.width,height:t.height})};if(t(),"undefined"==typeof ResizeObserver)return;const n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[s,n,i,c]);let h;h=d?`translate(${d.width+12>n-e?"calc(-100% - 12px)":"12px"}, ${d.height+12>i-t?"calc(-100% - 4px)":"4px"})`:`translate(${e>.7*n?"calc(-100% - 12px)":"12px"}, ${.3*i>t?"4px":"calc(-100% - 4px)"})`;const p=function(e){if(!Me.isValidElement(e))return!1;const t=e.type;if("string"!=typeof t&&t&&!0===t.ownsChrome)return!0;const n=e.props;if(!0===n["data-semiotic-tooltip-chrome"])return!0;if("true"===n["data-semiotic-tooltip-chrome"])return!0;const i=n.style;if(i&&"object"==typeof i){if(null!=i.background&&""!==i.background&&"transparent"!==i.background)return!0;if(null!=i.backgroundColor&&""!==i.backgroundColor&&"transparent"!==i.backgroundColor)return!0}return!1}(o),f=p?null:Pe;return c?(0,Ne.jsx)("div",{ref:l,className:p?s:(s+" semiotic-tooltip").trim(),style:{...f||{},position:"absolute",left:r.left+e,top:r.top+t,transform:h,pointerEvents:"none",zIndex:a,width:"max-content"},children:o}):null}var We={names:["--semiotic-bg","--surface-1","--surface-0"],fallback:"#f8fafc"},qe={names:["--semiotic-border","--surface-3"],fallback:"#334155"},Oe={names:["--semiotic-danger","--viz-4"],fallback:"#dc2626"},Fe={names:["--semiotic-focus","--accent","--viz-9"],fallback:"#f97316"},ze={names:["--semiotic-grid","--surface-3"],fallback:"#cbd5e1"},Le={names:["--semiotic-primary","--accent","--viz-5"],fallback:"#0ea5e9"},Ye={names:["--semiotic-success","--viz-2"],fallback:"#22c55e"},He={names:["--semiotic-text","--text-primary"],fallback:"#0f172a"},Ge={names:["--semiotic-text-secondary","--text-secondary"],fallback:"#475569"},Xe={names:["--semiotic-warning","--viz-9","--viz-3"],fallback:"#f97316"};function _e(e,t){const n=e.canvas;if("function"!=typeof getComputedStyle||!n)return t.fallback;const i=getComputedStyle(n);for(const n of t.names){const t=i.getPropertyValue(n).trim();if(t)return T(e,t)??t}return t.fallback}function Ve(e,t){const n=Math.max(0,Math.min(1,t)),i=e.trim(),r=i.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);if(r){const[,e,t,i]=r;return Ve(`#${e}${e}${t}${t}${i}${i}`,n)}const o=i.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(o){const[,e,t,i]=o;return`rgba(${parseInt(e,16)}, ${parseInt(t,16)}, ${parseInt(i,16)}, ${n})`}const s=i.match(/^rgb\s*\(\s*([^)]+?)\s*\)$/i);if(s)return`rgba(${s[1]}, ${n})`;const a=i.match(/^rgba\s*\(\s*([^,]+,\s*[^,]+,\s*[^,]+),\s*[^)]+\)$/i);return a?`rgba(${a[1]}, ${n})`:i}var Ue=c(require("react")),Ke=require("d3-scale"),Qe=c(require("react")),Ze=16,Je=6,et=10,tt=22,nt=require("react/jsx-runtime"),it={fill:(e,t)=>(0,nt.jsx)("rect",{style:e,width:t,height:t}),line:(e,t)=>(0,nt.jsx)("line",{style:e,x1:0,y1:0,x2:t,y2:t})};function rt(e,t,n,i,r){let o;return o="function"==typeof n?n(e):(0,it[n])(i(e,t),r),o}function ot({swatchSize:e}){return(0,nt.jsx)("path",{d:`M${.25*e},${.55*e} L${.45*e},${.75*e} L${.8*e},${.3*e}`,fill:"none",stroke:"white",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"})}function st(e,t,n){return n&&n.size>0?n.has(e.label)?1:.3:null!=t?e.label===t?1:.3:1}var at=(e,t,n,i,r,o,s,a,c,l,d)=>{const{type:u="fill",styleFn:h,items:p}=e,f=[];let m=0;const y=!(!t&&!n),g="isolate"===l||void 0===l&&null!=r,{swatchSize:x,labelGap:b,rowHeight:v}=d;return p.forEach((e,l)=>{const d=rt(e,l,u,h,x),w=st(e,i,r),k=r&&r.size>0&&r.has(e.label);f.push((0,nt.jsxs)("g",{transform:`translate(0,${m})`,onClick:t?()=>t(e):void 0,onMouseEnter:n?()=>n(e):void 0,onMouseLeave:n?()=>n(null):void 0,tabIndex:y?a===o&&l===s?0:-1:void 0,role:y?"option":void 0,"aria-selected":y&&g?k||!1:void 0,"aria-current":y&&!g&&null!=i&&e.label===i||void 0,"aria-label":e.label,onKeyDown:y?n=>{if("Enter"!==n.key&&" "!==n.key||(n.preventDefault(),t&&t(e)),"ArrowDown"===n.key||"ArrowUp"===n.key){n.preventDefault();const e=(l+("ArrowDown"===n.key?1:-1)+p.length)%p.length;c(a,e);const t=n.currentTarget.parentElement?.children[e];t instanceof SVGElement&&t.focus()}}:void 0,onFocus:y?t=>{c(a,l),n&&n(e);const i=t.currentTarget.querySelector(".semiotic-legend-focus-ring");i&&i.setAttribute("visibility","visible")}:void 0,onBlur:y?e=>{n&&n(null);const t=e.currentTarget.querySelector(".semiotic-legend-focus-ring");t&&t.setAttribute("visibility","hidden")}:void 0,style:{cursor:y?"pointer":"default",opacity:w,transition:"opacity 150ms ease",pointerEvents:"all",outline:"none"},children:[y&&(0,nt.jsx)("rect",{className:"semiotic-legend-focus-ring",x:-2,y:-2,width:x+b+2+7*e.label.length,height:x+4,fill:"none",stroke:"var(--semiotic-focus, #005fcc)",strokeWidth:2,rx:3,visibility:"hidden"}),d,k&&(0,nt.jsx)(ot,{swatchSize:x}),(0,nt.jsx)("text",{y:x/2,x:x+b,dominantBaseline:"central",style:{fontSize:"var(--semiotic-legend-font-size, 12px)"},fill:"var(--semiotic-text, #333)",children:e.label})]},"legend-item-"+l)),m+=v}),f},ct=({legendGroups:e,width:t,customClickBehavior:n,customHoverBehavior:i,highlightedCategory:r,isolatedCategories:o,focusedGroupIndex:s,focusedItemIndex:a,onFocusedIndexChange:c,legendInteraction:l,metrics:d})=>{const u=[],h=function(e,t){let n=24;return e.map(({hasLabel:e,itemCount:i})=>{n+=5;const r=n;let o;n+=8,e&&(n+=16,o=n,n+=8);const s=n;return n+=i*t+8,{lineY:r,labelY:o,itemsY:s,endY:n}})}(e.map(e=>({hasLabel:!!e.label,itemCount:e.items.length})),d.rowHeight);return e.forEach((e,p)=>{const f=h[p];u.push((0,nt.jsx)("line",{stroke:"gray",x1:0,y1:f.lineY,x2:t,y2:f.lineY},"legend-top-line legend-symbol-"+p)),e.label&&null!=f.labelY&&u.push((0,nt.jsx)("text",{y:f.labelY,className:"legend-group-label",style:{fontSize:"var(--semiotic-legend-font-size, 12px)"},fill:"var(--semiotic-text, #333)",children:e.label},"legend-text-"+p)),u.push((0,nt.jsx)("g",{className:"legend-item",transform:`translate(0,${f.itemsY})`,children:at(e,n,i,r,o,s,a,p,c,l,d)},"legend-group-"+p))}),u},lt=({legendGroups:e,height:t,width:n,customClickBehavior:i,customHoverBehavior:r,highlightedCategory:o,isolatedCategories:s,focusedGroupIndex:a,focusedItemIndex:c,onFocusedIndexChange:l,legendInteraction:d,metrics:u})=>{let h=0;const p=[];e.forEach((e,t)=>{let f=0;e.label&&(f+=16);const m=((e,t,n,i,r,o,s,a,c,l,d,u)=>{const{type:h="fill",styleFn:p,items:f}=e,m=[],{swatchSize:y,labelGap:g,itemGap:x,rowHeight:b,align:v}=d,w=!(!t&&!n),k="isolate"===l||void 0===l&&null!=r,M=f.map(e=>y+g+7*e.label.length),S=[];let I=0,j=0;M.forEach((e,t)=>{const n=0===j?e:j+x+e;u&&u>0&&j>0&&n>u?(S.push({start:I,end:t,width:j}),I=t,j=e):j=n}),f.length>0&&S.push({start:I,end:f.length,width:j}),S.forEach((e,l)=>{let d="center"===v?Math.max(0,((u??e.width)-e.width)/2):"end"===v?Math.max(0,(u??e.width)-e.width):0;for(let u=e.start;e.end>u;u++){const e=f[u],v=rt(e,u,h,p,y),S=st(e,i,r),I=r&&r.size>0&&r.has(e.label);m.push((0,nt.jsxs)("g",{transform:`translate(${d},${l*b})`,onClick:t?()=>t(e):void 0,onMouseEnter:n?()=>n(e):void 0,onMouseLeave:n?()=>n(null):void 0,tabIndex:w?a===o&&u===s?0:-1:void 0,role:w?"option":void 0,"aria-selected":w&&k?I||!1:void 0,"aria-current":w&&!k&&null!=i&&e.label===i||void 0,"aria-label":e.label,onKeyDown:w?n=>{if("Enter"!==n.key&&" "!==n.key||(n.preventDefault(),t&&t(e)),"ArrowRight"===n.key||"ArrowLeft"===n.key){n.preventDefault();const e=(u+("ArrowRight"===n.key?1:-1)+f.length)%f.length;c(a,e);const t=n.currentTarget.parentElement?.children[e];t instanceof SVGElement&&t.focus()}}:void 0,onFocus:w?t=>{c(a,u),n&&n(e);const i=t.currentTarget.querySelector(".semiotic-legend-focus-ring");i&&i.setAttribute("visibility","visible")}:void 0,onBlur:w?e=>{n&&n(null);const t=e.currentTarget.querySelector(".semiotic-legend-focus-ring");t&&t.setAttribute("visibility","hidden")}:void 0,style:{cursor:w?"pointer":"default",opacity:S,transition:"opacity 150ms ease",pointerEvents:"all",outline:"none"},children:[w&&(0,nt.jsx)("rect",{className:"semiotic-legend-focus-ring",x:-2,y:-2,width:y+g+2+7*e.label.length,height:y+4,fill:"none",stroke:"var(--semiotic-focus, #005fcc)",strokeWidth:2,rx:3,visibility:"hidden"}),v,I&&(0,nt.jsx)(ot,{swatchSize:y}),(0,nt.jsx)("text",{y:y/2,x:y+g,dominantBaseline:"central",style:{fontSize:"var(--semiotic-legend-font-size, 12px)"},fill:"var(--semiotic-text, #333)",children:e.label})]},"legend-item-"+u)),d+=M[u]+x}});const A=Math.max(0,...S.map(e=>e.width)),C=S.length;return{items:m,offset:A,totalRows:C,totalHeight:C*b}})(e,i,r,o,s,a,c,t,l,d,u,u.maxWidth??n);f+=m.offset+5,p.push({label:e.label,...m,offset:f,totalRows:m.totalRows,totalHeight:m.totalHeight}),h+=f+12});const f=u.maxWidth??n;let m=h>f?0:"center"===u.align?Math.max(0,(f-h)/2):"end"===u.align?Math.max(0,f-h):0;const y=[];return p.forEach((n,i)=>{const r=e[i];r.label&&(y.push((0,nt.jsx)("text",{transform:`translate(${m},0) rotate(90)`,textAnchor:"start",className:"legend-group-label",style:{fontSize:"var(--semiotic-legend-font-size, 12px)"},fill:"var(--semiotic-text, #333)",children:r.label},"legend-text-"+i)),m+=16),y.push((0,nt.jsx)("g",{className:"legend-item",transform:`translate(${m},0)`,children:n.items},"legend-group-"+i)),m+=n.offset+5,e[i+1]&&y.push((0,nt.jsx)("line",{stroke:"gray",x1:m,y1:-8,x2:m,y2:(n.totalHeight||t)+0+8},"legend-top-line legend-symbol-"+i)),m+=12}),(0,nt.jsx)("g",{children:y})};function dt({config:e,orientation:t="vertical",width:n=100}){const{colorFn:i,domain:r,label:o,format:s}=e,a=s||(e=>Math.round(100*e)/100+""),c="grad-legend-"+Qe.useId();if("horizontal"===t){const e=12,t=Math.min(n,200),s=Math.max(0,(n-t)/2),l=[];for(let e=0;64>=e;e++){const t=e/64;l.push((0,nt.jsx)("stop",{offset:100*t+"%",stopColor:i(r[0]+t*(r[1]-r[0]))},e))}return(0,nt.jsxs)("g",{"aria-label":o||"Gradient legend",children:[(0,nt.jsx)("defs",{children:(0,nt.jsx)("linearGradient",{id:c,x1:"0%",y1:"0%",x2:"100%",y2:"0%",children:l})}),o&&(0,nt.jsx)("text",{x:s+t/2,y:-4,textAnchor:"middle",fontSize:11,fill:"var(--semiotic-text, #333)",children:o}),(0,nt.jsx)("rect",{x:s,y:0,width:t,height:e,fill:`url(#${c})`,rx:2}),(0,nt.jsx)("text",{x:s,y:e+12,textAnchor:"start",fontSize:10,fill:"var(--semiotic-text-secondary, #666)",children:a(r[0])}),(0,nt.jsx)("text",{x:s+t,y:e+12,textAnchor:"end",fontSize:10,fill:"var(--semiotic-text-secondary, #666)",children:a(r[1])})]})}const l=[];for(let e=0;64>=e;e++){const t=e/64;l.push((0,nt.jsx)("stop",{offset:100*t+"%",stopColor:i(r[1]-t*(r[1]-r[0]))},e))}return(0,nt.jsxs)("g",{"aria-label":o||"Gradient legend",children:[o&&(0,nt.jsx)("text",{x:7,y:-6,textAnchor:"middle",fontSize:11,fill:"var(--semiotic-text, #333)",children:o}),(0,nt.jsx)("defs",{children:(0,nt.jsx)("linearGradient",{id:c,x1:"0%",y1:"0%",x2:"0%",y2:"100%",children:l})}),(0,nt.jsx)("rect",{x:0,y:0,width:14,height:100,fill:`url(#${c})`,rx:2}),(0,nt.jsx)("text",{x:19,y:10,fontSize:10,fill:"var(--semiotic-text-secondary, #666)",children:a(r[1])}),(0,nt.jsx)("text",{x:19,y:100,fontSize:10,fill:"var(--semiotic-text-secondary, #666)",children:a(r[0])})]})}function ut(e){const{legendGroups:t,customClickBehavior:n,customHoverBehavior:i,highlightedCategory:r,isolatedCategories:o,legendInteraction:s,title:a="Legend",width:c=100,height:l=20,orientation:d="vertical",legendLayout:u}=e,h=function(e){const t=Math.max(1,e?.swatchSize??Ze),n=Math.max(t,e?.rowHeight??tt);return{swatchSize:t,labelGap:Math.max(0,e?.labelGap??Je),itemGap:Math.max(0,e?.itemGap??et),rowHeight:n,align:"left"===e?.align?"start":"right"===e?.align?"end":e?.align??"start",maxWidth:e?.maxWidth}}(u),[p,f]=Qe.useState(0),[m,y]=Qe.useState(0),g=Qe.useCallback((e,t)=>{f(e),y(t)},[]),x="vertical"===d?ct({legendGroups:t||[],width:c,customClickBehavior:n,customHoverBehavior:i,highlightedCategory:r,isolatedCategories:o,focusedGroupIndex:p,focusedItemIndex:m,onFocusedIndexChange:g,legendInteraction:s,metrics:h}):lt({legendGroups:t||[],title:a,height:l,width:c,customClickBehavior:n,customHoverBehavior:i,highlightedCategory:r,isolatedCategories:o,focusedGroupIndex:p,focusedItemIndex:m,onFocusedIndexChange:g,legendInteraction:s,metrics:h}),b=!(!n&&!i);return(0,nt.jsxs)("g",{role:b?"listbox":void 0,"aria-multiselectable":!(!b||"isolate"!==s&&(void 0!==s||null==o))||void 0,"aria-label":"Chart legend",style:{fontFamily:"var(--semiotic-font-family, sans-serif)"},children:[void 0!==a&&""!==a&&"vertical"===d&&(0,nt.jsx)("text",{className:"legend-title",y:16,x:c/2,textAnchor:"middle",style:{fontSize:"var(--semiotic-legend-font-size, 12px)"},fill:"var(--semiotic-text, #333)",children:a}),x]})}function ht(e){return"object"==typeof e&&null!==e&&"legendGroups"in e&&Array.isArray(e.legendGroups)}var pt=require("react/jsx-runtime");function ft(e){const{legend:t,totalWidth:n,totalHeight:i,margin:r,legendPosition:o="right",legendLayout:s,title:a,legendHoverBehavior:c,legendClickBehavior:l,legendHighlightedCategory:d,legendIsolatedCategories:u,legendInteraction:h}=e;if(!t)return null;const p="top"===o||"bottom"===o,f=!!a,m=Math.max(0,n-r.left-r.right),y=Math.max(1,p?s?.maxWidth??m:100);let g,x;return"left"===o?(g=Math.max(4,r.left-y-10),x=r.top):"top"===o?(g=r.left,x=f?32:8):"bottom"===o?(g=r.left,x=i-r.bottom+38):(g=n-r.right+10,x=r.top),(0,pt.jsx)("g",{transform:`translate(${g}, ${x})`,children:(b=t,"object"==typeof b&&null!==b&&"gradient"in b?(0,pt.jsx)(dt,{config:t.gradient,orientation:p?"horizontal":"vertical",width:y}):ht(t)?(0,pt.jsx)(ut,{legendGroups:t.legendGroups,title:"",width:y,orientation:p?"horizontal":"vertical",legendLayout:s,customHoverBehavior:c,customClickBehavior:l,highlightedCategory:d,isolatedCategories:u,legendInteraction:h}):t)});var b}var mt=require("react/jsx-runtime"),yt={secondary:0,primary:3},gt=1,xt=2,bt=.6,vt="0.88em",wt=.95,kt=.72,Mt=.06,St=".annotation-deferred{opacity:0;pointer-events:none;transition:opacity .12s ease}.stream-xy-frame:hover .annotation-deferred,.stream-ordinal-frame:hover .annotation-deferred,.stream-network-frame:hover .annotation-deferred,.stream-geo-frame:hover .annotation-deferred,.stream-xy-frame:focus-within .annotation-deferred,.stream-ordinal-frame:focus-within .annotation-deferred,.stream-network-frame:focus-within .annotation-deferred,.stream-geo-frame:focus-within .annotation-deferred{opacity:1;pointer-events:auto}@media (prefers-reduced-motion:reduce){.annotation-deferred{transition:none}}",It=".annotation-cohesion--layer text,.annotation-cohesion--layer tspan{fill:var(--semiotic-annotation-color,var(--semiotic-text-secondary,#666));font-style:italic}";function jt(e){return!0===e?._annotationDeferred}function At(e){return"blended"===e?.cohesion||"layer"===e?.cohesion?e.cohesion:null}function Ct(e){const t=e?.provenance?.confidence;return"number"==typeof t&&Number.isFinite(t)?Math.max(0,Math.min(1,t)):null}function Rt(e){return Math.max(kt,wt-e*Mt)}var Pt=c(require("react")),Dt=require("react/jsx-runtime");function $t(e,t=120,n=8){if(!e)return[];const i=Math.max(1,Math.floor(t/n)),r=e.split(/\s+/),o=[];let s="";for(const e of r)s&&s.length+1+e.length>i?(o.push(s),s=e):s=s?`${s} ${e}`:e;return s&&o.push(s),o}function Bt(e,t,n,i){return"curly"===e?i?`M0,0 C${.6*n},0 ${.4*n},${t/2} ${n},${t/2} C${.4*n},${t/2} ${.6*n},${t} 0,${t}`:`M0,0 C0,${.6*n} ${t/2},${.4*n} ${t/2},${n} C${t/2},${.4*n} ${t},${.6*n} ${t},0`:i?`M0,0 L${n},0 L${n},${t} L0,${t}`:`M0,0 L0,${n} L${t},${n} L${t},0`}function Tt(e,t,n,i){if(!e)return(0,Dt.jsx)("g",{className:"annotation-note"});const{label:r,title:o,orientation:s,align:a,wrap:c=120,noWrap:l}=e;if(!r&&!o)return(0,Dt.jsx)("g",{className:"annotation-note"});let d=s;d||(d=Math.abs(t)>Math.abs(n)?"leftRight":"topBottom");let u=a;u&&"dynamic"!==u||(u="topBottom"===d?0>t?"right":"left":0>n?"bottom":"top");let h="start";"topBottom"===d?"right"===u?h="end":"middle"===u&&(h="middle"):h=0>t?"end":"start";const p=16,f=o?l?[o]:$t(o,c):[],m=r?l?[r]:$t(r,c):[],y="leftRight"===d?"end"===h?-4:4:0;let g=0;const x=[],b=i||"var(--semiotic-annotation-color, var(--semiotic-text, #333))";e.useHTML||e.html?x.push((0,Dt.jsx)("foreignObject",{className:"annotation-note-html",x:"end"===h?y-c:"middle"===h?y-c/2:y,y:-16,width:c,height:Math.max(p,(f.length+m.length)*p+(o&&r?2:0))+p,style:{overflow:"visible"},children:(0,Dt.jsxs)("div",{xmlns:"http://www.w3.org/1999/xhtml",style:{color:b,fontSize:"12px",lineHeight:"16px",overflow:"visible",textAlign:"end"===h?"right":"middle"===h?"center":"left",whiteSpace:l?"nowrap":"normal",wordBreak:"break-word"},children:[o&&(0,Dt.jsx)("div",{className:"annotation-note-title",style:{fontWeight:"bold"},children:o}),r&&(0,Dt.jsx)("div",{className:"annotation-note-label",children:r})]})},"annotation-note-html")):(f.length>0&&(x.push((0,Dt.jsx)("text",{className:"annotation-note-title",fill:b,textAnchor:h,fontWeight:"bold",children:f.map((e,t)=>(0,Dt.jsx)("tspan",{x:y,dy:0===t?0:p,children:e},t))},"annotation-note-title")),g=f.length*p),m.length>0&&x.push((0,Dt.jsx)("text",{className:"annotation-note-label",fill:b,textAnchor:h,y:g,children:m.map((e,t)=>(0,Dt.jsx)("tspan",{x:y,dy:0===t?0:p,children:e},t))},"annotation-note-label")));let v=null;if((o||r)&&(0!==t||0!==n))if("topBottom"===d){const e=Math.min(c,120);let t=0,n=e;"end"===h?(t=-e,n=0):"middle"===h&&(t=-e/2,n=e/2),v=(0,Dt.jsx)("line",{className:"note-line",x1:t,x2:n,y1:0,y2:0,stroke:i||"var(--semiotic-text-secondary, currentColor)"})}else{const e=(f.length+m.length)*p+(m.length>0?p:0);let t=0,n=e;"bottom"===u?(t=-e,n=0):"middle"===u&&(t=-e/2,n=e/2),v=(0,Dt.jsx)("line",{className:"note-line",x1:0,x2:0,y1:t,y2:n,stroke:i||"var(--semiotic-text-secondary, currentColor)"})}const w=Math.max(0,f.length+m.length-1)*p;let k=0;return"topBottom"===d?k=0>n?-(w+2):18:"leftRight"===d&&(k="middle"===u?-(w+p+(m.length>0&&f.length>0?2:0))/2+8:"bottom"===u||0>n?-(w+2):18),(0,Dt.jsxs)("g",{className:"annotation-note",transform:`translate(${t},${n})`,children:[(0,Dt.jsx)("g",{className:"annotation-note-content",transform:0!==k?`translate(0,${k})`:void 0,children:x}),v]})}function Nt(e,t,n,i,r){const o=[];switch(e){case"callout-circle":{const e=(t?.radius||0)+(t?.radiusPadding||0);e>0&&o.push((0,Dt.jsx)("circle",{r:e,fill:"none",stroke:n||"var(--semiotic-text-secondary, currentColor)"},"subject-circle"));break}case"callout-rect":{const e=t?.width||0,i=t?.height||0;(e>0||i>0)&&o.push((0,Dt.jsx)("rect",{width:e,height:i,fill:"none",stroke:n||"var(--semiotic-text-secondary, currentColor)"},"subject-rect"));break}case"callout-custom":t?.custom&&o.push(...Array.isArray(t.custom)?t.custom:[t.custom]);break;case"xy-threshold":{const e=i||0,s=r||0;if(void 0!==t?.x){const i=(t.x||0)-e;o.push((0,Dt.jsx)("line",{x1:i,y1:(t.y1||0)-s,x2:i,y2:(t.y2||0)-s,stroke:n||"var(--semiotic-text-secondary, currentColor)",strokeDasharray:"5,5"},"threshold-line"))}else if(void 0!==t?.y){const i=(t.y||0)-s;o.push((0,Dt.jsx)("line",{x1:(t.x1||0)-e,y1:i,x2:(t.x2||0)-e,y2:i,stroke:n||"var(--semiotic-text-secondary, currentColor)",strokeDasharray:"5,5"},"threshold-line"))}else void 0!==t?.x1||void 0!==t?.x2?o.push((0,Dt.jsx)("line",{x1:(t.x1||0)-e,y1:0,x2:(t.x2||0)-e,y2:0,stroke:n||"var(--semiotic-text-secondary, currentColor)",strokeDasharray:"5,5"},"threshold-line")):void 0===t?.y1&&void 0===t?.y2||o.push((0,Dt.jsx)("line",{x1:0,y1:(t.y1||0)-s,x2:0,y2:(t.y2||0)-s,stroke:n||"var(--semiotic-text-secondary, currentColor)",strokeDasharray:"5,5"},"threshold-line"));break}case"bracket":{const e=t?.type||"curly",i=t?.width??t?.height;void 0!==i&&o.push((0,Dt.jsx)("path",{d:Bt(e,i,t?.depth||30,void 0===t?.width),fill:"none",stroke:n||"var(--semiotic-text-secondary, currentColor)"},"bracket-path"));break}}return(0,Dt.jsx)("g",{className:"annotation-subject",children:o})}function Et(e,t,n,i,r,o){const s=[];let a=0,c=0;if("callout-circle"!==r&&"label"!==r||!o?.radius){if("callout-rect"===r&&o){const n=o.width||0,i=o.height||0;if(n>0||i>0){const r=n/2,o=i/2,s=e-r,l=t-o;if(0!==s||0!==l){const e=Math.abs(s),t=Math.abs(l),d=n/2,u=i/2,h=e*u>t*d?d/e:u/t;a=r+s*h,c=o+l*h}}}else if("bracket"===r&&o){const e=o.width,t=o.height,n=o.depth||30;void 0!==e?(a=e/2,c=n):void 0!==t&&(a=n,c=t/2)}}else{const n=(o.radius||0)+(o.radiusPadding||0);if(n>0&&(0!==e||0!==t)){const i=Math.atan2(t,e);a=Math.cos(i)*n,c=Math.sin(i)*n}}const l=Math.sqrt((e-a)**2+(t-c)**2);if(l>.5){const r=i||"var(--semiotic-text-secondary, currentColor)",o="curve"===n?.type;let d=Math.atan2(t-c,e-a);if(o){const i=(a+e)/2,o=(c+t)/2,u=-(t-c)/l,h=(e-a)/l,p=(n?.curve??.25)*l,f=i+u*p,m=o+h*p;s.push((0,Dt.jsx)("path",{className:"connector-curve",d:`M${a},${c}Q${f},${m} ${e},${t}`,fill:"none",stroke:r},"connector-line")),d=Math.atan2(m-c,f-a)}else s.push((0,Dt.jsx)("line",{x1:a,y1:c,x2:e,y2:t,stroke:r},"connector-line"));if("arrow"===n?.end){const e=10,t=16/180*Math.PI;s.push((0,Dt.jsx)("path",{d:`M${a},${c}L${a+e*Math.cos(d+t)},${c+e*Math.sin(d+t)}L${a+e*Math.cos(d-t)},${c+e*Math.sin(d-t)}Z`,fill:r,stroke:"none"},"connector-arrow"))}}return(0,Dt.jsx)("g",{className:"annotation-connector",children:s})}function Wt(e){const{x:t=0,y:n=0,dx:i,dy:r,nx:o,ny:s,note:a,connector:c,subject:l,type:d,color:u,className:h,disable:p,opacity:f,strokeDasharray:m,events:y={},"data-testid":g}=e,x=Array.isArray(t)?t[0]??0:t,b=Array.isArray(n)?n[0]??0:n,v=new Set(Array.isArray(p)?p:[]);let w=i||0,k=r||0;null!=o&&(w=o-x),null!=s&&(k=s-b);const M="string"==typeof d?d:"label";if("bracket"===M&&l&&0===w&&0===k)if(void 0!==l.width){w=l.width/2;const e=l.depth||30;k=e+(0>e?-5:5)}else if(void 0!==l.height){const e=l.depth||30;w=e+(0>e?-5:5),k=l.height/2}return(0,Dt.jsxs)("g",{className:("annotation "+(h||"")).trim(),transform:`translate(${x},${b})`,"data-testid":g,...null!=f&&{opacity:f},...m&&{strokeDasharray:m},...y,children:[!v.has("connector")&&Et(w,k,c,u,M,l),!v.has("subject")&&Nt(M,l,u,x,b),!v.has("note")&&Tt(a,w,k,u)]})}function qt(e){const{noteData:t}=e,{screenCoordinates:n}=t,i="string"==typeof t.type?t.type:"label",r=t.eventListeners||t.events||{};if(t.coordinates&&n){const e=t.nx||n[0][0]+(t.dx??0),r=t.ny||n[0][1]+(t.dy??0),o=n.map((n,o)=>{const s=Object.assign({},t,{note:0===o?t.note:{label:""},x:n[0],y:n[1],nx:e,ny:r});return(0,Dt.jsx)(Wt,{"data-testid":"semiotic-annotation",...s,type:i},"multi-annotation-"+o)});return(0,Dt.jsx)("g",{children:o})}const o=t.note||{title:"none",label:t.label},s=`${o.label}-${o.title}-${t.i}`;return(0,Dt.jsx)(Wt,{"data-testid":"semiotic-annotation",events:r,...t,type:i},s)}var Ot=require("d3-hierarchy"),Ft=require("d3-shape"),zt=2;function Lt(e){const t=10**zt;return Math.round(e*t)/t}function Yt(e,t=2){const n=[],i=[],r=t+1;for(let t=0;r>t;t++){let o=0;for(const[n,i]of e)null!==i&&(o+=n**t*i);n.push(o);const s=[];for(let n=0;r>n;n++){let i=0;for(const[r,o]of e)null!==o&&(i+=r**(t+n));s.push(i)}i.push(s)}i.push(n);const o=function(e,t){const n=e,i=e.length-1,r=[t];for(let e=0;i>e;e++){let t=e;for(let r=e+1;i>r;r++)Math.abs(n[e][r])>Math.abs(n[e][t])&&(t=r);for(let r=e;i+1>r;r++){const i=n[r][e];n[r][e]=n[r][t],n[r][t]=i}for(let t=e+1;i>t;t++)for(let r=i;r>=e;r--)n[r][t]-=n[r][e]*n[e][t]/n[e][e]}for(let e=i-1;e>=0;e--){let t=0;for(let o=e+1;i>o;o++)t+=n[o][e]*r[o];r[e]=(n[i][e]-t)/n[e][e]}return r}(i,r).map(Lt);return{points:e.map(([e])=>[Lt(e),Lt(o.reduce((t,n,i)=>t+n*e**i,0))]),equation:[...o].reverse()}}function Ht(e,t){const n=t.scales?.x??t.scales?.time;return n?null!=e.x?n(e.x):t.xAccessor&&null!=e[t.xAccessor]?n(e[t.xAccessor]):null:null}function Gt(e,t){const n=t.scales?.y??t.scales?.value;return n?null!=e.y?n(e.y):t.yAccessor&&null!=e[t.yAccessor]?n(e[t.yAccessor]):null:null}function Xt(e){return null==e?null:e+""}function _t(e,t,n){return t.stickyPositionCache?.set(e,n),n}function Vt(e,t,n){const i=e.anchor||e.lifecycle?.anchor||"fixed";if("latest"===i){if(null!=e.pointId&&n.pointNodes&&n.pointNodes.length>0)for(let i=n.pointNodes.length-1;i>=0;i--){const r=n.pointNodes[i];if(r.pointId===e.pointId)return _t(t,n,{x:r.x,y:r.y})}const i=function(e){const t=e.data;if(!t||0===t.length)return null;const n=t[t.length-1],i=e.scales?.x??e.scales?.time,r=e.scales?.y??e.scales?.value;if(!i||!r)return null;const o=n[e.xAccessor||"x"],s=n[e.yAccessor||"y"];return null==o||null==s?null:{x:i(o),y:r(s)}}(n);return i?_t(t,n,i):null}if("semantic"===i){const i=function(e,t,n){const i=function(e){return Xt(e.provenance?.stableId??e.stableId)}(e);if(!i)return null;const r=n.pointNodes?.find(e=>Xt(e.pointId)===i);if(r)return _t(t,n,{x:r.x,y:r.y});const o=n.data?.find(e=>function(e){return Xt(e.stableId??e.id??e.provenance?.stableId)}(e)===i);if(!o)return null;const s=Ht(o,n),a=Gt(o,n);return null==s||null==a?null:_t(t,n,{x:s,y:a})}(e,t,n);if(i)return i}let r=null,o=null;if(null!=e.pointId&&n.pointNodes){const t=n.pointNodes.find(t=>t.pointId===e.pointId);t&&(r=t.x,o=t.y)}if(null!=r&&null!=o||(r=Ht(e,n),o=Gt(e,n)),null!=r&&null!=o)return _t(t,n,{x:r,y:o});if("sticky"===i){const e=n.stickyPositionCache?.get(t);if(e)return e}return null}function Ut(e,t,n,i=50){return!(-i>e||e>(n.width||0)+i||-i>t||t>(n.height||0)+i)}function Kt(e){let t=1/0,n=-1/0;for(const i of e)t>i&&(t=i),i>n&&(n=i);return[t,n]}var Qt=c(require("react")),[Zt,Jt]=g(e=>({observations:[],maxObservations:100,version:0,pushObservation(t){e(e=>{const n=e.observations;return n.push(t),n.length>e.maxObservations&&n.shift(),{version:e.version+1}})},clearObservations(){e(()=>({observations:[],version:0}))}}));function en(e,t={}){const n=function(e){const t=e.provenance,n=e.id??e.stableId??t?.stableId;return null==n||""===n?void 0:n+""}(e);return{"data-semiotic-annotation-widget":"",...n?{"data-semiotic-annotation-id":n}:{},onClickCapture(i){const r=function(e){const t=e.nativeEvent;return"touch"===t.pointerType?"touch":0===t.detail?"keyboard":"pointer"}(i);t.onAnnotationActivate?.({annotation:e,annotationId:n,chartId:t.chartId,inputType:r}),n&&t.onObservation&&t.onObservation({type:"annotation-activate",annotationId:n,inputType:r,timestamp:Date.now(),chartType:t.chartType??"unknown",chartId:t.chartId})}}}var tn=16,nn=20,rn=require("react/jsx-runtime"),on="var(--semiotic-bg, #ffffff)",sn=.85;function an(e){const{x:t,y:n,text:i,fill:r,fontSize:o=12,fontWeight:s,fontFamily:a,textAnchor:c="start",dominantBaseline:l,background:d,className:u}=e,h=function(e){return void 0===e||!0===e||"halo"===e?{type:"halo"}:!1===e||"none"===e?null:"box"===e?{type:"box"}:{type:e.type??"halo",...e}}(d),p=e=>(0,rn.jsx)("text",{x:t,y:n,textAnchor:c,dominantBaseline:l,fill:r,fontSize:o,fontWeight:s,fontFamily:a,className:u,...e?{stroke:e.stroke,strokeWidth:e.strokeWidth,paintOrder:"stroke"}:{},children:i});if(!h)return p();if("halo"===h.type)return p({stroke:h.fill??on,strokeWidth:h.haloWidth??3});const f=h.padding??{x:6,y:3},m="number"==typeof f?f:f.x,y="number"==typeof f?f:f.y,g=function(e,t){return(e+"").length*t*.6}(i,o),x=o+2*y;let b,v;return b="middle"===c?t-g/2-m:"end"===c?t-g-m:t-m,v="middle"===l||"central"===l?n-x/2:"hanging"===l||"text-before-edge"===l?n-y:n-.8*o-y,(0,rn.jsxs)("g",{className:u,children:[(0,rn.jsx)("rect",{x:b,y:v,width:g+2*m,height:x,rx:h.radius??3,ry:h.radius??3,fill:h.fill??on,fillOpacity:h.opacity??sn,stroke:h.stroke,strokeWidth:h.strokeWidth}),p()]})}var cn=require("react/jsx-runtime"),ln={linear:Ft.curveLinear,monotoneX:Ft.curveMonotoneX,monotoneY:Ft.curveMonotoneY,step:Ft.curveStep,stepAfter:Ft.curveStepAfter,stepBefore:Ft.curveStepBefore,basis:Ft.curveBasis,cardinal:Ft.curveCardinal,catmullRom:Ft.curveCatmullRom};var dn=new Set(["label","callout","callout-circle","callout-rect","text","widget"]);function un(e){return!!e&&"object"==typeof e&&dn.has(function(e){return"string"==typeof e?.type?e.type:""}(e))}new Set(["label","callout","callout-circle","callout-rect"]);var hn=2e4,pn=1;function fn(e){return"primary"===e?.emphasis||!0===e?.defensive}function mn(e,t,n={}){return"number"==typeof n.maxAnnotations&&Number.isFinite(n.maxAnnotations)?Math.max(0,Math.floor(n.maxAnnotations)):e>0&&t>0?Math.max(1,Math.round(e*t/(n.areaPerAnnotation&&n.areaPerAnnotation>0?n.areaPerAnnotation:hn))):1/0}function yn(e){let t;const n=e?.emphasis;t="primary"===n?100:"secondary"===n?10:50;const i=e?.provenance?.confidence;switch("number"==typeof i&&Number.isFinite(i)&&(t+=15*Math.max(0,Math.min(1,i))),e?.lifecycle?.freshness){case"fresh":t+=8;break;case"aging":t+=4;break;case"stale":t+=1;break;case"expired":t-=200}return t}var gn=32,xn=6,bn=4,vn=8,wn=72,kn=30,Mn=-30,Sn=8,In=480,jn=3;var An={ai:"AI",agent:"agent",watcher:"watcher",system:"system",import:"imported",computed:"computed",user:"you"};function Cn(e){if(!Rn(e))return e;const t=("string"==typeof e.mobileText?e.mobileText:void 0)??("string"==typeof e.shortText?e.shortText:void 0);return!t||"string"!=typeof e.label&&null!=e.label?e:{...e,label:t}}function Rn(e){return un(e)}function Pn(e,t){if(!e)return[];const n=Math.max(1,Math.floor(t/7)),i=e.split(/\s+/).filter(Boolean),r=[];let o="";for(const e of i)o&&o.length+e.length+1>n?(r.push(o),o=e):o=o?`${o} ${e}`:e;return o&&r.push(o),r}function Dn(e,t,n,i,r){const o=e+n,s=t+i;return Math.abs(n)>Math.abs(i)?{x:0>n?o-r.width-4:o+4,y:0>i?s-r.height:s,width:r.width,height:r.height}:{x:0>n?o-r.width:o,y:0>i?s-r.height-4:s+4,width:r.width,height:r.height}}function $n(e,t){return{x:e.x-t,y:e.y-t,width:e.width+2*t,height:e.height+2*t}}function Bn(e,t){return Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x))*Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y))}function Tn(e,t,n,i,r,o,s,a){const c=$n(e,s);let l=.4*Math.hypot(t.dx,t.dy)+80*function(e,t,n,i){const r=Math.max(0,i-e.x),o=Math.max(0,i-e.y);return(r+Math.max(0,e.x+e.width-(t-i)))*e.height+(o+Math.max(0,e.y+e.height-(n-i)))*e.width}(c,r,o,a);for(const e of n)l+=12*Bn(c,e);for(const e of i)l+=4*Bn(c,e);return l}function Nn(e){const{annotations:t,context:n,defaultOffset:i=gn,notePadding:r=xn,markPadding:o=bn,edgePadding:s=vn,preserveManualOffsets:a=!0,routeLongConnectors:c=!0,connectorThreshold:l=wn,density:d,progressiveDisclosure:u=!1,redundantCues:h=!1,responsive:p,mobile:f,cohesion:m,audience:y}=e,g=n.width||0,x=n.height||0,b="object"==typeof f?f:{},v=b.breakpoint??In,w=!!f&&v>=g,k=w&&!1!==b.preferShortText?t.map(Cn):t,M=w&&!d?{maxAnnotations:b.maxAnnotations??("callout-list"===b.strategy?1:2),minVisible:b.minVisible??1}:d,S=u||w&&(!1!==b.progressiveDisclosure||"callout-list"===b.strategy),I=w&&!p?b.responsive??{minWidth:v}:p,j=w&&!m?b.cohesion:m;if(0===k.length||0>=g||0>=x)return k.slice();const A=[],C=function(e,t){return(e.pointNodes||[]).map(e=>{const n=Math.max(1,e.r||1)+t;return{x:e.x-n,y:e.y-n,width:2*n,height:2*n}})}(n,o);let R=!1;const P=k.map((e,t)=>{if(!Rn(e))return e;const o=function(e,t,n){if("widget"===e.type&&"number"==typeof e.px&&"number"==typeof e.py)return{x:e.px,y:e.py};const i=e.pointId??e.nodeId;if(null!=i&&n.pointNodes){const e=n.pointNodes.find(e=>e.pointId===i);if(e)return{x:e.x,y:e.y}}const r=e.coordinates,o=n.scales?.geoProjection;if(Array.isArray(r)&&r.length>=2&&o){const e=r[0],t=r[1];if("number"==typeof e&&"number"==typeof t){const n=o([e,t]);if(n&&"number"==typeof n[0]&&"number"==typeof n[1])return{x:n[0],y:n[1]}}}return n.scales||"number"!=typeof e.x||"number"!=typeof e.y?Vt(e,t,n):{x:e.x,y:e.y}}(e,t,n);if(!o)return e;const d=function(e){if("widget"===e.type)return{width:"number"==typeof e.width?e.width:32,height:"number"==typeof e.height?e.height:32};const t="number"==typeof e.wrap?e.wrap:120,n=[...Pn("string"==typeof e.title?e.title:void 0,t),...Pn("string"==typeof e.label?e.label:void 0,t)],i=n.reduce((e,t)=>Math.max(e,t.length),0);return{width:Math.max(24,Math.min(t,7*i)+10),height:Math.max(18,16*n.length+6)}}(e);if(a&&("number"==typeof(u=e).dx||"number"==typeof u.dy)){const t=function(e){return"text"===e.type||"widget"===e.type?{dx:0,dy:0}:{dx:kn,dy:Mn}}(e);return A.push($n(Dn(o.x,o.y,"number"==typeof e.dx?e.dx:t.dx,"number"==typeof e.dy?e.dy:t.dy,d),r)),e}var u;let h=null,p=1/0;for(const e of function(e){const t=1.6*e;return[{dx:e,dy:-e},{dx:-e,dy:-e},{dx:e,dy:e},{dx:-e,dy:e},{dx:e,dy:0},{dx:-e,dy:0},{dx:0,dy:-e},{dx:0,dy:e},{dx:t,dy:-t},{dx:-t,dy:-t},{dx:t,dy:t},{dx:-t,dy:t}]}(i)){const t=Tn(Dn(o.x,o.y,e.dx,e.dy,d),e,A,C,g,x,r,s);p>t&&(h=e,p=t)}if(!h)return e;const f=$n(Dn(o.x,o.y,h.dx,h.dy,d),r);A.push(f);const m=Math.hypot(h.dx,h.dy),y=c&&m>=l&&"text"!==e.type&&"widget"!==e.type?{...e.connector||{end:"arrow"},type:"curve"}:e.connector;return R=!0,{...e,dx:h.dx,dy:h.dy,...y?{connector:y}:{}}}),D=R?P:k.slice();let $=D;if(h){let e=!1;const t=D.map(t=>{const n=function(e){return"text"!==e.type||"string"!=typeof e.color||Math.hypot("number"==typeof e.dx?e.dx:0,"number"==typeof e.dy?e.dy:0)<Sn?e:{...e,_redundantConnector:!0}}(t);return n!==t&&(e=!0),n});$=e?t:D}{let e=!1;const t=$.map(t=>{if(!0!==t?.defensive)return t;const n=function(e){const t=e?.provenance;if(!t||"object"!=typeof t)return e;const n="string"==typeof t.source?An[t.source]??t.source:null,i="number"==typeof t.confidence&&Number.isFinite(t.confidence)?Math.round(100*Math.max(0,Math.min(1,t.confidence)))+"%":null;if(!n&&!i)return e;if(null!=e.label&&"string"!=typeof e.label)return e;const r=[n,i].filter(Boolean).join(" · "),o="string"==typeof e.label?e.label:"";return o.includes(`(${r})`)?e:{...e,label:o?`${o} (${r})`:`(${r})`}}(t);return n!==t&&(e=!0),n});$=e?t:$}const B=new Set;if(M){const e="object"==typeof M?M:{},t=function(e){if(!e)return 1;const t=function(e){const t=e?.familiarity;if(!t)return jn;const n=Object.values(t).filter(e=>"number"==typeof e&&Number.isFinite(e));return 0===n.length?jn:n.reduce((e,t)=>e+t,0)/n.length}(e);return t>2?4>t?1:.6:1.5}(y),n=1===t?e:{...e,maxAnnotations:Math.max(0,Math.round((e.maxAnnotations??mn(g,x,e))*t))},{deferred:i}=function(e){const{annotations:t,width:n,height:i}=e,r=Math.max(0,e.minVisible??pn),o=mn(n,i,e),s=t.map((e,t)=>{return{annotation:e,index:t,note:(n=e,un(n))};var n}),a=s.filter(e=>e.note);if(0===a.length||o>=a.length)return{visible:t.slice(),deferred:[],budget:o};const c=a.filter(e=>fn(e.annotation)),l=a.filter(e=>!fn(e.annotation)).sort((e,t)=>yn(t.annotation)-yn(e.annotation)||e.index-t.index),d=Math.min(l.length,Math.max(Math.max(0,o-c.length),Math.max(0,r-c.length))),u=new Set([...c.map(e=>e.index),...l.slice(0,d).map(e=>e.index)]),h=[],p=[];for(const{annotation:e,index:t,note:n}of s)!n||u.has(t)?h.push(e):p.push(e);return{visible:h,deferred:p,budget:o}}({annotations:$,width:g,height:x,...n});for(const e of i)B.add(e)}if(I&&("object"==typeof I&&"number"==typeof I.minWidth?I.minWidth:In)>=g)for(const e of $)Rn(e)&&"secondary"===e.emphasis&&B.add(e);if(B.size>0)for(const e of $)!0===e?.defensive&&B.delete(e);let T;return T=0===B.size?$:S?$.map(e=>B.has(e)?{...e,_annotationDeferred:!0}:e):$.filter(e=>!B.has(e)),j?function(e,t){let n=!1;const i=e.map(e=>Rn(e)?"blended"===e.cohesion||"layer"===e.cohesion?e:(n=!0,{...e,cohesion:t}):e);return n?i:e}(T,j):T}var En=require("react/jsx-runtime");function Wn(e){return"circle"===e.shape.type?e.shape.radius:Math.max(e.shape.width,e.shape.height)/2}function qn(e){return e.map(e=>({pointId:e.id,x:e.x,y:e.y,r:Math.max(1,Wn(e))}))}function On(e){const{width:t,height:n,pointNodes:i=[],data:r}=e;return{scales:{x:(0,Ke.scaleLinear)().domain([0,Math.max(1,t)]).range([0,Math.max(1,t)]),y:(0,Ke.scaleLinear)().domain([0,Math.max(1,n)]).range([0,Math.max(1,n)])},width:t,height:n,frameType:"network",pointNodes:i,data:r,xAccessor:"x",yAccessor:"y"}}function Fn(e){return e?.length?e.map(e=>null!=e.pointId||null==e.bodyId?e:{...e,pointId:e.bodyId+""}):e}function zn(e){const{width:t,height:n,totalWidth:i,totalHeight:r,margin:o,title:s,legend:a,legendHoverBehavior:c,legendClickBehavior:l,legendHighlightedCategory:d,legendIsolatedCategories:u,legendPosition:h="right",legendLayout:p,pointNodes:f=[],annotations:m,onAnnotationActivate:y,onObservation:g,chartId:x,chartType:b,autoPlaceAnnotations:v,svgAnnotationRules:w,children:k}=e,M=function(e){const t=Jt(e=>e.pushObservation),n=Qt.useCallback(n=>{e.onObservation?.(n),t?.(n)},[e,t]);return Qt.useMemo(()=>({...e,onObservation:n}),[n,e])}({onAnnotationActivate:y,onObservation:g,chartId:x,chartType:b}),S=Ue.useMemo(()=>Fn(m),[m]),I=Ue.useMemo(()=>On({width:t,height:n,pointNodes:f}),[n,f,t]),j=Ue.useMemo(()=>S&&v?Nn({annotations:S,context:I,..."object"==typeof v?v:{}}):S,[I,v,S]),A=Ue.useMemo(()=>function(e,t={}){return function(e,n,i){switch(e.type){case"label":case"callout":case"callout-circle":case"callout-rect":{const t=Vt(e,n,i);if(!t)return null;const{x:r,y:o}=t;if(!Ut(r,o,i))return null;const s="callout"===e.type?"callout-circle":e.type,a="callout-circle"===s?{radius:e.radius??12,radiusPadding:e.radiusPadding}:"callout-rect"===s?{width:e.width,height:e.height}:void 0;return(0,cn.jsx)(qt,{noteData:{x:r,y:o,dx:e.dx??30,dy:e.dy??-30,note:{label:e.label,title:e.title,wrap:e.wrap||120},type:s,...a?{subject:a}:{},connector:e.connector||{end:"arrow"},color:e.color,disable:e.disable,opacity:e.opacity,strokeDasharray:e.strokeDasharray,className:e.className}},"ann-"+n)}case"x-threshold":{const t=Ht(null!=e.value?{...e,x:e.value}:e,i);if(null==t)return null;const r=e.color||"#f97316",o=e.labelPosition||"top";let s;s="bottom"===o?(i.height||0)-4:"center"===o?(i.height||0)/2:tn;const a=t>.6*(i.width||0),c=a?t-4:t+4,l=a?"end":"start";return(0,cn.jsxs)("g",{opacity:e.opacity,children:[(0,cn.jsx)("line",{x1:t,y1:0,x2:t,y2:i.height||0,stroke:r,strokeWidth:e.strokeWidth||1.5,strokeDasharray:e.strokeDasharray||"6,3"}),e.label&&(0,cn.jsx)(an,{x:c,y:s,text:e.label,textAnchor:l,fill:r,fontSize:12,fontWeight:"bold",background:e.labelBackground??"halo"})]},"ann-"+n)}case"y-threshold":{const t=Gt(null!=e.value?{...e,y:e.value}:e,i);if(null==t)return null;const r=e.color||"#f97316",o=e.labelPosition||"right";let a,c;"left"===o?(a=4,c="start"):"center"===o?(a=(i.width||0)/2,c="middle"):(a=(i.width||0)-4,c="end");const l=nn>(s=t)?Math.min((i.height||0)-4,s+tn):s-4;return(0,cn.jsxs)("g",{opacity:e.opacity,children:[(0,cn.jsx)("line",{x1:0,y1:t,x2:i.width||0,y2:t,stroke:r,strokeWidth:e.strokeWidth||1.5,strokeDasharray:e.strokeDasharray||"6,3"}),e.label&&(0,cn.jsx)(an,{x:a,y:l,text:e.label,textAnchor:c,fill:r,fontSize:12,fontWeight:"bold",background:e.labelBackground??"halo"})]},"ann-"+n)}case"enclose":{const t=(e.coordinates||[]).map(e=>({x:Ht({...e,type:"point"},i),y:Gt({...e,type:"point"},i),r:1})).filter(e=>null!=e.x&&null!=e.y);if(2>t.length)return null;const r=(0,Ot.packEnclose)(t),o=e.padding||10;return(0,cn.jsxs)("g",{children:[(0,cn.jsx)("circle",{cx:r.x,cy:r.y,r:r.r+o,fill:e.fill||"none",fillOpacity:e.fillOpacity||.1,stroke:e.color||"var(--semiotic-text-secondary, #666)",strokeWidth:1.5,strokeDasharray:"4,2"}),e.label&&(0,cn.jsx)(an,{x:r.x,y:r.y-r.r-o-4,textAnchor:"middle",fill:e.color||"var(--semiotic-text-secondary, #666)",fontSize:12,text:e.label,background:e.labelBackground??"none"})]},"ann-"+n)}case"rect-enclose":{const t=(e.coordinates||[]).map(e=>({x:Ht({...e,type:"point"},i),y:Gt({...e,type:"point"},i)})).filter(e=>null!=e.x&&null!=e.y);if(2>t.length)return null;const r=e.padding||10,o=t.map(e=>e.x),s=t.map(e=>e.y),[a,c]=Kt(o),[l,d]=Kt(s),u=a-r,h=c+r,p=l-r;return(0,cn.jsxs)("g",{children:[(0,cn.jsx)("rect",{x:u,y:p,width:h-u,height:d+r-p,fill:e.fill||"none",fillOpacity:e.fillOpacity||.1,stroke:e.color||"var(--semiotic-text-secondary, #666)",strokeWidth:1.5,strokeDasharray:"4,2"}),e.label&&(0,cn.jsx)(an,{x:(u+h)/2,y:p-4,textAnchor:"middle",fill:e.color||"var(--semiotic-text-secondary, #666)",fontSize:12,text:e.label,background:e.labelBackground??"none"})]},"ann-"+n)}case"highlight":{const t=i.data||[],r="function"==typeof e.filter?t.filter(e.filter):e.field&&null!=e.value?t.filter(t=>t[e.field]===e.value):[],o={stroke:e.color||"#f97316",strokeWidth:2,fill:"none"};return(0,cn.jsx)("g",{children:r.map((t,n)=>{const r=Ht(t,i),s=Gt(t,i);if(null==r||null==s)return null;const a="function"==typeof e.r?e.r(t):e.r||6,c="function"==typeof e.style?e.style(t):e.style||o;return(0,cn.jsx)("circle",{cx:r,cy:s,r:a,...c},"hl-"+n)})},"ann-"+n)}case"bracket":{const t=Ht(e,i),r=Gt(e,i);return(0,cn.jsx)(qt,{noteData:{x:t??0,y:r??0,dx:e.dx||0,dy:e.dy||0,note:{label:e.label,title:e.title,wrap:e.wrap||120},type:"bracket",subject:{type:e.bracketType||"curly",width:e.width,height:e.height,depth:e.depth||30},color:e.color}},"ann-"+n)}case"trend":{const t=i.data||[];if(2>t.length)return null;const r=i.xAccessor||"x",o=i.yAccessor||"y",s="ordinal"===i.frameType,a="horizontal"===i.projection,c=s?r:null,l=s?o:null;let d;const u=[],h=new Map;if(s&&c&&l){for(const e of t){const t=e[c];if(null==t)continue;const n=t+"";h.has(n)||(h.set(n,u.length),u.push(n))}d=t.map(e=>{const t=e[c],n=e[l];if(null==t||null==n)return null;const i=h.get(t+"");return null!=i?[i,+n]:null}).filter(e=>null!==e)}else d=t.map(e=>[e[r],e[o]]).filter(e=>null!=e[0]&&null!=e[1]);if(2>d.length)return null;const p=i.scales?.x??i.scales?.time,f=i.scales?.y??i.scales?.value;if(!p||!f)return null;const m=e=>t=>{const n=Math.max(0,Math.floor(t)),i=Math.min(u.length-1,n+1),r=t-n,o=e(u[n]);return o+(e(u[i])-o)*r},y=p,g=f;let x;if(s)if(a){const e=m(g);x=(t,n)=>[y(n),e(t)]}else{const e=m(y);x=(t,n)=>[e(t),g(n)]}else x=(e,t)=>[y(e),g(t)];const b=e.method||"linear";let v;if("loess"===b)v=function(e,t=.3){const n=e.length;if(2>n)return e.slice();const i=e.slice().sort((e,t)=>e[0]-t[0]),r=i.map(e=>e[0]),o=i.map(e=>e[1]),s=Math.max(2,Math.ceil(t*n)),a=[];for(let e=0;n>e;e++){const t=r[e],i=r.map(e=>Math.abs(e-t)),c=i.slice().sort((e,t)=>e-t)[Math.min(s-1,n-1)]||1,l=[];for(let e=0;n>e;e++){const t=0===c?0:i[e]/c;l[e]=1>t?Math.pow(1-Math.pow(t,3),3):0}let d=0,u=0,h=0,p=0,f=0;for(let e=0;n>e;e++){const t=l[e];0!==t&&(d+=t,u+=t*r[e],h+=t*o[e],p+=t*r[e]*r[e],f+=t*r[e]*o[e])}if(0===d){a.push([t,o[e]]);continue}const m=d*p-u*u;if(1e-12>Math.abs(m))a.push([t,h/d]);else{const e=(d*f-u*h)/m;a.push([t,(h-e*u)/d+e*t])}}return a}(d,e.bandwidth??.3);else{const t="polynomial"===b?Yt(d,e.order||2):function(e){const t=[0,0,0,0];let n=0;for(const[i,r]of e)null!==r&&(n++,t[0]+=i,t[1]+=r,t[2]+=i*i,t[3]+=i*r);const i=n*t[2]-t[0]*t[0],r=0===i?0:Lt((n*t[3]-t[0]*t[1])/i),o=Lt(t[1]/n-r*t[0]/n);return{points:e.map(([e])=>[Lt(e),Lt(r*e+o)]),equation:[r,o]}}(d);v=t.points}const w=v.map(([e,t])=>{const[n,i]=x(e,t);return`${n},${i}`}).join(" "),k=e.color||"#6366f1",M=v[v.length-1],[S,I]=x(M[0],M[1]);return(0,cn.jsxs)("g",{children:[(0,cn.jsx)("polyline",{points:w,fill:"none",stroke:k,strokeWidth:e.strokeWidth||2,strokeDasharray:e.strokeDasharray||"6,3"}),e.label&&(0,cn.jsx)("text",{x:S+4,y:I-4,fill:k,fontSize:11,children:e.label})]},"ann-"+n)}case"band":{const t=i.scales?.y??i.scales?.value,s=t?.domain?.(),a=e.y0??s?.[0],c=e.y1??s?.[1],l=null!=a&&t?t(a):0,d=null!=c&&t?t(c):i.height||0,u=se(e.fill,"ann-"+n,"var(--semiotic-primary, #6366f1)");return(0,cn.jsxs)("g",{opacity:e.opacity,children:[u.def&&(0,cn.jsx)("defs",{children:u.def}),(0,cn.jsx)("rect",{x:0,y:Math.min(l,d),width:i.width||0,height:Math.abs(d-l),fill:u.fill,fillOpacity:e.fillOpacity||.1}),e.label&&(0,cn.jsx)(an,{x:(i.width||0)-4,y:(r=l,o=d,Math.max(Math.min(r,o),0)+tn),textAnchor:"end",fill:e.color||"var(--semiotic-primary, #6366f1)",fontSize:11,fontWeight:"bold",text:e.label,background:e.labelBackground??"halo"})]},"ann-"+n)}case"x-band":{const t=i.scales?.x??i.scales?.time,r=t?.domain?.(),o=e.x0??r?.[0],s=e.x1??r?.[1],a=null!=o&&t?t(o):null,c=null!=s&&t?t(s):null;if(null==a||null==c)return null;const l=se(e.fill||e.color,"ann-"+n,"var(--semiotic-primary, #6366f1)");return(0,cn.jsxs)("g",{opacity:e.opacity,children:[l.def&&(0,cn.jsx)("defs",{children:l.def}),(0,cn.jsx)("rect",{x:Math.min(a,c),y:0,width:Math.abs(c-a),height:i.height||0,fill:l.fill,fillOpacity:e.fillOpacity??.1}),e.label&&(0,cn.jsx)(an,{x:Math.min(a,c)+4,y:tn,textAnchor:"start",fill:e.color||"var(--semiotic-primary, #6366f1)",fontSize:11,fontWeight:"bold",text:e.label,background:e.labelBackground??"halo"})]},"ann-"+n)}case"envelope":{const t=i.data||[];if(2>t.length)return null;const r=i.xAccessor||"x",o=i.scales?.x??i.scales?.time,s=i.scales?.y??i.scales?.value;if(!o||!s)return null;const a=e.upperAccessor||"upperBounds",c=e.lowerAccessor||"lowerBounds",l=e.filter,d=t.filter(e=>null!=e[a]&&null!=e[c]&&!(l&&!l(e))).sort((e,t)=>e[r]-t[r]);if(2>d.length)return null;const u=ln[i.curve||"linear"]||Ft.curveLinear,h=(0,Ft.area)().x(e=>o(e[r])).y0(e=>s(e[c])).y1(e=>s(e[a])).curve(u)(d);if(!h)return null;const p=e.fill||"#6366f1";return(0,cn.jsxs)("g",{children:[(0,cn.jsx)("path",{d:h,fill:p,fillOpacity:e.fillOpacity??.15,stroke:"none"}),e.label&&d.length>0&&(0,cn.jsx)("text",{x:o(d[d.length-1][r])+4,y:s(d[d.length-1][a])-4,fill:p,fontSize:11,children:e.label})]},"ann-"+n)}case"anomaly-band":{const t=i.data||[];if(2>t.length)return null;const r=i.yAccessor||"y",o=i.scales?.x??i.scales?.time,s=i.scales?.y??i.scales?.value;if(!o||!s)return null;const a=t.map(e=>e[r]).filter(e=>null!=e&&isFinite(e));if(2>a.length)return null;const c=a.reduce((e,t)=>e+t,0)/a.length,l=a.reduce((e,t)=>e+(t-c)**2,0)/a.length,d=Math.sqrt(l),u=e.threshold??2,h=c-u*d,p=!1!==e.showBand,f=e.fill||"#6366f1",m=e.fillOpacity??.1,y=e.anomalyColor||"#ef4444",g=e.anomalyRadius??6,x=s(c+u*d),b=s(h),v=t.filter(e=>{const t=e[r];return null!=t&&Math.abs(t-c)>u*d});return(0,cn.jsxs)("g",{children:[p&&(0,cn.jsx)("rect",{x:0,y:Math.min(x,b),width:i.width||0,height:Math.abs(b-x),fill:f,fillOpacity:m}),v.map((e,t)=>{const n=Ht(e,i),r=Gt(e,i);return null==n||null==r?null:(0,cn.jsx)("circle",{cx:n,cy:r,r:g,fill:y,fillOpacity:.7,stroke:y,strokeWidth:1.5},"anomaly-"+t)}),e.label&&(0,cn.jsx)("text",{x:(i.width||0)-4,y:Math.min(x,b)-4,textAnchor:"end",fill:f,fontSize:11,children:e.label})]},"ann-"+n)}case"forecast":{const t=i.data||[];if(3>t.length)return null;const r=i.xAccessor||"x",o=i.yAccessor||"y",s=i.scales?.x??i.scales?.time,a=i.scales?.y??i.scales?.value;if(!s||!a)return null;const c=t.map(e=>[e[r],e[o]]).filter(e=>null!=e[0]&&null!=e[1]&&isFinite(e[0])&&isFinite(e[1])).sort((e,t)=>e[0]-t[0]);if(3>c.length)return null;let l;if("polynomial"===(e.method||"linear")){const t=Yt(c,e.order||2).equation;l=e=>t.reduce((t,n,i)=>t+n*Math.pow(e,i),0)}else{const e=c.length;let t=0,n=0,i=0,r=0;for(const[e,o]of c)t+=e,n+=o,i+=e*e,r+=e*o;const o=e*i-t*t;if(1e-12>Math.abs(o))return null;const s=(e*r-t*n)/o,a=(n-s*t)/e;l=e=>a+s*e}const d=c.length,u=c.map(([e,t])=>t-l(e)),h=u.reduce((e,t)=>e+t*t,0),p=Math.sqrt(h/Math.max(d-2,1)),f=c.reduce((e,t)=>e+t[0],0)/d,m=c.reduce((e,t)=>e+(t[0]-f)**2,0),y=e.confidence??.95,g=.99>y?.95>y?.9>y?1:1.645:1.96:2.576,x=e.steps??5,b=c[d-1][0],v=(b-c[0][0])/Math.max(d-1,1),w=[];for(let e=1;x>=e;e++)w.push(b+e*v);const k=[];for(const e of w){const t=l(e),n=p*Math.sqrt(1+1/d+(m>0?(e-f)**2/m:0))*g;k.push({x:e,yCenter:t,yUpper:t+n,yLower:t-n})}const M=`M${k.map(e=>`${s(e.x)},${a(e.yUpper)}`).join(" L")} L${k.slice().reverse().map(e=>`${s(e.x)},${a(e.yLower)}`).join(" L")} Z`,S=k.map(e=>`${s(e.x)},${a(e.yCenter)}`).join(" "),I=`${s(b)},${a(l(b))}`,j=e.strokeColor||"#6366f1";return(0,cn.jsxs)("g",{children:[(0,cn.jsx)("path",{d:M,fill:e.fill||"#6366f1",fillOpacity:e.fillOpacity??.15,stroke:"none"}),(0,cn.jsx)("polyline",{points:`${I} ${S}`,fill:"none",stroke:j,strokeWidth:e.strokeWidth??2,strokeDasharray:e.strokeDasharray??"6,3"}),e.label&&k.length>0&&(0,cn.jsx)("text",{x:s(k[k.length-1].x)+4,y:a(k[k.length-1].yCenter)-4,fill:j,fontSize:11,children:e.label})]},"ann-"+n)}case"widget":{let r,o;if(null!=e.px&&null!=e.py)r=e.px,o=e.py;else{const t=Vt(e,n,i);if(!t)return null;r=t.x,o=t.y}if(!Ut(r,o,i))return null;const s=e.dx??0,a=e.dy??0,c=e.width??32,l=e.height??32,d=e.content??(0,cn.jsx)("span",{style:{fontSize:18,cursor:"default"},title:e.label||"Info",children:"ℹ️"});return(0,cn.jsx)("foreignObject",{x:r+s-c/2,y:o+a-l/2,width:c,height:l,style:{overflow:"visible",pointerEvents:"auto"},children:(0,cn.jsx)("div",{...en(e,t),style:{width:c,height:l,display:"flex",alignItems:"center",justifyContent:"center"},children:d})},"ann-"+n)}case"text":{const t=Vt(e,n,i);if(!t)return null;const{x:r,y:o}=t,s=r+(e.dx||0),a=o+(e.dy||0),c=e.color||"var(--semiotic-text, #333)",l=(0,cn.jsx)("text",{x:s,y:a,fill:c,fontSize:e.fontSize||11,opacity:e.opacity,strokeDasharray:e.strokeDasharray,dominantBaseline:"middle",style:{fontFamily:"inherit"},children:e.label});return!0!==e._redundantConnector?Pt.cloneElement(l,{key:"ann-text-"+n}):(0,cn.jsxs)("g",{opacity:e.opacity,strokeDasharray:e.strokeDasharray,children:[(0,cn.jsx)("line",{x1:r,y1:o,x2:s,y2:a,stroke:c,strokeWidth:1,strokeOpacity:.5,style:{pointerEvents:"none"}}),Pt.cloneElement(l,{opacity:void 0,strokeDasharray:void 0})]},"ann-text-"+n)}case"category-highlight":{const t=e.category;if(null==t)return null;const r=e=>"function"==typeof e&&"function"==typeof e.bandwidth,o=i.scales?.o,s=i.scales?.x,a=i.scales?.y,c=r(o)?o:r(s)?s:r(a)?a:null;if(!c)return null;const l=c(t+"");if(null==l)return null;const d=c.bandwidth(),u=e.color||"var(--semiotic-primary, #4589ff)",h=e.opacity??.15,p=e.label;return(0,cn.jsxs)("g",(i.projection?"vertical"===i.projection:c===s)?{children:[(0,cn.jsx)("rect",{x:l,y:0,width:d,height:i.height||0,fill:u,fillOpacity:h}),p&&(0,cn.jsx)(an,{x:l+d/2,y:tn,textAnchor:"middle",fill:u,fontSize:12,fontWeight:"bold",text:p,background:e.labelBackground??"none"})]}:{children:[(0,cn.jsx)("rect",{x:0,y:l,width:i.width||0,height:d,fill:u,fillOpacity:h}),p&&(0,cn.jsx)(an,{x:12,y:l+d/2,dominantBaseline:"middle",fill:u,fontSize:12,fontWeight:"bold",text:p,background:e.labelBackground??"none"})]},"ann-"+n)}default:return null}var r,o,s}}(0,M),[M]),C=j?function(e,t,n,i){const r=[];return e.forEach((e,o)=>{let s;if(n){const r=n(e,o,i);s=null!=r?r:t(e,o,i)}else s=t(e,o,i);s&&r.push({node:s,annotation:e})}),function(e){const t=e.map((e,t)=>{return{p:e,i:t,emphasis:(n=e.annotation,"primary"===n?.emphasis||"secondary"===n?.emphasis?n.emphasis:null),confidence:Ct(e.annotation),readingOrder:null,rank:gt};var n}),n=t.some(e=>null!=e.emphasis||null!=e.confidence),i=e.some(e=>jt(e.annotation)),r=e.some(e=>null!=At(e.annotation)),o=e.some(e=>"layer"===At(e.annotation));if(!n&&!i&&!r)return e.map(e=>e.node);const s=t.filter(e=>null==e.emphasis&&null!=e.confidence).slice().sort((e,t)=>(t.confidence??0)-(e.confidence??0)||e.i-t.i);s.forEach((e,t)=>{e.readingOrder=t,e.rank=xt-t/Math.max(1,s.length)});for(const e of t)e.emphasis&&(e.rank=yt[e.emphasis]);const a=t.sort((e,t)=>e.rank-t.rank||e.i-t.i).map(e=>{const{p:t,i:n,emphasis:i,readingOrder:r}=e,o=jt(t.annotation);let s=t.node;if("primary"===i||"secondary"===i||null!=r){const e=null==i&&null!=r;s=(0,mt.jsx)("g",{className:e?"annotation-emphasis annotation-emphasis--inferred":"annotation-emphasis annotation-emphasis--"+i,..."secondary"===i?{opacity:bt,fontSize:vt}:{},...e?{opacity:Rt(r),"data-annotation-reading-order":r}:{},children:t.node},"annotation-emphasis-"+n)}const a=At(t.annotation);return a&&(s=(0,mt.jsx)("g",{className:"annotation-cohesion--"+a,children:s},"annotation-cohesion-"+n)),o&&(s=(0,mt.jsx)("g",{className:"annotation-deferred","data-annotation-disclosure":"deferred",children:s},"annotation-deferred-"+n)),s});return i&&a.unshift((0,mt.jsx)("style",{children:St},"annotation-disclosure-style")),o&&a.unshift((0,mt.jsx)("style",{children:It},"annotation-cohesion-style")),a}(r)}(j,A,w,I):null,R=!0===j?.some(e=>"widget"===e.type&&!0===e._annotationDeferred);return(0,En.jsxs)(En.Fragment,{children:[R?(0,En.jsx)("style",{children:St},"physics-annotation-disclosure-style"):null,(0,En.jsxs)("svg",{className:"stream-physics-frame__overlay","data-testid":"stream-physics-overlay",role:"presentation",width:i,height:r,style:{position:"absolute",top:0,left:0,pointerEvents:"none",overflow:"visible"},children:[(0,En.jsxs)("g",{transform:`translate(${o.left},${o.top})`,children:[C,k]}),s&&"string"==typeof s?(0,En.jsx)("text",{x:i/2,y:16,textAnchor:"middle",fontWeight:600,fill:"var(--semiotic-text, #333)",className:"semiotic-chart-title",style:{fontSize:"var(--semiotic-title-font-size, 14px)"},children:s}):s?(0,En.jsx)("foreignObject",{x:0,y:0,width:i,height:Math.max(o.top,28),children:s}):null,a?ft({legend:a,totalWidth:i,totalHeight:r,margin:o,legendPosition:h,legendLayout:p,title:s,legendHoverBehavior:c,legendClickBehavior:l,legendHighlightedCategory:d,legendIsolatedCategories:u}):null]})]})}function Ln(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function Yn(e,t){const n="sensor"===e.physics?t.sensorThickness:t.barrierThickness;return Math.max(0,Ln(e.thickness)??Ln(n)??Ln(t.thickness)??4)}var Hn=2500;function Gn(e){return"function"==typeof e}function Xn(e){return void 0===e||!1===e||!Gn(e.binAccessor)&&!Gn(e.labelAccessor)&&!Gn(e.valueAccessor)}function _n(e){if(void 0!==e){if(!1===e)return!1;if(!Xn(e))throw new TypeError("Physics worker sediment config only supports string or numeric accessors");return{binAccessor:"string"==typeof e.binAccessor?e.binAccessor:void 0,labelAccessor:"string"==typeof e.labelAccessor?e.labelAccessor:void 0,valueAccessor:"string"==typeof e.valueAccessor||"number"==typeof e.valueAccessor?e.valueAccessor:void 0,retainBodyIds:e.retainBodyIds}}}function Vn(e){if(e)return{chartId:e.chartId,chartType:e.chartType,sensors:e.sensors}}function Un(e){return function(e){return!Gn(e?.timeAccessor)}(e)}function Kn(e={}){if(e.engine)throw new TypeError("Physics workers use the built-in kernel adapter");const{engine:t,observation:n,sediment:i,...r}=e;return{...r,observation:Vn(n),sediment:_n(i)}}var Qn={};function Zn(){if("undefined"!=typeof DOMException)return new DOMException("Physics worker request aborted","AbortError");const e=Error("Physics worker request aborted");return e.name="AbortError",e}var Jn=class{constructor(e=function(){const e="string"==typeof Qn.url&&Qn.url?new URL("./physicsWorker.js",Qn.url):function(e){if("undefined"!=typeof __filename){const t=__filename.replace(/\\/g,"/"),n=t.startsWith("/")?t:"/"+t;return new URL("./"+e,"file:"+n)}throw Error("Cannot resolve module worker asset: "+e)}("physicsWorker.js");return new Worker(e,{type:"module",name:"semiotic-physics"})}()){this.nextRequestId=1,this.pending=new Map,this.worker=e,this.worker.onmessage=e=>{const t=e.data,n=this.pending.get(t.requestId);n&&(this.pending.delete(t.requestId),n.cleanup(),t.ok?n.resolve(t.payload):n.reject(function(e){const t=Error(e.error.message);return t.name=e.error.name??"Error",e.error.stack&&(t.stack=e.error.stack),t}(t)))},this.worker.onerror=e=>{this.rejectAll(Error(e.message||"Physics worker failed")),this.worker.terminate()}}request(e,t){if(t?.aborted)return Promise.reject(Zn());const n=this.nextRequestId;this.nextRequestId+=1;const i={command:e,requestId:n};return new Promise((e,r)=>{const o=()=>{this.pending.delete(n),t?.removeEventListener("abort",o),r(Zn())},s=()=>t?.removeEventListener("abort",o);this.pending.set(n,{cleanup:s,reject:r,resolve:e}),t?.addEventListener("abort",o,{once:!0});try{this.worker.postMessage(i)}catch(e){this.pending.delete(n),s(),r(e)}})}async init(e,t,n,i){if(!Un(n))throw new TypeError("Physics worker spawn pacing only supports string time accessors");const r=await this.request({type:"init",config:Kn(e),initialSpawns:t,initialSpawnPacing:n},i);if("frame"!==r.type)throw Error("Physics worker returned a non-frame init response");return r.frame}async restore(e,t){const n=await this.request({type:"restore",snapshot:e},t);if("frame"!==n.type)throw Error("Physics worker returned a non-frame restore response");return n.frame}async initFromSnapshot(e,t,n){const i=await this.request({type:"init",config:Kn(e),snapshot:t},n);if("frame"!==i.type)throw Error("Physics worker returned a non-frame init response");return i.frame}async enqueue(e,t,n){if(!Un(t))throw new TypeError("Physics worker spawn pacing only supports string time accessors");const i=await this.request({type:"enqueue",spawns:e,pacing:t},n);if("frame"!==i.type)throw Error("Physics worker returned a non-frame enqueue response");return i.frame}async tick(e,t){const n=await this.request({type:"tick",deltaSeconds:e},t);if("frame"!==n.type)throw Error("Physics worker returned a non-frame tick response");return n.frame}async settle(e,t){const n=await this.request({type:"settle",maxSteps:e},t);if("frame"!==n.type)throw Error("Physics worker returned a non-frame settle response");return n.frame}async snapshot(e){const t=await this.request({type:"snapshot"},e);if("snapshot"!==t.type)throw Error("Physics worker returned a non-snapshot response");return t.snapshot}async remove(e,t){const n=await this.request({type:"remove",ids:e},t);if("removed"!==n.type)throw Error("Physics worker returned a non-remove response");return{frame:n.frame,removed:n.removed}}terminate(){this.rejectAll(Error("Physics worker terminated")),this.worker.terminate()}rejectAll(e){for(const[t,n]of this.pending)this.pending.delete(t),n.cleanup(),n.reject(e)}};function ei(e){let t=e>>>0;return function(){t=t+1831565813|0;let e=Math.imul(t^t>>>15,1|t);return e=e+Math.imul(e^e>>>7,61|e)^e,((e^e>>>14)>>>0)/4294967296}}var ti={seed:1,gravity:{x:0,y:980},fixedDt:1/120,cellSize:64,collisionIterations:6,velocityDamping:.995,sleepSpeed:8,sleepAfter:.35,restitution:.1,friction:.35,maxVelocity:1600,contactWakeSpeed:200},ni=1e-9,ii=.005;function ri(e){return"circle"===e.type?{type:"circle",radius:e.radius}:{type:"aabb",width:e.width,height:e.height}}function oi(e){return"aabb"===e.type?{type:"aabb",x:e.x,y:e.y,width:e.width,height:e.height}:{type:"segment",x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2,thickness:e.thickness}}function si(e,t,n){return Math.max(t,Math.min(n,e))}function ai(e){return 0>e?-1:1}function ci(e){if("circle"===e.shape.type){const t=e.shape.radius;return{minX:e.x-t,minY:e.y-t,maxX:e.x+t,maxY:e.y+t}}const t=e.shape.width/2,n=e.shape.height/2;return{minX:e.x-t,minY:e.y-n,maxX:e.x+t,maxY:e.y+n}}function li(e){const t=e.shape;if("aabb"===t.type){const e=t.width/2,n=t.height/2;return{minX:t.x-e,minY:t.y-n,maxX:t.x+e,maxY:t.y+n}}const n=(t.thickness??0)/2;return{minX:Math.min(t.x1,t.x2)-n,minY:Math.min(t.y1,t.y2)-n,maxX:Math.max(t.x1,t.x2)+n,maxY:Math.max(t.y1,t.y2)+n}}function di(e,t){return!(e.minX>t.maxX||t.minX>e.maxX||e.minY>t.maxY||t.minY>e.maxY)}function ui(e,t,n,i,r,o,s,a){const c=r-e,l=(n+s)/2-Math.abs(c);if(0>=l)return null;const d=o-t,u=(i+a)/2-Math.abs(d);return u>0?u>l?{nx:ai(c),ny:0,penetration:l}:{nx:0,ny:ai(d),penetration:u}:null}function hi(e,t,n,i,r,o,s){const a=o/2,c=s/2;let l=e-si(e,i-a,i+a),d=t-si(t,r-c,r+c);const u=l*l+d*d;if(u>n*n)return null;if(ni>=u){const o=Math.abs(e-(i-a)),s=Math.abs(e-(i+a)),u=Math.abs(t-(r-c)),h=Math.abs(t-(r+c)),p=Math.min(o,s,u,h);return p===o?(l=-1,d=0,{nx:l,ny:d,penetration:n+o}):p===s?(l=1,d=0,{nx:l,ny:d,penetration:n+s}):p===u?(l=0,d=-1,{nx:l,ny:d,penetration:n+u}):(l=0,d=1,{nx:l,ny:d,penetration:n+h})}const h=Math.sqrt(u);return{nx:l/h,ny:d/h,penetration:n-h}}function pi(e,t){if("circle"===e.shape.type&&"circle"===t.shape.type)return function(e,t,n,i,r,o){const s=i-e,a=r-t,c=n+o,l=s*s+a*a;if(l>=c*c)return null;if(ni>=l)return{nx:1,ny:0,penetration:c};const d=Math.sqrt(l);return{nx:s/d,ny:a/d,penetration:c-d}}(e.x,e.y,e.shape.radius,t.x,t.y,t.shape.radius);if("aabb"===e.shape.type&&"aabb"===t.shape.type)return ui(e.x,e.y,e.shape.width,e.shape.height,t.x,t.y,t.shape.width,t.shape.height);if("circle"===e.shape.type&&"aabb"===t.shape.type){const n=hi(e.x,e.y,e.shape.radius,t.x,t.y,t.shape.width,t.shape.height);return n?{nx:-n.nx,ny:-n.ny,penetration:n.penetration}:null}return"aabb"===e.shape.type&&"circle"===t.shape.type?hi(t.x,t.y,t.shape.radius,e.x,e.y,e.shape.width,e.shape.height):null}function fi(e,t){const n=t.shape;return"aabb"===n.type?"circle"===e.shape.type?hi(e.x,e.y,e.shape.radius,n.x,n.y,n.width,n.height):ui(n.x,n.y,n.width,n.height,e.x,e.y,e.shape.width,e.shape.height):function(e,t,n,i,r,o,s,a=0){const c=o-i,l=s-r,d=c*c+l*l,u=d>ni?si(((e-i)*c+(t-r)*l)/d,0,1):0,h=n+a/2,p=e-(i+c*u),f=t-(r+l*u),m=p*p+f*f;if(m>=h*h)return null;if(ni>=m){const e=Math.sqrt(d);return e>ni?{nx:-l/e,ny:c/e,penetration:h}:{nx:1,ny:0,penetration:h}}const y=Math.sqrt(m);return{nx:p/y,ny:f/y,penetration:h-y}}(e.x,e.y,"circle"===e.shape.type?e.shape.radius:Math.sqrt(e.shape.width*e.shape.width+e.shape.height*e.shape.height)/2,n.x1,n.y1,n.x2,n.y2,n.thickness??0)}function mi(e,t){return`${e}\0${t}`}function yi(e){const t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}function gi(e){return{id:e.id,x:e.x,y:e.y,prevX:e.prevX,prevY:e.prevY,vx:e.vx,vy:e.vy,angle:e.angle,mass:e.mass,bodyCollisions:e.bodyCollisions,shape:ri(e.shape),sleeping:e.sleeping,datum:e.datum,index:e.index,sleepTime:e.sleepTime,restitution:e.restitution,friction:e.friction}}function xi(e){return e&&"function"!=typeof e?{property:e.property,equals:e.equals,notEquals:e.notEquals,oneOf:e.oneOf?.slice(),notOneOf:e.notOneOf?.slice()}:e}function bi(e){return{id:e.id,shape:oi(e.shape),sensor:e.sensor,restitution:e.restitution,friction:e.friction,bodyFilter:xi(e.bodyFilter),index:e.index}}function vi(e,t){return!!t?.some(t=>Object.is(e,t))}function wi(e,t){const n=e.bodyFilter;if(!n)return!0;if("function"==typeof n)return n(t);const i=function(e,t){if(!t)return;let n=e;for(const e of t.split(".")){if(null==n||"object"!=typeof n)return;n=n[e]}return n}(t,n.property);return!("equals"in n&&!Object.is(i,n.equals)||"notEquals"in n&&Object.is(i,n.notEquals)||n.oneOf&&!vi(i,n.oneOf)||n.notOneOf&&vi(i,n.notOneOf))}var ki=class{constructor(e={}){this.capabilities={determinism:"strict",sensors:!0,joints:!1,ccd:!1,maxBodiesHint:5e3,worker:!1},this.bodies=new Map,this.colliders=new Map,this.springs=new Map,this.activeSensors=new Set,this.supportedThisStep=new Set,this.lastEvents=[],this.nextBodyIndex=0,this.nextColliderIndex=0,this.nextSpringIndex=0,this.options={...ti,...e},this.random=ei(this.options.seed)}init(e={}){this.options={...ti,...e},this.random=ei(this.options.seed),this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors.clear(),this.lastEvents=[],this.nextBodyIndex=0,this.nextColliderIndex=0,this.nextSpringIndex=0}spawn(e){const t={id:e.id,x:e.x,y:e.y,prevX:e.x,prevY:e.y,vx:e.vx??0,vy:e.vy??0,angle:e.angle??0,mass:Math.max(ni,e.mass??1),bodyCollisions:e.bodyCollisions??!0,shape:ri(e.shape),sleeping:!1,datum:e.datum,restitution:e.restitution,friction:e.friction,index:this.nextBodyIndex,sleepTime:0};this.nextBodyIndex+=1,this.bodies.set(e.id,t)}remove(e){for(const t of e){this.bodies.delete(t);for(const e of Array.from(this.activeSensors))yi(e).bodyId===t&&this.activeSensors.delete(e)}}setColliders(e){this.colliders.clear(),this.activeSensors.clear(),this.nextColliderIndex=0;for(const t of e)this.colliders.set(t.id,{...t,shape:oi(t.shape),bodyFilter:xi(t.bodyFilter),index:this.nextColliderIndex}),this.nextColliderIndex+=1}setConstraint(e){const t=e.id??"spring-"+this.nextSpringIndex;return this.springs.set(t,{id:t,bodyId:e.bodyId,target:e.target,restLength:e.restLength??0,stiffness:e.stiffness??40,damping:e.damping??3}),this.nextSpringIndex+=1,t}removeConstraint(e){this.springs.delete(e)}applyImpulse(e,t,n){const i=this.bodies.get(e);i&&(i.vx+=t/i.mass,i.vy+=n/i.mass,this.wake(i))}step(e=this.options.fixedDt){const t=Math.max(0,e);if(this.lastEvents=[],0===t)return;const n=this.sortedBodies();for(const e of n)e.prevX=e.x,e.prevY=e.y;this.applySprings(t);const i=this.options.maxVelocity;for(const e of n)if(!e.sleeping){if(e.vx+=this.options.gravity.x*t,e.vy+=this.options.gravity.y*t,e.vx*=this.options.velocityDamping,e.vy*=this.options.velocityDamping,i>0){const t=Math.sqrt(e.vx*e.vx+e.vy*e.vy);if(t>i){const n=i/t;e.vx*=n,e.vy*=n}}e.x+=e.vx*t,e.y+=e.vy*t}this.supportedThisStep.clear();const r=this.bodyPairKeys(n),o=this.sortedColliders().filter(e=>!e.sensor);for(let e=0;this.options.collisionIterations>e;e+=1)this.resolveBodyPairs(n,r,0===e),this.resolveColliders(n,o,0===e);this.updateSensors(n),this.updateSleeping(n,t)}settle(e=1200,t=this.options.fixedDt){let n=0;for(;e>n&&!this.allSleeping();)this.step(t),n+=1;return n}readState(e=[]){e.length=0;for(const t of this.sortedBodies())e.push({id:t.id,x:t.x,y:t.y,prevX:t.prevX,prevY:t.prevY,vx:t.vx,vy:t.vy,angle:t.angle,mass:t.mass,shape:ri(t.shape),sleeping:t.sleeping,datum:t.datum});return e}events(){return this.lastEvents.slice()}activeSensorPairs(){return Array.from(this.activeSensors).sort().map(yi)}allSleeping(){for(const e of this.bodies.values())if(!e.sleeping)return!1;return!0}snapshot(){return{options:{...this.options,gravity:{...this.options.gravity}},bodies:this.sortedBodies().map(gi),colliders:this.sortedColliders().map(bi),springs:Array.from(this.springs.values()).map(e=>({...e,target:{...e.target}})),activeSensors:Array.from(this.activeSensors).sort()}}restore(e){this.options={...e.options,gravity:{...e.options.gravity}},this.random=ei(this.options.seed),this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors=new Set(e.activeSensors),this.lastEvents=[],this.nextBodyIndex=0;for(const t of e.bodies){const e=gi(t);this.bodies.set(e.id,e),this.nextBodyIndex=Math.max(this.nextBodyIndex,e.index+1)}this.nextColliderIndex=0;for(const t of e.colliders){const e=bi(t);this.colliders.set(e.id,e),this.nextColliderIndex=Math.max(this.nextColliderIndex,e.index+1)}this.nextSpringIndex=0;for(const t of e.springs){this.springs.set(t.id,{...t,target:{...t.target}});const e=/^spring-(\d+)$/.exec(t.id);e&&(this.nextSpringIndex=Math.max(this.nextSpringIndex,Number(e[1])+1))}}dispose(){this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors.clear(),this.lastEvents=[]}sortedBodies(){return Array.from(this.bodies.values()).sort((e,t)=>e.index-t.index)}sortedColliders(){return Array.from(this.colliders.values()).sort((e,t)=>e.index-t.index)}applySprings(e){for(const t of Array.from(this.springs.values()).sort((e,t)=>e.id.localeCompare(t.id))){const n=this.bodies.get(t.bodyId);if(!n||n.sleeping)continue;const i="point"===t.target.type?t.target:this.bodies.get(t.target.bodyId);if(!i)continue;const r=i.x-n.x,o=i.y-n.y,s=Math.sqrt(r*r+o*o);if(ni>=s)continue;const a=r/s,c=o/s,l=(s-t.restLength)*t.stiffness+((("vx"in i?i.vx:0)-n.vx)*a+(("vy"in i?i.vy:0)-n.vy)*c)*t.damping;n.vx+=l*a*e/n.mass,n.vy+=l*c*e/n.mass}}resolveBodyPairs(e,t,n){for(const i of t){const[t,r]=i.split(":").map(Number),o=e[t],s=e[r];if(!o||!s)continue;const a=pi(o,s);a&&(this.resolveDynamicCollision(o,s,a),n&&this.lastEvents.push({type:"contact",bodyId:o.id,otherId:s.id,sensor:!1}))}}bodyPairKeys(e){const t=Math.max(1,this.options.cellSize),n=new Map;for(let i=0;e.length>i;i+=1){if(!1===e[i].bodyCollisions)continue;const r=ci(e[i]),o=Math.floor(r.minX/t),s=Math.floor(r.maxX/t),a=Math.floor(r.minY/t),c=Math.floor(r.maxY/t);for(let e=o;s>=e;e+=1)for(let t=a;c>=t;t+=1){const r=`${e}:${t}`,o=n.get(r);o?o.push(i):n.set(r,[i])}}const i=new Set;for(const t of Array.from(n.keys()).sort()){const r=n.get(t)??[];r.sort((e,t)=>e-t);for(let t=0;r.length>t;t+=1)for(let n=t+1;r.length>n;n+=1){const o=r[t],s=r[n];!1!==e[o].bodyCollisions&&!1!==e[s].bodyCollisions&&di(ci(e[o]),ci(e[s]))&&i.add(`${o}:${s}`)}}return Array.from(i).sort((e,t)=>{const[n,i]=e.split(":").map(Number),[r,o]=t.split(":").map(Number);return n===r?i-o:n-r})}resolveDynamicCollision(e,t,n){e.sleeping&&this.supportedThisStep.add(t.id),t.sleeping&&this.supportedThisStep.add(e.id);const i=e.sleeping?0:1/e.mass,r=t.sleeping?0:1/t.mass,o=i+r;if(ni>=o)return;const s=Math.max(0,n.penetration-ii)/o;e.x-=n.nx*s*i,e.y-=n.ny*s*i,t.x+=n.nx*s*r,t.y+=n.ny*s*r;const a=(t.vx-e.vx)*n.nx+(t.vy-e.vy)*n.ny;if(a>0)return;const c=Math.abs(a),l=-(1+Math.min(e.restitution??this.options.restitution,t.restitution??this.options.restitution))*a/o,d=l*n.nx,u=l*n.ny;e.vx-=d*i,e.vy-=u*i,t.vx+=d*r,t.vy+=u*r,this.applyFriction(e,t,n,l,i,r),c>this.options.contactWakeSpeed&&(this.wake(e),this.wake(t))}applyFriction(e,t,n,i,r,o){const s=-n.ny,a=n.nx,c=(t.vx-e.vx)*s+(t.vy-e.vy)*a,l=r+o;if(ni>=Math.abs(c)||ni>=l)return;const d=Math.max(0,Math.min(1,Math.max(e.friction??this.options.friction,t.friction??this.options.friction))),u=si(-c/l,-i*d,i*d),h=u*s,p=u*a;e.vx-=h*r,e.vy-=p*r,t.vx+=h*o,t.vy+=p*o}resolveColliders(e,t,n){for(const i of e)for(const e of t){if(!wi(e,i))continue;if(!di(ci(i),li(e)))continue;const t=fi(i,e);t&&(this.resolveStaticCollision(i,e,t),this.supportedThisStep.add(i.id),n&&this.lastEvents.push({type:"contact",bodyId:i.id,otherId:e.id,sensor:!1}))}}resolveStaticCollision(e,t,n){e.x+=n.nx*Math.max(0,n.penetration-ii),e.y+=n.ny*Math.max(0,n.penetration-ii);const i=e.vx*n.nx+e.vy*n.ny;if(0>i){const r=Math.min(e.restitution??this.options.restitution,t.restitution??this.options.restitution);e.vx-=(1+r)*i*n.nx,e.vy-=(1+r)*i*n.ny;const o=-n.ny,s=n.nx,a=e.vx*o+e.vy*s,c=Math.max(0,Math.min(1,Math.max(e.friction??this.options.friction,t.friction??this.options.friction)));e.vx-=a*o*c,e.vy-=a*s*c}}updateSensors(e){const t=new Set,n=this.sortedColliders().filter(e=>e.sensor);for(const i of e){const e=ci(i);for(const r of n){if(!wi(r,i))continue;if(!di(e,li(r)))continue;if(!fi(i,r))continue;const n=mi(r.id,i.id);t.add(n),this.activeSensors.has(n)||this.lastEvents.push({type:"sensor-enter",bodyId:i.id,sensorId:r.id})}}for(const e of Array.from(this.activeSensors).sort()){if(t.has(e))continue;const{sensorId:n,bodyId:i}=yi(e);this.lastEvents.push({type:"sensor-exit",bodyId:i,sensorId:n})}this.activeSensors=t}updateSleeping(e,t){const n=Math.hypot(this.options.gravity.x,this.options.gravity.y)>1;for(const i of e)Math.sqrt(i.vx*i.vx+i.vy*i.vy)>=this.options.sleepSpeed||Math.sqrt((i.x-i.prevX)*(i.x-i.prevX)+(i.y-i.prevY)*(i.y-i.prevY))>=this.options.sleepSpeed*t||n&&!this.supportedThisStep.has(i.id)?i.sleeping?this.wake(i):i.sleepTime=0:(i.sleepTime+=t,i.sleeping||this.options.sleepAfter>i.sleepTime||(i.sleeping=!0,i.vx=0,i.vy=0,this.lastEvents.push({type:"sleep",bodyId:i.id})))}wake(e){e.sleeping&&this.lastEvents.push({type:"wake",bodyId:e.id}),e.sleeping=!1,e.sleepTime=0}nextRandom(){return this.random()}},Mi=class{constructor(e={}){this.id="builtin",this.capabilities={...(new ki).capabilities,engine:"builtin"},this.world=new ki(e)}init(e={}){this.world.init(e)}spawn(e){this.world.spawn(e)}remove(e){this.world.remove(e)}setColliders(e){this.world.setColliders(e)}setConstraint(e){return this.world.setConstraint(e)}removeConstraint(e){this.world.removeConstraint(e)}applyImpulse(e,t,n){this.world.applyImpulse(e,t,n)}step(e){this.world.step(e)}settle(e,t){return this.world.settle(e,t)}readState(e){return this.world.readState(e)}events(){return this.world.events()}activeSensorPairs(){return this.world.activeSensorPairs()}allSleeping(){return this.world.allSleeping()}snapshot(){return this.world.snapshot()}restore(e){this.world.restore(e)}nextRandom(){return this.world.nextRandom()}dispose(){this.world.dispose()}};function Si(e={}){return new Mi(e)}function Ii(e,t={}){return e?"function"==typeof e?e(t):(e.init(t),e):Si(t)}var ji=["binId","targetBin","category","windowIndex","lane","group"];function Ai(e,t){if(!Number.isFinite(t))return;e.count+=1,e.total+=t,e.min=Math.min(e.min,t),e.max=Math.max(e.max,t);const n=t-e.mean;e.mean+=n/e.count,e.m2+=n*(t-e.mean)}function Ci(e){return{count:e.count,total:e.total,mean:e.count>0?e.mean:0,min:e.count>0?e.min:0,max:e.count>0?e.max:0,variance:e.count>1?e.m2/(e.count-1):0}}function Ri(e){return{count:e.count,total:e.total,mean:e.mean,m2:e.variance*Math.max(0,e.count-1),min:e.count>0?e.min:1/0,max:e.count>0?e.max:-1/0}}function Pi(e,t){if(null!=e[t])return e[t];const n=e.datum;return n&&"object"==typeof n?n[t]:void 0}function Di(e,t,n){return"function"==typeof e?e(t,n):"string"==typeof e?Pi(t,e):void 0}function $i(e){if(null==e)return;const t=e+"";return t.trim()?t:void 0}function Bi(e){const t=Ci(e.value);return{id:e.id,label:e.label,count:t.count,total:t.total,bodyIds:e.bodyIds.slice(),lastBodyId:e.lastBodyId,lastDatum:e.lastDatum,x:Ci(e.x),y:Ci(e.y),value:t}}var Ti=class{constructor(e=!1){this.bins=new Map,this.nextIndex=0,this.config=e}updateConfig(e){void 0!==e&&(this.config=e,!1===e&&this.clear())}isEnabled(){return!1!==this.config}add(e){if(!1===this.config)return null;const t=this.nextIndex;this.nextIndex+=1;const n=$i(Di(this.config.binAccessor,e,t))??function(e){for(const t of ji){const n=$i(Pi(e,t));if(n)return n}return"sediment"}(e),i=$i(Di(this.config.labelAccessor,e,t))??n,r=function(e,t,n){if("number"==typeof e)return e;const i="function"==typeof e?e(t,n):"string"==typeof e?Pi(t,e):1,r="number"==typeof i?i:Number(i);return Number.isFinite(r)?r:1}(this.config.valueAccessor,e,t),o=Math.max(0,Math.floor(this.config.retainBodyIds??12));let s=this.bins.get(n);return s||(s={id:n,label:i,bodyIds:[],x:{count:0,total:0,mean:0,m2:0,min:1/0,max:-1/0},y:{count:0,total:0,mean:0,m2:0,min:1/0,max:-1/0},value:{count:0,total:0,mean:0,m2:0,min:1/0,max:-1/0}},this.bins.set(n,s)),s.label=i,s.lastBodyId=e.id,s.lastDatum=e.datum,Ai(s.x,e.x),Ai(s.y,e.y),Ai(s.value,r),o>0&&(s.bodyIds.push(e.id),s.bodyIds.length>o&&(s.bodyIds=s.bodyIds.slice(s.bodyIds.length-o))),Bi(s)}clear(){this.bins.clear(),this.nextIndex=0}snapshot(){return Array.from(this.bins.values()).map(Bi)}restore(e=[]){this.bins.clear();for(const t of e)this.bins.set(t.id,{id:t.id,label:t.label,bodyIds:t.bodyIds.slice(),lastBodyId:t.lastBodyId,lastDatum:t.lastDatum,x:Ri(t.x),y:Ri(t.y),value:Ri(t.value)});this.nextIndex=e.reduce((e,t)=>e+t.count,0)}totals(){const e=this.snapshot();return{bins:e.length,count:e.reduce((e,t)=>e+t.count,0),total:e.reduce((e,t)=>e+t.total,0)}}};function Ni(e,t={}){const{baselineY:n=0,binWidth:i=24,gap:r=2,maxHeight:o=80,value:s="count",x:a}=t,c=Math.max(1,...e.map(e=>e[s]));return e.map((e,t)=>{const l=Math.max(0,e[s]/c*o),d=a?.(e,t)??t*(i+r);return{binId:e.id,label:e.label,index:t,count:e.count,total:e.total,x:d,y:n-l,width:i,height:l,meanX:e.x.mean,meanY:e.y.mean}})}function Ei(e){const t=Number(e);if(Number.isFinite(t)&&t>0)return Math.floor(t)}function Wi(e){const t=Math.max(0,Math.floor(e.liveBodies)),n=Math.max(0,Math.floor(e.queuedBodies??0)),i=t+n,r=Ei(e.bodyLimit),o=Ei(e.engineMaxBodiesHint),s=function(e,t,n){if(!1===n)return;const i=Ei(n?.warnAt);return null!=i?i:null!=e?Math.max(1,Math.floor(.8*e)):null!=t?Math.max(1,Math.floor(.8*t)):void 0}(r,o,e.options),a=null==r?0:Math.max(0,t-r),c=a>0?"overflow":null==s||s>i?"ok":"warning";return{action:"overflow"!==c?"continue":e.sedimentEnabled?"sediment":e.evictionEnabled?"evict":"retain",bodyLimit:r,engineMaxBodiesHint:o,liveBodies:t,overflow:a,projectedBodies:i,queuedBodies:n,state:c,warnAt:s}}var qi={bodyLimit:1/0,eviction:"oldest",fixedDt:1/120,maxDeltaSeconds:.1,maxSubsteps:8,settleStepLimit:1200,timeScale:1},Oi={chartId:"physics",chartType:"physics",sensors:{},onObservation:void 0,onSimulationStateChange:void 0};function Fi(e={},t=Oi){return{chartId:e.chartId??t.chartId,chartType:e.chartType??t.chartType,sensors:e.sensors??t.sensors,onObservation:e.onObservation??t.onObservation,onSimulationStateChange:e.onSimulationStateChange??t.onSimulationStateChange}}function zi(e){return{...e,shape:{...e.shape},datum:e.datum,springs:e.springs?.map(e=>({...e,target:{...e.target}}))}}function Li(e){if(e instanceof Date){const t=e.getTime();return Number.isFinite(t)?t:void 0}const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:void 0}function Yi(e,t){if(null!=e[t])return e[t];const n=e.datum;return n&&"object"==typeof n?n[t]:void 0}function Hi(e){return{...zi(e),sequence:e.sequence,spawnAt:e.spawnAt}}function Gi(e){return e.map(e=>({...e,shape:{...e.shape},bodyFilter:e.bodyFilter&&"function"!=typeof e.bodyFilter?{...e.bodyFilter,oneOf:e.bodyFilter.oneOf?.slice(),notOneOf:e.bodyFilter.notOneOf?.slice()}:e.bodyFilter}))}function Xi(e){return!1!==e&&{...e}}function _i(e,t){return e.spawnAt===t.spawnAt?e.sequence-t.sequence:e.spawnAt-t.spawnAt}function Vi(e){return{...e,gravity:{...e.gravity}}}function Ui(e,t,n,i){if("circle"===e.shape.type){const r=e.x-t,o=e.y-n,s=e.shape.radius+i,a=r*r+o*o;return a>s*s?null:a}const r=Math.max(Math.abs(t-e.x)-e.shape.width/2,0),o=Math.max(Math.abs(n-e.y)-e.shape.height/2,0),s=r*r+o*o;return s>i*i?null:s}function Ki(e){const t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}function Qi(e,t={}){const{idPrefix:n="plot",includeFloor:i=!0,includeCeiling:r=!1,includeLeftWall:o=!0,includeRightWall:s=!0,wallThickness:a=20,floorThickness:c=a}=t,l=[],d=e.x+e.width/2,u=e.y+e.height/2;return i&&l.push({id:n+"-floor",shape:{type:"aabb",x:d,y:e.y+e.height+c/2,width:e.width+2*a,height:c}}),r&&l.push({id:n+"-ceiling",shape:{type:"aabb",x:d,y:e.y-c/2,width:e.width+2*a,height:c}}),o&&l.push({id:n+"-left-wall",shape:{type:"aabb",x:e.x-a/2,y:u,width:a,height:e.height+2*c}}),s&&l.push({id:n+"-right-wall",shape:{type:"aabb",x:e.x+e.width+a/2,y:u,width:a,height:e.height+2*c}}),l}function Zi(e){const{idPrefix:t="bin",count:n,domainStart:i,domainStep:r,xScale:o,yTop:s,yBottom:a,wallThickness:c=4,includeBoundaryWalls:l=!0,includeInteriorWalls:d=!0,closedBefore:u,lidY:h=s,lidThickness:p=Math.max(2,c)}=e,f=[],m=s+(a-s)/2,y=Math.abs(a-s),g=l?n:n-1;if(d||l)for(let e=l?0:1;g>=e;e+=1){if(!d&&e>0&&n>e)continue;const s=o(i+e*r);f.push({id:`${t}-wall-${e}`,shape:{type:"aabb",x:s,y:m,width:c,height:y}})}if(null!=u)for(let e=0;n>e;e+=1){const n=i+e*r,s=n+r;if(s>=u)continue;const a=o(n),l=o(s);f.push({id:`${t}-lid-${e}`,shape:{type:"segment",x1:Math.min(a,l)+c/2,y1:h,x2:Math.max(a,l)-c/2,y2:h,thickness:p}})}return f}var Ji={data:"data",domain:"domain",layout:"layout","scene-geometry":"sceneGeometry","scene-style":"sceneStyle","data-paint":"dataPaint","interaction-paint":"interactionPaint",overlay:"overlay",accessibility:"accessibility",evidence:"evidence"};function er(e,t){const n={...e};for(const e of t)n[Ji[e]]++;return n}function tr(e,t,n){const i=new Set(t);return{changeSet:{...e,...e.keys?{keys:[...e.keys]}:{}},changed:i,revisions:er(n,i)}}var nr=class{constructor(){this.revisions={data:0,domain:0,layout:0,sceneGeometry:0,sceneStyle:0,dataPaint:0,interactionPaint:0,overlay:0,accessibility:0,evidence:0},this.latest=tr({kind:"initialize"},[],this.revisions),this.listeners=new Set}get last(){return this.latest}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}record(e,t){const n=tr(e,t,this.revisions);this.revisions=n.revisions,this.latest=n;for(const e of[...this.listeners])e();return n}},ir=require("d3-quadtree"),rr=class{constructor(){this.maxSearchRadius=0,this.revision=-1,this.tree=null}hitTest(e,t,n,i,r,o=0){const s=this.ensure(e,t);if(!s)return null;let a=null,c=1/0;const l=Math.max(0,o)+this.maxSearchRadius,d=i-l,u=i+l,h=r-l,p=r+l;return s.visit((e,t,s,l,f)=>{if(d>l||t>u||h>f||s>p)return!0;if(e.length)return!1;let m=e;for(;m;){const e=m.data;if(e){const t=Ui(e,i,r,Math.max(0,o));null!=t&&(c>t||t===c&&n.indexOf(e.id)>n.indexOf(a?.id??""))&&(a=e,c=t)}m=m.next}return!1}),a}ensure(e,t){if(this.tree&&this.revision===t)return this.tree;const n=e.readState();return 0===n.length?(this.tree=null,this.maxSearchRadius=0,this.revision=t,null):(this.maxSearchRadius=n.reduce((e,t)=>Math.max(e,function(e){return"circle"===e.shape.type?e.shape.radius:Math.hypot(e.shape.width,e.shape.height)/2}(t)),0),this.tree=(0,ir.quadtree)().x(e=>e.x).y(e=>e.y).addAll(n),this.revision=t,this.tree)}},or=["data","scene-geometry","data-paint","accessibility","evidence"],sr=["scene-geometry","data-paint","accessibility","evidence"],ar=["overlay","accessibility","evidence"],cr=(e,t)=>({retainedData:e,invalidations:t}),lr=["layout","scene-geometry","data-paint","overlay","accessibility","evidence"],dr=["scene-geometry","data-paint","accessibility","evidence"],ur=[],hr={engine:cr("rebuild",["scene-geometry","data-paint","accessibility","evidence"]),kernel:cr("preserve",dr),colliders:cr("preserve",dr),sediment:cr("preserve",dr),bodyBudget:cr("preserve",lr),bodyLimit:cr("preserve",lr),eviction:cr("preserve",lr),fixedDt:cr("preserve",ur),maxDeltaSeconds:cr("preserve",ur),maxSubsteps:cr("preserve",ur),settleStepLimit:cr("preserve",ur),timeScale:cr("preserve",ur),observation:cr("preserve",ur)},pr=cr("preserve",lr);function fr(e){let t="preserve";const n=new Set;for(const i of e){const e=hr[i]??pr;"rebuild"===e.retainedData&&(t="rebuild");for(const t of e.invalidations)n.add(t)}return{retainedData:t,invalidations:n}}var mr=["seed","fixedDt","cellSize","collisionIterations","velocityDamping","sleepSpeed","sleepAfter","restitution","friction","maxVelocity","contactWakeSpeed"];function yr(e,t){return e===t||!(!e||!t)&&e.gravity?.x===t.gravity?.x&&e.gravity?.y===t.gravity?.y&&mr.every(n=>e[n]===t[n])}function gr(e,t,n,i){return e||!t?"paused":n||!i?"running":"settled"}var xr=class{constructor(){this.seconds=0,this.speed=8,this.scratch=[]}setKernelOptions(e){this.speed=function(e){const t=e?.sleepSpeed;return"number"==typeof t&&Number.isFinite(t)&&t>0?t:8}(e)}reset(){this.seconds=0}isAtRest(){return this.seconds>=.6}refresh(e,t,n){if(n>0)return void(this.seconds=0);const i=e.readState(this.scratch),r=this.speed*this.speed;let o=!0;for(const e of i)if(!e.sleeping&&e.vx*e.vx+e.vy*e.vy>=r){o=!1;break}this.seconds=o?this.seconds+Math.max(0,t):0}},br=class{constructor(e={}){this.activeSensorPairs=new Set,this.accumulator=0,this.bodyBudgetObservationKey="ok",this.bodySpatialIndex=new rr,this.elapsedSeconds=0,this.liveBodyOrder=[],this.nextSequence=0,this.paused=!1,this.queue=[],this.revision=0,this.updateResults=new nr,this.simulationState="settled",this.visible=!0,this.quiescence=new xr;const{bodyBudget:t,colliders:n,engine:i,kernel:r,observation:o,sediment:s,...a}=e;this.config={...qi,...a},this.configInput={...e},this.bodyBudget=t??{},this.engineInput=i,this.observation=Fi(o),this.sediment=new Ti(s??!1),this.world=Ii(i,{fixedDt:this.config.fixedDt,...r}),this.quiescence.setKernelOptions(r),n&&this.world.setColliders(Gi(n))}updateConfig(e){const t=function(e,t){return Object.keys(e).filter(n=>"kernel"===n?!yr(e.kernel,t.kernel):e[n]!==t[n])}(e,this.configInput),{colliders:n,bodyBudget:i,engine:r,kernel:o,observation:s,sediment:a,...c}=e;if(this.config={...this.config,...c},void 0!==i&&(this.bodyBudget=i,!1===i&&(this.bodyBudgetObservationKey="ok")),r&&r!==this.engineInput){const e=this.world.snapshot();this.world.dispose(),this.engineInput=r,this.world=Ii(r,e.options),this.world.restore(e),this.revision+=1}if(o&&!yr(o,this.configInput.kernel)){const e=this.world.snapshot(),t={...e.options,...o,gravity:{...e.options.gravity,...o.gravity}};this.world.restore({...e,options:t}),this.quiescence.setKernelOptions(t),this.revision+=1}s&&(this.observation=Fi(s,this.observation)),this.sediment.updateConfig(a),n&&(this.world.setColliders(Gi(n)),this.revision+=1),this.configInput={...this.configInput,...e};const l=fr(t);this.updateResults.record({kind:"config",keys:t},l.invalidations)}updateConfigWithResult(e){return this.updateConfig(e),this.updateResults.last}setColliders(e){this.world.setColliders(Gi(e)),this.revision+=1,this.updateResults.record({kind:"config",keys:["colliders"]},fr(["colliders"]).invalidations)}enqueue(e,t){const n=Array.isArray(e)?e:[e],i=t?function(e,t={}){const n=Li(t.startAt)??0,i=t.pacing??"immediate";if("arrival"===i){const i=e.map((e,n)=>function(e,t,n){return"function"==typeof n?Li(n(e,t)):"string"==typeof n?Li(Yi(e,n)):Li(e.spawnAt)??Li(Yi(e,"arrivalTime"))??Li(Yi(e,"timestamp"))??Li(Yi(e,"time"))??Li(Yi(e,"eventTime"))}(e,n,t.timeAccessor)),r=i.filter(e=>null!=e),o=r.length>0?Math.min(...r):0,s=Li(t.timeScale)??1,a=s>0?s:1;return e.map((e,t)=>{const r=i[t],s=null==r?0:Math.max(0,r-o);return{...zi(e),spawnAt:n+s/a}})}if("object"==typeof i){const t=Li(i.ratePerSec);if(t&&t>0)return e.map((e,i)=>({...zi(e),spawnAt:n+i/t}))}return e.map(e=>({...zi(e),spawnAt:n}))}(n,{...t,startAt:t.startAt??this.elapsedSeconds}):n;for(const e of i)this.queue.push({...zi(e),sequence:this.nextSequence,spawnAt:e.spawnAt??this.elapsedSeconds}),this.nextSequence+=1;this.queue.sort(_i),i.length>0&&(this.revision+=1),this.updateResults.record({kind:"enqueue",count:i.length},i.length?or:[])}enqueueWithResult(e,t){return this.enqueue(e,t),this.updateResults.last}spawnNow(e){this.spawnOne(zi(e)),this.nextSequence+=1,this.observeBodyBudget(),this.evictOverflow(),this.revision+=1,this.updateResults.record({kind:"enqueue",count:1},or)}materializeDueSpawns(){const e=this.revision,t=[],n=[];return this.spawnDue(t,n),0===t.length||(this.observeBodyBudget(n),this.evictOverflow(n),this.syncSimulationState(n),this.revision+=1,this.updateResults.record({kind:"enqueue",count:t.length},this.revision!==e?or:[])),t}clear(){const e=this.world.snapshot().options;this.world.init({...e,fixedDt:this.config.fixedDt}),this.activeSensorPairs.clear(),this.liveBodyOrder=[],this.queue=[],this.accumulator=0,this.elapsedSeconds=0,this.nextSequence=0,this.quiescence.reset(),this.sediment.clear(),this.bodyBudgetObservationKey="ok",this.revision+=1,this.syncSimulationState(),this.updateResults.record({kind:"clear"},or)}tick(e){const t=this.revision,n=[],i=[],r=[],o=[],s=[];if(this.paused||!this.visible){const e=this.result(0,n,i,r,o,s,!1);return this.updateResults.record({kind:"tick",count:0},[]),e}const a=Math.max(0,Math.min(e,this.config.maxDeltaSeconds))*this.config.timeScale;this.elapsedSeconds+=a,this.spawnDue(n,s);const c=this.observeBodyBudget(s),l=this.evictOverflow(s);i.push(...l.evicted),r.push(...l.sedimented),this.syncSimulationState(s),this.accumulator+=a;let d=0;for(;this.accumulator>=this.config.fixedDt&&this.config.maxSubsteps>d;){this.world.step(this.config.fixedDt);const e=this.world.events();o.push(...e),this.observeKernelEvents(e,s),this.observeSensorTransitions(s),this.accumulator-=this.config.fixedDt,d+=1}d===this.config.maxSubsteps&&(this.accumulator=Math.min(this.accumulator,this.config.fixedDt)),this.quiescence.refresh(this.world,a,n.length),(d>0||n.length>0||i.length>0||r.length>0||o.length>0)&&(this.revision+=1);const u=this.result(d,n,i,r,o,s,void 0,c);return this.updateResults.record({kind:"tick",count:d},this.revision!==t?n.length||i.length||r.length?or:sr:[]),u}settle(e=this.config.settleStepLimit){const t=this.revision;this.spawnDue([],[]);const n=this.world.settle(e,this.config.fixedDt);return n>0&&(this.revision+=1),this.syncSimulationState(),this.updateResults.record({kind:"settle",count:n},this.revision!==t?sr:[]),n}settleWithObservations(e=this.config.settleStepLimit){const t=this.revision,n=[],i=[],r=[],o=[],s=[];if(this.paused||!this.visible){const e=this.result(0,n,i,r,o,s,!1);return this.updateResults.record({kind:"settle",count:0},[]),e}this.spawnDue(n,s);const a=this.observeBodyBudget(s),c=this.evictOverflow(s);i.push(...c.evicted),r.push(...c.sedimented),this.syncSimulationState(s);let l=0;for(n.length>0&&this.quiescence.reset();e>l&&!this.atRest();){this.world.step(this.config.fixedDt);const e=this.world.events();o.push(...e),this.observeKernelEvents(e,s),this.observeSensorTransitions(s),l+=1,this.quiescence.refresh(this.world,this.config.fixedDt,0)}(l>0||n.length>0||i.length>0||r.length>0||o.length>0)&&(this.revision+=1);const d=this.result(l,n,i,r,o,s,void 0,a);return this.updateResults.record({kind:"settle",count:l},this.revision!==t?n.length||i.length||r.length?or:sr:[]),d}readBodies(e=[]){return this.world.readState(e)}readSediment(){return this.sediment.snapshot()}bodyBudgetStatus(){return this.evaluateBodyBudget()}sedimentTotals(){return this.sediment.totals()}sedimentHeightfield(e={}){return Ni(this.readSediment(),e)}hitTest(e,t,n=0){return this.bodySpatialIndex.hitTest(this.world,this.revision,this.liveBodyOrder,e,t,n)}events(){return this.world.events()}allSleeping(){return this.world.allSleeping()}atRest(){return this.world.allSleeping()||this.quiescence.isAtRest()}hasPendingWork(){return this.queue.length>0||!this.atRest()}queueSize(){return this.queue.length}liveBodyCount(){return this.liveBodyOrder.length}elapsed(){return this.elapsedSeconds}recordObservation(e){const{timestamp:t,chartType:n,chartId:i,...r}=e,o={...r,timestamp:t??this.elapsedSeconds,chartType:n??this.observation.chartType,chartId:i??this.observation.chartId};return this.emitObservation(o),this.updateResults.record({kind:"update",count:1},["evidence"]),o}getLastUpdateResult(){return this.updateResults.last}getUpdateSnapshot(){return this.updateResults.last}subscribeUpdateResult(e){return this.updateResults.subscribe(e)}version(){return this.revision}setPaused(e){const t=this.paused!==e;this.paused=e,this.syncSimulationState(),this.updateResults.record({kind:"pause"},t?ar:[])}setVisible(e){const t=this.visible!==e;this.visible=e,this.syncSimulationState(),this.updateResults.record({kind:"visibility"},t?ar:[])}remove(e){const t=new Set(e),n=new Set(this.liveBodyOrder),i=new Set(this.queue.map(e=>e.id));this.queue=this.queue.filter(e=>!t.has(e.id)),this.liveBodyOrder=this.liveBodyOrder.filter(e=>!t.has(e)),this.world.remove(e),this.removeActiveSensorPairsForBodies(t);const r=e.filter(e=>n.has(e)||i.has(e));return r.length>0&&(this.revision+=1,this.syncSimulationState()),this.updateResults.record({kind:"remove",keys:r,count:r.length},r.length?or:[]),r}setConstraint(e){const t=this.world.setConstraint(e);return this.revision+=1,this.updateResults.record({kind:"constraint",keys:[t]},sr),t}removeConstraint(e){this.world.removeConstraint(e),this.revision+=1,this.updateResults.record({kind:"constraint",keys:[e]},sr)}applyImpulse(e,t,n){this.world.applyImpulse(e,t,n),this.revision+=1,this.updateResults.record({kind:"impulse",keys:[e]},sr)}nextRandom(){return this.world.nextRandom()}controls(){return e=this,{applyImpulse:(t,n,i)=>e.applyImpulse(t,n,i),clear:()=>e.clear(),hitTest:(t,n,i)=>e.hitTest(t,n,i),pause:()=>e.setPaused(!0),push:(t,n)=>e.enqueue(t,n),pushMany:(t,n)=>e.enqueue(t,n),bodyBudgetStatus:()=>e.bodyBudgetStatus(),readBodies:t=>e.readBodies(t),readSediment:()=>e.readSediment(),recordObservation:t=>e.recordObservation(t),remove:t=>e.remove(t),restore:t=>e.restore(t),resume:()=>e.setPaused(!1),settle:t=>e.settle(t),settleWithObservations:t=>e.settleWithObservations(t),snapshot:()=>e.snapshot(),sedimentHeightfield:t=>e.sedimentHeightfield(t),sedimentTotals:()=>e.sedimentTotals(),step:t=>e.tick(t)};var e}snapshot(){const e=this.world.snapshot();return{accumulator:this.accumulator,activeSensorPairs:Array.from(this.activeSensorPairs).sort(),bodyBudget:Xi(this.bodyBudget),config:{...this.config,kernel:Vi(e.options)},elapsedSeconds:this.elapsedSeconds,paused:this.paused,queue:this.queue.map(Hi),revision:this.revision,sediment:this.readSediment(),simulationState:this.simulationState,liveBodyOrder:this.liveBodyOrder.slice(),visible:this.visible,world:e}}restore(e){this.config={bodyLimit:e.config.bodyLimit,eviction:e.config.eviction,fixedDt:e.config.fixedDt,maxDeltaSeconds:e.config.maxDeltaSeconds,maxSubsteps:e.config.maxSubsteps,settleStepLimit:e.config.settleStepLimit,timeScale:e.config.timeScale},this.configInput={...e.config,bodyBudget:Xi(e.bodyBudget??{}),kernel:Vi(e.world.options)},this.bodyBudget=Xi(e.bodyBudget??{}),this.bodyBudgetObservationKey="ok",this.quiescence.setKernelOptions(e.world.options),this.quiescence.reset(),this.activeSensorPairs=new Set(e.activeSensorPairs),this.accumulator=e.accumulator,this.elapsedSeconds=e.elapsedSeconds,this.paused=e.paused,this.queue=e.queue.map(Hi).sort(_i),this.revision=e.revision,this.sediment.restore(e.sediment??[]),this.simulationState=e.simulationState??gr(e.paused,e.visible,e.queue.length>0,e.world.bodies.every(e=>e.sleeping)),this.liveBodyOrder=e.liveBodyOrder.slice(),this.visible=e.visible,this.nextSequence=this.queue.reduce((e,t)=>Math.max(e,t.sequence),-1)+1,this.world.restore(e.world),this.updateResults.record({kind:"restore"},or)}spawnDue(e,t){for(;this.queue.length>0&&this.elapsedSeconds>=this.queue[0].spawnAt;){const n=this.queue.shift();if(!n)return;this.spawnOne(n,t),e.push(n.id)}}spawnOne(e,t){this.liveBodyOrder=this.liveBodyOrder.filter(t=>t!==e.id),this.removeActiveSensorPairsForBodies(new Set([e.id])),this.world.spawn(e),this.liveBodyOrder.push(e.id);for(const t of e.springs??[])this.world.setConstraint({...t,bodyId:e.id});const n=this.world.readState().find(t=>t.id===e.id);this.emitObservation({type:"physics-spawn",timestamp:this.elapsedSeconds,chartType:this.observation.chartType,chartId:this.observation.chartId,bodyId:e.id,datum:n?.datum??e.datum,x:n?.x??e.x,y:n?.y??e.y},t)}result(e,t,n,i,r,o,s,a=this.evaluateBodyBudget()){this.syncSimulationState(o);const c=this.world.allSleeping();return{budget:a,elapsedSeconds:this.elapsedSeconds,evicted:n,events:r,observations:o,queueSize:this.queue.length,revision:this.revision,shouldContinue:s??(this.queue.length>0||!this.atRest()),sleeping:c,sedimented:i,spawned:t,steps:e}}observeKernelEvents(e,t){!function(e,t,n){if(0===t.length)return;const i=new Map(e.readState().map(e=>[e.id,e]));for(const e of t){if("sleep"!==e.type)continue;const t=i.get(e.bodyId);n.emit({type:"physics-settle",timestamp:n.elapsedSeconds,chartType:n.observation.chartType,chartId:n.observation.chartId,bodyId:e.bodyId,datum:t?.datum,x:t?.x,y:t?.y})}}(this.world,e,this.observationContext(t))}observeSensorTransitions(e){this.activeSensorPairs=function(e,t,n){const i=new Set(e.activeSensorPairs().map(e=>`${e.sensorId}\0${e.bodyId}`));if(0===i.size&&0===t.size)return i;const r=new Map(e.readState().map(e=>[e.id,e])),o=(e,t)=>{const{sensorId:i,bodyId:o}=Ki(t),s=n.observation.sensors[i],a=r.get(o);n.emit({type:"enter"===e?s?.enterType??"physics-bin-enter":s?.exitType??"physics-bin-exit",timestamp:n.elapsedSeconds,chartType:n.observation.chartType,chartId:n.observation.chartId,bodyId:o,datum:a?.datum,x:a?.x,y:a?.y,sensorId:i,binId:s?.binId??i})};for(const e of Array.from(i).sort())t.has(e)||o("enter",e);for(const e of Array.from(t).sort())i.has(e)||o("exit",e);return i}(this.world,this.activeSensorPairs,this.observationContext(e))}removeActiveSensorPairsForBodies(e){!function(e,t){for(const n of e)t.has(Ki(n).bodyId)&&e.delete(n)}(this.activeSensorPairs,e)}observationContext(e){return{elapsedSeconds:this.elapsedSeconds,observation:this.observation,emit:t=>this.emitObservation(t,e)}}emitObservation(e,t){t?.push(e),this.observation.onObservation?.(e)}evaluateBodyBudget(){return Wi({bodyLimit:this.config.bodyLimit,engineMaxBodiesHint:this.world.capabilities.maxBodiesHint,evictionEnabled:!1!==this.config.eviction,liveBodies:this.liveBodyOrder.length,queuedBodies:this.queue.length,sedimentEnabled:this.sediment.isEnabled(),options:this.bodyBudget})}observeBodyBudget(e){const t=this.evaluateBodyBudget();if("ok"===t.state||!1===this.bodyBudget)return this.bodyBudgetObservationKey="ok",t;const n=`${t.state}:${t.action}`;return n===this.bodyBudgetObservationKey||(this.bodyBudgetObservationKey=n,this.emitObservation({type:"overflow"===t.state?"physics-budget-overflow":"physics-budget-warning",timestamp:this.elapsedSeconds,chartType:this.observation.chartType,chartId:this.observation.chartId,budgetAction:t.action,bodyLimit:t.bodyLimit,engineMaxBodiesHint:t.engineMaxBodiesHint,liveBodies:t.liveBodies,overflow:t.overflow,projectedBodies:t.projectedBodies,queuedBodies:t.queuedBodies,warnAt:t.warnAt},e)),t}syncSimulationState(e){const t=gr(this.paused,this.visible,this.queue.length>0,this.atRest());if(t===this.simulationState)return;const n=this.simulationState;this.simulationState=t,function(e,t,n){n.observation.onSimulationStateChange?.(t,e),"running"!==t&&"settled"!==t||n.emit({type:"running"===t?"sim-active":"sim-idle",timestamp:n.elapsedSeconds,chartType:n.observation.chartType,chartId:n.observation.chartId,simulationState:t,previousSimulationState:e})}(n,t,this.observationContext(e))}evictOverflow(e){const{evicted:t,sedimented:n,liveBodyOrder:i}=function(e,t,n,i,r,o){const s={evicted:[],sedimented:[],liveBodyOrder:r};if(!1===n)return s;const a=Math.max(0,Math.floor(i));if(!Number.isFinite(a))return s;const c=r.length-a;if(0>=c)return s;const l=function(e,t,n){if("sleeping-first"!==t)return n.slice();const i=new Map(e.readState().map(e=>[e.id,e.sleeping])),r=[],o=[];for(const e of n)i.get(e)?r.push(e):o.push(e);return[...r,...o]}(e,n,r),d=l.slice(0,c);if(0===d.length)return s;const u=function(e,t,n,i){const r=new Map(e.readState().map(e=>[e.id,e])),o=[];for(const e of n){const n=r.get(e);if(!n)continue;const s=t.add(n);s&&(o.push(e),i.emit({type:"physics-sediment",timestamp:i.elapsedSeconds,chartType:i.observation.chartType,chartId:i.observation.chartId,bodyId:e,datum:n.datum,x:n.x,y:n.y,binId:s.id,count:s.count,total:s.total}))}return o}(e,t,d,o);e.remove(d);const h=new Set(d);return{evicted:d,sedimented:u,liveBodyOrder:r.filter(e=>!h.has(e))}}(this.world,this.sediment,this.config.eviction,this.config.bodyLimit,this.liveBodyOrder,this.observationContext(e));return t.length>0&&(this.liveBodyOrder=i,this.removeActiveSensorPairsForBodies(new Set(t))),{evicted:t,sedimented:n}}};function vr(e,t,n){const i=new br(e);return t?.length&&(i.enqueue(t,n),i.materializeDueSpawns()),i}function wr(){return"undefined"!=typeof performance?performance.now():Date.now()}var kr=c(require("react-dom/server"));function Mr(e=[]){return e.map(e=>({id:e.id,label:e.label,count:e.count,...null!=e.secondary?{secondary:e.secondary}:{},...e.secondaryLabel?{secondaryLabel:e.secondaryLabel}:{},...null!=e.observed?{observed:e.observed}:{}}))}var Sr={fill:"#4e79a7",stroke:"#172033",strokeWidth:1,opacity:.85};function Ir(e){const t=e.datum;if(t&&"object"==typeof t){const e=t.label??t.name??t.id;if(null!=e&&""!==e)return e+""}return e.id}function jr(e,t){const n="function"==typeof t?t(e):t;return{...Sr,...n??{}}}function Ar(e,t={}){const n=e.settle(t.maxSteps),i=e.readBodies(),r=e.snapshot(),o=function(e,t={}){return e.map(e=>function(e,t={}){const n=function(e){return e.datum&&"object"==typeof e.datum?e.datum:null}(e),i={label:t.getBodyLabel?.(e)??Ir(e)},r={style:jr(e,t.bodyStyle),datum:n,accessibleDatum:n,accessibility:i,_transitionKey:e.id};return"aabb"===e.shape.type?{type:"rect",x:e.x-e.shape.width/2,y:e.y-e.shape.height/2,w:e.shape.width,h:e.shape.height,...r}:{type:"point",x:e.x,y:e.y,r:e.shape.radius,pointId:e.id,...r}}(e,t))}(i,t),s=function(e,t={}){const n=t.bodies??function(e){return e.world.bodies.map(e=>({id:e.id,x:e.x,y:e.y,prevX:e.prevX,prevY:e.prevY,vx:e.vx,vy:e.vy,angle:e.angle,mass:e.mass,shape:{...e.shape},sleeping:e.sleeping,datum:e.datum}))}(e),i=n.filter(e=>e.sleeping).length;return{bodyCount:n.length,sleepingCount:i,settled:"settled"===e.simulationState&&0===e.queue.length&&i===n.length,stepsRun:Math.max(0,Math.floor(t.stepsRun??0)),seed:e.world.options.seed,binCounts:Mr(t.projectionRows)}}(r,{bodies:i,projectionRows:t.projectionRows,stepsRun:n});return{snapshot:r,bodies:i,sceneNodes:o,evidence:s,stepsRun:n}}var Cr=require("react/jsx-runtime");function Rr(e,t){if("function"==typeof t){const n=t(e);return Number.isFinite(n)&&n>0?Number(n):1}const n=e.datum;if(t&&n&&"object"==typeof n){const e=Number(n[t]);if(Number.isFinite(e)&&e>0)return e}const i=Number(n?.work??n?.reviewWork??n?.value);return Number.isFinite(i)&&i>0?i:1}function Pr(e,t){if("function"==typeof t){const n=t(e);if(null!=n&&(n+"").length>0)return n+""}else if(t){const n=$r(e.datum,t),i=$r(e,t),r=n??i;if(null!=r&&(r+"").length>0)return r+""}return e.id}function Dr(e,t){if(0===e.length)return 0;if(1===e.length)return e[0];const n=Math.max(0,Math.min(1,t))*(e.length-1),i=Math.floor(n);return e[i]+(e[Math.ceil(n)]-e[i])*(n-i)}function $r(e,t){if(!t)return;let n=e;for(const e of t.split(".")){if(null==n||"object"!=typeof n)return;n=n[e]}return n}function Br(e,t){if(!t)return!0;if("function"==typeof t)return t(e);const n=$r(e,t.property);return!("equals"in t&&!Object.is(n,t.equals)||"notEquals"in t&&Object.is(n,t.notEquals)||t.oneOf&&!t.oneOf.some(e=>Object.is(n,e))||t.notOneOf&&t.notOneOf.some(e=>Object.is(n,e)))}function Tr(e){const t=e.regionId,n=Math.max(0,e.unitsPerSecond),i=e.queueLayout??"lane",r=e.queueSlotSpacing??14,o=e.queueStiffness??.35,s=Number.isFinite(e.maxQueue)?Math.max(0,Math.floor(Number(e.maxQueue))):1/0,a=Math.max(.25,e.metricWindowSeconds??30),c=Math.max(1/60,e.snapshotIntervalSeconds??.25),l=e.releaseImpulse??{x:90,y:0},d=new Map,u=new Map,h=new Map,p=new Map,f=new Map,m=new Map,y=new Map,g=[];let x=0,b=new Map,v=new Map,w=0,k=0,M=0,S=null,I=0,j=0,A=0,C=0,R=0,P=0,D=0,$=0,B=0,T=0,N=0,E=0,W=-1,q=!1;function O(e,n){const i=n(e);return!!i&&i.activeRegionIds.includes(t)}function F(){E+=1}function z(e){return{bodyId:e.bodyId,jobId:e.jobId,visitId:e.visitId,visit:e.visit,regionId:t,work:e.total,queuedAt:e.queuedAt}}function L(n,i,r,o){const s={bodyId:n.id,jobId:i.jobId,visitId:i.visitId,visit:i.visit,remaining:i.work,total:i.work,queuedAt:i.queuedAt,sequence:o};return d.set(i.jobId,s),y.delete(n.id),m.set(n.id,i.jobId),j+=1,A+=i.work,F(),function(n,i,r){const o=z(i);e.onQueued?.(n,o),r.controls.recordObservation({type:"physics-capacity-queued",bodyId:n.id,datum:n.datum,x:n.x,y:n.y,regionId:t,work:i.total,jobId:i.jobId,visitId:i.visitId,visit:i.visit,queuedAt:i.queuedAt,queueDepth:d.size})}(n,s,r),s}function Y(e){if(d.size>=s||0===u.size)return;const t=Array.from(u.values()).sort((e,t)=>e.sequence-t.sequence);for(const n of t){if(d.size>=s)break;const t=f.get(n.jobId);t&&h.has(n.jobId)?(u.delete(n.jobId),y.delete(n.bodyId),L(t,n,e,n.sequence)):u.delete(n.jobId)}}function H(){let e=0;for(const t of d.values())e+=t.remaining;return e}function G(){B=Math.max(B,d.size),T=Math.max(T,H())}function X(){const e=M-a,t=Math.max(0,Math.min(a,M-(S??M)));let i=0,r=0,o=0,s=0,c=0;for(const t of g){if(e>t.end)continue;i+=t.arrivals,r+=t.arrivalWork,o+=t.completions,s+=t.completedWork;const n=t.end-t.start;c+=n>0&&e>t.start?t.processedWork*Math.min(1,Math.max(0,t.end-e)/n):t.processedWork}const l=t>0?r/t:0;return{seconds:t,arrivals:i,arrivalWork:r,completions:o,completedWork:s,processedWork:c,arrivalsPerSecond:t>0?i/t:0,throughputPerSecond:t>0?o/t:0,utilization:t>0&&n>0?Math.max(0,Math.min(1,c/(n*t))):0,pressure:n>0?l/n:0}}return{id:e.id??"capacity-queue:"+t,continuous:!1!==e.continuous,tick:i=>{const r=i.controls.readBodies(),o=new Map,j=new Map;for(const t of r){if(o.set(t.id,t),!O(t.id,i.getRegionState))continue;if(!Br(t,e.bodyFilter))continue;const n=Pr(t,e.jobKey),r=j.get(n)??[];r.push(t),j.set(n,r)}const A=Number.isFinite(i.dt)?Math.max(0,i.dt):0;if(!q){const e=Number.isFinite(i.elapsed)?Math.max(0,i.elapsed):A;M=Math.max(0,e-A),q=!0}const B=M,T=B+A;M=T,S=null==S?B:Math.min(S,B);const E={start:B,end:T,arrivals:0,arrivalWork:0,completions:0,completedWork:0,processedWork:0},H=new Map;for(const[e,t]of j){const n=h.get(e)?.bodyId,i=t.find(e=>e.id===n)??t[0];H.set(e,i),f.set(e,i)}for(const[n,r]of h){if(H.has(n))continue;const s=d.get(n),a=o.get(r.bodyId)??f.get(n);if(s){d.delete(n),m.delete(s.bodyId),D+=1,$+=s.remaining,F();const o={...z(s),abandonedAt:M,remainingWork:s.remaining,queueSeconds:Math.max(0,M-s.queuedAt)};a&&e.onAbandoned?.(a,o),i.controls.recordObservation({type:"physics-capacity-abandoned",bodyId:r.bodyId,datum:a?.datum,x:a?.x,y:a?.y,regionId:t,work:s.total,remainingWork:s.remaining,jobId:n,visitId:s.visitId,visit:s.visit,queuedAt:s.queuedAt,abandonedAt:M,queueSeconds:o.queueSeconds,queueDepth:d.size})}u.delete(n),y.delete(r.bodyId),h.delete(n),f.delete(n)}for(const[n,r]of H){if(h.has(n))continue;const o=(p.get(n)??0)+1;p.set(n,o);const a=Rr(r,e.unitAccessor),c={bodyId:r.id,jobId:n,visitId:`${t}:${n}:${o}`,visit:o,regionId:t,work:a,queuedAt:M};h.set(n,c),I+=1,E.arrivals+=1,E.arrivalWork+=a;const l=x++;if(s>d.size)L(r,c,i,l);else{const s={...c,blockedAt:M,sequence:l};u.set(n,s),y.set(r.id,n),P+=1,F(),e.onBlocked?.(r,s),i.controls.recordObservation({type:"physics-capacity-blocked",bodyId:r.id,datum:r.datum,x:r.x,y:r.y,regionId:t,work:a,jobId:n,visitId:c.visitId,visit:o,queuedAt:M,blockedAt:M,queueDepth:d.size,blockedDepth:u.size})}}Y(i),G();const X=Array.from(d.values()).sort((e,t)=>e.sequence-t.sequence);let _=n*A;for(const n of X){if(0>=_)break;const r=Math.min(n.remaining,_);if(n.remaining-=r,_-=r,C+=r,E.processedWork+=r,n.remaining>1e-6)continue;d.delete(n.jobId),m.delete(n.bodyId),k+=1,R+=n.total,E.completions+=1,E.completedWork+=n.total;const s=Math.max(0,M-n.queuedAt);N+=s,F();const a=o.get(n.bodyId);if(!a)continue;i.controls.applyImpulse(n.bodyId,l.x??0,l.y??0);const c={...z(n),completedAt:M,queueSeconds:s};e.onProcessed?.(a,c),i.controls.recordObservation({type:"physics-capacity-processed",bodyId:n.bodyId,datum:a.datum,x:a.x,y:a.y,regionId:t,work:n.total,jobId:n.jobId,visitId:n.visitId,visit:n.visit,queuedAt:n.queuedAt,completedAt:M,queueSeconds:s,queueDepth:d.size})}Y(i),G(),function(){const e=Array.from(d.values()).sort((e,t)=>e.sequence-t.sequence);b=new Map(e.map((e,t)=>[e.bodyId,t]));const t=Array.from(u.values()).sort((e,t)=>e.sequence-t.sequence);v=new Map(t.map((e,t)=>[e.bodyId,t])),w=e.length}(),function(e){(e.end>e.start||e.arrivals>0||e.completions>0||e.processedWork>0)&&g.push(e);const t=M-a;for(;g.length>0&&t>g[0].end;)g.shift()}(E);const V=Math.floor(M/c);V!==W&&(W=V,F())},getSnapshot:()=>{const e=H(),i=function(){let e=0;for(const t of u.values())e+=t.work;return e}(),r=d.size,o=Array.from(d.values()).map(e=>Math.max(0,M-e.queuedAt)).sort((e,t)=>e-t),s=o.reduce((e,t)=>e+t,0);return{regionId:t,queueDepth:r,processedCount:k,unitsPerSecond:n,remainingWork:e,meanRemainingWork:r>0?e/r:0,waitingWork:e+i,blockedDepth:u.size,blockedWork:i,arrivalCount:I,admittedCount:j,admittedWork:A,processedWork:C,completedWork:R,blockedCount:P,abandonedCount:D,abandonedWork:$,peakQueueDepth:B,peakRemainingWork:T,queueAge:{count:o.length,meanSeconds:o.length>0?s/o.length:0,p50Seconds:Dr(o,.5),p95Seconds:Dr(o,.95),oldestSeconds:o.at(-1)??0},meanCompletedQueueSeconds:k>0?N/k:0,window:X(),simulatedAt:M,metricRevision:E}},bodyForce:e=>{if("none"===i)return null;const n=m.get(e.body.id),s=y.get(e.body.id),a=n?d.get(n):void 0,c=s?u.get(s):void 0;if(!a&&!c)return null;const l=a?b.get(e.body.id):v.get(e.body.id);if(null==l)return null;let h;const p=e.regions;if(p)for(let e=0;p.length>e;e+=1)if(p[e].id===t){const t=p[e].shape;t&&"aabb"===t.type&&(h=t);break}return h?{x:((c?h.x-.44*h.width:h.x-.22*h.width-l*(.15*r))-e.body.x)*o,y:(h.y-(l-((c?u.size:w)-1)/2)*r/Math.max(1,Math.sqrt(c?u.size:w))-e.body.y)*o*.85}:{x:8*-Math.sign(e.body.vx||1),y:0}}}}function Nr(e,t){if(!t)return;let n=e;for(const e of t.split(".")){if(null==n||"object"!=typeof n)return;n=n[e]}return n}function Er(e,t){if(!t)return!0;if("function"==typeof t)return t(e);const n=Nr(e,t.property);return!("equals"in t&&!Object.is(n,t.equals)||"notEquals"in t&&Object.is(n,t.notEquals)||t.oneOf&&!t.oneOf.some(e=>Object.is(n,e))||t.notOneOf&&t.notOneOf.some(e=>Object.is(n,e)))}function Wr(e){const t=e.resources.map(e=>({...e,bodyId:e.bodyId??e.id})),n=new Map(t.map(e=>[e.bodyId,e])),i=new Map,r=new Map,o=e.assignmentForce??.45,s=e.returnForce??.35,a=e.caseAttraction??.08,c=e.assignmentOffset??{x:0,y:0};let l=new Map,d=0,u=0;return{id:e.id??"service-resource-pool",continuous:!0,assign:e=>{const n=i.get(e);if(n)return n;const o=t.find(e=>!r.has(e.id));if(!o)return null;const s={resourceId:o.id,resourceBodyId:o.bodyId,caseBodyId:e,assignedAt:d};return i.set(e,s),r.set(o.id,s),u+=1,s},release:e=>{const t=i.get(e);return!!t&&(i.delete(e),r.delete(t.resourceId),u+=1,!0)},getAssignment:e=>i.get(e),tick:e=>{d=Math.max(d,e.elapsed),l=new Map(e.controls.readBodies().map(e=>[e.id,e]));for(const[e,t]of i)l.has(e)&&l.has(t.resourceBodyId)||(i.delete(e),r.delete(t.resourceId),u+=1)},getSnapshot:()=>({total:t.length,available:t.length-r.size,assigned:r.size,assignments:Array.from(i.values()),simulatedAt:d,metricRevision:u}),bodyForce:e=>{const t=n.get(e.body.id);if(t){const n=r.get(t.id),i=n?l.get(n.caseBodyId):void 0,a=n?o:s;return{x:((i?i.x+(c.x??0):t.home.x)-e.body.x)*a,y:((i?i.y+(c.y??0):t.home.y)-e.body.y)*a}}const d=i.get(e.body.id);if(!d||0>=a)return null;const u=l.get(d.resourceBodyId);return u?{x:(u.x-e.body.x)*a,y:(u.y-e.body.y)*a}:null}}}function qr(e,t){const n="function"==typeof t.deadlineAccessor?t.deadlineAccessor(e):Nr(e.datum,t.deadlineAccessor)??Nr(e,t.deadlineAccessor);return Number.isFinite(Number(n))?Math.max(0,Number(n)):0}function Or(e){const t=new Map;let n=0,i=0;function r(n){t.set(n.bodyId,n),i+=1,e.onStateChange?.({...n})}function o(e){const i=t.get(e);return!(!i||null!=i.completedAt||(r({...i,completedAt:n,state:"unhappy"===i.state?"resolved-unhappy":"resolved"}),0))}return{id:e.id??"service-level",continuous:!0,protect:e=>{const i=t.get(e);return!(!i||null!=i.completedAt||"unhappy"===i.state||(r({...i,state:"protected",protectedAt:n}),0))},complete:o,getCase:e=>t.get(e),tick:i=>{n=Math.max(n,i.elapsed);for(const s of i.controls.readBodies()){if(!Er(s,e.bodyFilter))continue;if(!t.has(s.id)){const t=qr(s,e);r({bodyId:s.id,openedAt:n,deadlineAt:n+t,state:"waiting"})}const a=t.get(s.id);a&&null==a.completedAt&&(e.completionRegionId&&i.getRegionState(s.id)?.activeRegionIds.includes(e.completionRegionId)?o(s.id):"waiting"!==a.state||a.deadlineAt>n||r({...a,state:"unhappy"}))}},getSnapshot:()=>{const e=Array.from(t.values()),r=t=>e.filter(e=>e.state===t).length;return{total:e.length,waiting:r("waiting"),protected:r("protected"),unhappy:r("unhappy"),resolved:r("resolved"),resolvedUnhappy:r("resolved-unhappy"),simulatedAt:n,metricRevision:i}}}}function Fr(e){const t=new Set;let n=0,i=0,r=0,o=!1;return{id:e.id??"dependency-gate:"+e.regionId,continuous:!0,tick:s=>{n=Math.max(n,s.elapsed);const a=o;var c;c=n,o=e.isOpen?e.isOpen(c):null!=e.opensAt&&c>=e.opensAt;const l=s.controls.readBodies(),d=new Map(l.map(e=>[e.id,e]));for(const n of l){const i=s.getRegionState(n.id)?.activeRegionIds.includes(e.regionId);i&&Er(n,e.bodyFilter)&&(o||t.has(n.id)||(t.add(n.id),r+=1,e.onHeld?.(n)))}if(o&&!a){for(const n of t){const t=d.get(n);t&&(s.controls.applyImpulse(n,e.releaseImpulse?.x??86,e.releaseImpulse?.y??0),i+=1,e.onReleased?.(t))}t.clear(),r+=1}for(const e of t)d.has(e)||(t.delete(e),r+=1)},getSnapshot:()=>({regionId:e.regionId,isOpen:o,blocked:t.size,released:i,simulatedAt:n,metricRevision:r}),bodyForce:n=>{if(o||!t.has(n.body.id))return null;const i=n.regions?.find(t=>t.id===e.regionId),r=i?.shape;if(!r||"aabb"!==r.type)return{x:.8*-n.body.vx,y:.8*-n.body.vy};const s=e.holdForce??.4;return{x:(r.x-n.body.x)*s-.45*n.body.vx,y:(r.y-n.body.y)*s-.45*n.body.vy}}}}function zr(e,t){return e||t?{x:(e?.x??0)+(t?.x??0),y:(e?.y??0)+(t?.y??0)}:null}function Lr(e){if(!e?.length)return null;const t=e.slice(),n=t.some(e=>!1!==e.continuous);return{controllers:t,continuous:n,onTick:(e,n,i)=>{const r={result:e,controls:n,dt:i.dt,elapsed:i.elapsed,getRegionState:i.getRegionState};for(const e of t)e.tick(r)},bodyForce:e=>{let n=null;for(const i of t)i.bodyForce&&(n=zr(n,i.bodyForce(e)));return n}}}function Yr(e){const t=new Set,n=e.impulse??{x:-60,y:0};return{id:e.id??"portal:"+e.fromRegionId,continuous:!0===e.continuous,tick:i=>{const r=i.controls.readBodies();for(const o of r){const r=i.getRegionState(o.id),s=r?.activeRegionIds.includes(e.fromRegionId);s?t.has(o.id)||(t.add(o.id),i.controls.applyImpulse(o.id,n.x??0,n.y??0),e.onPortal?.(o)):t.delete(o.id)}}}}var Hr=require("react");function Gr(){return"undefined"==typeof document||!document.hidden}var Xr=require("react/jsx-runtime"),_r="var(--semiotic-focus, #005fcc)";function Vr({active:e,hoverPoint:t,margin:n,size:i,shape:r="circle",width:o,height:s,pathData:a}){if(!e||!t)return null;const c=t.x+n.left,l=t.y+n.top;let d;if("geoarea"!==r&&"path"!==r||!a)if("rect"===r&&null!=o&&null!=s){const e=Math.max(o,4),t=Math.max(s,4);d=(0,Xr.jsx)("rect",{x:c-e/2-3,y:l-t/2-3,width:e+6,height:t+6,rx:3,fill:"none",stroke:_r,strokeWidth:2,strokeDasharray:"4,2"})}else d=(0,Xr.jsx)("circle","wedge"===r?{cx:c,cy:l,r:12,fill:"none",stroke:_r,strokeWidth:2.5,strokeDasharray:"6,3"}:{cx:c,cy:l,r:8,fill:"none",stroke:_r,strokeWidth:2,strokeDasharray:"4,2"});else d=(0,Xr.jsx)("g",{transform:`translate(${n.left},${n.top})`,children:(0,Xr.jsx)("path",{d:a,fill:"none",stroke:_r,strokeWidth:2.5,strokeDasharray:"6,3"})});return(0,Xr.jsx)("svg",{style:{position:"absolute",left:0,top:0,width:i[0],height:i[1],pointerEvents:"none",zIndex:2},"aria-hidden":"true",children:d})}var Ur=require("react"),Kr={sceneGeometry:0,layout:0,domain:0};function Qr(e){const{domain:t,layout:n,sceneGeometry:i}=e.revisions;return{domain:t,layout:n,sceneGeometry:i}}function Zr(e,t){return{sceneGeometry:Math.max(e.sceneGeometry,t.sceneGeometry),layout:Math.max(e.layout,t.layout),domain:Math.max(e.domain,t.domain)}}var Jr="production"!==process.env.NODE_ENV,eo={revisions:Kr,signature:"",sawSignals:!1,wasUnconsumed:!1,warnUnconsumed:!1},to=class{constructor(e="scene host"){this.hostName=e,this.lastConsumed=Kr,this.lastObserved=Kr,this.lastDuplicateWarning="",this.lastUnconsumedWarning=""}observeUpdateResult(e){Jr&&(this.lastObserved=Zr(this.lastObserved,Qr(e)))}beforeCompute(e,t){if(!Jr)return eo;const n=Zr(Qr(e),this.lastObserved),i=function(e){return`${e.sceneGeometry}|${e.layout}|${e.domain}`}(n),r=!((o=n).sceneGeometry===(s=this.lastConsumed).sceneGeometry&&o.layout===s.layout&&o.domain===s.domain);var o,s;return{revisions:n,signature:i,sawSignals:e.changed.has("scene-geometry")||e.changed.has("layout")||e.changed.has("domain"),wasUnconsumed:r,warnUnconsumed:!t&&r&&this.lastUnconsumedWarning!==i}}afterCompute(e,t,n){if(Jr){if(t&&e.wasUnconsumed&&(this.lastConsumed=e.revisions),e.warnUnconsumed&&!t)return console.warn(`[semiotic] ${this.hostName} observed scene-affecting revisions without a scene rebuild: ${e.signature}.`),void(this.lastUnconsumedWarning=e.signature);t&&e.sawSignals&&!e.wasUnconsumed&&!n&&this.lastDuplicateWarning!==e.signature?(console.warn(`[semiotic] ${this.hostName} performed scene rebuild with unchanged scene revisions: ${e.signature}.`),this.lastDuplicateWarning=e.signature):t&&!e.sawSignals&&(this.lastDuplicateWarning="")}}},no=(0,Ur.memo)(function({store:e,diagnostics:t}){return(0,Ur.useEffect)(()=>{const n=()=>t.observeUpdateResult(e.getUpdateSnapshot());return n(),e.subscribeUpdateResult(n)},[t,e]),null}),io=(c(require("react")),c(require("react"))),ro=(require("react/jsx-runtime"),io.createContext(null)),oo=require("react/jsx-runtime"),so={position:"absolute",width:1,height:1,overflow:"hidden",clip:"rect(0,0,0,0)",whiteSpace:"nowrap",border:0};function ao({hoverPoint:e}){let t="";if(e){const n=e.data||e;t="object"==typeof n?"Data point: "+Object.entries(n).filter(([,e])=>"object"!=typeof e&&"function"!=typeof e).map(([e,t])=>`${e}: ${t}`).join(", "):"Data point: "+n}return(0,oo.jsx)("div",{"aria-live":"polite","aria-atomic":"true",style:so,children:t})}var co=require("react/jsx-runtime");function lo({summary:e}){return e?(0,co.jsx)("div",{role:"note",style:so,children:e}):null}function uo({tableId:e}){return(0,co.jsx)("a",{href:"#"+e,style:so,onClick:t=>{t.preventDefault();const n=document.getElementById(e);n&&requestAnimationFrame(()=>n.focus())},onFocus:e=>{Object.assign(e.currentTarget.style,{position:"absolute",width:"auto",height:"auto",overflow:"visible",clip:"auto",whiteSpace:"normal",padding:"4px 8px",background:"var(--semiotic-bg, #fff)",color:"var(--semiotic-text, #000)",border:"2px solid var(--semiotic-focus, #005fcc)",borderRadius:"4px",zIndex:"10",fontSize:"12px",top:"4px",left:"4px"})},onBlur:e=>{const t=e.currentTarget;t.removeAttribute("style"),Object.assign(t.style,so)},children:"Skip to data table"})}function ho(e,t,n){const i=function(e,t){if(null==t)return;const n=le(e,t,"");return""===n?void 0:n}(e,n.fill)??"#4e79a7",r=n.stroke,o=n.strokeWidth??0,s=n.opacity??1,a=n.fillOpacity??1,c=function(e,t){const n=t.mark;if(n)return n;const i=e.datum,r=i?.__physicsMark??i?.mark;return"circle"===r||"halo"===r||"faceted"===r||"pill"===r||"diamond"===r||"square"===r?r:"circle"===e.shape.type?"circle":"square"}(t,n),l="circle"===t.shape.type?n.r??t.shape.radius:Math.max(t.shape.width,t.shape.height)/2;if(e.save(),e.globalAlpha*=s,e.beginPath(),"pill"===c||"square"===c||"aabb"===t.shape.type){const n="pill"===c?2.4*l:"aabb"===t.shape.type?t.shape.width:1.7*l,i="pill"===c?1.35*l:"aabb"===t.shape.type?t.shape.height:1.7*l,r=t.x-n/2,o=t.y-i/2,s="pill"===c?i/2:Math.min(4,n/4);e.moveTo(r+s,o),e.arcTo(r+n,o,r+n,o+i,s),e.arcTo(r+n,o+i,r,o+i,s),e.arcTo(r,o+i,r,o,s),e.arcTo(r,o,r+n,o,s),e.closePath()}else if("diamond"===c)e.moveTo(t.x,t.y-l),e.lineTo(t.x+l,t.y),e.lineTo(t.x,t.y+l),e.lineTo(t.x-l,t.y),e.closePath();else if("faceted"===c){const n=6;for(let i=0;n>i;i+=1){const r=2*Math.PI*i/n-Math.PI/2,o=t.x+Math.cos(r)*l,s=t.y+Math.sin(r)*l;0===i?e.moveTo(o,s):e.lineTo(o,s)}e.closePath()}else e.arc(t.x,t.y,l,0,2*Math.PI);i&&(e.save(),e.globalAlpha*=a,e.fillStyle=i,e.fill(),e.restore()),"halo"===c&&(e.beginPath(),e.arc(t.x,t.y,1.35*l,0,2*Math.PI),e.strokeStyle=r??i,e.lineWidth=Math.max(1.5,o||1.5),e.globalAlpha*=.55,e.stroke(),e.globalAlpha/=.55),r&&o>0&&(e.strokeStyle=r,e.lineWidth=o,n.strokeDasharray&&e.setLineDash(n.strokeDasharray.split(/[,\s]+/).map(e=>Number(e)).filter(e=>Number.isFinite(e))),e.stroke()),e.restore()}function po(e){return"circle"===e.shape.type?e.shape.radius:Math.max(e.shape.width,e.shape.height)/2}function fo(e){return e.sensorId??"stream-region-"+e.id}function mo(e){const t=fo(e),n={bodyFilter:e.bodyFilter,friction:e.friction,restitution:e.restitution};if("boundary"===e.collider&&"aabb"===e.shape.type){const i=e.colliderThickness??8,r=e.shape.x-e.shape.width/2,o=e.shape.x+e.shape.width/2,s=e.shape.y-e.shape.height/2,a=e.shape.y+e.shape.height/2;return[{...n,id:t+"-top",shape:{type:"segment",x1:r,y1:s,x2:o,y2:s,thickness:i}},{...n,id:t+"-right",shape:{type:"segment",x1:o,y1:s,x2:o,y2:a,thickness:i}},{...n,id:t+"-bottom",shape:{type:"segment",x1:o,y1:a,x2:r,y2:a,thickness:i}},{...n,id:t+"-left",shape:{type:"segment",x1:r,y1:a,x2:r,y2:s,thickness:i}}]}return e.collider?[{...n,id:t+"-collider",shape:e.shape}]:[]}function yo(e){if(e)return{activeRegionIds:Array.from(e.activeRegionIds),regionIds:Array.from(e.regionIds),charges:{...e.charges},attributes:{...e.attributes},energy:e.energy}}function go(e,t){const n="function"==typeof e?e(t):e;if(!n)return null;const i=Number(n.x??0),r=Number(n.y??0);return Number.isFinite(i)||Number.isFinite(r)?{x:Number.isFinite(i)?i:0,y:Number.isFinite(r)?r:0}:null}function xo(e){if(!1===e.semanticItem)return null;const t=e.shape,n=e.semanticItem??{},i="aabb"===t.type?{id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"region",x:t.x,y:t.y,width:t.width,height:t.height}:{id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"region",x:(t.x1+t.x2)/2,y:(t.y1+t.y2)/2,pathData:`M ${t.x1} ${t.y1} L ${t.x2} ${t.y2}`};return{...i,...n,id:n.id??i.id}}function bo(e){return e.some(e=>null!=e.force||null!=e.damping||null!=e.impulseOnEnter||null!=e.impulseOnExit)}function vo(e,t){const n="function"==typeof e?e(t):e;if(!n)return null;const i=Number(n.x??0),r=Number(n.y??0);return Number.isFinite(i)||Number.isFinite(r)?{x:Number.isFinite(i)?i:0,y:Number.isFinite(r)?r:0}:null}var wo=[];function ko(e){const t=e.store.controls(),n=e.store.snapshot(),i=Math.max(0,e.result.steps*(n.config.fixedDt||1/60)),r=function(e,t,n,i){const r=Number.isFinite(i)?Math.max(0,i):0;if(0>=r||!bo(t))return!1;const o=new Map(t.map(e=>[e.id,e])),s=e.readBodies();let a=!1;for(const t of s){const i=n.get(t.id);if(!i||!i.activeRegionIds.size)continue;const s=yo(i);if(s)for(const n of i.activeRegionIds){const i=o.get(n);if(!i)continue;const c=go(i.force,{body:t,region:i,regionState:s}),l=Number(i.damping??0),d=(c?.x??0)*r-(Number.isFinite(l)?t.vx*l*r:0),u=(c?.y??0)*r-(Number.isFinite(l)?t.vy*l*r:0);(d||u)&&(e.applyImpulse(t.id,d,u),a=!0)}}return a}(t,e.regionEffects,e.regionState,i),o=function(e,t,n,i,r,o){const s=Number.isFinite(o)?Math.max(0,o):0;if(0>=s||!t)return!1;const a=new Map(n.map(e=>[e.id,e])),c=e.readBodies();let l=!1;for(let n=0;c.length>n;n+=1){const o=c[n],d=i.get(o.id),u=yo(d);let h=wo;if(d&&d.activeRegionIds.size>0){const e=[];for(const t of d.activeRegionIds){const n=a.get(t);n&&e.push(n)}h=e}const p=vo(t,{body:o,bodies:c,index:n,regionState:u,regions:h,simulationState:r});if(!p)continue;const f=(p.x??0)*s,m=(p.y??0)*s;(f||m)&&(e.applyImpulse(o.id,f,m),l=!0)}return l}(t,e.bodyForces,e.regionEffects,e.regionState,n.simulationState,i);return e.composed&&e.composed.onTick(e.result,t,{dt:i,elapsed:e.result.elapsedSeconds,getRegionState:t=>yo(e.regionState.get(t))}),e.onTick?.(e.result,t),{regionEffectsApplied:r,bodyForcesApplied:o,snapshot:n}}function Mo(e,t,n,i,r,o,s,a,c,l){const d=function(e,t){return!!t?.isActive&&(t.predicate?.(e)??!0)}(e,r),u={selected:d,simulationState:t,regionState:o,regions:s},h="function"==typeof n?n(e,u):n,p=s.reduce((t,n)=>n.bodyStyle?{...t,..."function"==typeof n.bodyStyle?n.bodyStyle(e,u):n.bodyStyle}:t,{}),f=d?"function"==typeof i?i(e,u):i:void 0;return{fill:l?.color??a,stroke:l?.stroke??c,strokeWidth:l?.strokeWidth??1,opacity:l?.opacity??.9,...h,...p,...f}}var So=require("react"),Io=c(require("react")),jo=require("react/jsx-runtime"),Ao={border:0,clip:"rect(0 0 0 0)",height:1,margin:-1,overflow:"hidden",padding:0,position:"absolute",whiteSpace:"nowrap",width:1},Co="semiotic-accessible-data-table",Ro=Co+" semiotic-accessible-data-table-hidden",Po=Co+" semiotic-accessible-data-table-visible",Do={position:"absolute",top:0,left:0,right:0,zIndex:"var(--semiotic-data-table-z-index, var(--semiotic-overlay-z-index, 20))",padding:"14px 16px 12px",borderBottom:"1px solid var(--semiotic-data-table-border, var(--semiotic-border, #e0e0e0))",fontFamily:"var(--semiotic-font-family, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif)",fontSize:13,lineHeight:1.5,color:"var(--semiotic-data-table-text, var(--semiotic-text, #333))",background:"var(--semiotic-data-table-bg, var(--semiotic-surface, var(--semiotic-bg, #fff)))",borderRadius:"var(--semiotic-border-radius, 0px) var(--semiotic-border-radius, 0px) 0 0"},$o={marginBottom:8,paddingRight:28,color:"var(--semiotic-data-table-muted-text, var(--semiotic-text-secondary, #666))",fontSize:12,letterSpacing:"0.01em"},Bo={position:"absolute",top:10,right:10,width:22,height:22,display:"flex",alignItems:"center",justifyContent:"center",border:"1px solid var(--semiotic-data-table-border, var(--semiotic-border, #e0e0e0))",background:"var(--semiotic-data-table-bg, var(--semiotic-surface, var(--semiotic-bg, #fff)))",cursor:"pointer",color:"var(--semiotic-data-table-muted-text, var(--semiotic-text-secondary, #666))",fontSize:13,lineHeight:1,padding:0,borderRadius:"var(--semiotic-border-radius, 4px)"},To={width:"100%",borderCollapse:"collapse",fontSize:12,marginTop:4,fontVariantNumeric:"tabular-nums"},No={textAlign:"left",padding:"5px 10px",borderBottom:"2px solid var(--semiotic-data-table-border, var(--semiotic-border, #e0e0e0))",fontWeight:600,fontSize:11,textTransform:"uppercase",letterSpacing:"0.04em",color:"var(--semiotic-data-table-muted-text, var(--semiotic-text-secondary, #666))"},Eo={padding:"4px 10px",borderBottom:"1px solid var(--semiotic-data-table-border, var(--semiotic-border, #e0e0e0))"},Wo={textAlign:"left",fontSize:11,color:"var(--semiotic-data-table-muted-text, var(--semiotic-text-secondary, #666))",marginBottom:4,fontStyle:"italic"},qo={marginTop:8,padding:"4px 10px",fontSize:12,cursor:"pointer",border:"1px solid var(--semiotic-data-table-border, var(--semiotic-border, #e0e0e0))",borderRadius:"var(--semiotic-border-radius, 4px)",background:"var(--semiotic-data-table-bg, var(--semiotic-surface, var(--semiotic-bg, #fff)))",color:"var(--semiotic-data-table-text, var(--semiotic-text, #333))",fontFamily:"inherit"};function Oo(e){return null==e?null:"string"==typeof e||"number"==typeof e||"boolean"==typeof e?e+"":null}function Fo(e){return{__semioticHoverData:!0,body:e,data:e.datum??e,id:e.id,type:"body",x:e.x,y:e.y}}function zo(e){if("circle"===e.shape.type){const t=Math.max(4,2*e.shape.radius);return{height:t,shape:"circle",width:t}}return{height:e.shape.height,shape:"rect",width:e.shape.width}}function Lo(e){const t=e.datum;if(t&&"object"==typeof t){const e=t.label??t.name??t.id;if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e+""}return e.id}function Yo(e){const t=Ho(e.datum??e);return t.length?t.map(([e,t])=>`${e}: ${t}`).join(", "):"Physics body "+e.id}function Ho(e){return e&&"object"==typeof e?Object.entries(e).map(([e,t])=>{if(e.startsWith("_"))return null;const n=Oo(t);return null==n?null:[e,n]}).filter(e=>null!=e).slice(0,8):[]}function Go({hover:e}){const t=Ho(e.data);return(0,jo.jsxs)("div",{className:"semiotic-tooltip",style:Pe,children:[(0,jo.jsx)("div",{style:{fontWeight:700,marginBottom:t.length?4:0},children:e.id}),t.map(([e,t])=>(0,jo.jsxs)("div",{children:[(0,jo.jsxs)("span",{style:{opacity:.72},children:[e,": "]}),(0,jo.jsx)("span",{children:t})]},e))]})}function Xo(e){return e.datum&&"object"==typeof e.datum?Object.entries(e.datum).map(([e,t])=>{const n=Oo(t);return null==n?null:`${e}: ${n}`}).filter(e=>null!=e).slice(0,8).join(", "):""}function _o(e){const t=[`${e.length} semantic item${1===e.length?"":"s"}.`],n=new Map;for(const t of e)t.group&&n.set(t.group,(n.get(t.group)??0)+1);return n.size&&t.push(Array.from(n).map(([e,t])=>`${e}: ${t}`).join(", ")),t.join(" ")}function Vo(e){const{chartTitle:t,items:n,tableId:i}=e,[r,o]=Io.useState(!1),[s,a]=Io.useState(5),c=io.useContext(ro),l=c?.visible??!1,d=r||l,u=Io.useRef(null),h="Data summary for "+(t??"physics chart");Io.useEffect(()=>{d||a(5)},[d]);const p=Io.useCallback(e=>{e.target===e.currentTarget&&(r||l||o(!0))},[r,l]),f=Io.useCallback(e=>{l||u.current?.contains(e.relatedTarget)||o(!1)},[l]);if(!n.length)return(0,jo.jsx)("span",{id:i,tabIndex:-1,style:Ao});if(!d)return(0,jo.jsx)("div",{id:i,className:Ro,role:"region","aria-label":h,tabIndex:-1,style:Ao,onFocus:p,children:(0,jo.jsxs)("button",{type:"button",onClick:()=>o(!0),children:["View data summary (",n.length," semantic items)"]})});const m=Math.min(s,n.length),y=n.slice(0,m),g=n.length-m;return(0,jo.jsxs)("div",{ref:u,id:i,className:Po,role:"region","aria-label":h,tabIndex:-1,onBlur:f,style:Do,children:[(0,jo.jsx)("button",{type:"button",className:"semiotic-accessible-data-table-close","aria-label":"Close data summary",onClick:()=>{l&&c&&c.setVisible(!1),o(!1)},style:Bo,children:"×"}),(0,jo.jsx)("div",{className:"semiotic-accessible-data-table-summary",role:"note",style:$o,children:_o(n)}),(0,jo.jsxs)("table",{className:"semiotic-accessible-data-table-table",role:"table","aria-label":"Semantic items for "+(t??"physics chart"),style:To,children:[(0,jo.jsx)("caption",{className:"semiotic-accessible-data-table-caption",style:Wo,children:g>0?`First ${m} of ${n.length} semantic items`:`All ${n.length} semantic items`}),(0,jo.jsx)("thead",{children:(0,jo.jsxs)("tr",{children:[(0,jo.jsx)("th",{scope:"col",style:No,children:"Item"}),(0,jo.jsx)("th",{scope:"col",style:No,children:"Description"}),(0,jo.jsx)("th",{scope:"col",style:No,children:"Group"}),(0,jo.jsx)("th",{scope:"col",style:No,children:"Position"}),(0,jo.jsx)("th",{scope:"col",style:No,children:"Data"})]})}),(0,jo.jsx)("tbody",{children:y.map((e,t)=>(0,jo.jsxs)("tr",{children:[(0,jo.jsx)("th",{scope:"row",style:Eo,children:e.label}),(0,jo.jsx)("td",{style:Eo,children:e.description??e.label}),(0,jo.jsx)("td",{style:Eo,children:e.group??""}),(0,jo.jsxs)("td",{style:Eo,children:[Math.round(e.x),", ",Math.round(e.y)]}),(0,jo.jsx)("td",{style:Eo,children:Xo(e)})]},e.id??`${e.label}-${t}`))})]}),g>0?(0,jo.jsxs)("button",{type:"button",className:"semiotic-accessible-data-table-show-more",onClick:()=>a(e=>e+25),style:qo,children:["Show ",Math.min(25,g)," more"," ",1===g?"row":"rows"," (",g," remaining)"]}):null]})}Go.ownsChrome=!0;var Uo=require("react/jsx-runtime"),Ko=[640,360],Qo={top:0,right:0,bottom:0,left:0},Zo=new Set(["ArrowRight","ArrowLeft","ArrowUp","ArrowDown","Home","End","PageUp","PageDown"]),Jo="StreamPhysicsFrame",es=(0,h.memo)((0,h.forwardRef)(function(e,t){const{accessibleTable:n=!0,annotations:i,onAnnotationActivate:r,autoPlaceAnnotations:o,background:s,backgroundGraphics:a,bodySemanticItemLimit:c=200,bodySemanticItems:l=!1,bodySemanticUpdateMs:d=200,bodyForces:p,bodyStyle:f,chartId:m,className:y,frameScheduler:g,clock:x,random:b,seed:v,color:w,config:k,controllers:M,continuous:S=!1,description:I,emphasis:j,chartMode:A,enableHover:C=!0,foregroundGraphics:R,hoverRadius:P=16,initialSpawns:D,initialSpawnPacing:$,legend:B,legendClickBehavior:T,legendHighlightedCategory:N,legendHoverBehavior:E,legendIsolatedCategories:W,legendLayout:q,legendPosition:O,margin:F,onClick:V,onObservation:K,onRegionEvent:Q,onSimulationExecutionChange:Z,onBodyHover:J,onBodyPointerDown:ee,onSemanticItemActivate:te,onSemanticItemFocus:ne,onTick:ie,opacity:re,paused:oe=!1,regionEffects:se=[],responsiveHeight:ae,responsiveWidth:ce,selectedBodyStyle:le={stroke:"#111827",strokeWidth:2,opacity:1},selection:de,semanticItems:ue=[],simulationExecution:he="auto",size:pe=Ko,stroke:fe,strokeWidth:me,summary:ye,suspendWhenHidden:ge=!0,svgAnnotationRules:xe,title:be,tooltipContent:ve,workerBodyThreshold:Me=Hn,renderBody:Se,beforePaint:Ie,afterPaint:je}=e,Ae=u.useMemo(()=>({color:w,stroke:fe,strokeWidth:me,opacity:re}),[w,re,fe,me]),Ce=(0,h.useRef)(K);Ce.current=K;const Re=(0,h.useRef)(m);Re.current=m;const Pe=(0,h.useRef)(new Map),De=(0,h.useRef)(se);De.current=se;const $e=(0,h.useRef)(p);$e.current=p;const Be=(0,h.useRef)(ie);Be.current=ie;const Te=u.useMemo(()=>Lr(M),[M]),Ne=(0,h.useRef)(Te);Ne.current=Te;const Ue=S||!!Te?.continuous,Ke=(0,h.useRef)(Ue);Ke.current=Ue;const Qe=u.useMemo(()=>{if(!p&&!Te?.bodyForce)return p;if(!Te?.bodyForce)return p;if(!p)return Te.bodyForce;const e=Te.bodyForce;return t=>{const n="function"==typeof p?p(t):p,i="function"==typeof e?e(t):e;return n||i?{x:(n?.x??0)+(i?.x??0),y:(n?.y??0)+(i?.y??0)}:null}},[p,Te]);$e.current=Qe;const Ze=u.useMemo(()=>new Map(se.map(e=>[fo(e),e])),[se]),Je=u.useMemo(()=>new Map(se.map(e=>[e.id,e])),[se]),et=u.useMemo(()=>se.map(xo).filter(e=>null!=e),[se]),[tt,nt]=u.useState([]),it=u.useMemo(()=>tt.length||et.length?[...ue,...tt,...et]:ue,[tt,et,ue]),rt=u.useMemo(()=>bo(se),[se]),ot=!!Qe,st=(0,h.useRef)(null),at=(0,h.useRef)(x??wr);at.current=x??wr;const ct=(0,h.useCallback)((e,t,n)=>{const i=st.current;if(!i||!n)return!1;const r=i.readBodies().find(t=>t.id===e),o=yo(Pe.current.get(e));if(!r||!o)return!1;const s=go(n,{body:r,region:t,regionState:o});return!(!s||!s.x&&!s.y||(i.applyImpulse(e,s.x??0,s.y??0),0))},[]),lt=(0,h.useCallback)((e,t,n)=>{if(!n.bodyId)return;const i=yo(Pe.current.get(n.bodyId));if(!i)return;const r={bodyId:n.bodyId,datum:n.datum,observation:n,region:t,regionState:i,type:e};"region-enter"===e?t.onEnter?.(r):t.onExit?.(r),Q?.(r)},[Q]),dt=(0,h.useCallback)(e=>{const t=e.sensorId?Ze.get(e.sensorId):void 0;if(!t||!e.bodyId)return;const n=function(e,t){let n=e.get(t);return n||(n={activeRegionIds:new Set,attributes:{},charges:{},energy:0,regionIds:new Set},e.set(t,n)),n}(Pe.current,e.bodyId),i=st.current?.readBodies().find(t=>t.id===e.bodyId),r=yo(n),o=i&&r?{body:i,region:t,regionState:r}:null;if("physics-proximity-enter"===e.type){if(n.activeRegionIds.add(t.id),n.regionIds.add(t.id),n.energy+=t.energyDelta??0,o){!function(e,t,n){const i="function"==typeof e.attributes?e.attributes(t):e.attributes;i&&(n.attributes={...n.attributes,...i})}(t,o,n);const e=function(e,t){return void 0!==e.charge?"function"==typeof e.charge?e.charge(t):e.charge:"charge-gate"===e.kind?1:void 0}(t,o);void 0!==e&&(n.charges[t.id]=e)}ct(e.bodyId,t,t.impulseOnEnter),lt("region-enter",t,e)}else"physics-proximity-exit"===e.type&&(n.activeRegionIds.delete(t.id),ct(e.bodyId,t,t.impulseOnExit),lt("region-exit",t,e))},[ct,lt,Ze]),ut=u.useMemo(()=>{if(!i?.length)return[];const e=i.filter(e=>"barrier"===e.physics||"sensor"===e.physics);return e.length?function(e=[],t={}){const n=t.idPrefix?t.idPrefix+"-":"",i=[];for(const r of e){if("barrier"!==r.physics&&"sensor"!==r.physics)continue;const e=r.axis??t.defaultAxis??"x",o=Yn(r,t),s=r.colliderId??`${n}${r.id}`;let a;if("x"===e){const e=Ln(r.x),n=Ln(r.y1)??Ln(t.plotBounds?.y)??Ln(r.y),i=Ln(r.y2)??(t.plotBounds?t.plotBounds.y+t.plotBounds.height:void 0)??Ln(r.y);if(null==e||null==n||null==i)continue;a={type:"segment",x1:e,y1:n,x2:e,y2:i,thickness:o}}else{const e=Ln(r.y),n=Ln(r.x1)??Ln(t.plotBounds?.x)??Ln(r.x),i=Ln(r.x2)??(t.plotBounds?t.plotBounds.x+t.plotBounds.width:void 0)??Ln(r.x);if(null==e||null==n||null==i)continue;a={type:"segment",x1:n,y1:e,x2:i,y2:e,thickness:o}}i.push({id:s,shape:a,sensor:"sensor"===r.physics,..."barrier"!==r.physics||null==r.restitution&&null==t.barrierRestitution?{}:{restitution:Ln(r.restitution)??Ln(t.barrierRestitution)},..."barrier"!==r.physics||null==r.friction&&null==t.barrierFriction?{}:{friction:Ln(r.friction)??Ln(t.barrierFriction)}})}return i}(e,{idPrefix:m?m+"-ann":"physics-ann",plotBounds:{x:0,y:0,width:pe?.[0]??Ko[0],height:pe?.[1]??Ko[1]}}):[]},[i,m,pe]),ht=u.useMemo(()=>{const e=void 0===v||void 0!==k?.kernel?.seed?k:{...k,kernel:{...k?.kernel,seed:v}},t=se.flatMap(e=>[{id:fo(e),sensor:!0,shape:e.shape,bodyFilter:e.bodyFilter,friction:e.friction,restitution:e.restitution},...mo(e)]),n=Object.fromEntries(se.map(e=>[fo(e),{binId:e.binId??e.id,enterType:"physics-proximity-enter",exitType:"physics-proximity-exit"}])),i=e?.observation,r=se.length>0;return r||t.length>0||ut.length>0||null!=m||i?{...e,colliders:[...e?.colliders??[],...t,...ut],observation:{...i,chartId:m??i?.chartId,chartType:i?.chartType??Jo,sensors:{...i?.sensors??{},...n},onObservation:e=>{r&&dt(e),i?.onObservation?.(e)}}}:e},[ut,m,k,dt,se,v]);if(!st.current){const e=vr(ht,D,$);e.setPaused(oe),ge&&e.setVisible(Gr()),st.current=e}const pt=(0,h.useRef)(-1),ft=(0,h.useRef)(null),mt=(0,h.useRef)(!0),yt=(0,Ur.useRef)(new to("StreamPhysicsFrame")),gt=(0,h.useRef)(""),xt=(0,h.useId)().replace(/:/g,""),bt=(0,h.useRef)(!1),vt=(0,h.useRef)(!1),wt=(0,h.useRef)(0),kt=(0,h.useRef)(!1),Mt=(0,h.useRef)(null),St=(0,h.useRef)(!1),It=z({sizeProp:pe,responsiveWidth:ce,responsiveHeight:ae,userMargin:F,marginDefault:Qo,foregroundGraphics:R,backgroundGraphics:a,frameScheduler:g,clock:x,random:b,seed:v,paused:oe,suspendWhenHidden:ge}),{margin:jt,rafRef:At,reducedMotionRef:Ct,renderFnRef:Rt,cancelRender:Pt,resolvedBackground:Dt,resolvedForeground:$t,responsiveRef:Bt,scheduleRender:Tt,size:Nt,frameRuntime:Et}=It,Wt=(0,h.useRef)(Et.now);Wt.current=Et.now;const qt=function(){const[e,t]=(0,L.useState)(!1);return Y(()=>{t(!0)},[]),e}(),Ot=function(){const e=(0,L.useSyncExternalStore)(H,G,X);return(0,L.useRef)(e).current}(),[Ft,zt]=u.useState(null),[Lt,Yt]=u.useState(null),Ht=(0,h.useRef)(null),Gt=(0,h.useRef)(0),Xt=(0,h.useRef)(new Map),_t=xt+"-physics-live",Vt=(0,h.useCallback)((e,t,n=!1)=>{if(!l)return void nt(e=>e.length?[]:e);const i=Wt.current();if(!n&&d>0&&d>i-Gt.current)return;Gt.current=i;const r=function(e,t,n,i){if(!n)return[];const r=Math.max(0,Math.floor(i));if(!r)return[];const o=[];for(let i=0;e.length>i&&r>o.length;i+=1){const r=e[i],s="function"==typeof n?n(r,{index:i,simulationState:t}):void 0;if(!1===s)continue;const a=zo(r);o.push({datum:r.datum??r,description:Yo(r),group:"body",label:Lo(r),...a,...s??{},bodyId:s?.bodyId??r.id,id:s?.id??"body:"+r.id,x:s?.x??r.x,y:s?.y??r.y})}return o}(e,t,l,c);nt(e=>function(e,t){if(e.length!==t.length)return!0;for(let n=0;e.length>n;n+=1){const i=e[n],r=t[n];if(i.id!==r.id||i.label!==r.label||i.description!==r.description||i.group!==r.group||i.bodyId!==r.bodyId||Math.round(i.x)!==Math.round(r.x)||Math.round(i.y)!==Math.round(r.y))return!0}return!1}(e,r)?r:e)},[c,l,d]),Ut=(0,h.useCallback)(e=>{if(!it.length)return;const t=Math.max(0,Math.min(e,it.length-1));pt.current=t;const n=it[t];if(Ht.current=n.bodyId??null,zt(n),ne?.(n),n.bodyId&&st.current){const e=st.current.readBodies().find(e=>e.id===n.bodyId);if(e){const t=Fo(e);Yt(t),J?.(e,t)}}},[it,J,ne]),Kt=(0,h.useCallback)(()=>{pt.current=-1,Ht.current=null,zt(null),ne?.(null)},[ne]),Qt=function({onObservationRef:e,chartIdRef:t,wallClockRef:n}){return(0,So.useCallback)((i,r)=>{const o=e.current;if(!o)return;const s={timestamp:n.current(),chartType:"StreamPhysicsFrame",chartId:t.current};o("hover"===i||"click"===i?{...s,type:i,datum:r?.datum??{},x:r?.x??0,y:r?.y??0}:"focus"===i?{...s,type:i,datum:r?.datum??{},inputType:"touch"===r?.inputType?"pointer":r?.inputType??"keyboard"}:"activate"===i?{...s,type:i,datum:r?.datum??{},inputType:r?.inputType??"keyboard"}:{...s,type:i})},[t,e,n])}({onObservationRef:Ce,chartIdRef:Re,wallClockRef:at}),Zt=(0,h.useCallback)(()=>{Yt(e=>e?(J?.(null,null),Qt("hover-end"),null):e)},[Qt,J]),Jt=(0,h.useCallback)(e=>{if(!C||!st.current)return;const t=e.currentTarget.getBoundingClientRect(),n=st.current.hitTest(e.clientX-t.left,e.clientY-t.top,P);if(!n)return void Zt();const i=Fo(n);Yt(e=>e&&e.id===i.id&&e.x===i.x&&e.y===i.y?e:(J?.(n,i),Qt("hover",{datum:n.datum,x:n.x,y:n.y}),i))},[Zt,Qt,C,P,J]),en=(0,h.useCallback)(e=>{Kt();const t=st.current,n=e.currentTarget.getBoundingClientRect(),i=e.clientX-n.left,r=e.clientY-n.top,o=t?t.hitTest(i,r,Math.max(16,P)):null;ee?.(o,e),o?(Qt("click",{datum:o.datum,x:o.x,y:o.y}),Qt("activate",{datum:o.datum,inputType:"touch"===e.pointerType?"touch":"pointer"}),V?.(o.datum??null,{x:o.x,y:o.y,body:o})):(Qt("click-end"),V?.(null,{x:i,y:r,body:null}),Zt())},[Zt,Kt,Qt,P,ee,V]);(0,h.useEffect)(()=>{if(!it.length)return void Kt();const e=pt.current;if(it.length>e){if(e>=0){const t=it[e];if(Ht.current=t.bodyId??null,zt(e=>null!=e&&e.id===t.id&&Math.round(e.x)===Math.round(t.x)&&Math.round(e.y)===Math.round(t.y)?e:t),t.bodyId&&st.current){const e=st.current.readBodies().find(e=>e.id===t.bodyId);if(e){const t=Fo(e);Yt(e=>e?.id===t.id&&Math.round(e.x)===Math.round(t.x)&&Math.round(e.y)===Math.round(t.y)?e:t)}}}}else Ut(it.length-1)},[it,Kt,Ut]),(0,h.useEffect)(()=>{C||Zt()},[Zt,C]);const tn=(0,h.useCallback)(e=>{if(function(e){const t=e.target;return t instanceof Element&&t!==e.currentTarget&&null!=t.closest("button, a[href], input, select, textarea, summary, [contenteditable='true'], [role='button'], [role='link'], [role='checkbox'], [role='radio'], [role='switch']")}(e))return;if(!it.length)return;if("Escape"===e.key)return e.preventDefault(),void Kt();if(("Enter"===e.key||" "===e.key)&&pt.current>=0){e.preventDefault();const t=it[pt.current];return Qt("activate",{datum:t.datum??{id:t.id,label:t.label},inputType:"keyboard"}),void te?.(t)}if(!Zo.has(e.key))return;e.preventDefault();const t=pt.current;if(0>t){Ut(0);const e=it[0];return void Qt("focus",{datum:e.datum??{id:e.id,label:e.label},inputType:"keyboard"})}const n=Math.max(1,Math.floor(.1*it.length));let i=t;if("Home"===e.key?i=0:"End"===e.key?i=it.length-1:"PageDown"===e.key?i=Math.min(it.length-1,t+n):"PageUp"===e.key?i=Math.max(0,t-n):"ArrowRight"===e.key||"ArrowDown"===e.key?i=Math.min(it.length-1,t+1):"ArrowLeft"!==e.key&&"ArrowUp"!==e.key||(i=Math.max(0,t-1)),Ut(i),i!==t){const e=it[i];Qt("focus",{datum:e.datum??{id:e.id,label:e.label},inputType:"keyboard"})}},[Kt,Qt,Ut,te,it]),[nn,rn]=u.useState([]),on=(0,h.useRef)(0),sn=!!i?.length&&i.some(e=>null!=e.pointId||null!=e.bodyId||"latest"===e.anchor),{canvasRef:an}=function(e,t){return function(e){const{cancelRender:t,dirtyRef:n,frameRuntime:i,manageFrameRuntime:r,scheduleRender:o}=e,s=(0,_.useRef)(null),a=(0,_.useRef)(null),c=(0,_.useRef)(!1);return function(e){const{hydrated:t,wasHydratingFromSSR:n,storeRef:i,dirtyRef:r,renderFnRef:o,cancelRender:s,cleanup:a}=e;Y(()=>{const e=i.current;t&&n&&e?.cancelIntroAnimation?.(),!n&&e?.sceneNodes&&e.sceneNodes.length>0&&e?.markStylePaintPending?e.markStylePaintPending():r.current=!0,s?.(),o.current()},[t,n]);const c=(0,L.useRef)(a);c.current=a,(0,L.useEffect)(()=>()=>c.current?.(),[])}({hydrated:e.hydrated,wasHydratingFromSSR:e.wasHydratingFromSSR,storeRef:e.storeRef,dirtyRef:e.dirtyRef,renderFnRef:e.renderFnRef,cancelRender:e.cancelRender,cleanup:e.cleanup}),(0,_.useEffect)(()=>{if(!1!==r)return i.subscribe(()=>{i.isActive?(n.current=!0,o()):t()})},[t,n,i,r,o]),(0,_.useEffect)(()=>{!c.current&&(c.current=!0,e.skipInitialCanvasPaintInvalidation)||(e.dirtyRef.current=!0,e.scheduleRender())},e.canvasPaintDependencies),{canvasRef:s,interactionCanvasRef:a}}({...t,renderFnRef:e.renderFnRef,scheduleRender:e.scheduleRender,cancelRender:e.cancelRender,frameRuntime:e.frameRuntime})}(It,{hydrated:qt,wasHydratingFromSSR:Ot,storeRef:st,dirtyRef:mt,manageFrameRuntime:!1,skipInitialCanvasPaintInvalidation:!0,canvasPaintDependencies:[s,a,Tt]}),cn=(0,h.useCallback)(()=>{const e=an.current,t=st.current;if(!e||!t)return;const n=yt.current.beforeCompute(t.getLastUpdateResult(),!1),i=function(){if("undefined"==typeof window)return 1;const e=window.devicePixelRatio||1,t=function(){if("undefined"==typeof window)return!1;const e="function"==typeof window.matchMedia&&window.matchMedia("(pointer: coarse)").matches,t=768>Math.min(window.innerWidth||1/0,window.innerHeight||1/0);return e||t}()?2:3;return Math.max(1,Math.min(e,t))}(),r=function(e,t,n,i){const r=e.getContext("2d");if(!r)return null;const o=Math.round(t[0]*i),s=Math.round(t[1]*i),a=o/t[0],c=s/t[1],l=t[0]+"px",d=t[1]+"px";return e.style.width!==l&&(e.style.width=l),e.style.height!==d&&(e.style.height=d),e.width===o&&e.height===s||(e.width=o,e.height=s),r.setTransform(a,0,0,c,0,0),r.translate(n.left,n.top),r}(e,Nt,jt,i);if(!r)return void yt.current.afterCompute(n,!1,!1);const o=function(e){const t=_e(e,Le),n=_e(e,Oe),i=_e(e,Xe),r=_e(e,Ye),o=_e(e,qe),s=_e(e,We),a=_e(e,He),c=_e(e,Ge),l=_e(e,Fe),d=_e(e,ze);return{annotationBackground:Ve(s,.94),annotationStroke:o,annotationText:a,background:s,border:o,closedWindowFill:Ve(n,.08),closedWindowStroke:Ve(n,.55),danger:n,focus:l,grid:d,gutterFill:Ve(c,.14),lateFill:i,openWindowFill:Ve(t,.07),openWindowStroke:Ve(t,.3),primary:t,selectedFill:i,selectedStroke:l,success:r,text:a,textSecondary:c,warning:i}}(r);r.clearRect(-jt.left,-jt.top,Nt[0],Nt[1]),a||"transparent"===s||(r.fillStyle=s??o.background,r.fillRect(-jt.left,-jt.top,Nt[0],Nt[1]));const c=t.snapshot(),l=t.readBodies();if(Vt(l,c.simulationState),sn){const e=Wt.current();if(e-on.current>=100){on.current=e;const t=qn(l);rn(e=>e.length===t.length&&e.every((e,n)=>e.pointId===t[n].pointId&&Math.round(e.x)===Math.round(t[n].x)&&Math.round(e.y)===Math.round(t[n].y))?e:t)}}Ie&&(r.save(),Ie(r,l),r.restore());for(const e of l){const t=Pe.current.get(e.id),n=t?Array.from(t.activeRegionIds).map(e=>Je.get(e)).filter(e=>null!=e):[],i=Mo(e,c.simulationState,f,le,de,yo(t),n,o.primary,o.text,Ae);Se?(r.save(),Se(r,e,i),r.restore()):ho(r,e,i)}je&&(r.save(),je(r,l),r.restore()),function(e,t,n){let i=!1;for(const[r,o]of t){const s=Math.min(1,Math.max(0,(n-o.startedAt)/o.durationMs));if(s>=1){t.delete(r);continue}i=!0;const a=1-Math.pow(1-s,3),{body:c}=o,l=o.scale>0?o.scale:1,d=(o.radius+28*a)*l,u=1-s;e.save(),e.globalAlpha*=u,e.strokeStyle=o.color,e.fillStyle=o.color,e.lineWidth=Math.max(.5,(2.4*u+.4)*l),e.beginPath(),e.arc(c.x,c.y,d,0,2*Math.PI),e.stroke(),e.globalAlpha*=.18,e.beginPath(),e.arc(c.x,c.y,.52*d,0,2*Math.PI),e.fill(),e.restore(),e.save(),e.globalAlpha*=u,e.strokeStyle=o.color,e.lineWidth=Math.max(.5,1.8*l);for(let t=0;8>t;t+=1){const n=t*(Math.PI/4)+1.4*s,i=(o.radius+5+12*a)*l,r=(o.radius+12+34*a)*l;e.beginPath(),e.moveTo(c.x+Math.cos(n)*i,c.y+Math.sin(n)*i),e.lineTo(c.x+Math.cos(n)*r,c.y+Math.sin(n)*r),e.stroke()}e.restore()}}(r,Xt.current,Wt.current()),yt.current.afterCompute(n,!0,!1),mt.current=!1},[an,yt,Nt,jt,a,s,Vt,sn,Ie,je,f,le,de,Ae,Se,Je]),ln=(0,h.useCallback)((e,t)=>{const n=st.current,i=`${he}:${e}:${t??""}`;gt.current!==i&&(gt.current=i,Z?.({execution:e,liveBodies:n?.liveBodyCount()??0,queuedBodies:n?.queueSize()??0,reason:t,requested:he}))},[Z,he]),dn=(0,h.useCallback)((e,t=!0)=>{wt.current+=1,bt.current=!1,kt.current=!1,St.current=!1,Mt.current?.terminate(),Mt.current=null,t&&ln("sync",e)},[ln]),un=(0,h.useCallback)(()=>qt?"undefined"==typeof window||"undefined"==typeof Worker?"worker unavailable":rt?"runtime region effects require sync":ot?"body forces require sync":Te?"physics controllers require sync":function(e){return!e||!e.engine&&Xn(e.sediment)&&(!(t=e.colliders)||t.every(e=>{const t=e.bodyFilter;return!t||"function"!=typeof t}));var t}(ht??{})?Un($)?vt.current?"worker fallback":null:"spawn pacing is not worker-cloneable":"config is not worker-cloneable":"hydrating",[ht,Te,ot,rt,qt,$]),hn=(0,h.useCallback)(()=>{const e=st.current,t=un();if(!e||t)return{reason:t,useWorker:!1};const n=e.liveBodyCount(),i=e.queueSize(),r=function(e,t,n=0,i=Hn){return"sync"!==e&&("worker"===e||t+n>=i)}(he,n,i,Me);return{reason:r?"worker"===he?"forced worker":"body threshold":"below threshold",useWorker:r}},[he,Me,un]),pn=(0,h.useCallback)(e=>{const t=st.current;return t&&e.snapshot?(t.restore(e.snapshot),mt.current=!0,t):t},[]),fn=(0,h.useCallback)((e,t=!0)=>{const n=pn(e);if(!n)return;t&&ie?.(e.result,n.controls()),cn();const i=n.snapshot();!e.result.shouldContinue&&Xt.current.size<=0||i.paused||!i.visible||Ct.current||Tt()},[pn,ie,cn,Ct,Tt]),mn=(0,h.useCallback)(e=>{vt.current=!0,dn("worker failed: "+((e instanceof Error?e.message:e+"")||"unknown error"))},[dn]),yn=(0,h.useCallback)(()=>{const e=st.current;if(!e)return!1;const t=hn();if(!t.useWorker)return bt.current||St.current?dn(t.reason??"sync fallback"):ln("sync",t.reason??"sync"),!1;if(bt.current||St.current)return!0;const n=Mt.current??new Jn;Mt.current=n,St.current=!0;const i=wt.current+1;return wt.current=i,n.initFromSnapshot(ht??{},e.snapshot()).then(e=>{if(wt.current!==i)return;St.current=!1,bt.current=!0,vt.current=!1,pn(e),ln("worker",t.reason??"worker"),cn();const n=st.current?.snapshot();e.result.shouldContinue&&n&&!n.paused&&n.visible&&!Ct.current&&(ft.current=null,Tt())}).catch(e=>{wt.current===i&&mn(e)}),!0},[pn,ht,mn,cn,Ct,ln,Tt,dn,hn]),gn=(0,h.useCallback)(e=>"frame"===e.type||"removed"===e.type?e.frame:null,[]),xn=(0,h.useCallback)((e,t=!0)=>{const n=Mt.current;if(!n||!bt.current)return;const i=wt.current;n.request(e).then(e=>{if(wt.current!==i)return;const n=gn(e);n&&fn(n,t)}).catch(mn)},[fn,gn,mn]),bn=(0,h.useCallback)(()=>{const e=st.current;if(!e)return;const t=yn(),n=e.snapshot(),i=Ue||ot||rt||!!Te;n.paused||!n.visible||!e.hasPendingWork()&&!i||Ct.current?Rt.current():t&&St.current||Tt()},[Te,Ue,ot,rt,Ct,Rt,Tt,yn]),vn=(0,h.useCallback)(()=>{Pt(),At.current=null;const e=st.current;if(!e)return;if(bt.current&&Mt.current){if(kt.current)return;let t=0;if(!Ct.current){const e=Wt.current();t=null!==ft.current?(e-ft.current)/1e3:0,ft.current=e}const n=Mt.current,i=wt.current;return kt.current=!0,void(Ct.current?n.settle():n.tick(t)).then(e=>{kt.current=!1,wt.current===i&&fn(e)}).catch(n=>{if(kt.current=!1,wt.current!==i)return;mn(n);const r=Ct.current?e.settleWithObservations():e.tick(t);ko({store:e,result:r,regionEffects:De.current,regionState:Pe.current,bodyForces:$e.current,composed:Ne.current,onTick:Be.current}),cn()})}let t;if(Ct.current)t=e.settleWithObservations();else{const n=Wt.current(),i=null!==ft.current?(n-ft.current)/1e3:0;ft.current=n,t=e.tick(i)}const n=Ne.current,{regionEffectsApplied:i,bodyForcesApplied:r,snapshot:o}=ko({store:e,result:t,regionEffects:De.current,regionState:Pe.current,bodyForces:$e.current,composed:n,onTick:Be.current});cn(),(Ke.current||t.shouldContinue||i||r||n||Xt.current.size>0)&&!o.paused&&o.visible&&!Ct.current&&Tt()},[fn,mn,cn,Pt,Tt,Ct,At]);Rt.current=vn,(0,h.useEffect)(()=>{vt.current=!1,(bt.current||St.current)&&dn("config changed",!1),st.current?.updateConfig(ht??{}),bn()},[ht,dn]),(0,h.useEffect)(()=>{vt.current=!1,bn()},[qt,he,Me]),function({cancelRender:e,frameRuntime:t,lastFrameTimeRef:n,paused:i,postWorkerCommand:r,requestRender:o,storeRef:s,suspendWhenHidden:a}){const c=(0,Hr.useRef)(r);c.current=r;const l=(0,Hr.useRef)(o);l.current=o,(0,Hr.useEffect)(()=>{const r=s.current;r&&(t.setPaused(i),r.setPaused(i),i&&(n.current=null,e()),c.current({type:"setPaused",paused:i},!1),l.current())},[e,t,i]),(0,Hr.useEffect)(()=>{if(!a){const e=s.current;return t.setVisible(!0),void(e&&!e.snapshot().visible&&(e.setVisible(!0),c.current({type:"setVisible",visible:!0},!1),l.current()))}if("undefined"==typeof document)return;const i=()=>{const i=s.current;if(!i)return;const r=Gr();t.setVisible(r),i.setVisible(r),r||(n.current=null,e()),c.current({type:"setVisible",visible:r},!1),l.current()};return i(),document.addEventListener("visibilitychange",i),()=>document.removeEventListener("visibilitychange",i)},[e,t,a])}({cancelRender:Pt,frameRuntime:Et,lastFrameTimeRef:ft,paused:oe,postWorkerCommand:xn,requestRender:bn,storeRef:st,suspendWhenHidden:ge}),(0,h.useEffect)(()=>()=>dn("unmount",!1),[dn]),(0,h.useEffect)(()=>{cn()},[cn]),(0,h.useImperativeHandle)(t,()=>({...st.current.controls(),applyImpulse:(e,t,n)=>{st.current.applyImpulse(e,t,n),xn({type:"applyImpulse",id:e,ix:t,iy:n}),bn()},clear:()=>{st.current.clear(),Pe.current.clear(),Xt.current.clear(),xn({type:"clear"}),bn()},clearRegionState:e=>{e?Pe.current.delete(e):Pe.current.clear(),bn()},getData:()=>st.current.readBodies(),getRegionState:e=>e?yo(Pe.current.get(e)):function(e){const t={};return e.forEach((e,n)=>{const i=yo(e);i&&(t[n]=i)}),t}(Pe.current),getStore:()=>st.current,pause:()=>{Et.setPaused(!0),ft.current=null,Pt(),st.current.setPaused(!0),xn({type:"setPaused",paused:!0},!1),bn()},push:(e,t)=>{st.current.enqueue(e,t),Un(t)?xn({type:"enqueue",spawns:[e],pacing:t}):(bt.current||St.current)&&dn("spawn pacing is not worker-cloneable"),bn()},pushMany:(e,t)=>{st.current.enqueue(e,t),Un(t)?xn({type:"enqueue",spawns:e,pacing:t}):(bt.current||St.current)&&dn("spawn pacing is not worker-cloneable"),bn()},popBodies:(e,t={})=>{const n=st.current,i=new Map(n.readBodies().map(e=>[e.id,e])),r=n.remove(e),o=Wt.current();for(const e of r){const n=i.get(e);n&&(Pe.current.delete(e),Xt.current.set(e,{body:n,color:t.color??"#f59e0b",durationMs:Math.max(120,t.durationMs??520),radius:t.radius??po(n),scale:null!=t.scale&&t.scale>0?t.scale:1,startedAt:o}),Ht.current===e&&(Ht.current=null,zt(null)),Yt(t=>t?.id===e?null:t))}return r.length&&(xn({type:"remove",ids:r}),bn()),r},remove:e=>{const t=st.current.remove(e);for(const t of e)Pe.current.delete(t);return xn({type:"remove",ids:e}),bn(),t},restore:e=>{st.current.restore(e),Pe.current.clear(),Xt.current.clear(),xn({type:"restore",snapshot:e},!1),bn()},resume:()=>{Et.setPaused(!1),ft.current=null,st.current.setPaused(!1),xn({type:"setPaused",paused:!1},!1),bn()},settle:e=>{const t=st.current.settle(e);return xn({type:"settle",maxSteps:e}),bn(),t},settleWithObservations:e=>{const t=st.current.settleWithObservations(e);return xn({type:"settle",maxSteps:e}),bn(),t},step:e=>{const t=st.current,n=t.tick(e);return ko({store:t,result:n,regionEffects:De.current,regionState:Pe.current,bodyForces:$e.current,composed:Ne.current,onTick:Be.current}),xn({type:"tick",deltaSeconds:e}),cn(),n}}),[Pt,Et,cn,xn,bn,dn]);const wn=ke||!qt&&Ot,kn=["stream-physics-frame",A?"stream-physics-frame--mode-"+A:null,j?"stream-physics-frame--emphasis-"+j:null,y].filter(Boolean).join(" "),Mn=I??("string"==typeof be?be:void 0)??"Physics chart",Sn=xt+"-physics-table",In=Math.max(1,Nt[0]-jt.left-jt.right),jn=Math.max(1,Nt[1]-jt.top-jt.bottom),An=C&&Lt?ve?ve(Lt):(0,Uo.jsx)(Go,{hover:Lt}):null,Cn=An&&Lt?(0,Uo.jsx)(Ee,{x:Lt.x-jt.left,y:Lt.y-jt.top,containerWidth:Math.max(1,Nt[0]-jt.left-jt.right),containerHeight:Math.max(1,Nt[1]-jt.top-jt.bottom),margin:jt,className:"stream-physics-tooltip",children:An}):null;if(wn){const e=st.current??vr(ht,D,$),t="string"==typeof be?be:void 0,{svg:n}=function(e,t={}){const{width:n=640,height:i=360,title:r,description:o,background:s,className:a,idPrefix:c="physics",...l}=t,d=Ar(e,l),u=function(e){const t=e.replace(/[^A-Za-z0-9_-]/g,"_");return!t||/^\d/.test(t)?"physics-"+t:t}(c),h=r?u+"-title":void 0,p=o?u+"-desc":void 0,f=[h,p].filter(Boolean).join(" ")||void 0;return{svg:kr.renderToStaticMarkup((0,Cr.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",className:a??"stream-physics-frame",width:n,height:i,viewBox:`0 0 ${n} ${i}`,role:"img","aria-labelledby":f,children:[r&&(0,Cr.jsx)("title",{id:h,children:r}),o&&(0,Cr.jsx)("desc",{id:p,children:o}),s&&"transparent"!==s?(0,Cr.jsx)("rect",{x:0,y:0,width:n,height:i,fill:s}):null,(0,Cr.jsx)("g",{id:u+"-data-area",children:d.sceneNodes.map((e,t)=>we(e,t,u))})]})),scene:d,evidence:d.evidence}}(e,{width:Nt[0],height:Nt[1],title:t,description:I,background:"transparent"===s?void 0:s,className:"stream-physics-frame__svg",idPrefix:"physics-"+xt});return(0,Uo.jsxs)("div",{ref:Bt,className:kn,"data-semiotic-mode":A,role:"img","aria-label":Mn,style:{width:Nt[0],height:Nt[1]},children:[(0,Uo.jsx)(lo,{summary:ye}),(0,Uo.jsx)("div",{dangerouslySetInnerHTML:{__html:n}})]})}return(0,Uo.jsxs)("div",{ref:Bt,className:kn,"data-semiotic-mode":A,role:"group","aria-label":Mn,"aria-describedby":Ft?_t:void 0,tabIndex:0,style:{position:"relative",width:Nt[0],height:Nt[1]},onKeyDown:tn,children:["production"!==process.env.NODE_ENV&&st.current&&(0,Uo.jsx)(no,{store:st.current,diagnostics:yt.current}),n?(0,Uo.jsx)(uo,{tableId:Sn}):null,n?(0,Uo.jsx)(Vo,{chartTitle:"string"==typeof be?be:Mn,items:it,tableId:Sn}):null,(0,Uo.jsx)(lo,{summary:ye}),(0,Uo.jsx)(ao,{hoverPoint:Lt}),(0,Uo.jsx)("div",{id:_t,"aria-live":"polite","aria-atomic":"true",style:Ao,children:Ft?Ft.description??Ft.label:""}),(0,Uo.jsxs)("div",{role:"img","aria-label":Mn,style:{position:"relative",width:"100%",height:"100%"},children:[(0,Uo.jsx)(U,{size:Nt,margin:jt,children:Dt}),(0,Uo.jsx)("canvas",{ref:an,width:Nt[0],height:Nt[1],"aria-hidden":"true",style:{position:"absolute",left:0,top:0,display:"block"},onPointerDown:en,onPointerMove:C?Jt:void 0,onPointerLeave:C?Zt:void 0}),$t,(0,Uo.jsx)(zn,{width:In,height:jn,totalWidth:Nt[0],totalHeight:Nt[1],margin:jt,title:be,legend:B,legendPosition:O,legendLayout:q,legendHoverBehavior:E,legendClickBehavior:T,legendHighlightedCategory:N,legendIsolatedCategories:W,pointNodes:nn,annotations:i,onAnnotationActivate:r,onObservation:K,chartId:m,chartType:Jo,autoPlaceAnnotations:o,svgAnnotationRules:xe}),(0,Uo.jsx)(Vr,{active:null!=Ft,hoverPoint:Ft?{x:Ft.x,y:Ft.y}:null,margin:jt,size:Nt,shape:Ft?.shape,width:Ft?.width,height:Ft?.height,pathData:Ft?.pathData}),Cn]})]})}));es.displayName="StreamPhysicsFrame";var ts=es;function ns(e){if(null==e)return()=>{};const t="function"==typeof e?e:t=>t[e];return e=>is(t(e))}function is(e){if("number"==typeof e)return Number.isFinite(e)?e:void 0;if("string"==typeof e&&""!==e.trim()){const t=Number(e);return Number.isFinite(t)?t:void 0}}function rs(e,t,n){const i=null!=e.axis?n[e.axis]:null!=e.field?t[e.field]:n.value;if(void 0!==e.eq&&i!==e.eq)return!1;if(void 0!==e.ne&&i===e.ne)return!1;if(void 0!==e.in&&!e.in.includes(i))return!1;if(void 0===e.gt&&void 0===e.gte&&void 0===e.lt&&void 0===e.lte&&void 0===e.within&&void 0===e.outside)return!0;const r=is(i);if(void 0===r)return!1;if(void 0!==e.gt&&e.gt>=r)return!1;if(void 0!==e.gte&&e.gte>r)return!1;if(void 0!==e.lt&&r>=e.lt)return!1;if(void 0!==e.lte&&r>e.lte)return!1;if(void 0!==e.within){const[t,n]=e.within;if(t>r||r>n)return!1}if(void 0!==e.outside){const[t,n]=e.outside;if(r>=t&&n>=r)return!1}return!0}function os(e,t,n){const i=e.when;return void 0===i||!0===i||!1!==i&&("function"==typeof i?i(t,n):rs(i,t,n))}function ss(e,t,n){if(!t||0===t.length)return{};let i={};for(const r of t){if(!os(r,e,n))continue;const t="function"==typeof r.style?r.style(e,n):r.style;t&&(i={...i,...t})}return i}function as(e,t,n,i=e=>e){const r=e??(()=>({}));return t&&0!==t.length?(e,o)=>{const s=i(e),a={...r(e,o)};return Object.assign(a,ss(s,t,n(s,o))),a}:r}function cs(e){const[t,n]=e,i=160>t||116>n,r=i?Math.min(12,Math.max(2,.08*t)):32,o=i?Math.min(8,Math.max(2,.12*n)):24,s=i?o:34;return{width:t,height:n,plot:{x:r,y:o,width:Math.max(1,t-2*r),height:Math.max(1,n-o-s)}}}function ls(e){const t=(e??"")+"";if(!t)return"#4e79a7";const n=["#4e79a7","#59a14f","#e15759","#f28e2b","#76b7b2","#edc948","#b07aa1","#ff9da7"];let i=0;for(let e=0;t.length>e;e+=1)i=31*i+t.charCodeAt(e)>>>0;return n[i%n.length]}function ds(e,t="#4e79a7",n){const i=n?.styleRules,r=!!i&&i.length>0,o=r?ns(n?.valueAccessor):void 0;return n=>{const s=n.datum,a=s&&e?"function"==typeof e?e(s,0):s[e]:void 0,c={fill:null==a?t:ls(a),stroke:"#111827",strokeWidth:1,opacity:.9};return r&&s&&Object.assign(c,ss(s,i,{value:o?o(s):void 0,category:null==a?void 0:a+""})),c}}function us(e,t,n,i){return{fixedDt:1/120,maxSubsteps:8,colliders:t,observation:{chartType:n},kernel:{seed:e,gravity:{x:0,y:760},cellSize:36,collisionIterations:6,velocityDamping:.995,restitution:.08,friction:.4,sleepSpeed:8,sleepAfter:.6,...i}}}function hs(e,t,n){if(!e.length)return[];const i=cs(t),r=i.plot.width/Math.max(1,e.length),o=Math.max(1,...e.map(e=>e.value)),s=.62*i.plot.height,a=i.plot.y+i.plot.height;return e.map((e,t)=>{const c=Math.max(8,e.value/o*s),l=`${n} ${e.label}: ${e.value}${null==e.secondary?"":`, ${e.secondary} secondary`}`;return{id:`${n}-${e.label}`,label:l,description:l,datum:e,x:i.plot.x+(t+.5)*r,y:a-c/2,shape:"rect",width:Math.max(12,.58*r),height:c,group:n}})}function ps(e,t,n){return"function"==typeof n?n(e,t):e[n]}function fs(e){if(e instanceof Date){const t=e.getTime();return Number.isFinite(t)?t:null}const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:null}function ms(e,t,n){return Math.max(t,Math.min(n,e))}function ys(e,t){const n=fs(e);return null!=n&&n>0?n:t}function gs(e){return((e??"unknown")+"").trim().replace(/[^A-Za-z0-9_-]+/g,"_")||"unknown"}function xs(e){let t=e>>>0;return()=>{t+=1831565813;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}var bs=require("d3-scale");function vs(e){const{data:t,valueAccessor:n,bins:i,ballRadius:r,seed:o,size:s,valueExtent:a}=e,c=cs(s),l=t.map((e,t)=>fs(ps(e,t,n))).filter(e=>null!=e),d=function(e){if(!e)return;const t=fs(e[0]),n=fs(e[1]);return null!=t&&null!=n?t>n?[n,t]:[t,n]:void 0}(a),u=d?.[0]??(l.length?Math.min(...l):0),h=d?.[1]??(l.length?Math.max(...l):1),p=h===u?1:h-u,f=(0,bs.scaleLinear)().domain([0,i]).range([c.plot.x,c.plot.x+c.plot.width]),m=Array.from({length:i},()=>0),y=[];t.forEach((e,t)=>{const o=fs(ps(e,t,n));if(null==o)return;const s=Math.max(0,Math.min(i-1,Math.floor((o-u)/p*i)));m[s]+=1,y.push({id:(e.id??"galton-"+t)+"",x:f(s+.5),y:c.plot.y+r+2,vx:8*(t%5-2),vy:0,mass:1,shape:{type:"circle",radius:r},datum:{...e,value:o,bin:s}})});const g=c.plot.y+c.plot.height;return{config:us(o,[...Qi({x:c.plot.x,y:c.plot.y,width:c.plot.width,height:c.plot.height},{idPrefix:"galton",wallThickness:20,floorThickness:20}),...Zi({idPrefix:"galton-bin",count:i,domainStart:0,domainStep:1,xScale:f,yTop:c.plot.y-400,yBottom:g,wallThickness:6})],"GaltonBoardChart"),initialSpawns:y,initialSpawnPacing:{pacing:{ratePerSec:55}},projectionRows:m.map((e,t)=>({label:t+1+"",value:e})),metadata:{kind:"galton-board",bins:i,plot:c.plot,valueExtent:[u,h]}}}var ws=require("d3-scale");function ks(e){const{count:t,idPrefix:n,wallThickness:i,xScale:r,yBottom:o,yTop:s,yTopForIndex:a}=e;return Array.from({length:t+1},(e,t)=>{const c=Math.min(o-1,a?.(t)??s),l=Math.max(1,o-c);return{id:`${n}-wall-${t}`,shape:{type:"aabb",x:r(t),y:c+l/2,width:i,height:l}}})}function Ms(e){const{data:t,timeAccessor:n,arrivalAccessor:i,windows:r,watermark:o,ballRadius:s,seed:a,size:c,timeExtent:l,timeScale:d=1}=e,u=cs(c),h=t.map((e,t)=>fs(ps(e,t,n))).filter(e=>null!=e),p=fs(l?.[0]),f=fs(l?.[1]),m=h.length?Math.min(...h):0,y=h.length?Math.max(...h):m+r.size,g=Math.min(p??m,m),x=Math.max(f??y,y),b=Math.floor(g/r.size)*r.size,v=Math.max(1,Math.ceil((x-b+r.size)/r.size)),w=h.length?Math.max(...h):0,k="function"==typeof o?o(w):fs(o?.value)??w-(o?.delay??r.size),M=Math.max(0,Math.min(v,Array.from({length:v},(e,t)=>t).reduce((e,t)=>b+(t+1)*r.size>k?e:e+1,0))),S=function(e,t){const n=Math.max(5*t,Math.min(92,.13*e.plot.width));return{gutter:{x:e.plot.x,y:e.plot.y,width:n,height:e.plot.height},windowPlot:{x:e.plot.x+n,y:e.plot.y,width:Math.max(40,e.plot.width-n),height:e.plot.height},wallTop:e.plot.y+.48*e.plot.height}}(u,s),I=b+v*r.size,j=(0,ws.scaleLinear)().domain([b,I]).range([S.windowPlot.x,S.windowPlot.x+S.windowPlot.width]),A=Array.from({length:v},()=>({value:0,secondary:0})),C=[];t.forEach((e,t)=>{const o=fs(ps(e,t,n));if(null==o)return;const a=fs(ps(e,t,i))??o,c=Math.max(0,Math.min(v-1,Math.floor((o-b)/r.size))),l=k>=b+(c+1)*r.size;A[c].value+=l?0:1,A[c].secondary+=l?1:0,C.push({id:(e.id??"event-"+t)+"",x:Math.max(S.windowPlot.x+s,Math.min(S.windowPlot.x+S.windowPlot.width-s,j(o))),y:u.plot.y+s+2,vx:8*(t%3-1),vy:0,mass:1,friction:.02,spawnAt:a,shape:{type:"circle",radius:s},datum:{...e,eventTime:o,arrivalTime:a,windowIndex:c,late:l}})});const R=u.plot.y+u.plot.height,P=function(e,t){const n=Math.max(0,Math.min(e.windowCount,e.closedWindowCount));if(!n)return[];const i=e.windowStart,r=e.windowStart+e.windowCount*e.windowSize,o=(0,ws.scaleLinear)().domain([i,r]).range([e.windowPlot.x,e.windowPlot.x+e.windowPlot.width]),s=o(e.windowStart+n*e.windowSize),a=e.windowPlot.x,c=t+Math.max(18,Math.min(.3*e.windowPlot.height,s-a)),l=e=>s===a?t:c+(e-a)/(s-a)*(t-c),d=[];for(let t=0;n>t;t+=1){const n=e.windowStart+t*e.windowSize,i=n+e.windowSize,r=o(n),s=o(i);d.push({id:"eventdrop-lid-"+t,windowIndex:t,x1:r,y1:l(r),x2:s,y2:l(s)})}return d}({closedWindowCount:M,gutter:S.gutter,plot:u.plot,windowCount:v,windowPlot:S.windowPlot,windowSize:r.size,windowStart:b},u.plot.y+.28*u.plot.height);return{config:us(a,[...Qi({x:u.plot.x,y:u.plot.y,width:u.plot.width,height:u.plot.height},{idPrefix:"eventdrop",wallThickness:20,floorThickness:20}),...ks({idPrefix:"eventdrop-window",count:v,xScale:e=>j(b+e*r.size),yTop:S.wallTop,yTopForIndex:e=>{const t=(e=>{if(0>e||e>M)return null;const t=0===e?P[0]?.y1:P[e-1]?.y2??P[e]?.y1;return"number"==typeof t&&Number.isFinite(t)?t:null})(e);return null==t?S.wallTop:t+1.25*s},yBottom:R,wallThickness:6}),...P.map(e=>({id:e.id,shape:{type:"segment",x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2,thickness:Math.max(4,.42*s)},friction:.02,restitution:.01}))],"EventDropChart",{friction:.08}),initialSpawns:C,initialSpawnPacing:{pacing:"arrival",timeAccessor:e=>e.datum?.arrivalTime,timeScale:d},projectionRows:A.map((e,t)=>({label:`${b+t*r.size}-${b+(t+1)*r.size}`,value:e.value,secondary:e.secondary})),metadata:{kind:"event-drop",closedWindowCount:M,gutter:S.gutter,lidSegments:P,lateCount:A.reduce((e,t)=>e+t.secondary,0),plot:u.plot,windowPlot:S.windowPlot,watermarkValue:k,windowCount:v,windowSize:r.size,windowStart:b}}}function Ss(e,t,n){const i=e.width/Math.max(1,t),r=Math.max(2,2*n),o=Math.min(.7*i,Math.max(3.2*r,r+8)),s=Math.max(1,Math.floor(o/r));return{laneWidth:i,tubeWidth:o,ballDiameter:r,perRow:s,centerX:t=>e.x+(t+.5)*i,pileHeight:e=>Math.ceil(Math.max(0,e)/s)*r}}function Is(e){const{data:t,categoryAccessor:n,valueAccessor:i,unitValue:r,ballRadius:o,seed:s,size:a}=e,c=ys(r,1),l=cs(a),d=[],u=new Map,h=new Map,p=[];function f(e){let t=u.get(e);return null==t&&(t=d.length,d.push(e),u.set(e,t)),t}t.forEach((e,t)=>{f((ps(e,t,n)??"unknown")+"")});const m=Math.max(1,d.length),y=Ss(l.plot,m,o),g=Math.max(0,y.tubeWidth/2-o-1),x=d.map(()=>[]);t.forEach((e,t)=>{const r=(ps(e,t,n)??"unknown")+"",s=f(r),a=i?fs(ps(e,t,i)):1,d=Math.max(0,Math.round((a??0)/c)),u=y.centerX(s);for(let n=0;d>n;n+=1){const i=h.get(r)??0,a=y.perRow>1?((y.perRow>1?i%y.perRow:0)/(y.perRow-1)*2-1)*g:0;h.set(r,i+1),x[s].push({id:`${(e.id??"pile-"+t)+""}-${n}`,x:u+a,y:l.plot.y+o+2,vx:(n%3-1)*o/2,vy:0,mass:1,shape:{type:"circle",radius:o},datum:{...e,category:r,unitIndex:n}})}});const b=x.reduce((e,t)=>Math.max(e,t.length),0);for(let e=0;b>e;e+=1)for(const t of x)t.length>e&&p.push(t[e]);const v=l.plot.y+l.plot.height,w=[...Qi({x:l.plot.x,y:l.plot.y,width:l.plot.width,height:l.plot.height},{idPrefix:"pile",wallThickness:20,floorThickness:20})],k=l.plot.y-400;for(let e=0;m>e;e+=1){const t=y.centerX(e);for(const n of[-1,1])w.push({id:`pile-tube-${e}-${0>n?"l":"r"}`,shape:{type:"aabb",x:t+n*y.tubeWidth/2,y:(k+v)/2,width:6,height:v-k}})}return{config:us(s,w,"PhysicsPileChart"),initialSpawns:p,initialSpawnPacing:{pacing:{ratePerSec:20}},projectionRows:d.map(e=>({label:e,value:h.get(e)??0}))}}var js=require("d3-scale");function As(e){const{data:t,xAccessor:n,groupAccessor:i,radiusAccessor:r,pointRadius:o,seed:s,size:a,xExtent:c,collisionIterations:l,settle:d}=e,u=cs(a),h=xs(s),p=[],f=[],m=new Map;t.forEach((e,t)=>{const s=fs(ps(e,t,n));if(null==s)return;const a=i?(ps(e,t,i)??"All")+"":"All",c=r?fs(ps(e,t,r)):null,l=ms(null!=c&&c>0?c:o,2,18);!function(e){let t=m.get(e);null==t&&(t=f.length,f.push(e),m.set(e,t))}(a),p.push({datum:e,index:t,value:s,group:a,radius:l})});const y=p.map(e=>e.value),g=c?fs(c[0]):null,x=c?fs(c[1]):null,b=y.length?Math.min(...y):0,v=y.length?Math.max(...y):1;let w=g??b,k=x??v;if(w===k&&(w-=.5,k+=.5),w>k){const e=k;k=w,w=e}const M=Math.max(o,...p.map(e=>e.radius)),S=u.plot.x+M+8,I=u.plot.x+u.plot.width-M-8,j=(0,js.scaleLinear)().domain([w,k]).range([S,I]),A=Math.max(1,f.length),C=Math.min(Math.max(28,3*M),u.plot.height/4),R=u.plot.y+C,P=Math.max(0,u.plot.y+u.plot.height-C-R),D=e=>{const t=m.get(e)??0;return 1===A?u.plot.y+.54*u.plot.height:R+t/(A-1)*P},$=new Map,B=p.map((e,t)=>{$.set(e.group,($.get(e.group)??0)+1);const n=j(e.value),i=D(e.group),r=(h()-.5)*e.radius*1.6,o=(h()-.5)*e.radius*1.6;return{id:(e.datum.id??"collision-swarm-"+t)+"",x:d?n+r:ms(n+(t%9-4)*e.radius*2.5,S,I),y:d?i+o:u.plot.y-18-t%12*e.radius,vx:d?0:22*(h()-.5),vy:d?0:24+18*h(),mass:1,shape:{type:"circle",radius:e.radius},datum:{...e.datum,xValue:e.value,group:e.group,radius:e.radius,targetX:n,targetY:i},springs:[{target:{type:"point",x:n,y:i},restLength:0,stiffness:34,damping:5.5}]}});return{config:us(s,Qi({x:u.plot.x,y:u.plot.y,width:u.plot.width,height:u.plot.height},{idPrefix:"collision-swarm",includeCeiling:!1,wallThickness:20,floorThickness:20}),"CollisionSwarmChart",{gravity:{x:0,y:0},cellSize:Math.max(24,4*M),collisionIterations:Math.max(1,Math.round(l??6)),velocityDamping:.992,restitution:.02,friction:.18,sleepSpeed:3,sleepAfter:.5}),initialSpawns:B,projectionRows:f.map(e=>({label:e,value:$.get(e)??0})),metadata:{kind:"collision-swarm",xExtent:[w,k],xRange:[S,I],groups:f.map(e=>({label:e,y:D(e),count:$.get(e)??0})),plot:u.plot}}}function Cs(e){if(Array.isArray(e)&&e.length>=2){const t=fs(e[0]),n=fs(e[1]);return null!=t&&null!=n?{x:t,y:n}:null}if(e&&"object"==typeof e){const t=e,n=fs(t.x),i=fs(t.y);return null!=n&&null!=i?{x:n,y:i}:null}return null}function Rs(e){return Array.isArray(e)?e.map(Cs).filter(e=>null!=e):[]}function Ps(e,t,n){return"normalized"===n?{x:t.plot.x+e.x*t.plot.width,y:t.plot.y+e.y*t.plot.height}:{x:ms(e.x,t.plot.x,t.plot.x+t.plot.width),y:ms(e.y,t.plot.y,t.plot.y+t.plot.height)}}function Ds(e){let t=0;for(let n=1;e.length>n;n+=1)t+=Math.hypot(e[n].x-e[n-1].x,e[n].y-e[n-1].y);return t}function $s(e,t){if(0===e.length)return{x:0,y:0};if(1===e.length)return{...e[0]};const n=ms(t,0,1)*Ds(e);let i=0;for(let t=1;e.length>t;t+=1){const r=e[t-1],o=e[t],s=Math.hypot(o.x-r.x,o.y-r.y);if(s>0){if(i+s>=n){const e=(n-i)/s;return{x:r.x+(o.x-r.x)*e,y:r.y+(o.y-r.y)*e}}i+=s}}return{...e[e.length-1]}}function Bs(e,t){const n=$s(e,Math.max(0,t-.02)),i=$s(e,Math.min(1,t+.02)),r=i.x-n.x,o=i.y-n.y,s=Math.hypot(r,o)||1;return{x:r/s,y:o/s}}function Ts(e){const{coordinateMode:t,flowSpeed:n,links:i,maxParticles:r,nodeIdAccessor:o,nodeXAccessor:s,nodeYAccessor:a,nodes:c,particleRadius:l,particleRate:d,pathAccessor:u,pathConstraint:h="path",reducedMotion:p,seed:f,size:m,sourceAccessor:y,targetAccessor:g,throughputAccessor:x}=e,b=cs(m),v=xs(f),w=new Map,k=new Map,M=[];function S(e){if(e&&"object"==typeof e){const t=e;if("function"==typeof o){const e=o(t,0);if(null!=e)return e+""}if("string"==typeof o&&null!=t[o])return t[o]+"";if(null!=t.id)return t.id+""}return(e??"unknown")+""}c.forEach((e,t)=>{const n=(ps(e,t,o)??e.id??t)+"",i=fs(ps(e,t,s)),r=fs(ps(e,t,a));if(null!=i&&null!=r){const e={x:i,y:r};w.set(n,e),M.push(e)}k.set(n,(e.label??e.name??n)+"")});const I=[];i.forEach((e,t)=>{const n=S(ps(e,t,y)),i=S(ps(e,t,g)),r=Math.max(0,fs(ps(e,t,x))??0),o=Rs(u?ps(e,t,u):void 0),s=o.length?o:Rs(e.path??e.points??e.route);s.forEach(e=>M.push(e)),I.push({id:(e.id??`physical-flow-${n}-${i}-${t}`)+"",link:e,index:t,source:n,target:i,throughput:r,rawPath:s})});const j=(C=M,"normalized"===(A=t)||"pixels"===A?A:C.length>0&&C.every(e=>!(0>e.x||e.x>1||0>e.y||e.y>1))?"normalized":"pixels");var A,C;const R=new Map;for(const[e,t]of w)R.set(e,Ps(t,b,j));const P=[];for(const e of I){let t=e.rawPath.map(e=>Ps(e,b,j));if(2>t.length){const n=R.get(e.source),i=R.get(e.target);n&&i&&(t=[n,i])}else R.has(e.source)||R.set(e.source,t[0]),R.has(e.target)||R.set(e.target,t[t.length-1]);t.length>=2&&e.throughput>0&&(k.has(e.source)||k.set(e.source,e.source),k.has(e.target)||k.set(e.target,e.target),P.push({...e,path:t,packetCount:0}))}const D=ys(d,.12),$=Math.max(1,Math.round(r)),B=P.map(e=>Math.max(1,Math.round(e.throughput*D))),T=B.reduce((e,t)=>e+t,0),N=T>$?$/T:1;P.forEach((e,t)=>{e.packetCount=Math.max(1,Math.floor(B[t]*N))});let E=P.reduce((e,t)=>e+t.packetCount,0);for(;E>$;){const e=P.reduce((e,t,n)=>t.packetCount>1&&(-1===e||t.packetCount>P[e].packetCount)?n:e,-1);if(-1===e)break;P[e].packetCount-=1,E-=1}const W=new Map,q=new Map,O=[],F=ys(n,90),z=ys(l,4);P.forEach((e,t)=>{W.set(e.target,(W.get(e.target)??0)+e.throughput),q.set(e.source,(q.get(e.source)??0)+e.throughput);const n=Ds(e.path);for(let i=0;e.packetCount>i;i+=1){const r=(i+.5)/e.packetCount,o=p?r:ms(.12+.84*r+.04*(v()-.5),.04,.98),s=p?o:Math.max(0,o-(.18+.12*v())),a=$s(e.path,s),c=$s(e.path,o),l=Bs(e.path,s),d={x:-l.y,y:l.x},u=(v()-.5)*z*1.5;O.push({id:`${e.id}-packet-${i}`,x:a.x+d.x*u,y:a.y+d.y*u,vx:p?0:l.x*F+10*(v()-.5),vy:p?0:l.y*F+10*(v()-.5),mass:.8,spawnAt:p?0:.04*t+i/32,shape:{type:"circle",radius:z},datum:{...e.link,source:e.source,target:e.target,throughput:e.throughput,packetIndex:i,packetCount:e.packetCount,routeProgress:o,flowPath:e.path,flowPathLength:n,flowRouteId:e.id,flowSpeed:F,sourceLabel:k.get(e.source)??e.source,targetLabel:k.get(e.target)??e.target},springs:"none"!==h&&p?[{target:{type:"point",x:c.x,y:c.y},restLength:.7*z,stiffness:26,damping:4.25}]:void 0})}});const L=Math.max(18,5*z),Y=Array.from(R,([e,t])=>({nodeId:e,label:k.get(e)??e,sensorId:"physical-flow-node-"+gs(e),point:t})),H=Y.map(e=>({id:e.sensorId,sensor:!0,shape:{type:"aabb",x:e.point.x,y:e.point.y,width:L,height:L}})),G=Object.fromEntries(Y.map(e=>[e.sensorId,{binId:e.label,enterType:"physics-proximity-enter",exitType:"physics-proximity-exit"}])),X=us(f,[...Qi({x:b.plot.x,y:b.plot.y,width:b.plot.width,height:b.plot.height},{idPrefix:"physical-flow",wallThickness:18,floorThickness:18}),...H],"PhysicalFlowChart",{gravity:{x:0,y:0},cellSize:Math.max(24,7*z),collisionIterations:3,velocityDamping:.994,restitution:.01,friction:.16,sleepSpeed:2.5,sleepAfter:.7});X.bodyLimit=$,X.eviction="oldest",X.observation={...X.observation,sensors:G};const _=Array.from(R,([e,t])=>({id:e,label:k.get(e)??e,x:t.x,y:t.y,sensorId:"physical-flow-node-"+gs(e),incoming:W.get(e)??0,outgoing:q.get(e)??0})),V=P.map(e=>({id:e.id,source:e.source,target:e.target,sourceLabel:k.get(e.source)??e.source,targetLabel:k.get(e.target)??e.target,throughput:e.throughput,packetCount:e.packetCount,path:e.path}));return{config:X,initialSpawns:O,projectionRows:_.filter(e=>e.incoming>0||e.outgoing>0).map(e=>({label:e.label,value:e.incoming,secondary:e.outgoing})),metadata:{kind:"physical-flow",coordinateMode:j,particleCount:O.length,totalThroughput:P.reduce((e,t)=>e+t.throughput,0),plot:b.plot,nodes:_,links:V}}}function Ns(e,t){if("region-enter"!==t.type)return e;const n=t.region.id,i=e[n]??{id:n,label:t.region.label??n,count:0,bodyIds:[]};if(i.bodyIds.includes(t.bodyId))return e;const r=[...i.bodyIds,t.bodyId];return{...e,[n]:{...i,count:r.length,bodyIds:r}}}function Es(e,t){return(t??Object.keys(e)).map(t=>e[t]).filter(e=>null!=e).map(e=>({label:e.label??e.id,value:e.count}))}function Ws(e,t){const n=t instanceof Set?t:new Set(t);return e.map(e=>{const t=e.bodyIds??[],i=t.filter(e=>!n.has(e)),r=t.length-i.length,o=e.completion?.mode??"allMembersAbsorbed",s=e.completion?.valueByBodyId,a=e=>{const t=s?.[e];return Number.isFinite(t)&&Number(t)>=0?Number(t):1},c=t.reduce((e,t)=>e+a(t),0),l=t.reduce((e,t)=>e+(n.has(t)?a(t):0),0),d=e.completion?.threshold,u="threshold"===o?Number.isFinite(d)&&Number(d)>=0?Number(d):c:void 0;return{id:e.id,label:e.label??e.id,mode:o,complete:t.length>0&&("anyAbsorbed"===o?r>0:"threshold"===o?l>=(u??c):0===i.length),absorbed:r,total:t.length,absorbedValue:l,totalValue:c,threshold:u,missing:i}})}function qs(e,t,n){return Math.max(t,Math.min(n,e))}function Os(e,t,n={}){const i=n.random??Math.random,r=e.stages.find(e=>e.id===t)??e.stages[e.stages.length-1],o=qs(n.along??.5,.05,.95),s=n.jitterX??0,a=n.padY??20,c=r.x0+(r.x1-r.x0)*o+(2*i()-1)*s,l=Math.min(1,r.width/2),d=qs(c,r.x0+l,r.x1-l),u=e.boundaryY(d,"top")+a,h=e.boundaryY(d,"bottom")-a;return{x:d,y:h>u?u+i()*Math.max(1,h-u):e.midY}}function Fs(e){return"bowtie"===e.shape?[{id:"incoming",role:"incoming",points:[[e.left,e.topY],[e.centerLeft,e.pinchTop],[e.centerLeft,e.pinchBottom],[e.left,e.bottomY]]},{id:"center",role:"center",points:[[e.centerLeft,e.pinchTop],[e.centerRight,e.pinchTop],[e.centerRight,e.pinchBottom],[e.centerLeft,e.pinchBottom]]},{id:"outgoing",role:"outgoing",points:[[e.centerRight,e.pinchTop],[e.right,e.topY],[e.right,e.bottomY],[e.centerRight,e.pinchBottom]]}]:[{id:"volume",role:"volume",points:[[e.left,e.topY],[e.right,"funnel"===e.shape?e.pinchTop:e.topY],[e.right,"funnel"===e.shape?e.pinchBottom:e.bottomY],[e.left,e.bottomY]]}]}function zs(e,t,n){return Math.max(t,Math.min(n,e))}function Ls(e,t,n,i,r,o={}){return{id:e,friction:o.friction,restitution:o.restitution,bodyFilter:o.bodyFilter,shape:{type:"segment",x1:t,y1:n,x2:i,y2:r,thickness:o.thickness??8}}}function Ys(e){const t=e.shape??"lane",n=Math.max(1,Math.round(e.width)),i=Math.max(1,Math.round(e.height)),r=e.padX??46,o=e.padY??72,s=r,a=n-r,c=o,l=i-Math.max(24,Math.round(.45*o)),d=(c+l)/2,u=Math.max(1,l-c),h=zs(e.pinchRatio??.18,.06,.5),p=Number(e.pinchHeightOffset??0),f=Number.isFinite(p)?p:0,m=zs(u*h+f,.06*u,.5*u),y=m/2,g=d-y,x=d+y,b=e.idPrefix??"process",v=e.friction??.58,w=e.restitution??.18,k=e.wallThickness??8,M=e.stages;if(!M.length)throw Error("processStageLayout requires at least one stage");const S=zs(e.centerStageIndex??Math.floor(M.length/2),0,M.length-1),I=function(e){const t=e.reduce((e,t)=>e+(t.share??1),0);return t>0?t:e.length}(M),j=a-s;let A=s;const C=M.map((e,t)=>{const n=A,i=t===M.length-1?a:A+(e.share??1)/I*j;return A=i,{id:e.id,label:e.label,description:e.description,kind:e.kind??"stage",index:t,x0:n,x1:i,x:(n+i)/2,width:i-n,y:d,height:u}}),R=C[S],P=R.x0,D=R.x1,$=(e,n)=>{if("lane"===t)return"top"===n?c:l;if("funnel"===t){const t=zs((e-s)/Math.max(1,a-s),0,1);return"top"===n?c+(g-c)*t:l+(x-l)*t}if(P>=e){const t=zs((e-s)/Math.max(1,P-s),0,1);return"top"===n?c+(g-c)*t:l+(x-l)*t}if(D>=e)return"top"===n?g:x;const i=zs((e-D)/Math.max(1,a-D),0,1);return"top"===n?g+(c-g)*i:x+(l-x)*i},B=C.map(e=>{const t=Math.min($(e.x0,"top"),$(e.x1,"top")),n=Math.max($(e.x0,"bottom"),$(e.x1,"bottom"));return{...e,y:(t+n)/2,height:Math.max(1,n-t)}}),T={thickness:k,friction:v,restitution:w},N=[];"lane"===t?N.push(Ls(b+"-top",s,c,a,c,T),Ls(b+"-bottom",s,l,a,l,T),Ls(b+"-left",s,c,s,l,{...T,thickness:Math.max(6,k-2)}),Ls(b+"-right",a,c,a,l,{...T,thickness:Math.max(6,k)})):"funnel"===t?N.push(Ls(b+"-top",s,c,a,g,T),Ls(b+"-bottom",s,l,a,x,T),Ls(b+"-left",s,c,s,l,{...T,thickness:Math.max(6,k-2)}),Ls(b+"-right",a,g,a,x,{...T,thickness:Math.max(6,k)})):N.push(Ls(b+"-left-top",s,c,P,g,T),Ls(b+"-left-bottom",s,l,P,x,T),Ls(b+"-center-top",P,g,D,g,T),Ls(b+"-center-bottom",P,x,D,x,T),Ls(b+"-right-top",D,g,a,c,T),Ls(b+"-right-bottom",D,x,a,l,T),Ls(b+"-left",s,c,s,l,{...T,thickness:Math.max(6,k-2)}),Ls(b+"-right",a,c,a,l,{...T,thickness:Math.max(6,k)}));const E=e.membraneDampingScale??.5,W=s,q=Math.max(1,("bowtie"===t?P:a)-W),O=(e.membranes??[]).map(e=>{const t=W+zs(e.offset,0,1)*q,n=e.width??18+18*e.cost,i=u-16,r=d+.25*(e.wobble??0);return{...e,x:t,y:r,width:n,height:i}}),F=!1===e.includeMembraneRegions?[]:O.map(e=>Xs({id:e.id,label:e.label??e.id,description:e.description??(e.label??e.id)+" is a permeable region. It taxes energy and damps velocity while bodies overlap it.",x:e.x,y:e.y,width:e.width,height:e.height,cost:e.cost,dampingScale:e.dampingScale??E,bodyStyle:e.bodyStyle,metadata:e.metadata,semanticItem:e.semanticItem,color:e.color}));return{shape:t,width:n,height:i,padX:r,padY:o,left:s,right:a,topY:c,bottomY:l,midY:d,centerLeft:P,centerRight:D,pinchHeight:m,pinchTop:g,pinchBottom:x,stages:B,membranes:O,colliders:N,regionEffects:F,boundaryY:$}}function Hs(e){return{id:e.id,label:e.label,description:e.description,kind:e.kind,shape:(t=e.x,n=e.y,i=e.width,r=e.height,{type:"aabb",x:t,y:n,width:i,height:r}),bodyFilter:e.bodyFilter,collider:e.collider,colliderThickness:e.colliderThickness,friction:e.friction,restitution:e.restitution,semanticItem:e.semanticItem,metadata:e.metadata,bodyStyle:e.bodyStyle,attributes:e.attributes,onEnter:e.onEnter,onExit:e.onExit};var t,n,i,r}function Gs(e,t={}){const n=t.idPrefix??"stage",i=Math.max(0,t.insetX??0),r=Math.max(0,t.insetY??1);return e.stages.map(e=>{const o="function"==typeof t.metadata?t.metadata(e):t.metadata??{};return{...Hs({id:n?`${n}:${e.id}`:e.id,label:e.label??e.id,description:e.description,kind:"region",x:e.x,y:e.y,width:Math.max(1,e.width-2*i),height:Math.max(1,e.height-2*r),bodyFilter:t.bodyFilter,semanticItem:t.semanticItem,attributes:{primitive:"processStage",stageId:e.id,stageIndex:e.index},metadata:{...o,primitive:"processStage",stageId:e.id,stageIndex:e.index}})}})}function Xs(e){const t=e.dampingScale??.5,n=e.energyScale??1,i=zs(e.cost,0,2);return{...Hs({...e,kind:e.kind??"membrane",attributes:{primitive:"membrane",membraneCost:i,..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),damping:i*t,energyDelta:-i*n}}function _s(e){return{...Hs({...e,kind:e.kind??"charge-gate",attributes:{primitive:"chargeGate",..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),charge:e.charge??!0,energyDelta:e.energyDelta,impulseOnEnter:e.impulseOnEnter}}function Vs(e){const t="number"==typeof e.force?{x:e.force,y:0}:e.force??{x:12,y:0};return{...Hs({...e,kind:e.kind??"force-field",attributes:{primitive:"routeSurface",..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),force:t,damping:e.damping??.015}}function Us(e){const t=e.pressure??e.occupancy??0,n=e.baseDamping??.08,i=e.dampingPerUnit??.12,r=e.energyPerUnit??0;return{...Hs({...e,kind:e.kind??"membrane",attributes:{primitive:"pressureField",pressure:t,..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),damping:n+t*i,energyDelta:r?-t*r:void 0,force:e.force}}function Ks(e){const t="number"==typeof e.force?{x:e.force,y:0}:e.force;return{...Hs({...e,kind:e.kind??"force-field",attributes:{primitive:"capacitatedSensor",capacity:e.capacity,unitsPerSecond:e.unitsPerSecond??e.capacity,..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),force:t,damping:e.damping,charge:e.charge??e.capacity}}function Qs(e){return{...Hs({...e,kind:e.kind??"force-field",attributes:{primitive:"portal",targetStage:e.targetStage,..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),force:e.force,impulseOnEnter:e.impulseOnEnter,damping:e.damping??.08}}function Zs(e){const t="number"==typeof e.force?{x:e.force,y:0}:e.force??{x:24,y:0};return{...Hs({...e,kind:e.kind??"sink",attributes:{primitive:"absorb",..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),force:t,damping:e.damping??.02,charge:e.charge??"absorbed"}}function Js(e){return{...Hs({...e,kind:e.kind??"force-field",attributes:{primitive:"forceField",..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),force:e.force,damping:e.damping,energyDelta:e.energyDelta}}function ea(e){const t=e.x??e.anchor?.x??0,n=e.y??e.anchor?.y??0;return{id:e.id,label:e.label,description:e.description,group:e.group,bodyIds:e.bodyIds,datum:e.datum,state:e.state,x:t,y:n,width:e.width,height:e.height,anchor:e.anchor??{x:t,y:n},completion:e.completion,tether:e.tether,semanticItem:e.semanticItem}}function ta(e){const t=e.idPrefix??"lane",n={thickness:e.thickness??8,friction:e.friction??.5,restitution:e.restitution??.16},i=[Ls(t+"-top",e.left,e.top,e.right,e.top,n),Ls(t+"-bottom",e.left,e.bottom,e.right,e.bottom,n)];return e.openEnds||i.push(Ls(t+"-left",e.left,e.top,e.left,e.bottom,n),Ls(t+"-right",e.right,e.top,e.right,e.bottom,n)),i}function na(e,t=12){return"number"==typeof e?{x:e,y:0}:e&&"object"==typeof e?{x:Number.isFinite(e.x)?Number(e.x):t,y:Number.isFinite(e.y)?Number(e.y):0}:{x:t,y:0}}function ia(e){const t=e.stages;if(!t.length)throw Error("buildProcessFlowPhysics requires at least one stage");const n=e.size,i=cs(n),r=ms(e.ballRadius??6,2,18),o=e.seed??1,s=xs(o),a=e.idAccessor,c=e.stageAccessor??"stage",l=e.groupBy,d=e.groupLabelAccessor,u=e.workAccessor,h=e.radiusAccessor,p=e.groupCompletion??(l?"allAbsorbed":"none"),f=e.springStiffness??.28,m=e.springDamping??.72,y=!0===e.settle,g=t.map(e=>({id:e.id,label:e.label??e.id,description:e.description,share:e.share})),x=Ys({width:n[0],height:n[1],shape:"lane",padX:Math.max(28,i.plot.x),padY:Math.max(36,i.plot.y+8),stages:g,idPrefix:"process-flow",includeMembraneRegions:!1,friction:.48,restitution:.14}),b=new Map(x.stages.map((e,t)=>[e.id,t])),v=new Map(x.stages.map(e=>[e.id,e])),w=x.stages[0].id,k=x.stages[0],M=new Set(t.filter(e=>e.absorb).map(e=>e.id)),S=t.map(e=>{const t=v.get(e.id)??k;return function(e,t){const n={id:"process-stage-"+e.id,label:e.label??e.id,description:e.description,x:t.x,y:t.y,width:Math.max(12,.92*t.width),height:Math.max(40,.88*t.height),semanticItem:!1,attributes:{stageId:e.id}};if(e.absorb)return Zs({...n,kind:e.kind??"sink",force:na(e.force,28),damping:e.damping??.04,charge:"absorbed",attributes:{...n.attributes,primitive:"absorb"}});if(e.portal){const t=e.portal.force??e.force??{x:-40,y:0};return Qs({...n,kind:e.kind??"force-field",force:na(t,-40),damping:e.damping??.1,targetStage:e.portal.targetStageId,attributes:{...n.attributes,primitive:"portal",targetStage:e.portal.targetStageId}})}if(e.capacity){const t=Math.max(.1,e.capacity.unitsPerSecond);return Ks({...n,kind:e.kind??"force-field",capacity:t,unitsPerSecond:t,force:na(e.force,10+.8*t),damping:e.damping??Math.max(.04,.32-.01*t),attributes:{...n.attributes,unitAccessor:e.capacity.unitAccessor,reviewerCapacity:t}})}if(e.pressure){const t="object"==typeof e.pressure&&e.pressure?e.pressure:{};return Us({...n,kind:e.kind??"membrane",pressure:t.pressure,occupancy:t.occupancy,baseDamping:t.baseDamping??e.damping??.1,dampingPerUnit:t.dampingPerUnit??.1,energyPerUnit:t.energyPerUnit??0,force:na(e.force,8),attributes:{...n.attributes,primitive:"pressureField"}})}return null!=e.force||null!=e.damping?Vs({...n,kind:e.kind??"force-field",force:na(e.force,14),damping:e.damping??.02,attributes:{...n.attributes,primitive:"routeSurface"}}):Js({...n,kind:e.kind??"force-field",force:{x:10,y:0},damping:.02,attributes:{...n.attributes,primitive:"forceField"}})}(e,{x:t.x,y:x.midY,width:t.width,height:x.bottomY-x.topY})});S.unshift(Vs({id:"process-flow-route",label:"process route",description:"Baseline conveyor along the process lane.",x:(x.left+x.right)/2,y:x.midY,width:x.right-x.left,height:x.bottomY-x.topY-12,force:8,damping:.012,semanticItem:!1}));const I=new Map;for(const e of x.stages)I.set(e.id,0);const j=[];e.data.forEach((e,t)=>{const n=(a?ps(e,t,a)??e.id??"process-flow-"+t:e.id??"process-flow-"+t)+"",i=(ps(e,t,c)??w)+"",o=b.has(i)?i:w;I.set(o,(I.get(o)??0)+1);const s=l?(ps(e,t,l)??"")+"":void 0,p=s&&d?(ps(e,t,d)??s)+"":s,f=u?fs(ps(e,t,u))??1:1,m=h?fs(ps(e,t,h)):null,y=ms(null!=m&&m>0?m:r,2,18);j.push({datum:e,id:n,stageId:o,groupId:s||void 0,groupLabel:p||void 0,work:f,radius:y,index:t})});const A=new Map,C=new Map;for(const e of j){if(!e.groupId)continue;const t=A.get(e.groupId)??[];t.push(e.id),A.set(e.groupId,t),e.groupLabel&&C.set(e.groupId,e.groupLabel)}const R=ms(e.groupAnchorAlong??.55,.15,.9),P=x.left+(x.right-x.left)*R,D=Array.from(A.keys()),$=D.map((e,n)=>{const i=A.get(e)??[],r=D.length>1?x.topY+28+n/Math.max(1,D.length-1)*(x.bottomY-x.topY-56):x.midY;return ea({id:e,label:C.get(e)??e,bodyIds:i,anchor:{x:P,y:r},x:P,y:r,completion:"allAbsorbed"===p?{mode:"allMembersAbsorbed",targetZone:t.find(e=>e.absorb)?.id??"merged"}:void 0,tether:{stiffness:.06,visible:!0,restLength:18}})}),B=Ws($,j.filter(e=>M.has(e.stageId)).map(e=>e.id)),T=new Map($.map(e=>[e.id,e])),N=j.map((e,t)=>{const n=v.get(e.stageId)??k,i=n.x+(s()-.5)*Math.min(24,.2*n.width),r=x.boundaryY(i,"top")+e.radius+10,o=x.boundaryY(i,"bottom")-e.radius-10,a=o>r?r+s()*Math.max(1,o-r):x.midY,c=y?i:x.left+18+t%7*4,l=y?a:x.midY+(s()-.5)*(x.bottomY-x.topY)*.35,d=[{target:{type:"point",x:i,y:a},restLength:.45*e.radius,stiffness:f,damping:m}];if(e.groupId){const t=T.get(e.groupId);t?.anchor&&!M.has(e.stageId)&&d.push({target:{type:"point",x:t.anchor.x,y:t.anchor.y},restLength:t.tether?.restLength??22,stiffness:t.tether?.stiffness??.05,damping:.8})}return{id:e.id,x:c,y:l,vx:y?0:40+40*s(),vy:y?0:20*(s()-.5),mass:1,shape:{type:"circle",radius:e.radius},spawnAt:y?0:.03*t,springs:d,datum:{...e.datum,id:e.id,stage:e.stageId,groupId:e.groupId,groupLabel:e.groupLabel,work:e.work,__processFlow:!0}}}),E={kernel:{seed:o,gravity:{x:e.gravityX??22,y:e.gravityY??0},restitution:.14,friction:.48,velocityDamping:.988,maxVelocity:420,sleepSpeed:8,sleepAfter:.9,collisionIterations:4},colliders:x.colliders,fixedDt:1/60,maxSubsteps:8},W=x.stages.map(e=>({label:e.label??e.id,value:I.get(e.id)??0})),q=t.map(e=>{const t=v.get(e.id)??k;return{id:e.id,label:e.label??e.id,x:t.x,width:t.width,count:I.get(e.id)??0,capacity:e.capacity?.unitsPerSecond,absorb:!0===e.absorb,portalTarget:e.portal?.targetStageId}});return{config:E,initialSpawns:N,initialSpawnPacing:y?void 0:{pacing:"arrival",timeAccessor:"spawnAt",timeScale:1},projectionRows:W,metadata:{kind:"process-flow",plot:i.plot,volume:x,stages:q,groups:$,groupCompletion:B,regionEffects:S}}}var ra=require("react");function oa(e,t){if(!t?.length)return[e];const n=t.filter(t=>{if(t.id===e||t.id.startsWith(e+"-"))return!0;const n=t.datum;return!(!n||"object"!=typeof n||null==n.id)&&n.id+""===e}).map(e=>e.id);return n.length?n:[e]}function sa(e,t,n){if("function"==typeof n)return n(e,t)+"";if("string"==typeof n){const t=e[n];if(null!=t)return t+""}return null!=e&&"object"==typeof e&&"id"in e&&null!=e.id?e.id+"":"physics-row-"+t}function aa(e,t){const n=e?.getData().find(e=>e.id===t),i=n?.datum;if(i&&"object"==typeof i)return i}function ca(e,t){const{frameRef:n,spawnDatum:i,seedRows:r,idAccessor:o,bodyIdsForSeed:s,seedSpawns:a}=t,c=(0,ra.useRef)(new Map),l=(0,ra.useRef)(new Map),d=(0,ra.useRef)(""),u=r?r.map((e,t)=>sa(e,t,o)).join("\0"):"";if(u!==d.current&&(d.current=u,r))for(let e=0;r.length>e;e+=1){const t=r[e],n=sa(t,e,o);c.current.set(n,t),l.current.set(n,s?.(t,n,e)??oa(n,a))}(0,ra.useImperativeHandle)(e,()=>{const e=c.current,t=l.current;function r(e,t){const n=i(e,t);return{datumId:n.datumId||sa(e,t,o),spawns:n.spawns.map(e=>({...e,spawnAt:void 0}))}}function s(i){const r=[];for(const{datum:n,result:o}of i)e.set(o.datumId,n),t.set(o.datumId,o.spawns.map(e=>e.id)),r.push(...o.spawns);if(!r.length)return;const o=n.current;o?(o.pushMany(r),o.step(0)):"production"!==process.env.NODE_ENV&&console.warn("[semiotic/physics] push() called before the physics frame mounted (loading/empty early-return). Omit data for push mode and ensure the chart is mounted.")}function a(i){const r=e.get(i);if(r)return r;const o=t.get(i)??[i];for(const r of o){const o=aa(n.current,r);if(o)return e.set(i,o),t.has(i)||t.set(i,[r]),o}}return{push:t=>{s([{datum:t,result:r(t,e.size)}])},pushMany:t=>{const n=e.size;s(t.map((e,t)=>({datum:e,result:r(e,n+t)})))},remove:i=>{const r=Array.isArray(i)?i:[i],o=[],s=[];for(const n of r){const i=a(n);i&&o.push(i),e.delete(n),s.push(...t.get(n)??[n]),t.delete(n)}return s.length&&n.current?.remove(s),o},update:(i,o)=>{const c=Array.isArray(i)?i:[i],l=[];for(const i of c){const c=a(i);if(!c)continue;l.push(c);const d=t.get(i)??[i];n.current?.remove(d),e.delete(i),t.delete(i);const u=o(c);s([{datum:u,result:r(u,e.size)}])}return l},clear:()=>{e.clear(),t.clear(),d.current="",n.current?.clear()},getData:()=>{const t=n.current;if(!t)return Array.from(e.values());const i=t.getData().map(e=>e.datum).filter(e=>!!e&&"object"==typeof e);return i.length?i:Array.from(e.values())},getScales:()=>null,getCustomLayout:()=>n.current?.snapshot()??null,popBodies:(e,t)=>n.current?.popBodies(e,t)??[]}},[n,o,i])}var la=require("react"),da=c(require("react")),ua=require("react/jsx-runtime");function ha({componentName:e,message:t,diagnosticHint:n,width:i,height:r}){return(0,ua.jsx)("div",{role:"alert",style:{width:i,height:Math.max(r,120),display:"flex",alignItems:"center",justifyContent:"center",border:"1px dashed rgba(128, 128, 128, 0.4)",borderRadius:8,background:"rgba(128, 128, 128, 0.04)",padding:24,boxSizing:"border-box"},children:(0,ua.jsxs)("div",{style:{textAlign:"center",maxWidth:400},children:[(0,ua.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"rgba(128, 128, 128, 0.7)",marginBottom:6,fontFamily:"monospace"},children:e}),(0,ua.jsx)("div",{style:{fontSize:14,color:"rgba(128, 128, 128, 0.9)",lineHeight:1.5},children:t}),n&&(0,ua.jsx)("div",{"data-testid":"semiotic-diagnostic-hint",style:{marginTop:10,padding:"8px 12px",background:"rgba(128, 128, 128, 0.06)",borderRadius:4,fontSize:12,color:"rgba(128, 128, 128, 0.8)",fontFamily:"monospace",textAlign:"left",whiteSpace:"pre-wrap",lineHeight:1.6},children:n})]})})}var pa=require("react/jsx-runtime"),fa=class extends da.Component{constructor(e){super(e),this.state={error:null}}static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){this.props.onError?.(e,t)}render(){if(this.state.error){const{fallback:e}=this.props,t=this.state.error;return"function"==typeof e?e(t):void 0!==e?e:(0,pa.jsx)(ha,{componentName:"ChartErrorBoundary",message:t.message||"An unexpected error occurred while rendering this chart.",width:600,height:400})}return this.props.children}},ma=require("react/jsx-runtime");function ya({componentName:e,width:t,height:n,children:i}){return(0,ma.jsx)(fa,{fallback:i=>(0,ma.jsx)(ha,{componentName:e,message:i.message,width:t,height:n}),children:i})}"undefined"!=typeof process&&process;var ga={display:"flex",alignItems:"center",justifyContent:"center",color:"var(--semiotic-text-secondary, #666)",fontSize:13,fontFamily:"inherit",border:"1px dashed var(--semiotic-border, #ddd)",borderRadius:4,boxSizing:"border-box"},xa={background:"var(--semiotic-border, #e0e0e0)",borderRadius:2};function ba(e){return[parseInt(e.slice(1,3),16),parseInt(e.slice(3,5),16),parseInt(e.slice(5,7),16)]}function va(e,t,n){const i=e=>e.toString(16).padStart(2,"0");return`#${i(e)}${i(t)}${i(n)}`}function wa(e){const t=e.map(ba),n=t.length-1;return e=>{if(0>=e){const[e,n,i]=t[0];return va(e,n,i)}if(e>=1){const[e,i,r]=t[n];return va(e,i,r)}const i=e*n,r=Math.floor(i),o=i-r,[s,a,c]=t[r],[l,d,u]=t[r+1];return va(Math.round(s+(l-s)*o),Math.round(a+(d-a)*o),Math.round(c+(u-c)*o))}}require("react"),require("d3-scale");var ka=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],Ma=wa(["#f7fbff","#deebf7","#c6dbef","#9ecae1","#6baed6","#4292c6","#2171b5","#08519c","#08306b"]),Sa=wa(["#fff5f0","#fee0d2","#fcbba1","#fc9272","#fb6a4a","#ef3b2c","#cb181d","#a50f15","#67000d"]),Ia=wa(["#f7fcf5","#e5f5e0","#c7e9c0","#a1d99b","#74c476","#41ab5d","#238b45","#006d2c","#00441b"]),ja=wa(["#fff5eb","#fee6ce","#fdd0a2","#fdae6b","#fd8d3c","#f16913","#d94801","#a63603","#7f2704"]),Aa=wa(["#fcfbfd","#efedf5","#dadaeb","#bcbddc","#9e9ac8","#807dba","#6a51a3","#54278f","#3f007d"]),Ca=wa(["#ffffff","#f0f0f0","#d9d9d9","#bdbdbd","#969696","#737373","#525252","#252525","#000000"]),Ra={blues:Ma,reds:Sa,greens:Ia,viridis:wa(["#440154","#482878","#3e4989","#31688e","#26828e","#1f9e89","#35b779","#6ece58","#b5de2b","#fde725"]),oranges:ja,purples:Aa,greys:Ca,plasma:wa(["#0d0887","#41049d","#6a00a8","#8f0da4","#b12a90","#cb4679","#e16462","#f1844b","#fca636","#fcce25","#f0f921"]),inferno:wa(["#000004","#160b39","#420a68","#6a176e","#932667","#bc3754","#dd513a","#f3771a","#fca50a","#f6d746","#fcffa4"]),magma:wa(["#000004","#140e36","#3b0f70","#641a80","#8c2981","#b73779","#de4968","#f7705c","#fe9f6d","#fecf92","#fcfdbf"]),cividis:wa(["#00224e","#123570","#3b496c","#575d6d","#707173","#8a8678","#a59c74","#c3b369","#e1cc55","#fee838","#ffea46"]),turbo:wa(["#23171b","#4a58dd","#3f9ee9","#46c7af","#7eed5a","#cdf134","#fbb91f","#f56918","#c52f06","#7a0403"])},Pa=(wa(["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#f7f7f7","#d1e5f0","#92c5de","#4393c3","#2166ac","#053061"]),wa(["#8e0152","#c51b7d","#de77ae","#f1b6da","#fde0ef","#f7f7f7","#e6f5d0","#b8e186","#7fbc41","#4d9221","#276419"]),wa(["#40004b","#762a83","#9970ab","#c2a5cf","#e7d4e8","#f7f7f7","#d9f0d3","#a6dba0","#5aae61","#1b7837","#00441b"]),wa(["#543005","#8c510a","#bf812d","#dfc27d","#f6e8c3","#f5f5f5","#c7eae5","#80cdc1","#35978f","#01665e","#003c30"]),wa(["#a50026","#d73027","#f46d43","#fdae61","#fee090","#ffffbf","#e0f3f8","#abd9e9","#74add1","#4575b4","#313695"]),wa(["#a50026","#d73027","#f46d43","#fdae61","#fee08b","#ffffbf","#d9ef8b","#a6d96a","#66bd63","#1a9850","#006837"]),wa(["#9e0142","#d53e4f","#f46d43","#fdae61","#fee08b","#ffffbf","#e6f598","#abdda4","#66c2a5","#3288bd","#5e4fa2"]),{category10:ka,tableau10:["#4e79a7","#f28e2c","#e15759","#76b7b2","#59a14f","#edc949","#af7aa1","#ff9da7","#9c755f","#bab0ab"],set3:["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5","#d9d9d9","#bc80bd","#ccebc5","#ffed6f"],...Ra}),Da=ka;function $a(e,t){if(null==t||!Object.prototype.hasOwnProperty.call(e,t))return;const n=e[t];return"string"==typeof n&&n.length>0?n:void 0}function Ba(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}var Ta={enabled:!0,tapToSelect:!0,tapToLockTooltip:!0,clearSelection:"backgroundTap",targetSize:44,snap:"nearestDatum",brushHandleSize:44,standardControls:!1,enabled:!1,tapToSelect:!1,tapToLockTooltip:!1};function Na(e,t={}){const n=t.mobileSemantics?.interaction,i="number"==typeof n?.targetSize?n.targetSize:"number"==typeof t.mobileSemantics?.minimumHitTarget?t.mobileSemantics.minimumHitTarget:void 0,r="mobile"===t.mode||"number"==typeof t.width&&480>=t.width,o=!!n||void 0!==i,s=e&&"object"==typeof e?e:void 0;if(!1===e||!1===s?.enabled||void 0===e&&!r&&!o)return Ta;const a=s??{};return{enabled:!0,tapToSelect:a.tapToSelect??!0,tapToLockTooltip:a.tapToLockTooltip??!0,clearSelection:a.clearSelection??"backgroundTap",targetSize:a.targetSize??i??44,snap:a.snap??"nearestDatum",brushHandleSize:a.brushHandleSize??44,standardControls:a.standardControls??!1}}var Ea={primary:{width:600,height:400,showAxes:!0,showGrid:!1,enableHover:!0,showLegend:void 0,showLabels:void 0,marginDefaults:{top:50,bottom:60,left:70,right:40}},context:{width:400,height:250,showAxes:!1,showGrid:!1,enableHover:!1,showLegend:!1,showLabels:!1,marginDefaults:{top:10,bottom:10,left:10,right:10}},sparkline:{width:120,height:24,showAxes:!1,showGrid:!1,enableHover:!1,showLegend:!1,showLabels:!1,marginDefaults:{top:2,bottom:2,left:0,right:0}},mobile:{width:390,height:300,showAxes:!0,showGrid:!1,enableHover:!0,showLegend:!1,showLabels:!0,marginDefaults:{top:28,bottom:42,left:44,right:16}}};function Wa(e,t,n){if(!1!==t)return e;const i={...e};return"horizontal"===n?i.left=Math.min(i.left,15):i.bottom=Math.min(i.bottom,15),i}function qa(e,t,n){return function(e,t,n){const i=Ea[e||"primary"],r=e&&"primary"!==e||!n?.width?i.width:n.width,o=e&&"primary"!==e||!n?.height?i.height:n.height,s=function(e,t,n=e.responsiveRules){if(!Array.isArray(n)||0===n.length)return{props:e,matches:[]};const i=n.map((e,t)=>({rule:e,index:t})).filter(e=>function(e,t){const{when:n}=e,i=t.width,r=t.height,o=function(e){if("number"==typeof e.height&&e.height>0)return e.width/e.height}(t),s=function(e){if("number"==typeof e.height&&e.height>0)return e.height>e.width?"portrait":"landscape"}(t);return!("number"==typeof n.minWidth&&n.minWidth>i||"number"==typeof n.maxWidth&&i>n.maxWidth||"number"==typeof n.minHeight&&("number"!=typeof r||n.minHeight>r)||"number"==typeof n.maxHeight&&("number"!=typeof r||r>n.maxHeight)||"number"==typeof n.minAspectRatio&&("number"!=typeof o||n.minAspectRatio>o)||"number"==typeof n.maxAspectRatio&&("number"!=typeof o||o>n.maxAspectRatio)||n.orientation&&s!==n.orientation)}(e.rule,t)).sort((e,t)=>("number"==typeof e.rule.priority?e.rule.priority:e.index)-("number"==typeof t.rule.priority?t.rule.priority:t.index));return{props:i.reduce((e,t)=>function(e,t){const n={...e,...t};for(const i of["margin","frameProps","mobileSemantics","style"])Ba(e[i])&&Ba(t[i])&&(n[i]={...e[i],...t[i]});return"string"==typeof e.className&&"string"==typeof t.className&&(n.className=`${e.className} ${t.className}`),n}(e,t.rule.transform),e),matches:i}}({...t,mode:e},{width:t.width??r,height:t.height??o}).props,a=s.mode||e||"primary",c=Ea[a],l="context"===a||"sparkline"===a,d="primary"===a&&n?.width?n.width:c.width;return{mode:a,width:s.width??d,height:s.height??("primary"===a&&n?.height?n.height:c.height),showAxes:s.showAxes??c.showAxes,showGrid:s.showGrid??c.showGrid,enableHover:s.enableHover??(!!s.linkedHover||c.enableHover),showLegend:s.showLegend??c.showLegend,showLabels:s.showLabels??c.showLabels,title:l?void 0:s.title,description:s.description,summary:s.summary,accessibleTable:s.accessibleTable,xLabel:l?void 0:s.xLabel,yLabel:l?void 0:s.yLabel,categoryLabel:l?void 0:s.categoryLabel,valueLabel:l?void 0:s.valueLabel,marginDefaults:Wa(c.marginDefaults,s.showCategoryTicks,s.orientation),compactMode:l,mobileInteraction:Na(s.mobileInteraction,{mode:a,width:s.width??d,mobileSemantics:s.mobileSemantics}),mobileSemantics:s.mobileSemantics}}(e,t,n)}var Oa=require("react/jsx-runtime"),Fa=new Set(["sample","mechanical"]);function za(e,t,n,i){const[r,o]=(0,la.useState)(0),s=(0,la.useRef)(null),a=(0,la.useRef)(!1),c=function(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0?e:null}(t),l=(0,la.useRef)(c),d=(0,la.useRef)(!!n),u=(0,la.useRef)(i);l.current=c,d.current=!!n,u.current=i;const h=(0,la.useCallback)(()=>{null!=s.current&&(clearTimeout(s.current),s.current=null)},[]),p=(0,la.useCallback)(()=>{h();const e=l.current;null!=e&&!d.current&&a.current&&(s.current=setTimeout(()=>{s.current=null,a.current=!1,u.current?.(),o(e=>e+1)},e))},[h]);(0,la.useEffect)(()=>{null==c||n?h():a.current&&p()},[h,c,n,p]),(0,la.useEffect)(()=>h,[h]);const f=e?.observation?.onSimulationStateChange,m=(0,la.useCallback)((e,t)=>{if(f?.(e,t),"running"===e)return a.current=!1,void h();"settled"===e&&"running"===t&&(a.current=!0,p())},[h,f,p]);return{config:(0,la.useMemo)(()=>null==c?e:{...e,observation:{...e?.observation,onSimulationStateChange:m}},[e,c,m]),rerunKey:r}}function La(e,t,n){const i=n?.hasSimulationMode?function(e){const t=e=>"string"==typeof e&&Fa.has(e);return e.simulationMode?{chartMode:t(e.mode)?void 0:e.mode,simulationMode:e.simulationMode}:t(e.mode)?{chartMode:void 0,simulationMode:e.mode}:{chartMode:e.mode,simulationMode:"sample"}}({mode:e.mode,simulationMode:e.simulationMode}):{chartMode:"sample"===e.mode||"mechanical"===e.mode?void 0:e.mode,simulationMode:"sample"},r=qa(i.chartMode,{width:e.width,height:e.height,enableHover:e.enableHover,title:e.title,description:e.description,summary:e.summary,accessibleTable:e.accessibleTable,mobileInteraction:e.mobileInteraction,mobileSemantics:e.mobileSemantics,responsiveRules:e.responsiveRules},{width:t[0],height:t[1]}),o=e.size?.[0],s=e.size?.[1],a=t[0],c=t[1],l=(0,la.useMemo)(()=>{return e=[a,c],(null!=o&&null!=s?[o,s]:void 0)??[r.width??e[0],r.height??e[1]];var e},[c,a,r.height,r.width,s,o]),d=r.compactMode?"sparkline"===i.chartMode?{top:2,right:2,bottom:2,left:2}:{top:8,right:8,bottom:8,left:8}:{top:0,right:0,bottom:0,left:0};const u=e.showProjection??!r.compactMode,h=e.showChrome??!r.compactMode,p=Xa(e.tooltip,void 0),f=void 0!==p.enableHover?p.enableHover:r.enableHover,m=r.compactMode?r.title:r.title??e.title,y=[e.className,i.chartMode&&"primary"!==i.chartMode?"semiotic-physics--"+i.chartMode:null].filter(Boolean).join(" ")||void 0;return{chartMode:i.chartMode,simulationMode:i.simulationMode,resolved:r,chartSize:l,margin:d,showProjection:u,showChrome:h,enableHover:f,title:m,description:r.description??e.description,summary:r.summary??e.summary,accessibleTable:r.accessibleTable??e.accessibleTable,className:y,compactMode:r.compactMode,mobileInteraction:r.mobileInteraction,mobileSemantics:r.mobileSemantics}}function Ya(e){const[t,n]=e.size,i=function(e,t,n,i){if(!e)return null;if(!1===i)return null;if(null!=i)return(0,ma.jsx)("div",{style:{width:t,height:n,display:"flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box"},children:i});const r=Math.min(5,Math.floor(n/40)),o=Math.max(8,Math.floor(n/(3*r))),s=Math.max(6,Math.floor(n/(2.5*r))),a=Math.floor((n-(r*(o+s)-s))/2);return(0,ma.jsx)("div",{style:{width:t,height:n,position:"relative",overflow:"hidden",border:"1px solid var(--semiotic-border, #e0e0e0)",borderRadius:4,boxSizing:"border-box"},children:Array.from({length:r},(e,n)=>(0,ma.jsx)("div",{className:"semiotic-loading-bar",style:{...xa,position:"absolute",top:a+n*(o+s),left:Math.floor(.1*t),width:30+(37*n+13)%50+"%",height:o,opacity:.5+n%2*.2}},n))})}(e.loading,t,n,e.loadingContent);return i||function(e,t,n,i){return!1===i||null==e||Array.isArray(e)&&e.length>0?null:Array.isArray(e)?(0,ma.jsx)("div",{style:{...ga,width:t,height:n},children:i||"No data available"}):null}(e.data,t,n,e.emptyContent)}function Ha(e,t,n){return(0,Oa.jsx)(ya,{componentName:e,width:t[0],height:t[1],children:n})}function Ga(e,t){return e?t?n=>(0,Oa.jsxs)(Oa.Fragment,{children:["function"==typeof e?e(n):e,"function"==typeof t?t(n):t]}):e:t}function Xa(e,t){return!1===e?{enableHover:!1}:{enableHover:t?.enableHover,tooltipContent:Te(e)||t?.tooltipContent}}function _a(e,t,n,i){return{accessibleTable:i?.accessibleTable??e.accessibleTable??t?.accessibleTable,annotations:e.annotations??t?.annotations,autoPlaceAnnotations:e.autoPlaceAnnotations??t?.autoPlaceAnnotations,background:e.background??t?.background,chartId:e.chartId??t?.chartId,chartMode:i?.chartMode??t?.chartMode,className:i?.className??e.className??t?.className,color:e.color??t?.color,description:i?.description??e.description??t?.description,emphasis:e.emphasis??t?.emphasis,enableHover:i?.enableHover??t?.enableHover,hoverRadius:e.hoverRadius??t?.hoverRadius,legend:e.legend??t?.legend,legendLayout:e.legendLayout??t?.legendLayout,legendPosition:e.legendPosition??t?.legendPosition,margin:i?.margin??t?.margin,onClick:null!=e.onClick?(t,n)=>{t&&e.onClick?.(t,{x:n.x,y:n.y})}:t?.onClick,onObservation:e.onObservation??t?.onObservation,onAnnotationActivate:t?.onAnnotationActivate,opacity:e.opacity??t?.opacity,semanticItems:t?.semanticItems??n,stroke:e.stroke??t?.stroke,strokeWidth:e.strokeWidth??t?.strokeWidth,summary:i?.summary??e.summary??t?.summary,svgAnnotationRules:e.svgAnnotationRules??t?.svgAnnotationRules,title:i?.title??e.title??t?.title}}var Va=require("react/jsx-runtime"),Ua=(0,d.forwardRef)(function(e,t){const{data:n,valueAccessor:i="value",styleRules:r,bins:o=21,ballRadius:s,colorBy:a,branchProbability:c=.5,emptyContent:l,frameProps:u,loading:h,loadingContent:p,mechanicalCount:f,paused:m,pegRows:y,referenceLines:g,rerunMS:x,responsiveHeight:b,responsiveWidth:v,seed:w=1,valueExtent:k}=e,M=La(e,[700,420],{hasSimulationMode:!0}),{chartSize:S,simulationMode:I,showProjection:j,className:A,title:C,chartMode:R,margin:P,enableHover:D,description:$,summary:B,accessibleTable:T}=M,N=s??("sparkline"===R?1.5:"context"===R?4:6),E=(0,d.useRef)(null),W=Math.max(1,Math.round(y??o-1)),q=(0,d.useMemo)(()=>"mechanical"===I?[0,W]:function(e){if(!e)return;const t=Number(e[0]),n=Number(e[1]);return Number.isFinite(t)&&Number.isFinite(n)?t>n?[n,t]:[t,n]:void 0}(k),[W,I,k]),O=(0,d.useMemo)(()=>"mechanical"===I?function(e){const t=Math.max(2,Math.round(e.bins)),n=Math.max(1,Math.round(e.pegRows??t-1)),i=Math.max(1,Math.round(e.count??Math.max(64,4*t))),r=ms(Number.isFinite(e.branchProbability)?e.branchProbability??.5:.5,0,1),o=xs(e.seed??1),s=e.idPrefix??"mechanical";return Array.from({length:i},(e,t)=>{let i=0;for(let e=0;n>e;e+=1)o()<r&&(i+=1);const a=n/2;return{id:`${s}-${t}`,value:i,mechanical:!0,pegRows:n,branchProbability:r,pathRights:i,side:a>i?"left":i>a?"right":"center"}})}({bins:o,branchProbability:c,count:f,pegRows:W,seed:w}):n??[],[o,c,n,f,W,w,I]),F=(0,d.useMemo)(()=>vs({data:O,valueAccessor:i,bins:o,ballRadius:N,seed:w,size:S,valueExtent:q}),[o,O,S,N,q,w,i]),z=za(F.config,x,m);ca(t,{frameRef:E,spawnDatum:(0,d.useCallback)((e,t)=>{const n=vs({data:[e],valueAccessor:i,bins:o,ballRadius:N,seed:w+t+1,size:S,valueExtent:q}).initialSpawns[0]??{id:(e.id??"galton-push-"+t)+"",x:cs(S).plot.x,y:cs(S).plot.y,mass:1,shape:{type:"circle",radius:N},datum:e};return{datumId:(e.id??n.id)+"",spawns:[n]}},[o,S,N,q,w,i]),seedRows:O,seedSpawns:F.initialSpawns});const L="mechanical"===I&&null==a?"side":a,Y=(0,d.useMemo)(()=>ds(L,"#4e79a7",{styleRules:r,valueAccessor:i}),[L,r,i]),H=(0,d.useMemo)(()=>hs(F.projectionRows,S,"bin"),[S,F.projectionRows]),G=Ya({data:"mechanical"===I?O:n,emptyContent:l,loading:h,loadingContent:p,size:S});if(G)return G;const X=function(e,t,n,i,r){const o=Array.isArray(r)?r:r?[r]:[];if(!1!==n||0!==o.length)return({size:r})=>{const s=[Number(r[0])||700,Number(r[1])||420],a=cs(s),c=Math.max(2,Math.round(t)),l=a.plot.width/c,d=a.plot.y+a.plot.height,u=Math.max(1,...e.map(e=>e.value)),h=!1!==n,[p,f]=i?.valueExtent??[0,c],m=f===p?1:f-p,y=e.map((e,t)=>{const n=d-e.value/u*a.plot.height*.9;return`${0===t?"M":"L"} ${(a.plot.x+(t+.5)*l).toFixed(1)} ${n.toFixed(1)}`}).join(" ");return(0,Va.jsxs)("svg",{"aria-hidden":"true","data-testid":"galton-board-structure-overlay",width:s[0],height:s[1],viewBox:`0 0 ${s[0]} ${s[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[h?(0,Va.jsxs)(Va.Fragment,{children:[Array.from({length:c+1},(e,t)=>{const n=a.plot.x+t*l;return(0,Va.jsx)("line",{"data-testid":"galton-board-bin-wall",x1:n,x2:n,y1:a.plot.y,y2:d,stroke:"var(--semiotic-border, #d1d5db)",strokeOpacity:.28,strokeWidth:1},"bin-wall-"+t)}),(0,Va.jsx)("line",{x1:a.plot.x,x2:a.plot.x+a.plot.width,y1:d,y2:d,stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:1.5}),(0,Va.jsx)("path",{d:y,fill:"none",stroke:"var(--semiotic-accent, #4e79a7)",strokeOpacity:.7,strokeWidth:2,strokeLinejoin:"round"}),e.map((e,t)=>e.value>0?(0,Va.jsx)("text",{x:a.plot.x+(t+.5)*l,y:Math.max(a.plot.y+10,d-e.value/u*a.plot.height*.9-6),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:e.value},`${e.label}-${t}`):null)]}):null,o.map((e,t)=>{const n=Number(e.value);if(!Number.isFinite(n))return null;const i=a.plot.x+Math.max(0,Math.min(1,(n-p)/m))*a.plot.width,r=e.color??"var(--semiotic-warning, #f28e2b)",o="bottom"===e.labelPosition?Math.min(s[1]-8,d+16):a.plot.y+16;return(0,Va.jsxs)("g",{className:e.className,"data-testid":"galton-board-reference-line",children:[(0,Va.jsx)("line",{x1:i,x2:i,y1:a.plot.y+8,y2:d-4,stroke:r,strokeDasharray:e.strokeDasharray??"6 5",strokeWidth:e.strokeWidth??2}),null==e.label?null:(0,Va.jsx)("text",{x:Math.min(a.plot.x+a.plot.width-4,i+6),y:o,fill:r,fontSize:10,fontWeight:700,children:e.label})]},`galton-reference-${t}-${n}`)})]})}}(F.projectionRows,o,j,F.metadata,g),_=Xa(e.tooltip,u),V=_a(e,u,H,{chartMode:R,className:A,title:C,description:$,summary:B,accessibleTable:T,enableHover:D,margin:P});return Ha("GaltonBoardChart",S,(0,Va.jsx)(ts,{...u,..._,...V,ref:E,config:z.config,foregroundGraphics:Ga(X,u?.foregroundGraphics),initialSpawns:F.initialSpawns,initialSpawnPacing:F.initialSpawnPacing,paused:m,responsiveHeight:b,responsiveWidth:v,size:S,bodyStyle:Y},z.rerunKey))}),Ka=require("react"),Qa=require("react/jsx-runtime"),Za=(0,Ka.forwardRef)(function(e,t){const{arrivalAccessor:n="arrivalTime",ballRadius:i=7,colorBy:r,styleRules:o,data:s,emptyContent:a,frameProps:c,loading:l,loadingContent:d,paused:u,responsiveHeight:h,responsiveWidth:p,seed:f=1,timeAccessor:m="time",timeExtent:y,timeScale:g=1,watermark:x,windows:b={size:10}}=e,v=La(e,[760,360]),{chartSize:w,showProjection:k,className:M,title:S,chartMode:I,margin:j,enableHover:A,description:C,summary:R,accessibleTable:P}=v,D=(0,Ka.useRef)(null),$=(0,Ka.useMemo)(()=>s??[],[s]),B=(0,Ka.useMemo)(()=>Ms({data:$,timeAccessor:m,arrivalAccessor:n,windows:b,watermark:x,ballRadius:i,seed:f,size:w,timeExtent:y,timeScale:g}),[n,i,w,$,f,m,y,g,x,b]),T=B.metadata;ca(t,{frameRef:D,spawnDatum:(0,Ka.useCallback)((e,t)=>{const r=T?function(e,t,n,i){const r=fs(ps(e,t,i.timeAccessor));if(null==r)return null;const o=fs(ps(e,t,i.arrivalAccessor))??r,{windowPlot:s,windowStart:a,windowCount:c,windowSize:l,watermarkValue:d}=n,u=a+c*l,h=(0,ws.scaleLinear)().domain([a,u]).range([s.x,s.x+s.width]),p=Math.max(0,Math.min(c-1,Math.floor((r-a)/l))),f=d>=a+(p+1)*l,{ballRadius:m}=i;return{id:(e.id??"event-push-"+t)+"",x:Math.max(s.x+m,Math.min(s.x+s.width-m,h(r))),y:s.y+m+2,vx:8*(t%3-1),vy:0,mass:1,friction:.02,shape:{type:"circle",radius:m},datum:{...e,eventTime:r,arrivalTime:o,windowIndex:p,late:f}}}(e,t,T,{timeAccessor:m,arrivalAccessor:n,ballRadius:i}):null,o=r??{id:(e.id??"event-push-"+t)+"",x:cs(w).plot.x,y:cs(w).plot.y,mass:1,shape:{type:"circle",radius:i},datum:e};return{datumId:(e.id??o.id)+"",spawns:[o]}},[n,i,w,T,m]),seedRows:$,seedSpawns:B.initialSpawns});const N=(0,Ka.useMemo)(()=>ds(r,"#4e79a7",{styleRules:o,valueAccessor:m}),[r,o,m]),E=(0,Ka.useMemo)(()=>function(e,t,n){if(!t)return hs(e,n,"window");const i=t.windowPlot.width/Math.max(1,e.length),r=Math.max(1,...e.map(e=>e.value+(e.secondary??0))),o=.62*t.windowPlot.height,s=t.windowPlot.y+t.windowPlot.height;return e.map((e,n)=>{const a=Math.max(8,(e.value+(e.secondary??0))/r*o),c=`window ${e.label}: ${e.value} on time${e.secondary?`, ${e.secondary} late`:""}`;return{id:"window-"+e.label,label:c,description:c,datum:e,x:t.windowPlot.x+(n+.5)*i,y:s-a/2,shape:"rect",width:Math.max(12,.58*i),height:a,group:"window"}})}(B.projectionRows,T,w),[w,B.projectionRows,T]),W=Ya({data:s,emptyContent:a,loading:l,loadingContent:d,size:w});if(W)return W;const q=function(e,t,n){if(!1!==n&&t)return({size:n})=>{const i=[Number(n[0])||760,Number(n[1])||360],r=cs(i),o=Math.max(1,t.windowCount),s=t.plot??r.plot,a=t.gutter??{x:s.x,y:s.y,width:0,height:s.height},c=t.windowPlot??s,l=c.width/o,d=s.y+s.height,u=s.y+.48*s.height,h=t.lidSegments[0]?.y1??u,p=t.windowStart,f=t.windowStart+o*t.windowSize,m=c.x+Math.max(0,Math.min(1,f===p?0:(t.watermarkValue-p)/(f-p)))*c.width;return(0,Qa.jsxs)("svg",{"aria-hidden":"true","data-testid":"event-drop-window-overlay",width:i[0],height:i[1],viewBox:`0 0 ${i[0]} ${i[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[(0,Qa.jsx)("rect",{x:s.x,y:s.y,width:s.width,height:s.height,fill:"none",stroke:"var(--semiotic-border, #d1d5db)",strokeOpacity:.7,strokeWidth:1}),a.width>0?(0,Qa.jsxs)("g",{children:[(0,Qa.jsx)("rect",{x:a.x,y:h,width:a.width,height:d-h,fill:"var(--semiotic-negative, #e15759)",fillOpacity:.07,stroke:"var(--semiotic-border, #d1d5db)",strokeOpacity:.55,strokeWidth:1}),(0,Qa.jsx)("text",{x:a.x+a.width/2,y:h-8,textAnchor:"middle",fill:"var(--semiotic-negative, #e15759)",fontSize:10,fontWeight:700,children:"gutter"})]}):null,Array.from({length:o},(n,r)=>{const o=e[r],s=c.x+r*l,a=t.closedWindowCount>r,h=o?.secondary??0;return(0,Qa.jsxs)("g",{children:[(0,Qa.jsx)("rect",{x:s,y:u,width:l,height:d-u,fill:a?"var(--semiotic-negative, #e15759)":"var(--semiotic-accent, #4e79a7)",fillOpacity:a?.08:.06,stroke:"var(--semiotic-border, #d1d5db)",strokeOpacity:.68,strokeWidth:1}),a?t.lidSegments.filter(e=>e.windowIndex===r).map(e=>(0,Qa.jsx)("line",{x1:e.x1,x2:e.x2,y1:e.y1,y2:e.y2,stroke:"var(--semiotic-negative, #e15759)",strokeOpacity:.78,strokeWidth:2,strokeLinecap:"round"},e.id)):null,(0,Qa.jsxs)("text",{x:s+l/2,y:u-8,textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:[o?.value??0,h?` / ${h} late`:""]}),(0,Qa.jsx)("text",{x:s+l/2,y:Math.min(i[1]-8,d+16),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:o?.label??""})]},"window-"+r)}),t.lidSegments.filter(e=>null==e.windowIndex).map(e=>(0,Qa.jsx)("line",{x1:e.x1,x2:e.x2,y1:e.y1,y2:e.y2,stroke:"var(--semiotic-negative, #e15759)",strokeOpacity:.62,strokeWidth:2,strokeLinecap:"round"},e.id)),(0,Qa.jsx)("line",{x1:s.x,x2:s.x+s.width,y1:d,y2:d,stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:1.5}),(0,Qa.jsx)("line",{"data-testid":"event-drop-watermark",x1:m,x2:m,y1:s.y+8,y2:d,stroke:"var(--semiotic-warning, #f28e2b)",strokeDasharray:"5 4",strokeWidth:2}),(0,Qa.jsxs)("text",{x:Math.min(s.x+s.width-4,m+6),y:s.y+16,fill:"var(--semiotic-warning, #f28e2b)",fontSize:10,fontWeight:700,children:["watermark ",Math.round(100*t.watermarkValue)/100]}),t.lateCount>0?(0,Qa.jsxs)("text",{x:a.x+a.width/2,y:s.y+32,textAnchor:"middle",fill:"var(--semiotic-negative, #e15759)",fontSize:10,fontWeight:700,children:[t.lateCount," late"]}):null]})}}(B.projectionRows,B.metadata,k),O=Xa(e.tooltip,c),F=_a(e,c,E,{chartMode:I,className:M,title:S,description:C,summary:R,accessibleTable:P,enableHover:A,margin:j});return Ha("EventDropChart",w,(0,Qa.jsx)(ts,{...c,...O,...F,ref:D,config:B.config,foregroundGraphics:Ga(q,c?.foregroundGraphics),initialSpawns:B.initialSpawns,initialSpawnPacing:B.initialSpawnPacing,paused:u,responsiveHeight:h,responsiveWidth:p,size:w,bodyStyle:N}))}),Ja=require("react"),ec=require("react/jsx-runtime"),tc=(0,Ja.forwardRef)(function(e,t){const{ballRadius:n=8,categoryAccessor:i="category",colorBy:r,data:o,emptyContent:s,frameProps:a,loading:c,loadingContent:l,mechanicalCategories:d,mechanicalCount:u,paused:h,responsiveHeight:p,responsiveWidth:f,seed:m=1,unitValue:y=1,valueAccessor:g,styleRules:x}=e,b=La(e,[700,380],{hasSimulationMode:!0}),{chartSize:v,simulationMode:w,showProjection:k,className:M,title:S,chartMode:I,margin:j,enableHover:A,description:C,summary:R,accessibleTable:P}=b,D=(0,Ja.useRef)(null),$="mechanical"===w&&null==g?"value":g,B=(0,Ja.useMemo)(()=>"mechanical"===w?function(e={}){const t=(e.categories?.length?e.categories:["Intake","Review","Build","Ship"]).map(e=>(e+"").trim()).filter(Boolean),n=t.length?t:["Intake"],i=Math.max(n.length,Math.round(e.count??Math.max(48,12*n.length))),r=ys(e.unitValue,1),o=xs(e.seed??1),s=e.idPrefix??"mechanical-pile",a=n.map(()=>.65+.9*o()),c=a.reduce((e,t)=>e+t,0)||1,l=i-n.length,d=a.map(e=>e/c*l),u=d.map(e=>1+Math.floor(e));let h=i-u.reduce((e,t)=>e+t,0);const p=d.map((e,t)=>({index:t,fraction:e-Math.floor(e)})).sort((e,t)=>t.fraction-e.fraction);for(let e=0;h>0;e=(e+1)%p.length)u[p[e].index]+=1,h-=1;return n.map((e,t)=>({id:`${s}-${t}`,category:e,value:u[t]*r,mechanical:!0,unitCount:u[t],unitValue:r,share:u[t]/i}))}({categories:d,count:u,seed:m,unitValue:y}):o??[],[o,d,u,m,w,y]),T=(0,Ja.useMemo)(()=>Is({data:B,categoryAccessor:i,valueAccessor:$,unitValue:y,ballRadius:n,seed:m,size:v}),[n,i,v,B,$,m,y]);ca(t,{frameRef:D,spawnDatum:(0,Ja.useCallback)((e,t)=>{const r=Is({data:[e],categoryAccessor:i,valueAccessor:$,unitValue:y,ballRadius:n,seed:m+t+1,size:v}),o={id:(e.id??"pile-push-"+t)+"",x:cs(v).plot.x,y:cs(v).plot.y,mass:1,shape:{type:"circle",radius:n},datum:e},s=r.initialSpawns.length?r.initialSpawns:[o];return{datumId:(e.id??s[0].id)+"",spawns:s}},[n,i,v,$,m,y]),seedRows:B,seedSpawns:T.initialSpawns});const N="mechanical"===w&&null==r?"category":r,E=(0,Ja.useMemo)(()=>ds(N,"#4e79a7",{styleRules:x,valueAccessor:g}),[N,x,g]),W=(0,Ja.useMemo)(()=>hs(T.projectionRows,v,"category"),[v,T.projectionRows]),q=Ya({data:"mechanical"===w?B:o,emptyContent:s,loading:c,loadingContent:l,size:v});if(q)return q;const O=function(e,t,n){if(!1!==n&&0!==e.length)return({size:n})=>{const i=[Number(n[0])||700,Number(n[1])||380],r=cs(i),o=Ss(r.plot,e.length,t),s=r.plot.y+r.plot.height;return(0,ec.jsxs)("svg",{"aria-hidden":"true","data-testid":"physics-pile-projection-overlay",width:i[0],height:i[1],viewBox:`0 0 ${i[0]} ${i[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[(0,ec.jsx)("line",{x1:r.plot.x,x2:r.plot.x+r.plot.width,y1:s,y2:s,stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:1}),e.map((e,t)=>{const n=Math.min(r.plot.height,o.pileHeight(e.value)),a=o.tubeWidth,c=o.centerX(t),l=s-n;return(0,ec.jsxs)("g",{children:[(0,ec.jsx)("rect",{x:c-a/2,y:l,width:a,height:n,rx:3,fill:"var(--semiotic-accent, #4e79a7)",fillOpacity:.08,stroke:"var(--semiotic-accent, #4e79a7)",strokeOpacity:.42,strokeWidth:1,strokeDasharray:"4 3"}),(0,ec.jsx)("text",{x:c,y:Math.max(r.plot.y+12,l-6),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:11,fontWeight:700,children:e.value}),(0,ec.jsx)("text",{x:c,y:Math.min(i[1]-8,s+16),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:e.label})]},`${e.label}-${t}`)})]})}}(T.projectionRows,n,k),F=Xa(e.tooltip,a),z=_a(e,a,W,{chartMode:I,className:M,title:S,description:C,summary:R,accessibleTable:P,enableHover:A,margin:j});return Ha("PhysicsPileChart",v,(0,ec.jsx)(ts,{...a,...F,...z,ref:D,config:T.config,foregroundGraphics:Ga(O,a?.foregroundGraphics),initialSpawns:T.initialSpawns,initialSpawnPacing:T.initialSpawnPacing,paused:h,responsiveHeight:p,responsiveWidth:f,size:v,bodyStyle:E}))}),nc=require("react"),ic=Object.freeze([]);function rc(e){if(!e)return ic;let t=!1;for(let n=0;e.length>n;n++){const i=e[n];if(null==i||"object"!=typeof i){t=!0;break}}if(!t)return e;const n=[];for(const t of e)null!=t&&"object"==typeof t&&n.push(t);return n}var oc=require("d3-scale");function sc(e,t){const n=t&&"object"==typeof t&&!Array.isArray(t)?t:void 0;return 0===e.length?e=>n&&$a(n,e)||"#4e79a7":t=>{if(n){const e=$a(n,t);if(e)return e}let i=0;for(let e=0;t.length>e;e++)i=31*i+t.charCodeAt(e)|0;return e[Math.abs(i)%e.length]??"#4e79a7"}}function ac(e,t){const n=t.config??{},i=(t.sensors??[]).map(e=>({...e,sensor:!0})),r=[...t.colliders??[],...i],o=[...e.colliders??[],...n.colliders??[],...r];return{...e,...n,observation:{...e.observation,...n.observation},...o.length>0&&{colliders:o}}}function cc(e){const t=function(e,t,n){const i=e?.observation;return{...e,observation:{...i,chartId:t??i?.chartId??"physics-custom",chartType:i?.chartType??"PhysicsCustomChart",onObservation:n??i?.onObservation}}}(e.config,e.chartId,e.onObservation),n=function(e,t,n=Da){if(e&&"object"==typeof e&&!Array.isArray(e)){const t=Object.values(e).filter(e=>"string"==typeof e&&e.length>0);if(t.length>0)return t}if(Array.isArray(e)&&e.length>0)return e;if("string"==typeof e){const t=Pa[e];if(Array.isArray(t)&&t.length>0)return t}return t&&t.length>0?t:n}(e.colorScheme,e.themeCategorical,ka),i=cs(e.size),r={data:e.data,scales:{x:(0,oc.scaleLinear)().domain(e.xExtent??[0,1]).range([i.plot.x,i.plot.x+i.plot.width]),y:(0,oc.scaleLinear)().domain(e.yExtent??[0,1]).range([i.plot.y+i.plot.height,i.plot.y])},dimensions:i,theme:{semantic:e.semantic,categorical:[...n]},resolveColor:sc(n,e.colorScheme),config:e.layoutConfig??{},world:new br(t)},o=e.skipLayout?{}:e.layout(r)??{},s=function(e,t){if(!t?.length)return e;const n=new Map;for(const e of t){const{bodyId:t,...i}=e,r=n.get(t)??[];r.push(i),n.set(t,r)}return e.map(e=>{const t=n.get(e.id);return t?.length?{...e,springs:[...e.springs??[],...t]}:e})}([...o.initialSpawns??o.bodies??[]],o.constraints);return{config:ac(t,o),context:r,initialSpawnPacing:o.initialSpawnPacing,initialSpawns:s,result:o}}var lc=require("react/jsx-runtime"),dc=(0,nc.forwardRef)(function(e,t){const{chartId:n,color:i,colorBy:r,colorScheme:o,config:s,controllers:a,data:c,emptyContent:l,frameProps:d={},layout:u,layoutConfig:h,loading:p,loadingContent:f,onObservation:m,opacity:y,paused:g,spawnDatum:x,stroke:b,strokeWidth:v,title:k,xExtent:M,yExtent:S}=e,I=La(e,[700,380]),{chartSize:A,className:C,title:R,chartMode:P,margin:D,enableHover:$,description:B,summary:T,accessibleTable:N}=I,E=(0,nc.useRef)(null),W=(0,nc.useRef)(null),q=(0,nc.useRef)(""),O=Ya({data:c,emptyContent:l,loading:p,loadingContent:f,size:A}),F=null!=O,z=(0,nc.useMemo)(()=>rc(c??[]),[c]),L=j(e=>e.theme),Y=(0,nc.useMemo)(()=>function(e){if(!e?.colors)return;const t=e.colors;return{primary:t.primary,secondary:t.secondary||t.primary,surface:t.surface||t.background,success:t.success,danger:t.danger,warning:t.warning,error:t.error,info:t.info,text:t.text,textSecondary:t.textSecondary,border:t.border,grid:t.grid}}(L)??{},[L]),H=L?.colors?.categorical??w.colors.categorical,G=(0,nc.useMemo)(()=>[A[0],A[1],z.length,z.map((e,t)=>(e.id??t)+"").join("|"),M?.join(",")??"",S?.join(",")??""].join("::"),[A,z,M,S]),X=(0,nc.useMemo)(()=>cc({chartId:n,colorScheme:o,config:s,data:z,layout:u,layoutConfig:h,onObservation:m,semantic:Y,skipLayout:F,size:A,themeCategorical:H,xExtent:M,yExtent:S}),[n,A,o,s,u,h,m,z,Y,F,H,M,S]);q.current===G&&null!=W.current||(q.current=G,W.current=X.initialSpawns);const _=W.current,V=(0,nc.useMemo)(()=>{const e=[...X.result.controllers??[],...a??[],...d.controllers??[]];return e.length?e:void 0},[d.controllers,a,X.result.controllers]),U=(0,nc.useMemo)(()=>{const e=[...X.result.regionEffects??[],...d.regionEffects??[]];return e.length?e:void 0},[d.regionEffects,X.result.regionEffects]),K=(0,nc.useCallback)(e=>{const t=e.datum,n=t&&r?function(e,t,n){return"function"==typeof n?n(e,0):e[n]}(t,0,r)+"":e.id;return{fill:i??X.context.resolveColor(n,t),stroke:b??"#111827",strokeWidth:v??1,opacity:y??.9}},[i,r,y,X.context,b,v]);ca(t,{frameRef:E,spawnDatum:(0,nc.useCallback)((e,t)=>{const i=e;if(x)return function(e,t,n){return Array.isArray(n)?{datumId:(e.id??n[0]?.id??"physics-custom-"+t)+"",spawns:n}:"spawns"in n?n:{datumId:(e.id??n.id??"physics-custom-"+t)+"",spawns:[n]}}(e,t,x(i,t,X.context));const r=cc({chartId:n,colorScheme:o,config:s,data:[i],layout:u,layoutConfig:h,onObservation:m,semantic:Y,size:A,themeCategorical:H,xExtent:M,yExtent:S}),a=r.initialSpawns.length?r.initialSpawns:[{id:(e.id??"physics-custom-"+t)+"",x:r.context.dimensions.plot.x+r.context.dimensions.plot.width/2,y:r.context.dimensions.plot.y+12,mass:1,shape:{type:"circle",radius:5},datum:e}];return{datumId:(e.id??a[0].id)+"",spawns:a}},[n,A,o,s,x,u,h,m,X.context,Y,H,M,S]),seedRows:z,seedSpawns:_});const Q=(0,nc.useCallback)((e,t)=>{d.onBodyPointerDown?.(e,t)},[d]);if(O)return O;const Z=Xa(e.tooltip,d),J=_a(e,d,X.result.semanticItems,{chartMode:P,className:C,title:R??k,description:B,summary:T,accessibleTable:N,enableHover:$,margin:D});return Ha("PhysicsCustomChart",A,(0,lc.jsx)(ts,{...d,...Z,...J,ref:E,backgroundGraphics:Ga(d.backgroundGraphics,X.result.backgroundOverlays),bodyForces:X.result.bodyForces??d.bodyForces,bodyStyle:X.result.bodyStyle??d.bodyStyle??K,config:X.config,controllers:V,foregroundGraphics:Ga(d.foregroundGraphics,X.result.overlays),initialSpawnPacing:X.initialSpawnPacing,initialSpawns:_,onBodyPointerDown:Q,paused:g,regionEffects:U,responsiveHeight:e.responsiveHeight,responsiveWidth:e.responsiveWidth,selectedBodyStyle:X.result.selectedBodyStyle??d.selectedBodyStyle,size:A}))});dc.displayName="PhysicsCustomChart";var uc=require("react"),hc=require("react/jsx-runtime");function pc(e){return e.toLocaleString(void 0,Math.abs(e)>=1e3||.01>Math.abs(e)?{maximumFractionDigits:0}:{maximumFractionDigits:2})}var fc=(0,uc.forwardRef)(function(e,t){const{colorBy:n,styleRules:i,collisionIterations:r,data:o,emptyContent:s,frameProps:a,groupAccessor:c,loading:l,loadingContent:d,paused:u,pointRadius:h,radiusAccessor:p,rerunMS:f,responsiveHeight:m,responsiveWidth:y,seed:g=1,settle:x,xAccessor:b="x",xExtent:v}=e,w=La(e,[700,360]),{chartSize:k,showProjection:M,className:S,title:I,chartMode:j,margin:A,enableHover:C,description:R,summary:P,accessibleTable:D}=w,$=h??("sparkline"===j?2:"context"===j?4:5),B=(0,uc.useRef)(null),T=(0,uc.useMemo)(()=>o??[],[o]),N=(0,uc.useMemo)(()=>As({data:T,xAccessor:b,groupAccessor:c,radiusAccessor:p,pointRadius:$,seed:g,size:k,xExtent:v,collisionIterations:r,settle:x}),[T,k,r,c,$,p,g,x,b,v]),E=za(N.config,f,u);ca(t,{frameRef:B,spawnDatum:(0,uc.useCallback)((e,t)=>{const n=As({data:[e],xAccessor:b,groupAccessor:c,radiusAccessor:p,pointRadius:$,seed:g+t+1,size:k,xExtent:v,collisionIterations:r,settle:x}).initialSpawns[0]??{id:(e.id??"collision-swarm-push-"+t)+"",x:cs(k).plot.x,y:cs(k).plot.y,mass:1,shape:{type:"circle",radius:$},datum:e};return{datumId:(e.id??n.id)+"",spawns:[n]}},[k,r,c,$,p,g,x,b,v]),seedRows:T,seedSpawns:N.initialSpawns});const W=n??c,q=(0,uc.useMemo)(()=>ds(W,"#4e79a7",{styleRules:i,valueAccessor:b}),[W,i,b]),O=Ya({data:o,emptyContent:s,loading:l,loadingContent:d,size:k});if(O)return O;const F=function(e,t){if(!1!==t&&e)return({size:t})=>{const n=[Number(t[0])||700,Number(t[1])||360],i=cs(n),r=i.plot.y+i.plot.height,[o,s]=e.xExtent,a=o+(s-o)/2,c=[{label:pc(o),x:e.xRange[0]},{label:pc(a),x:e.xRange[0]+(e.xRange[1]-e.xRange[0])/2},{label:pc(s),x:e.xRange[1]}];return(0,hc.jsxs)("svg",{"aria-hidden":"true","data-testid":"collision-swarm-projection-overlay",width:n[0],height:n[1],viewBox:`0 0 ${n[0]} ${n[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[e.groups.map(e=>(0,hc.jsxs)("g",{children:[(0,hc.jsx)("line",{x1:i.plot.x,x2:i.plot.x+i.plot.width,y1:e.y,y2:e.y,stroke:"var(--semiotic-border, #d1d5db)",strokeDasharray:"3 5",strokeWidth:1}),(0,hc.jsx)("text",{x:i.plot.x+4,y:e.y-7,fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:e.label}),(0,hc.jsxs)("text",{x:i.plot.x+i.plot.width-4,y:e.y-7,textAnchor:"end",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:["n=",e.count]})]},e.label)),(0,hc.jsx)("line",{x1:e.xRange[0],x2:e.xRange[1],y1:r,y2:r,stroke:"var(--semiotic-text-secondary, #555)",strokeWidth:1}),c.map(e=>(0,hc.jsxs)("g",{children:[(0,hc.jsx)("line",{x1:e.x,x2:e.x,y1:r,y2:r+5,stroke:"var(--semiotic-text-secondary, #555)",strokeWidth:1}),(0,hc.jsx)("text",{x:e.x,y:Math.min(n[1]-8,r+18),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:e.label})]},`${e.label}-${e.x}`))]})}}(N.metadata,M),z=function(e){if(!e)return[];const t=Math.max(24,e.xRange[1]-e.xRange[0]),n=e.xRange[0]+t/2;return e.groups.map(e=>{const i=`${e.label} lane: ${e.count} points`;return{id:"collision-swarm-"+e.label,label:i,description:i,datum:e,x:n,y:e.y,shape:"rect",width:t,height:28,group:"lane"}})}(N.metadata),L=Xa(e.tooltip,a),Y=_a(e,a,z,{chartMode:j,className:S,title:I,description:R,summary:P,accessibleTable:D,enableHover:C,margin:A});return Ha("CollisionSwarmChart",k,(0,hc.jsx)(ts,{...a,...L,...Y,ref:B,config:E.config,foregroundGraphics:Ga(F,a?.foregroundGraphics),initialSpawns:N.initialSpawns,paused:u,responsiveHeight:m,responsiveWidth:y,size:k,bodyStyle:q},E.rerunKey))}),mc={fresh:1,aging:1.5,stale:3};function yc(e,t,n={}){return Number.isFinite(t)&&t>0?Number.isNaN(e)?"fresh":e===1/0?"expired":0>e||t*(n.fresh??mc.fresh)>e?"fresh":t*(n.aging??mc.aging)>e?"aging":t*(n.stale??mc.stale)>e?"stale":"expired":"fresh"}function gc(e,t,n){if(null!=e)return"function"==typeof e?e(t,n):"object"==typeof e&&null!==e&&"constant"in e?e.constant:t[e]}function xc(e){const{data:t,encoding:n}=e,i=[],r=new Map;return t.forEach((e,t)=>{const o=gc(n.id,e,t);if(null==o||""===o)throw Error(`[semiotic] Motion encoding row ${t} resolved an empty id.`);const s=o+"";if(r.has(s))throw Error(`[semiotic] Duplicate motion encoding id "${s}".`);const a=gc(n.process?.group,e,t),c=gc(n.process?.stage,e,t),l=gc(n.accessible?.group,e,t)??(null!=a?a+"":null!=c?c+"":void 0),d={};for(const i of Object.keys(n.evidence??{}))d[i]=gc(n.evidence?.[i],e,t);const u={id:s,datum:e,time:{arrival:gc(n.time?.arrival,e,t),basis:n.time?.basis,unit:n.time?.unit},placement:{x:gc(n.placement?.x,e,t),y:gc(n.placement?.y,e,t),lane:gc(n.placement?.lane,e,t),space:n.placement?.space},kinematics:{velocityX:gc(n.kinematics?.velocityX,e,t),velocityY:gc(n.kinematics?.velocityY,e,t),space:n.kinematics?.space},process:{group:a,stage:c,target:gc(n.process?.target,e,t),work:gc(n.process?.work,e,t)},evidence:d,accessible:{description:gc(n.accessible?.description,e,t),group:l,label:gc(n.accessible?.label,e,t)??s}};i.push(u),r.set(s,u)}),{rows:i,byId:r}}function bc(e){const t=e.now-e.arrival;return{age:t,progress:Number.isFinite(t)&&Number.isFinite(e.ttl)&&e.ttl>0?Math.max(0,t)/e.ttl:t===1/0&&Number.isFinite(e.ttl)&&e.ttl>0?1/0:0,lifecycle:yc(t,e.ttl,e.thresholds)}}function vc(e){const t=Math.max(0,Math.min(1,e.minOpacity??.1));if(Number.isNaN(e.age))return 1;if(e.age===1/0)return t;if(!Number.isFinite(e.extent)||0>=e.extent)return 1;const n=Math.max(0,e.age);if("step"===e.type)return(e.threshold??.5*e.extent)>n?1:t;if("exponential"===e.type){const i=e.halfLife??e.extent/2;return t+Math.pow(.5,n/(i>0?i:e.extent/2))*(1-t)}return t+Math.max(0,Math.min(1,1-n/e.extent))*(1-t)}function wc(e,t){const n=Number.isFinite(e)?e:0,i=Number.isFinite(t)?t:0;return{velocityX:n,velocityY:i,speed:Math.hypot(n,i),direction:Math.atan2(i,n)}}function kc(e,t,n){return Number.isFinite(n)&&n>0?wc((t.x-e.x)/n,(t.y-e.y)/n):wc(0,0)}function Mc(e){const{data:t,encoding:n,defaults:i={},scales:r}=e,o=xc({data:t,encoding:n}),s=[],a=new Map,c=[],l=[],d=new Map;return o.rows.forEach((e,t)=>{const{id:o,datum:u}=e,h=Math.max(0,gc(n.appearance?.size,u,t)??i.size??6),p=gc(n.appearance?.shape,u,t)??i.shape??{type:"circle",radius:h},f=e.placement.x??i.x??0,m=e.placement.y??i.y??0,y=r?.x?r.x(f):f,g=r?.y?r.y(m):m,x=gc(n.appearance?.color,u,t)??i.color,b=gc(n.appearance?.opacity,u,t)??i.opacity,v=gc(n.appearance?.stroke,u,t)??i.stroke,w=gc(n.appearance?.strokeWidth,u,t)??i.strokeWidth,k=gc(n.time?.spawnAt,u,t)??e.time.arrival,M=e.kinematics.velocityX,S=e.kinematics.velocityY,I=gc(n.dynamics?.mass,u,t)??i.mass??1,j=gc(n.dynamics?.friction,u,t),A=gc(n.dynamics?.restitution,u,t),C=gc(n.dynamics?.bodyCollisions,u,t),R={id:o,x:y,y:g,mass:I,shape:{...p},datum:u,...null!=k&&{spawnAt:k},...null!=M&&{vx:M},...null!=S&&{vy:S},...null!=j&&{friction:j},...null!=A&&{restitution:A},...null!=C&&{bodyCollisions:C}},P={...null!=x&&{fill:x},...null!=b&&{opacity:b},...null!=v&&{stroke:v},...null!=w&&{strokeWidth:w}},D={id:o,datum:u,appearance:{color:x,opacity:b,shape:p,size:h,stroke:v,strokeWidth:w},placement:{x:y,y:g,lane:e.placement.lane,space:n.placement?.space??"world"},time:{arrival:k,spawnAt:k,basis:n.time?.basis??"simulation",unit:n.time?.unit},kinematics:{velocityX:M,velocityY:S,space:n.kinematics?.space??"world"},dynamics:{bodyCollisions:C,friction:j,mass:I,restitution:A},process:e.process,evidence:e.evidence,accessible:e.accessible,spawn:R};s.push(D),a.set(o,D),c.push(R),d.set(o,P),l.push({id:o,bodyId:o,label:e.accessible.label,description:e.accessible.description,datum:u,x:y,y:g,group:e.accessible.group})}),{rows:s,byId:a,spawns:c,semanticItems:l,bodyStyle:e=>d.get(e.id)??{}}}function Sc(e){return t=>{const n=Mc({data:t.data,encoding:e.encoding,defaults:e.defaults,scales:t.scales}),i=e.extend?.(t,n)??{};return{...i,initialSpawns:n.spawns,bodyStyle:n.bodyStyle,semanticItems:[...n.semanticItems,...i.semanticItems??[]]}}}var Ic=require("react");function jc(e,t={}){const n=t.id??"physics-process-boundary",i={bodyFilter:t.bodyFilter,friction:t.friction,restitution:t.restitution};if("segment"===e.type)return[{...i,id:n,shape:e}];const r=t.thickness??8,o=e.x-e.width/2,s=e.x+e.width/2,a=e.y-e.height/2,c=e.y+e.height/2;return[{...i,id:n+"-top",shape:{type:"segment",x1:o,y1:a,x2:s,y2:a,thickness:r}},{...i,id:n+"-right",shape:{type:"segment",x1:s,y1:a,x2:s,y2:c,thickness:r}},{...i,id:n+"-bottom",shape:{type:"segment",x1:s,y1:c,x2:o,y2:c,thickness:r}},{...i,id:n+"-left",shape:{type:"segment",x1:o,y1:c,x2:o,y2:a,thickness:r}}]}function Ac(e){if(!1===e.semanticItem)return null;const t=e.semanticItem??{},n=e.shape,i="aabb"===n.type?{id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"region",x:n.x,y:n.y,width:n.width,height:n.height}:{id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"region",x:(n.x1+n.x2)/2,y:(n.y1+n.y2)/2,pathData:`M ${n.x1} ${n.y1} L ${n.x2} ${n.y2}`};return{...i,...t,id:t.id??i.id}}function Cc(e){return e.map(e=>({id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"stage",x:e.x??0,y:e.y??0,width:e.width,height:e.height}))}function Rc(e){return e.flatMap(e=>{if(!1===e.semanticItem)return[];const t=e.semanticItem??{},n={id:e.id,label:e.label??e.id,description:e.description,datum:e.datum,group:e.group??e.state??"body group",x:e.x??0,y:e.y??0,width:e.width,height:e.height};return[{...n,...t,id:t.id??n.id}]})}var Pc="gauntlet-core",Dc="gauntlet-positive",$c="gauntlet-negative";function Bc(e){const t=Fc(e);return[{id:"gauntlet-left",restitution:.12,friction:.42,shape:{type:"segment",x1:t.left,y1:t.top,x2:t.left,y2:e.floorY,thickness:t.thickness}},{id:"gauntlet-ceiling",restitution:.12,friction:.42,shape:{type:"segment",x1:t.left,y1:t.top,x2:e.width-t.rightInset,y2:t.top,thickness:t.thickness}},{id:"gauntlet-floor",restitution:.12,friction:.42,shape:{type:"segment",x1:t.left,y1:e.floorY,x2:e.width-t.rightInset,y2:e.floorY,thickness:t.thickness}},{id:"gauntlet-right",restitution:.12,friction:.42,shape:{type:"segment",x1:e.width-t.rightInset,y1:t.top,x2:e.width-t.rightInset,y2:e.floorY,thickness:t.thickness}}]}function Tc(e,t,n,i){return n?"function"==typeof n?n(e,t):e[n]??i:i}function Nc(e){return e?.label??e?.id??"property"}function Ec(e){return`gauntlet:${e}:core`}function Wc(e,t){return`gauntlet:${e}:positive:${t}`}function qc(e,t,n){return`gauntlet:${e}:negative:${t}:${n}`}var Oc={left:28,top:76,rightInset:30,thickness:8};function Fc(e){const t=e.height??e.floorY+36;if(e.width>=220&&t>=160)return Oc;const n=Math.max(1,Math.min(e.width,t)),i=Math.max(2,.04*e.width);return{left:i,top:Math.max(2,.08*t),rightInset:i,thickness:Math.max(1,Math.min(4,.04*n))}}function zc(e){return Math.max(.12,Math.min(1,e.width/500,(e.height??e.floorY+36)/260))}function Lc(e,t,n,i){const r=Fc(i),o=Math.max(2,n+2),s=r.top+r.thickness/2+o,a=i.floorY-o,c=(e,t,n)=>t>n?(t+n)/2:Math.max(t,Math.min(n,e));return{x:c(e,r.left+r.thickness/2+o,i.width-r.rightInset-r.thickness/2-o),y:c(t,s,a)}}function Yc(e){return{graveyardX:e.graveyardX,graveyardY:e.graveyardY,routeY:e.routeY,socketX:e.socketX,socketY:e.routeY-4,startX:e.startX,startY:e.routeY}}function Hc(e,t,n,i){const r=Yc(n),o=i?.(e,t,n)??{};return{...r,...o,startY:o.startY??o.routeY??r.startY,socketY:o.socketY??o.routeY??r.socketY,graveyardY:o.graveyardY??r.graveyardY}}function Gc(e,t,n=1){const i=[...e].sort((e,t)=>e.localeCompare(t)),r=Math.max(0,i.indexOf(t));return{angle:.82*-Math.PI+(i.length>1?r/(i.length-1):.5)*Math.PI*.64,index:r,radius:(48+r%2*6)*n}}function Xc(e,t,n){const i=e.activePositiveIds.reduce((e,n)=>e+(t.get(n)?.value??1),0),r=e.missingPositiveIds.length+e.poppedPositiveIds.length,o=e.negativeIds.reduce((e,t)=>e+(n.get(t)?.load??1),0);return Math.max(0,Math.min(100,75+3*i-8*o-1.2*e.delay-5*r))}function _c(e,t,n,i,r){const o=Tc(e,t,n.idAccessor,null!=e.id?e.id+"":"project-"+t)+"",s=i.map(e=>e.id),a=[...Tc(e,t,n.positiveAccessor,s)],c=[...Tc(e,t,n.negativeAccessor,[])].filter(e=>r.has(e));return{id:o,activePositiveIds:a,datum:e,delay:0,eventsApplied:[],eventHistory:[],killed:!1,metrics:{...Tc(e,t,n.metricsAccessor,{})},missingPositiveIds:s.filter(e=>!a.includes(e)),negativeIds:c,outcome:"in_process",poppedPositiveIds:[],poppedNegativeIds:[],startedAt:Math.max(0,Number(Tc(e,t,n.startTimeAccessor,0))||0),stage:"project filed",viability:Tc(e,t,n.initialViability,100)}}function Vc(e,t,n,i,r,o,s){const a=zc(n),c=Math.max(3,28*a),l=i.startX,d=i.startY+(i.startY===n.routeY?38*t*a:0),u=s?.(e,t,n,i)??{},h=u.x??l,p=u.y??d,f={__gauntlet:!0,kind:Pc,projectId:e.id,sourceDatum:e.datum},m=[{...u,id:Ec(e.id),x:h,y:p,vx:u.vx??42,vy:u.vy??0,mass:u.mass??7,bodyCollisions:u.bodyCollisions??!0,shape:u.shape??{type:"circle",radius:c},spawnAt:u.spawnAt??e.startedAt,datum:f}],y=Lc(h,p,u.shape&&"radius"in u.shape&&Number(u.shape.radius)||c,n);m[0].x=y.x,m[0].y=y.y;for(const t of e.activePositiveIds){const i=r.get(t);if(!i)continue;const o=Gc(e.activePositiveIds,t,a),s=i.radius??Math.max(2,10*a),c=Lc(y.x+Math.cos(o.angle)*o.radius,y.y+Math.sin(o.angle)*o.radius,s,n);m.push({id:Wc(e.id,t),x:c.x,y:c.y,vx:18*Math.cos(o.angle),vy:18*Math.sin(o.angle),mass:i.mass??.75,bodyCollisions:!1,shape:{type:"circle",radius:s},spawnAt:u.spawnAt??e.startedAt,datum:{__gauntlet:!0,kind:Dc,projectId:e.id,property:i,sourceDatum:e.datum},springs:!1===i.spring?[]:[{target:{type:"body",bodyId:Ec(e.id)},stiffness:.56,damping:.9,restLength:Math.max(6,(52+o.index%2*4)*a),...i.spring??{}}]})}return e.negativeIds.forEach((t,i)=>{const r=o.get(t);r&&m.push(Uc(e,r,i,y.x,y.y,n,u.spawnAt??e.startedAt))}),m}function Uc(e,t,n,i,r,o,s){const a=zc(o),c=t.radius??Math.max(2,7.2*a),l=Lc(i+(n%4*12-12)*a,r+(54+12*Math.floor(n/4))*a,c,o);return{id:qc(e.id,t.id,n),x:l.x,y:l.y,vx:10,vy:6,mass:t.mass??.72,bodyCollisions:!1,shape:{type:"circle",radius:c},spawnAt:s,datum:{__gauntlet:!0,kind:$c,projectId:e.id,property:t,sourceDatum:e.datum},springs:!1===t.spring?[]:[{target:{type:"body",bodyId:Ec(e.id)},stiffness:.62,damping:.92,restLength:Math.max(6,(52+n%4*3)*a),...t.spring??{}}]}}function Kc(e){return e?Array.isArray(e)?[...e]:Object.entries(e).flatMap(([e,t])=>Array.from({length:Math.max(0,Math.round(Number(t)||0))},()=>e)):[]}function Qc(e,t){return t?Array.isArray(t)?[...t]:t.ids?[...t.ids]:t.candidates?t.candidates.filter(t=>e.includes(t)).slice(0,t.count??1):[]:[]}function Zc(e,t){return Qc(e.activePositiveIds,t.popPositive)}function Jc(e){const t=Number(e.budget),n=Number.isFinite(t)?Math.max(0,t):0,i=e.properties instanceof Map?e.properties:new Map(e.properties.map(e=>[e.id,e])),r=e.candidates?new Set(e.candidates):null,o=e.attachedIds.map((e,t)=>{const n=i.get(e),r=Number(n?.work??1),o=Number(n?.priority??t);return{id:e,index:t,priority:Number.isFinite(o)?o:t,work:Number.isFinite(r)&&r>0?r:1}}).filter(e=>!r||r.has(e.id)).sort((e,t)=>e.priority-t.priority||e.index-t.index),s=[],a=[];let c=0;for(const e of o)c+e.work>n+Number.EPSILON?a.push(e.id):(s.push(e.id),c+=e.work);return{ids:s,used:c,budget:n,remaining:Math.max(0,n-c),skippedIds:a}}function el(e,t){if(!t.from||!t.to||t.from===t.to)return{};const n=Math.max(0,Math.floor(Number(t.count??1)||0)),i=e.negativeIds.filter(e=>e===t.from).length,r=Math.min(n,i);return r?{addNegative:{[t.to]:r},popNegative:{ids:Array.from({length:r},()=>t.from)}}:{}}function tl(e,t){const n=Qc(e.negativeIds,t.popNegative);if(!n.length)return[];const i=new Map;for(const e of n)i.set(e,(i.get(e)??0)+1);const r=[];return e.negativeIds.forEach((e,t)=>{const n=i.get(e)??0;n>0&&(r.push({propertyId:e,index:t}),i.set(e,n-1))}),r}function nl(e,t,n){if(t.when&&!t.when(n))return e;let i={...e};const r=Zc(i,t);r.length&&(i={...i,activePositiveIds:i.activePositiveIds.filter(e=>!r.includes(e)),poppedPositiveIds:Array.from(new Set([...i.poppedPositiveIds,...r]))});const o=tl(i,t);if(o.length){const e=new Set(o.map(e=>e.index));i={...i,negativeIds:i.negativeIds.filter((t,n)=>!e.has(n)),poppedNegativeIds:[...i.poppedNegativeIds,...o.map(e=>e.propertyId)]}}const s=Kc(t.addPositive);s.length&&(i={...i,activePositiveIds:Array.from(new Set([...i.activePositiveIds,...s])),missingPositiveIds:i.missingPositiveIds.filter(e=>!s.includes(e))});const a=Kc(t.addNegative);if(a.length&&(i={...i,negativeIds:[...i.negativeIds,...a]}),t.delayDelta&&(i={...i,delay:i.delay+t.delayDelta}),t.metricsDelta){const e={...i.metrics};for(const[n,i]of Object.entries(t.metricsDelta))e[n]=Number(e[n]??0)+i;i={...i,metrics:e}}return t.viabilityDelta&&(i={...i,viability:i.viability+t.viabilityDelta}),t.stage&&(i={...i,stage:t.stage}),t.outcome&&(i={...i,outcome:t.outcome}),i}function il(e,t){return{id:e.id,label:e.label??e.id,summary:e.summary??t.find(e=>e.summary)?.summary,time:e.time}}function rl(e,t){return e.eventsApplied.includes(t.id)?e:{...e,eventsApplied:[...e.eventsApplied,t.id],eventHistory:[...e.eventHistory??[],t],lastEvent:t,stage:t.label??e.stage}}function ol(e,t){const n=e.datum;return!(!n?.__gauntlet||n.projectId!==t||n.kind!==$c)}function sl(e){const t=e.id.slice(e.id.lastIndexOf(":")+1),n=Number(t);return Number.isFinite(n)?n:-1}function al(e,t){return 2>Math.hypot(e.vx,e.vy)&&4>Math.hypot(t.x,t.y)?null:t}var cl=require("react/jsx-runtime");function ll(e){const t=e.data;return t?.__gauntlet?(0,cl.jsxs)("div",{className:"semiotic-tooltip",style:{background:"var(--semiotic-tooltip-bg, rgba(15, 23, 42, 0.94))",color:"var(--semiotic-tooltip-text, #f8fafc)",padding:"8px 12px",borderRadius:6,boxShadow:"var(--semiotic-tooltip-shadow, 0 8px 24px rgba(0,0,0,0.35))",maxWidth:280},children:[(0,cl.jsx)("strong",{children:t.kind===Pc?"string"==typeof t.sourceDatum?.label?t.sourceDatum.label:t.projectId:Nc(t.property)}),(0,cl.jsx)("div",{children:t.kind===Dc?"Positive property":t.kind===$c?"Negative property":"Project core"})]}):null}function dl(e,t,n){const i=t.datum;if(!i?.__gauntlet)return;const r="circle"===t.shape.type?t.shape.radius:8;if(e.save(),e.translate(t.x,t.y),i.kind===Pc)e.fillStyle=ul(e,n.fill,"#0f766e"),e.strokeStyle=ul(e,n.stroke,"#f8fafc"),e.lineWidth=2.4,e.beginPath(),e.arc(0,0,r,0,2*Math.PI),e.fill(),e.stroke();else{const t=i.property;e.fillStyle=ul(e,n.fill??t?.color,"#38bdf8"),e.strokeStyle=ul(e,n.stroke,"#0f172a"),e.lineWidth=1.1,e.beginPath(),i.kind===$c?e.rect(-r,-r,2*r,2*r):e.arc(0,0,r,0,2*Math.PI),e.fill(),e.stroke(),e.fillStyle=ul(e,"var(--semiotic-background, #07111f)","#07111f"),e.font=`900 ${i.kind===$c?9:8}px system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,e.textAlign="center",e.textBaseline="middle",e.fillText(t?.short??t?.id?.slice(0,1).toUpperCase()??"?",0,.5)}e.restore()}function ul(e,t,n){if("string"!=typeof t)return n;if("function"!=typeof getComputedStyle||!e.canvas)return t||n;const i=t.startsWith("var(")?t.match(/var\((--[^,\s)]+)/)?.[1]:t.startsWith("--")?t:null;return i?getComputedStyle(e.canvas).getPropertyValue(i).trim()||n:t||n}function hl({layout:e,compact:t,showLabels:n}){const i=t?Math.round(.14*e.height):Math.max(80,e.routeY-180),r=t?Math.max(6,Math.round(.72*e.height)):Math.min(360,e.height-170);return(0,cl.jsx)(cl.Fragment,{children:e.gates.map(o=>(0,cl.jsxs)("g",{children:[(0,cl.jsx)("rect",{x:o.x-o.width/2,y:i,width:o.width,height:r,rx:t?2:12,fill:o.color??"var(--semiotic-accent, #38bdf8)",fillOpacity:.1,stroke:o.color??"var(--semiotic-accent, #38bdf8)",strokeDasharray:"5 5",strokeOpacity:.7}),n?(0,cl.jsx)("text",{x:o.x,y:Math.max(64,e.routeY-196),fill:"var(--semiotic-text-secondary, #64748b)",fontSize:10,fontWeight:800,textAnchor:"middle",children:o.label??o.id}):null]},o.id))})}function pl({layout:e,states:t,compact:n=!1}){return n?(0,cl.jsx)("svg",{"aria-hidden":"true",viewBox:`0 0 ${e.width} ${e.height}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:(0,cl.jsx)(hl,{layout:e,compact:!0,showLabels:!1})}):(0,cl.jsxs)("svg",{"aria-hidden":"true",viewBox:`0 0 ${e.width} ${e.height}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[(0,cl.jsx)("path",{d:`M ${e.startX-42} ${e.routeY} C ${.24*e.width} ${e.routeY-70}, ${.42*e.width} ${e.routeY+78}, ${.58*e.width} ${e.routeY} S ${.78*e.width} ${e.routeY-82}, ${e.socketX+36} ${e.routeY}`,fill:"none",stroke:"var(--semiotic-accent, #38bdf8)",strokeDasharray:"18 12",strokeLinecap:"round",strokeOpacity:.45,strokeWidth:7}),(0,cl.jsx)("line",{x1:Math.round(.06*e.width),x2:Math.round(.94*e.width),y1:e.crashY,y2:e.crashY,stroke:"var(--semiotic-negative, #ef4444)",strokeDasharray:"3 7",strokeOpacity:.64}),(0,cl.jsx)("text",{x:Math.round(.07*e.width),y:e.crashY-8,fill:"var(--semiotic-negative, #ef4444)",fontSize:9,fontWeight:800,children:"CRASH LINE"}),(0,cl.jsx)(hl,{layout:e,compact:!1,showLabels:!0}),(0,cl.jsxs)("g",{children:[(0,cl.jsx)("rect",{x:e.socketX-52,y:e.routeY-56,width:104,height:112,rx:13,fill:"var(--semiotic-positive, #22c55e)",fillOpacity:.12,stroke:"var(--semiotic-positive, #22c55e)",strokeWidth:1.5}),(0,cl.jsx)("text",{x:e.socketX,y:e.routeY-72,fill:"var(--semiotic-text-secondary, #64748b)",fontSize:10,fontWeight:800,textAnchor:"middle",children:"SOCKET"})]}),(0,cl.jsxs)("g",{children:[(0,cl.jsx)("rect",{x:e.graveyardX-82,y:e.graveyardY-34,width:164,height:58,rx:11,fill:"var(--semiotic-negative, #ef4444)",fillOpacity:.16,stroke:"var(--semiotic-negative, #ef4444)",strokeOpacity:.7}),(0,cl.jsx)("text",{x:e.graveyardX,y:e.graveyardY-8,fill:"var(--semiotic-negative, #ef4444)",fontSize:10,fontWeight:800,textAnchor:"middle",children:"GRAVEYARD"}),(0,cl.jsx)("text",{x:e.graveyardX,y:e.graveyardY+12,fill:"var(--semiotic-text-secondary, #64748b)",fontSize:9,fontWeight:700,textAnchor:"middle",children:t.some(e=>e.killed)?"lift shut off":"too heavy or too small"})]})]})}function fl(e){const t=e.datum;return!!t?.__gauntlet&&(t.kind===Pc?{label:t.projectId+" project core",group:"project",description:"Project core carrying positive and negative properties."}:{label:`${Nc(t.property)} ${t.kind===Dc?"positive":"negative"} property`,group:t.kind===Dc?"positive property":"negative property",description:`${Nc(t.property)} attached to ${t.projectId}.`})}function ml({states:e,layout:t}){const n=function(e){return e.map(e=>({label:e.id,value:Math.max(0,Number(e.viability)||0),outcome:e.outcome||e.stage||"in-process"}))}(e);if(!n.length)return null;const i=Math.max(1,...n.map(e=>e.value)),r=Math.max(40,(t.width-80)/n.length);return(0,cl.jsxs)("svg",{"aria-hidden":"true","data-testid":"gauntlet-projection-overlay",width:t.width,height:t.height,viewBox:`0 0 ${t.width} ${t.height}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[(0,cl.jsx)("text",{x:36,y:18,fill:"var(--semiotic-text-secondary, #64748b)",fontSize:9,fontWeight:800,children:"SETTLED · viability / outcome"}),n.map((e,t)=>{const n=40+t*r,o=Math.max(2,e.value/i*28),s=/kill|crash|block|grave/i.test(e.outcome);return(0,cl.jsxs)("g",{children:[(0,cl.jsx)("rect",{x:n+.18*r,y:28-o+22,width:Math.max(10,.45*r),height:o,rx:2,fill:s?"var(--semiotic-danger, #ef4444)":"var(--semiotic-success, #16a34a)",fillOpacity:.35,stroke:s?"var(--semiotic-danger, #ef4444)":"var(--semiotic-success, #16a34a)",strokeOpacity:.55,strokeWidth:1}),(0,cl.jsx)("text",{x:n+.4*r,y:62,textAnchor:"middle",fill:"var(--semiotic-text-secondary, #64748b)",fontSize:9,fontWeight:700,children:e.label})]},e.label)})]})}var yl=require("react/jsx-runtime"),gl=require("react"),xl=[],bl=(0,Ic.forwardRef)(function(e,t){const{bodyGroups:n,coreBody:i,coreForceMode:r="route",crashDetection:o=!0,crashOffset:s=30,data:a,emptyContent:c,events:l,frameProps:d={},gates:u,initialSpawnPacing:h,loading:p,loadingContent:f,negativeProperties:m,onCapacityChange:y,onClick:g,onStateChange:x,outcome:b,paused:v,positiveProperties:w=xl,projectPlacement:k,rerunMS:M,responsiveHeight:S,responsiveWidth:I,showTethers:j=!0,terminalBehavior:A="outcome",viability:C}=e,R=(0,Ic.useRef)(null),P=(0,Ic.useMemo)(()=>({idAccessor:e.idAccessor,initialViability:e.initialViability,metricsAccessor:e.metricsAccessor,negativeAccessor:e.negativeAccessor,positiveAccessor:e.positiveAccessor,startTimeAccessor:e.startTimeAccessor}),[e.idAccessor,e.initialViability,e.metricsAccessor,e.negativeAccessor,e.positiveAccessor,e.startTimeAccessor]),D=La(e,[900,520]),{chartSize:$,showProjection:B,showChrome:T,className:N,title:E,chartMode:W,margin:q,enableHover:O,description:F,summary:z,accessibleTable:L}=D,Y=Ya({data:a,emptyContent:c,loading:p,loadingContent:f,size:$}),H=(0,Ic.useMemo)(()=>rc(a??[]),[a]),G=(0,Ic.useMemo)(()=>H.map((e,t)=>Tc(e,t,P.idAccessor,null!=e.id?e.id+"":"project-"+t)+"").join("|"),[H,P.idAccessor]),X=(0,Ic.useMemo)(()=>new Map(w.map(e=>[e.id,e])),[w]),_=(0,Ic.useMemo)(()=>new Map(m.map(e=>[e.id,e])),[m]),V=(0,Ic.useMemo)(()=>function(e,t,n){const[i,r]=e,o=220>i||160>r,s=Math.round(.48*r),a=o?r-Math.max(3,Math.min(12,.1*r)):r-36,c=(t??[]).filter(e=>!1!==e.enabled),l=Math.max(1,c.length),d=.22*i,u=l>1?(.78*i-d)/(l-1):0,h=o?Math.max(Math.round(.12*i),.08*i+6):Math.max(Math.round(.14*i),110);return{crashY:a-(o?Math.min(n,Math.max(3,.22*r)):n),floorY:a,gates:c.map((e,t)=>({...e,id:e.id,x:e.x??Math.round(d+t*u),width:e.width??Math.max(o?8:54,Math.round(.07*i))})),graveyardX:Math.round(i*(o?.72:.84)),graveyardY:a-4,height:r,routeY:s,socketX:Math.round(i*(o?.82:.92)),startX:h,width:i}}($,u,s),[$,s,u]),U=(0,Ic.useMemo)(()=>new Map(V.gates.map(e=>[e.id,e])),[V.gates]),K=(0,Ic.useMemo)(()=>V.gates.map(e=>({kind:"force-field",damping:.035,force:{x:12,y:0},semanticItem:!1,...e.regionEffect,id:"gauntlet-gate-"+e.id,label:e.label??e.id,description:e.description,bodyFilter:e.capacity?{property:"datum.kind",equals:Pc}:e.regionEffect?.bodyFilter,shape:{type:"aabb",x:e.x,y:V.routeY,width:e.capacity?e.capacity.sensorWidth??Math.max(220>V.width?12:96,e.width*(220>V.width?2:6)):Math.max(e.width,220>V.width?10:54),height:Math.max(4,Math.min(360,V.height-(160>V.height?8:170)))}})),[V.gates,V.height,V.routeY,V.width]),[Q,Z]=(0,Ic.useState)(()=>H.map((e,t)=>{const n=_c(e,t,P,w,_);return{...n,viability:C?.(n,{negativeProperties:_,positiveProperties:X})??Xc(n,X,_)}})),J=(0,Ic.useRef)(Q),ee=(0,Ic.useRef)(0),te=(0,Ic.useRef)(new Map),ne=(0,Ic.useRef)([]),ie=(0,Ic.useRef)(y);ie.current=y;const re=(0,Ic.useRef)(H);re.current=H;const oe=(0,Ic.useRef)(x);oe.current=x;const se=(0,Ic.useRef)({negativeById:_,positiveById:X,positiveProperties:w,stateAccessors:P,viability:C});se.current={negativeById:_,positiveById:X,positiveProperties:w,stateAccessors:P,viability:C};const ae=(0,Ic.useCallback)((e,t,n=0)=>{const i=se.current,r=_c(e,t,i.stateAccessors,i.positiveProperties,i.negativeById);return i.stateAccessors.startTimeAccessor||(r.startedAt=Math.max(0,n)),{...r,viability:i.viability?.(r,{negativeProperties:i.negativeById,positiveProperties:i.positiveById})??Xc(r,i.positiveById,i.negativeById)}},[]),ce=(0,Ic.useCallback)(()=>{te.current.clear(),ne.current=[],ee.current=0;const e=re.current.map((e,t)=>ae(e,t));J.current=e,Z(e)},[ae]),le=za((0,Ic.useMemo)(()=>({fixedDt:1/60,maxSubsteps:8,kernel:{gravity:{x:0,y:0},restitution:.16,friction:.44,velocityDamping:.982,maxVelocity:520,sleepAfter:.8,sleepSpeed:7,...d.config?.kernel??{}},colliders:[...Bc(V),...d.config?.colliders??[]]}),[d.config?.colliders,d.config?.kernel,V]),M,v,ce),de=(0,Ic.useMemo)(()=>function(e){const{dataKey:t,gates:n,statesRef:i,processedGateVisitsRef:r}=e;return n.flatMap(e=>e.capacity&&e.capacity.unitsPerSecond>0?[Tr({id:`gauntlet-capacity-${t}-${e.id}`,regionId:"gauntlet-gate-"+e.id,unitsPerSecond:e.capacity.unitsPerSecond,bodyFilter:{property:"datum.kind",equals:Pc},maxQueue:e.capacity.maxQueue,queueLayout:e.capacity.queueLayout,queueSlotSpacing:e.capacity.queueSlotSpacing,queueStiffness:e.capacity.queueStiffness??24,releaseImpulse:{x:36,y:0},unitAccessor:t=>{const n=t.datum,r=n?.sourceDatum,o=e.capacity?.unitAccessor,s=i.current.find(e=>e.id===n?.projectId);let a;"function"==typeof o?a=s?o(s):void 0:o&&(a=r?.[o]);const c=Number(a??r?.reviewWork??r?.work??s?.metrics.reviewWork??r?.points);return Number.isFinite(c)&&c>0?c:1},onProcessed:t=>{const n=t.datum;if(!n?.projectId)return;const i=`${n.projectId}:${e.id}`;r.current.set(i,(r.current.get(i)??0)+1)}})]:[])}({dataKey:`${G}:${le.rerunKey}`,gates:V.gates,statesRef:J,processedGateVisitsRef:te}),[G,V.gates,le.rerunKey]),ue=(0,Ic.useMemo)(()=>[...de,...d.controllers??[]],[de,d.controllers]);(0,Ic.useEffect)(()=>{te.current.clear(),ne.current=[],ee.current=0;const e=re.current.map((e,t)=>ae(e,t));J.current=e,Z(e)},[ae,G]),(0,Ic.useEffect)(()=>{J.current=Q,oe.current?.(Q)},[Q]);const he=(0,Ic.useCallback)(e=>[...("function"==typeof l?l(e,V):l)??[]].sort((e,t)=>e.time-t.time),[l,V]),pe=(0,Ic.useCallback)((e,t,n)=>{if(!t.gateId||!U.get(t.gateId)?.capacity)return!0;const i=Number(t.gateVisit),r=Number.isFinite(i)&&i>0?Math.floor(i):n.filter(e=>e.gateId===t.gateId).findIndex(e=>e.id===t.id)+1;return r>0&&(te.current.get(`${e.id}:${t.gateId}`)??0)>=r},[U]),fe=(0,Ic.useCallback)(()=>{if(!de.length)return;const e=de.flatMap(e=>{const t=e.getSnapshot?.();return t?[t]:[]});var t,n;(t=ne.current).length===(n=e).length&&t.every((e,t)=>{const i=n[t];return!!i&&e.regionId===i.regionId&&e.queueDepth===i.queueDepth&&e.blockedDepth===i.blockedDepth&&e.processedCount===i.processedCount&&e.metricRevision===i.metricRevision})||(ne.current=e,ie.current?.(e))},[de]),me=(0,Ic.useMemo)(()=>Q.flatMap((e,t)=>{const n=Hc(e,t,V,k);return Vc(e,t,V,n,X,_,i)}),[i,V,_,X,k,Q]),ye=(0,Ic.useCallback)((e,t)=>{let n=!1;const i=J.current.map(i=>{if(i.id!==e)return i;const r=t(i);return n=n||r!==i,r});n&&(J.current=i,Z(i))},[]);(0,Ic.useImperativeHandle)(t,()=>function(e){const{statesRef:t,setStates:n,elapsedRef:i,frameRef:r,layout:o,projectPlacement:s,positiveById:a,negativeById:c,coreBody:l,createState:d}=e;return{push:e=>{const u=d(e,t.current.length,i.current),h=Hc(u,t.current.length,o,s),p=Vc(u,t.current.length,o,h,a,c,l),f=[...t.current,u];t.current=f,n(f),r.current?.pushMany(p),r.current?.step(0)},pushMany:e=>{const u=[...t.current],h=[],p=i.current;e.forEach(e=>{const t=d(e,u.length,p),n=Hc(t,u.length,o,s);h.push(...Vc(t,u.length,o,n,a,c,l)),u.push(t)}),t.current=u,n(u),h.length&&r.current?.pushMany(h),r.current?.step(0)},remove:e=>{const i=Array.isArray(e)?e:[e],o=[],s=[];for(const e of i){const n=t.current.find(t=>t.id===e);n&&(o.push(n.datum),s.push(Ec(n.id),...n.activePositiveIds.map(e=>Wc(n.id,e))),n.negativeIds.forEach((e,t)=>{s.push(qc(n.id,e,t))}))}return t.current=t.current.filter(e=>!i.includes(e.id)),n(t.current),r.current?.remove(s),o},update:(e,u)=>{const h=Array.isArray(e)?e:[e],p=[];for(const e of h){const n=t.current.find(t=>t.id===e);if(!n)continue;const h=t.current.findIndex(t=>t.id===e);p.push(n.datum);const f=u(n.datum),m=d(f,0>h?t.current.length:h,n.startedAt??i.current),y=Hc(m,0>h?t.current.length:h,o,s);r.current?.remove([Ec(n.id),...n.activePositiveIds.map(e=>Wc(n.id,e)),...n.negativeIds.map((e,t)=>qc(n.id,e,t))]),r.current?.pushMany(Vc(m,0>h?t.current.length:h,o,y,a,c,l)),t.current=t.current.map(t=>t.id===e?m:t)}return n(t.current),p},clear:()=>{t.current=[],n([]),r.current?.clear()},getData:()=>t.current.map(e=>e.datum),getScales:()=>null,getCustomLayout:()=>r.current?.snapshot()??null,popBodies:(e,t)=>r.current?.popBodies(e,t)??[]}}({statesRef:J,setStates:Z,elapsedRef:ee,frameRef:R,layout:V,projectPlacement:k,positiveById:X,negativeById:_,coreBody:i,createState:ae}),[i,ae,V,_,X,k]);const ge="sparkline"===W?.22:"mobile"===W?.55:1,xe=(0,Ic.useCallback)((e,t,n)=>{!function(e){const{project:t,effect:n,controls:i,layout:r,positiveById:o,negativeById:s,coreBody:a,popBodies:c,popScale:l}=e,d=i.readBodies().find(e=>e.id===Ec(t.id)),u=i.readBodies(),h=d?.x??r.startX,p=d?.y??r.routeY,f=function(e,t){let n=-1;for(const i of t)ol(i,e.id)&&(n=Math.max(n,sl(i)));return Math.max(e.negativeIds.length,n+1)}(t,u),m=Kc(n.addNegative).flatMap((e,n)=>{const i=s.get(e);return i?[Uc(t,i,f+n,h,p,r)]:[]}),y=Kc(n.addPositive).flatMap(e=>{if(!o.get(e)||t.activePositiveIds.includes(e))return[];const n={...Yc(r),routeY:p,socketY:p,startX:h,startY:p};return Vc({...t,activePositiveIds:[e],negativeIds:[]},0,r,n,o,s,a).filter(e=>e.id.includes(":positive:"))});(m.length||y.length)&&i.pushMany([...m,...y]);const g=Zc(t,n);for(const e of g){const n=o.get(e);c([Wc(t.id,e)],{color:n?.popColor??n?.color,durationMs:900,radius:(n?.radius??10)+3,scale:l})}const x=tl(t,n),b=function(e,t,n){const i=t.filter(t=>ol(t,e.id)).sort((e,t)=>sl(e)-sl(t)||e.id.localeCompare(t.id)),r=new Set;return n.map(t=>{const n=i.find(e=>!r.has(e.id)&&e.datum.property?.id===t.propertyId);return n?(r.add(n.id),n.id):qc(e.id,t.propertyId,t.index)})}(t,u,x);x.forEach((e,t)=>{const n=s.get(e.propertyId);c([b[t]],{color:n?.popColor??n?.color,durationMs:900,radius:(n?.radius??7)+3,scale:l})})}({project:e,effect:t,controls:n,layout:V,positiveById:X,negativeById:_,coreBody:i,popBodies:(e,t)=>R.current?.popBodies(e,t),popScale:ge})},[i,V,_,X,ge]),be=(0,Ic.useCallback)(({body:e,bodies:t})=>function(e){const{body:t,bodies:n,layout:i,states:r,projectPlacement:o,positiveById:s,negativeById:a,projectEvents:c,gateById:l,coreForceMode:d,terminalBehavior:u,elapsed:h}=e,p=t.datum;if(!p?.__gauntlet)return null;const f=r.findIndex(e=>e.id===p.projectId),m=0>f?void 0:r[f];if(!m)return null;const y=Hc(m,f,i,o),g=n.find(e=>e.id===Ec(m.id)),x=zc(i),b=m.negativeIds.reduce((e,t)=>e+(a.get(t)?.load??1),0),v=m.killed?0:58*Math.max(.25,x);if(p.kind!==Pc){if(!g)return null;let e;const r=p.property;if(r?.target){const o=n.filter(e=>{const t=e.datum;return t?.__gauntlet&&t.projectId===m.id&&t.kind===p.kind}).sort((e,t)=>(e.id+"").localeCompare(t.id+"")),s=Math.max(0,o.findIndex(e=>e.id===t.id));e=r.target({body:t,bodies:n,core:g,index:s,layout:i,placement:y,project:m})??{x:g.x,y:g.y}}else if(p.kind===Dc&&p.property){const t=Gc(m.activePositiveIds,p.property.id,x);e={x:g.x+Math.cos(t.angle)*t.radius,y:g.y+Math.sin(t.angle)*t.radius-2}}else{const i=n.filter(e=>e.datum?.kind===$c&&e.datum.projectId===m.id).sort((e,t)=>(e.id+"").localeCompare(t.id+"")),r=Math.max(0,i.findIndex(e=>e.id===t.id)),o=Math.floor(r/4);e={x:g.x+18*(r%4-(Math.min(4,i.length-4*o)-1)/2)*x,y:g.y+(54+13*o)*x}}const o="circle"===t.shape.type?t.shape.radius:8;e=Lc(e.x,e.y,o,i);const s=Lc(t.x,t.y,o,i);if(Math.abs(s.x-t.x)>.5||Math.abs(s.y-t.y)>.5)return{x:48*(s.x-t.x)-6*t.vx,y:48*(s.y-t.y)-6*t.vy};const a=p.kind!==Dc||m.killed?0:3.2*(r?.buoyancy??r?.value??1),c=p.kind===$c?{x:.22*(r?.pull?.x??-8),y:.22*(r?.pull?.y??22)}:{x:0,y:0};return al(t,{x:28*(e.x-t.x)-3*(t.vx-g.vx)+c.x+.01*v,y:28*(e.y-t.y)-3*(t.vy-g.vy)+c.y-a})}if(m.killed)return al(t,{x:44*((m.crashX??m.metrics.lastX??t.x)-t.x)-9*t.vx,y:(160+12*b)*x-1.6*t.vy});const w=c(m),k=function(e,t,n,i,r,o,s){const a=zc(n);if(t.killed)return{x:t.metrics.lastX??i.graveyardX,y:i.graveyardY};const c=r[r.length-1];if(!c)return{x:i.socketX,y:i.routeY};const l=r.find(n=>e>=n.time&&!t.eventsApplied.includes(n.id)&&!(!n.gateId||!o.get(n.gateId)?.capacity)),d=l?Math.min(e,l.time):e,u="built"===t.outcome||"built_diminished"===t.outcome;if(d>c.time+.85){if("hold-last"===s){const e=c.gateId?o.get(c.gateId):void 0;return{x:c.routeX??e?.x??i.socketX,y:c.routeY??i.routeY}}return u?{x:i.socketX,y:i.socketY}:{x:i.graveyardX,y:i.graveyardY-14}}const h=.85*t.delay+12*t.negativeIds.length+8*(t.poppedPositiveIds.length+t.missingPositiveIds.length),p=[{time:0,x:i.startX,y:i.startY},...r.map(e=>{const t=e.gateId?o.get(e.gateId):void 0;return{time:e.time,x:e.routeX??t?.x??i.startX,y:e.routeY??i.routeY+.28*Math.min(180,h)*a}})].sort((e,t)=>e.time-t.time);let f=p[0],m=p[p.length-1];for(let e=1;p.length>e;e+=1){if(p[e].time>=d){m=p[e];break}f=p[e]}const y=Math.max(0,Math.min(1,(d-f.time)/Math.max(.1,m.time-f.time))),g=y*y*(3-2*y);return{x:f.x+(m.x-f.x)*g,y:f.y+(m.y-f.y)*g+7*Math.sin(2.6*d)*a}}(Math.max(0,h-(m.startedAt??0)),m,i,y,w,l,u),M=m.activePositiveIds.reduce((e,t)=>e+(s.get(t)?.buoyancy??s.get(t)?.value??1),0);return al(t,"net"===d?{x:15*(k.x-t.x)-1.8*t.vx+.18*v,y:1.25*(y.routeY-t.y)-1.4*t.vy+32*(b-M)}:{x:15*(k.x-t.x)-1.8*t.vx+.18*v,y:15*(k.y-t.y)-1.8*t.vy+13*b-2.2*M})}({body:e,bodies:t,layout:V,states:J.current,projectPlacement:k,positiveById:X,negativeById:_,projectEvents:he,gateById:U,coreForceMode:r,terminalBehavior:A,elapsed:ee.current}),[r,U,V,_,X,he,k,A]),ve=(0,Ic.useCallback)((e,t)=>{!function(e,t,n){const{frameProps:i,elapsedRef:r,statesRef:o,crashDetection:s,layout:a,projectEvents:c,gateById:l,capacityEventReady:d,addBodiesForEffect:u,updateProjectState:h,viability:p,positiveById:f,negativeById:m,outcome:y,reportCapacity:g}=n;i.onTick?.(e,t),r.current=e.elapsedSeconds??t.snapshot().elapsedSeconds,g();for(const e of o.current){const n=t.readBodies().find(t=>t.id===Ec(e.id));if(!n)continue;if(s&&!e.killed&&n.y+("circle"===n.shape.type?n.shape.radius:28)>=a.crashY){t.readBodies().forEach(n=>{const i=n.datum;i?.__gauntlet&&i.projectId===e.id&&t.applyImpulse(n.id,-n.vx*n.mass,0)}),h(e.id,e=>{const t={appliedAt:Math.max(0,r.current-(e.startedAt??0)),id:"gauntlet-crash-line",label:"Crash Line",summary:"The project hit the crash threshold; lift and forward motion shut off.",time:Math.max(0,r.current-(e.startedAt??0))};return{...e,crashX:n.x,eventHistory:[...e.eventHistory??[],t],killed:!0,lastEvent:t,metrics:{...e.metrics,lastX:n.x},outcome:"bad_design_crash",stage:"Crash Line",viability:Math.min(0,e.viability)}});continue}if(e.killed)continue;const i=Math.max(0,r.current-(e.startedAt??0)),o=c(e),g=o.filter(t=>i>=t.time&&!e.eventsApplied.includes(t.id)&&d(e,t,o));let x=e;for(const n of g){const r=n.gateId?l.get(n.gateId):void 0,o=n.effects??[];for(const e of o){const i={event:n,gate:r,negativeProperties:m,positiveProperties:f,project:x};e.when&&!e.when(i)||(u(x,e,t),x=nl(x,e,i))}const s={...il(n,o),appliedAt:i};x=rl(x,s),h(e.id,e=>{let t=rl(e,s);if(t===e)return e;for(const e of o)t=nl(t,e,{event:n,gate:r,negativeProperties:m,positiveProperties:f,project:t});const i=p?.(t,{negativeProperties:m,positiveProperties:f})??Xc(t,f,m);return t={...t,viability:i},n.final&&(t={...t,outcome:n.outcome??y?.(t,{layout:a,negativeProperties:m,positiveProperties:f})??(t.viability>20?"built":"approved_not_built")}),t})}}}(e,t,{frameProps:d,elapsedRef:ee,statesRef:J,crashDetection:o,layout:V,projectEvents:he,gateById:U,capacityEventReady:pe,addBodiesForEffect:xe,updateProjectState:ye,viability:C,positiveById:X,negativeById:_,outcome:b,reportCapacity:fe})},[xe,pe,o,d,U,V,_,b,X,he,fe,ye,C]),we=(0,Ic.useCallback)((e,t)=>{const n="function"==typeof d.bodyStyle?d.bodyStyle(e,t):d.bodyStyle,i=e.datum;return i?.__gauntlet?{fill:i.kind===Pc?"var(--semiotic-accent, #0f766e)":i.property?.color??"var(--semiotic-accent, #38bdf8)",stroke:i.kind===Pc?"#f8fafc":"#0f172a",opacity:.96,...n}:n??{}},[d]),ke=(0,Ic.useMemo)(()=>"function"==typeof n?n(Q,V):n??[],[n,V,Q]),Me=(0,Ic.useMemo)(()=>Rc(ke),[ke]),Se=(0,Ic.useMemo)(()=>B?function(e,t){if(!e.length)return[];const n=Math.max(40,(t.width-80)/e.length);return e.map((e,t)=>{const i=`${e.id}: viability ${Math.round(e.viability)}, ${e.outcome||e.stage}`;return{id:"gauntlet-projection-"+e.id,label:i,description:i,datum:e,x:40+(t+.5)*n,y:28,shape:"rect",width:Math.max(16,.55*n),height:22,group:"settled projection"}})}(Q,V):[],[V,B,Q]),Ie=(0,Ic.useMemo)(()=>[...Se,...Me],[Me,Se]),je=(0,Ic.useCallback)((e,t)=>{d.onBodyPointerDown?.(e,t)},[d]),Ae=(0,Ic.useCallback)((e,t)=>{g&&(e&&"object"==typeof e&&e.__gauntlet?g(e.sourceDatum,{x:t.x,y:t.y}):e&&g(e,{x:t.x,y:t.y}))},[g]),Ce=(0,Ic.useCallback)((e,t)=>{d.beforePaint?.(e,t),j&&function(e,t){const n=new Map(t.filter(e=>e.datum?.kind===Pc).map(e=>[e.datum.projectId,e]));e.save(),e.lineWidth=1.1,e.setLineDash([3,4]);for(const i of t){const t=i.datum;if(!t?.__gauntlet||t.kind===Pc)continue;const r=n.get(t.projectId);r&&(e.globalAlpha=t.kind===$c?.24:.36,e.strokeStyle=t.kind===$c?"#d94a45":"#7a8794",e.beginPath(),e.moveTo(r.x,r.y),e.lineTo(i.x,i.y),e.stroke())}e.restore()}(e,t)},[d,j]),Re=(0,Ic.useMemo)(()=>[...K,...d.regionEffects??[]],[d.regionEffects,K]);if(Y)return Y;const Pe=Xa(e.tooltip,d),De=_a(e,d,Ie,{chartMode:W,className:N,title:E,description:F,summary:z,accessibleTable:L,enableHover:O,margin:q}),$e=B?(0,yl.jsx)(ml,{states:Q,layout:V}):void 0,Be=Ga(T?(0,yl.jsx)(pl,{layout:V,states:Q,compact:D.resolved.compactMode}):void 0,d.backgroundGraphics),Te=Ga($e,d.foregroundGraphics),Ne=d.renderBody??dl,Ee=Pe.tooltipContent??ll;return Ha("GauntletChart",$,(0,gl.createElement)(ts,{...d,...Pe,...De,key:`${$[0]}x${$[1]}:${G}:${le.rerunKey}`,ref:R,accessibleTable:e.accessibleTable??d.accessibleTable,backgroundGraphics:Be,bodyForces:be,bodySemanticItems:d.bodySemanticItems??fl,bodyStyle:we,beforePaint:Ce,onClick:g?Ae:De.onClick,config:le.config,controllers:ue,enableHover:Pe.enableHover??!0,foregroundGraphics:Te,hoverRadius:e.hoverRadius??d.hoverRadius??18,initialSpawns:me,initialSpawnPacing:h,onBodyPointerDown:je,onTick:ve,paused:v,regionEffects:Re,renderBody:Ne,responsiveHeight:S,responsiveWidth:I,size:$,tooltipContent:Ee}))});bl.displayName="GauntletChart";var vl=bl,wl=require("react"),kl=require("react/jsx-runtime");function Ml(e){return e.toLocaleString(void 0,1e3>Math.abs(e)?{maximumFractionDigits:1}:{maximumFractionDigits:0})}function Sl(e){return e.map((e,t)=>`${0===t?"M":"L"} ${e.x} ${e.y}`).join(" ")}function Il(e){if(!e||"object"!=typeof e)return null;const t=e,n=Number(t.x),i=Number(t.y);return Number.isFinite(n)&&Number.isFinite(i)?{x:n,y:i}:null}function jl(e){if(!e||"object"!=typeof e)return[];const t=e.flowPath;return Array.isArray(t)?t.map(Il).filter(e=>null!=e):[]}function Al(e,t){if(2>t.length)return null;let n=0;const i=[];for(let e=1;t.length>e;e+=1){const r=Math.hypot(t[e].x-t[e-1].x,t[e].y-t[e-1].y);i.push(r),n+=r}if(0>=n)return null;let r=null,o=0;for(let s=1;t.length>s;s+=1){const a=t[s-1],c=t[s],l=i[s-1];if(0>=l)continue;const d=c.x-a.x,u=c.y-a.y,h=Math.max(0,Math.min(1,((e.x-a.x)*d+(e.y-a.y)*u)/(l*l))),p={x:a.x+d*h,y:a.y+u*h},f={distance:Math.hypot(e.x-p.x,e.y-p.y),point:p,progress:(o+h*l)/n,tangent:{x:d/l,y:u/l},totalLength:n};r&&f.distance>=r.distance||(r=f),o+=l}return r}function Cl(e,t,n){if(0===e.length)return{x:0,y:0};if(1===e.length||0>=n)return{...e[0]};let i=0;const r=Math.max(0,Math.min(1,t))*n;for(let t=1;e.length>t;t+=1){const n=e[t-1],o=e[t],s=Math.hypot(o.x-n.x,o.y-n.y);if(s>0){if(i+s>=r){const e=(r-i)/s;return{x:n.x+(o.x-n.x)*e,y:n.y+(o.y-n.y)*e}}i+=s}}return{...e[e.length-1]}}function Rl(e){return"circle"===e.shape.type?e.shape.radius:Math.max(e.shape.width,e.shape.height)/2}function Pl(e,t,n){const i=Math.hypot(e,t);if(n>=i||0>=i)return[e,t];const r=n/i;return[e*r,t*r]}function Dl(e,t,n){const i=Al({...e,x:t[0].x,y:t[0].y},t),r=i?.tangent??{x:t[1].x-t[0].x,y:t[1].y-t[0].y},o=Math.hypot(r.x,r.y)||1,s=r.x/o,a=r.y/o,c=Rl(e),l=function(e,t){let n=0;for(let t=0;e.length>t;t+=1)n=31*n+e.charCodeAt(t)>>>0;return(n%1e3/1e3-.5)*t*1.4}(e.id,c);return{id:e.id,x:t[0].x+-a*l,y:t[0].y+s*l,vx:s*n,vy:a*n,mass:e.mass,shape:e.shape,datum:{...e.datum&&"object"==typeof e.datum?e.datum:{},routeProgress:0}}}var $l=(0,wl.forwardRef)(function(e,t){const{chartId:n,colorBy:i,coordinateMode:r="auto",data:o,edges:s,emptyContent:a,flowSpeed:c=90,frameProps:l,links:d,loading:u,loadingContent:h,maxParticles:p=180,nodeIdAccessor:f="id",nodeXAccessor:m="x",nodeYAccessor:y="y",nodes:g,onObservation:x,particleRadius:b=4,particleRate:v=.16,pathAccessor:w="path",pathConstraint:k="path",paused:M,reducedMotion:S=!1,responsiveHeight:I,responsiveWidth:j,seed:A=1,showNodeLabels:C=!0,showSensors:R=!1,showStaticFlow:P=!0,sourceAccessor:D="source",styleRules:$,targetAccessor:B="target",throughputAccessor:T="value"}=e,N=La(e,[760,420]),{chartSize:E,className:W,title:q,chartMode:O,margin:F,enableHover:z,description:L,summary:Y,accessibleTable:H}=N,G=(0,wl.useRef)(null),X=(0,wl.useMemo)(()=>g??[],[g]),_=(0,wl.useMemo)(()=>d??s??o??[],[o,s,d]),V=(0,wl.useMemo)(()=>Ts({nodes:X,links:_,nodeIdAccessor:f,nodeXAccessor:m,nodeYAccessor:y,sourceAccessor:D,targetAccessor:B,throughputAccessor:T,pathAccessor:w,coordinateMode:r,particleRate:v,maxParticles:p,particleRadius:b,flowSpeed:c,pathConstraint:k,reducedMotion:S,seed:A,size:E}),[_,X,E,r,c,p,f,m,y,b,v,w,k,S,A,D,B,T]);ca(t,{frameRef:G,spawnDatum:(0,wl.useCallback)((e,t)=>{const n=Ts({nodes:X,links:[e],nodeIdAccessor:f,nodeXAccessor:m,nodeYAccessor:y,sourceAccessor:D,targetAccessor:B,throughputAccessor:T,pathAccessor:w,coordinateMode:r,particleRate:v,maxParticles:p,particleRadius:b,flowSpeed:c,pathConstraint:k,reducedMotion:S,seed:A+t+1,size:E}),i={id:(e.id??"physical-flow-push-"+t)+"",x:cs(E).plot.x,y:cs(E).plot.y,mass:1,shape:{type:"circle",radius:b},datum:e},o=n.initialSpawns.length?n.initialSpawns:[i];return{datumId:(e.id??o[0].id)+"",spawns:o}},[X,E,r,c,p,f,m,y,b,v,w,k,S,A,D,B,T]),seedRows:_,seedSpawns:V.initialSpawns});const U=i??"source",K=(0,wl.useMemo)(()=>ds(U,"#2563eb",{styleRules:$,valueAccessor:T}),[U,$,T]),Q=(0,wl.useMemo)(()=>function(e,t,n){return{...e,observation:{...e.observation,chartId:t??e.observation?.chartId??"physical-flow",chartType:"PhysicalFlowChart",onObservation:n??e.observation?.onObservation}}}(V.config,n,x),[n,V.config,x]),Z=(0,wl.useRef)(l?.onTick);Z.current=l?.onTick;const J=(0,wl.useCallback)((e,t)=>{S||"none"===k||function(e,t){const n=e.readBodies(),i=[],r=[];for(const o of n){const n=jl(o.datum);if(2>n.length)continue;const s=Al(o,n);if(!s)continue;const a=o.datum,c=Number(a?.flowSpeed),l=Number.isFinite(c)&&c>0?c:t;if(s.progress>=.985||s.distance>Math.max(90,14*Rl(o))){i.push(o.id),r.push(Dl(o,n,l));continue}const d=Cl(n,Math.min(1,s.progress+Math.max(.035,Math.min(.12,l/s.totalLength*.16))),s.totalLength),u=s.tangent,h=(u.x*l-o.vx)*o.mass*.16+(d.x-o.x)*o.mass*.045+(s.point.x-o.x)*o.mass*.08,p=(u.y*l-o.vy)*o.mass*.16+(d.y-o.y)*o.mass*.045+(s.point.y-o.y)*o.mass*.08,[f,m]=Pl(h,p,o.mass*l*.35);e.applyImpulse(o.id,f,m)}i.length&&e.remove(i),r.length&&e.pushMany(r)}(t,c),Z.current?.(e,t)},[c,k,S]),ee=Ya({data:null==d&&null==s&&null==o?void 0:_,emptyContent:a,loading:u,loadingContent:h,size:E});if(ee)return ee;const te=function(e,t){const{showNodeLabels:n,showSensors:i,showStaticFlow:r}=t;if(e&&(r||i))return({size:t})=>{const o=[Number(t[0])||760,Number(t[1])||420],s=Math.max(1,...e.links.map(e=>e.throughput)),a=new Set(e.nodes.map(e=>e.sensorId));return(0,kl.jsxs)("svg",{"aria-hidden":"true","data-testid":"physical-flow-static-flow-overlay",width:o[0],height:o[1],viewBox:`0 0 ${o[0]} ${o[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[r?e.links.map(e=>{const t=3+e.throughput/s*16,n=e.path[Math.floor(e.path.length/2)];return(0,kl.jsxs)("g",{children:[(0,kl.jsx)("path",{d:Sl(e.path),fill:"none",stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:t+5,strokeLinecap:"round",strokeLinejoin:"round",opacity:.26}),(0,kl.jsx)("path",{d:Sl(e.path),fill:"none",stroke:"var(--semiotic-accent, #4e79a7)",strokeWidth:t,strokeLinecap:"round",strokeLinejoin:"round",opacity:.16}),n?(0,kl.jsx)("text",{x:n.x,y:n.y-t/2-5,textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:Ml(e.throughput)}):null]},e.id)}):null,e.nodes.map(e=>(0,kl.jsxs)("g",{children:[i&&a.has(e.sensorId)?(0,kl.jsx)("rect",{"data-testid":"physical-flow-sensor-overlay",x:e.x-12,y:e.y-12,width:24,height:24,rx:4,fill:"none",stroke:"var(--semiotic-warning, #f59e0b)",strokeDasharray:"3 3",strokeWidth:1.5,opacity:.88}):null,r?(0,kl.jsx)("circle",{cx:e.x,cy:e.y,r:6,fill:"var(--semiotic-bg, #fff)",stroke:"var(--semiotic-text-secondary, #555)",strokeWidth:1.2}):null,n?(0,kl.jsx)("text",{x:e.x,y:e.y-14,textAnchor:"middle",fill:"var(--semiotic-text-primary, #111827)",fontSize:11,fontWeight:800,children:e.label}):null]},e.id))]})}}(V.metadata,{showNodeLabels:C,showSensors:R,showStaticFlow:P}),ne=(ie=V.metadata)?ie.links.map(e=>{const t=e.path[Math.floor(e.path.length/2)]??e.path[0],n=`${e.sourceLabel} to ${e.targetLabel}: ${Ml(e.throughput)} throughput, ${e.packetCount} packets`;return{id:e.id,label:n,description:n,datum:e,x:t?.x??0,y:t?.y??0,shape:"path",pathData:Sl(e.path),group:"flow"}}):[];var ie;const re=Xa(e.tooltip,l),oe=_a(e,l,ne,{chartMode:O,className:W,title:q,description:L,summary:Y,accessibleTable:H,enableHover:z,margin:F});return Ha("PhysicalFlowChart",E,(0,kl.jsx)(ts,{...l,...re,...oe,ref:G,config:Q,continuous:!S&&"none"!==k,foregroundGraphics:Ga(te,l?.foregroundGraphics),initialSpawns:V.initialSpawns,onTick:J,paused:M||S,responsiveHeight:I,responsiveWidth:j,simulationExecution:"none"===k?l?.simulationExecution:"sync",size:E,bodyStyle:K,workerBodyThreshold:l?.workerBodyThreshold??1/0}))});$l.displayName="PhysicalFlowChart";var Bl=require("react"),Tl=require("react/jsx-runtime"),Nl={flow:{fill:"rgba(59, 130, 246, 0.14)",stroke:"rgba(96, 165, 250, 0.7)",accent:"#60a5fa"},capacity:{fill:"rgba(251, 146, 60, 0.18)",stroke:"rgba(251, 146, 60, 0.85)",accent:"#fb923c"},portal:{fill:"rgba(244, 114, 182, 0.14)",stroke:"rgba(244, 114, 182, 0.7)",accent:"#f472b6"},absorb:{fill:"rgba(52, 211, 153, 0.18)",stroke:"rgba(52, 211, 153, 0.8)",accent:"#34d399"}},El=6.2;function Wl(e,t,n){return Math.max(t,Math.min(n,e))}function ql(e){return e.length*El}function Ol(e,t){const n=e.trim();if(t>=n.length)return n;if(1>=t)return n.slice(0,1);const i=n.split(/\s+/).filter(Boolean).map(e=>e[0]).join("").toUpperCase();return i.length>1&&t>=i.length?i:t>3?n.slice(0,Math.max(1,t-2))+"..":n.slice(0,t).toUpperCase()}function Fl(e,t,n="auto"){const i=Math.max(1,Math.floor(t/El)),r="compact"===n?Ol(e,i):"full"===n?e:ql(e)>t?Ol(e,i):e;return{text:r,textLength:ql(r)>t?Math.max(4,t):void 0}}function zl(e,t={}){const{showFlowSpine:n=!0,showStageCounts:i=!0,showCapacityBadges:r=!0,showGroupSockets:o=!0,stageLabelMode:s="auto",outlineStages:a=!1,testId:c="process-flow-chrome"}=t,{width:l,height:d,left:u,right:h,topY:p,bottomY:f,midY:m,stages:y,groups:g=[]}=e,x=f-p;return(0,Tl.jsxs)("svg",{"aria-hidden":"true","data-testid":c,"data-outline-stages":a?"true":void 0,width:l,height:d,viewBox:`0 0 ${l} ${d}`,style:{position:"absolute",inset:0,pointerEvents:"none"},className:["semiotic-process-chrome",a?"semiotic-process-chrome--outline-stages":null].filter(Boolean).join(" "),children:[(0,Tl.jsx)("defs",{children:(0,Tl.jsxs)("linearGradient",{id:"semiotic-process-floor",x1:"0",x2:"0",y1:"0",y2:"1",children:[(0,Tl.jsx)("stop",{offset:"0%",stopColor:"var(--semiotic-process-floor, var(--semiotic-bg, #0f172a))",stopOpacity:"0.2"}),(0,Tl.jsx)("stop",{offset:"100%",stopColor:"var(--semiotic-process-lane, var(--semiotic-surface, #1e293b))",stopOpacity:"0.55"})]})}),(0,Tl.jsx)("rect",{x:0,y:0,width:l,height:d,fill:"url(#semiotic-process-floor)"}),(0,Tl.jsx)("rect",{x:u-6,y:p-8,width:h-u+12,height:x+16,rx:14,fill:"var(--semiotic-process-lane, var(--semiotic-surface, #111827))",fillOpacity:.45,stroke:"var(--semiotic-process-border, var(--semiotic-border, #334155))",strokeOpacity:.95}),n?(0,Tl.jsx)("line",{x1:u+8,x2:h-8,y1:m,y2:m,stroke:"var(--semiotic-process-border, var(--semiotic-border, #475569))",strokeWidth:2,strokeDasharray:"6 8",opacity:.55}):null,y.map((e,t)=>{const n=function(e){return e.absorb?"absorb":e.portalTarget?"portal":null!=e.capacity?"capacity":"flow"}(e),o=Nl[n],c=Math.max(12,e.width-8),l=Wl(c-8,22,88),u=Fl(e.label,Math.max(8,l-10),s),h="none"!==s&&c-8>=22,g=function(e){if(null!=e.capacity){const t=null!=e.queueDepth?" · q "+e.queueDepth:"";return e.capacityLabel?`${e.capacityLabel}${t}`:`cap ${Number.isInteger(e.capacity)?e.capacity+"":e.capacity.toFixed(1)}${t}`}return e.absorb?"absorb":e.portalTarget?"portal":"flow"}(e),b=Fl(g,Math.max(16,c-10),"auto"),v=r&&!1!==e.showBadge&&c>=32,w=null!=e.count?`n=${e.count}${null!=e.processed?" done "+e.processed:""}`:"",k=Fl(w,Math.max(16,c-8),"auto"),M=Math.max(30,p-15),S=M-13;return(0,Tl.jsxs)("g",{"data-stage":e.id,"data-role":n,children:[(0,Tl.jsx)("rect",{className:"semiotic-process-chrome__stage-bay",x:e.x0+4,y:p+6,width:c,height:x-12,rx:10,fill:a?"none":o.fill,stroke:o.stroke,strokeWidth:a?1.85:"flow"===n?1:1.6}),y.length-1>t?(0,Tl.jsx)("polygon",{points:`${e.x1-2},${m-7} ${e.x1+8},${m} ${e.x1-2},${m+7}`,fill:o.accent,opacity:.85}):null,h?(0,Tl.jsxs)(Tl.Fragment,{children:[(0,Tl.jsx)("rect",{className:"semiotic-process-chrome__stage-label-bg",x:e.x-l/2,y:S,width:l,height:18,rx:9,fill:"var(--semiotic-bg, #0f172a)",fillOpacity:.75,stroke:o.stroke}),(0,Tl.jsxs)("text",{x:e.x,y:M,textAnchor:"middle",fill:o.accent,fontSize:10,fontWeight:800,className:"semiotic-process-chrome__stage-label",textLength:u.textLength,lengthAdjust:u.textLength?"spacingAndGlyphs":void 0,children:[(0,Tl.jsx)("title",{children:e.label}),u.text]})]}):null,v?(0,Tl.jsxs)("text",{x:e.x,y:p+22,textAnchor:"middle",fill:"var(--semiotic-process-muted, var(--semiotic-text-secondary, #94a3b8))",fontSize:9,fontWeight:700,textLength:b.textLength,lengthAdjust:b.textLength?"spacingAndGlyphs":void 0,children:[(0,Tl.jsx)("title",{children:g}),b.text]}):null,i&&null!=e.count?(0,Tl.jsxs)("text",{x:e.x,y:Math.min(d-8,f+16),textAnchor:"middle",fill:"var(--semiotic-process-text, var(--semiotic-text, #e2e8f0))",fontSize:11,fontWeight:800,textLength:k.textLength,lengthAdjust:k.textLength?"spacingAndGlyphs":void 0,children:[(0,Tl.jsx)("title",{children:w}),k.text]}):null]},e.id)}),o?g.map((e,t)=>{const n=e.total??0,i=e.absorbed??0,r=e.complete??(n>0&&i>=n),o=!r&&n>0&&i/n>=.75,s=r?"rgba(52, 211, 153, 0.35)":o?"rgba(251, 191, 36, 0.28)":"rgba(15, 23, 42, 0.75)",a=r?"#34d399":o?"#fbbf24":"var(--semiotic-border, #64748b)",c=n>0?`${i}/${n}${r?" shipped":o?" almost":""}`:"feature "+(t+1),l=Wl(Math.max(54,ql(e.label)+18,ql(c)+16),54,104),d=Fl(e.label,l-12,"auto"),u=Fl(c,l-12,"auto");return(0,Tl.jsxs)("g",{"data-group":e.id,children:[(0,Tl.jsx)("rect",{x:e.x-l/2,y:e.y-22,width:l,height:44,rx:10,fill:s,stroke:a,strokeWidth:1.5}),(0,Tl.jsxs)("text",{x:e.x,y:e.y-4,textAnchor:"middle",fill:"var(--semiotic-process-text, var(--semiotic-text, #f8fafc))",fontSize:10,fontWeight:800,textLength:d.textLength,lengthAdjust:d.textLength?"spacingAndGlyphs":void 0,children:[(0,Tl.jsx)("title",{children:e.label}),d.text]}),(0,Tl.jsxs)("text",{x:e.x,y:e.y+12,textAnchor:"middle",fill:a,fontSize:9,fontWeight:700,textLength:u.textLength,lengthAdjust:u.textLength?"spacingAndGlyphs":void 0,children:[(0,Tl.jsx)("title",{children:c}),u.text]})]},e.id)}):null]})}var Ll=require("react/jsx-runtime"),Yl=(0,Bl.forwardRef)(function(e,t){const{ballRadius:n=6,chromeOptions:i,colorBy:r,data:o,emptyContent:s,frameProps:a={},groupAnchorAlong:c,groupBy:l,groupCompletion:d,groupLabelAccessor:u,gravityX:h,gravityY:p,idAccessor:f,initialSpawnPacing:m,liveCapacity:y=!0,onCapacityChange:g,selection:x,bodyLimit:b,bodyMark:v,loading:w,loadingContent:k,paused:M,radiusAccessor:S,responsiveHeight:I,responsiveWidth:j,route:A="horizontal",seed:C=1,settle:R,springDamping:P,springStiffness:D,stageAccessor:$="stage",stages:B,workAccessor:T}=e,N=La(e,[900,420]),{chartSize:E,showProjection:W,showChrome:q,className:O,title:F,chartMode:z,margin:L,enableHover:Y,description:H,summary:G,accessibleTable:X}=N,_=(0,Bl.useRef)(null),V=(0,Bl.useMemo)(()=>rc(o??[]),[o]),U=(0,Bl.useMemo)(()=>({data:V,stages:B,size:E,idAccessor:f,stageAccessor:$,groupBy:l,groupLabelAccessor:u,workAccessor:T,radiusAccessor:S,ballRadius:n,seed:C,route:A,groupCompletion:d,groupAnchorAlong:c,springStiffness:D,springDamping:P,gravityX:h,gravityY:p,settle:R}),[n,E,h,p,c,l,d,u,f,S,A,V,C,R,P,D,$,B,T]),K=(0,Bl.useMemo)(()=>ia(U),[U]),Q=K.metadata;ca(t,{frameRef:_,spawnDatum:(0,Bl.useCallback)((e,t)=>{const i=ia({...U,data:[e],seed:C+t+1,settle:!0}).initialSpawns[0]??{id:(e.id??"process-flow-push-"+t)+"",x:cs(E).plot.x,y:cs(E).plot.y,mass:1,shape:{type:"circle",radius:n},datum:e};return{datumId:(e.id??i.id)+"",spawns:[i]}},[n,U,E,C]),seedRows:V,seedSpawns:K.initialSpawns});const Z=(0,Bl.useMemo)(()=>ds(r),[r]),J=(0,Bl.useMemo)(()=>{if(!y)return a.controllers;const e=[...B.filter(e=>e.capacity&&e.capacity.unitsPerSecond>0).map(e=>{const t=e.capacity.unitsPerSecond;return Tr({id:"process-capacity-"+e.id,regionId:"process-stage-"+e.id,unitsPerSecond:t,unitAccessor:e.capacity.unitAccessor??(T?"string"==typeof T?T:e=>{const t=e.datum;if(!t)return 1;try{return Number(T(t,0))||1}catch{return 1}}:"work"),releaseImpulse:{x:70+Math.min(40,2*t),y:0},queueLayout:"lane",continuous:!0})}),...a.controllers??[]];return e.length?e:void 0},[a.controllers,y,B,T]),[ee,te]=(0,Bl.useState)({}),ne=(0,Bl.useRef)(J);ne.current=J;const ie=(0,Bl.useRef)(a.onTick);ie.current=a.onTick;const re=!1!==q||null!=g;(0,Bl.useEffect)(()=>{if(!g)return;const e=Object.values(ee);e.length&&g(e)},[ee,g]);const oe=(0,Bl.useCallback)((e,t)=>{if(ie.current?.(e,t),!re)return;const n=ne.current;if(!n?.length)return;const i={};for(const e of n){const t=e.getSnapshot?.();t&&"string"==typeof t.regionId&&(i[t.regionId]=t)}te(e=>function(e,t){const n=Object.keys(e),i=Object.keys(t);if(n.length!==i.length)return!1;for(const i of n){const n=e[i],r=t[i];if(!r)return!1;if(n.queueDepth!==r.queueDepth||n.blockedDepth!==r.blockedDepth||n.processedCount!==r.processedCount||n.unitsPerSecond!==r.unitsPerSecond||n.regionId!==r.regionId||n.metricRevision!==r.metricRevision)return!1}return!0}(e,i)?e:i)},[re]),se=(0,Bl.useMemo)(()=>{const e=Z,t=a.bodyStyle;return v||t?(n,i)=>{const r="function"==typeof t?t(n,i):t;return{..."function"==typeof e?e(n):e,...r,mark:r?.mark??n.datum?.__physicsMark??n.datum?.mark??v}}:e},[v,Z,a.bodyStyle]),ae=Ya({data:o,emptyContent:s,loading:w,loadingContent:k,size:E});if(ae)return ae;if(!B?.length)return Ha("ProcessFlowChart",E,(0,Ll.jsx)("div",{role:"status",style:{width:E[0],height:E[1],display:"grid",placeItems:"center",color:"var(--semiotic-text-secondary, #64748b)"},children:"ProcessFlowChart requires a non-empty stages array."}));const ce=function(e,t,n={},i){if(!1===t||!e)return;const{volume:r,stages:o,groups:s,groupCompletion:a}=e,c=new Map(r.stages.map(e=>[e.id,e])),l=new Map(a.map(e=>[e.id,e]));return({size:e})=>{const t=Number(e[0])||r.width,a=Number(e[1])||r.height,d=o.map(e=>{const t=c.get(e.id),i=n["process-stage-"+e.id];return{id:e.id,label:e.label,x0:t?.x0??e.x-e.width/2,x1:(t?.x0??e.x-e.width/2)+(t?.width??e.width),x:e.x,width:t?.width??e.width,count:e.count,capacity:e.capacity,absorb:e.absorb,portalTarget:e.portalTarget,queueDepth:i?.queueDepth,processed:i?.processedCount}}),u=s.map(e=>{const t=l.get(e.id);return{id:e.id,label:e.label??e.id,x:e.anchor?.x??e.x??0,y:e.anchor?.y??e.y??0,absorbed:t?.absorbed,total:t?.total,complete:t?.complete}});return zl({width:t,height:a,left:r.left,right:r.right,topY:r.topY,bottomY:r.bottomY,midY:r.midY,stages:d,groups:u},{showCapacityBadges:!0,showGroupSockets:!0,...i})}}(Q,q,ee,i),le=function(e,t,n){if(!1===n||!t||0===e.length)return;const i=new Map(t.volume.stages.map(e=>[e.id,e]));return({size:n})=>{const r=[Number(n[0])||t.volume.width,Number(n[1])||t.volume.height],o=cs(r),s=Math.max(1,...e.map(e=>e.value)),a=Math.min(48,.18*o.plot.height),c=o.plot.y+6;return(0,Ll.jsx)("svg",{"aria-hidden":"true","data-testid":"process-flow-projection-overlay",width:r[0],height:r[1],viewBox:`0 0 ${r[0]} ${r[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:t.stages.map((t,n)=>{const r=e[n];if(!r)return null;const o=i.get(t.id);if(!o)return null;const l=Math.max(2,r.value/s*a),d=Math.max(8,.35*o.width);return(0,Ll.jsx)("rect",{x:o.x-d/2,y:c,width:d,height:l,rx:2,fill:"var(--semiotic-primary, #4e79a7)",fillOpacity:.18,stroke:"var(--semiotic-primary, #4e79a7)",strokeOpacity:.45,strokeWidth:1},t.id)})})}}(K.projectionRows,Q,W),de=[...hs(K.projectionRows,E,"stage"),...Rc(Q?.groups??[])],ue=Xa(e.tooltip,a),he=_a(e,a,de,{chartMode:z,className:O,title:F,description:H,summary:G,accessibleTable:X,enableHover:Y,margin:L}),pe=[...Q?.regionEffects??[],...a.regionEffects??[]];return Ha("ProcessFlowChart",E,(0,Ll.jsx)(ts,{...a,...ue,...he,ref:_,controllers:J,regionEffects:pe,selection:x??a.selection,backgroundGraphics:Ga(ce,a.backgroundGraphics),foregroundGraphics:Ga(le,a.foregroundGraphics),initialSpawns:K.initialSpawns,initialSpawnPacing:m??K.initialSpawnPacing,onTick:oe,paused:M,responsiveHeight:I,responsiveWidth:j,size:E,bodyStyle:se,config:{...K.config,...null!=b?{bodyLimit:b,eviction:"oldest"}:{},...a.config}}))});Yl.displayName="ProcessFlowChart";var Hl=[.1,.5,.9],Gl=1e6,Xl=12;function _l(e){const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:null}function Vl(e,t,n,i,r){return"function"==typeof i?i(e,t,n):function(e,t){let n=e;for(const e of t.split(".")){if(null==n||"object"!=typeof n)return;n=n[e]}return n}(e,i??r)}function Ul(e){const t=Number(e.toFixed(Xl));return Object.is(t,-0)?0:t}function Kl(e,t,n,i){const r=e.flatMap((e,r)=>{const o=_l(Vl(e,r,t,n,"time")),s=_l(Vl(e,r,t,i,"value"));return null==o||null==s?[]:[{time:Ul(o),value:s,index:r}]});r.sort((e,t)=>e.time-t.time||e.index-t.index);const o=[];for(const e of r){const t=o[o.length-1];t?.time===e.time?t.value=e.value:o.push({time:e.time,value:e.value})}return o}function Ql(e,t,n,i){if(!e.length)return null;const r=e[0],o=e[e.length-1];if(r.time>t)return"clamp"===i?r.value:null;if(t>o.time)return"clamp"===i?o.value:null;const s=function(e,t){let n=0,i=e.length;for(;i>n;){const r=n+i>>>1;t>e[r].time?n=r+1:i=r}return n}(e,t),a=e[s];if(a?.time===t)return a.value;const c=e[Math.max(0,s-1)];return"step"!==n&&a&&a.time!==c.time?c.value+(t-c.time)/(a.time-c.time)*(a.value-c.value):c.value}function Zl(e,t){if(1===e.length)return e[0];const n=(e.length-1)*t,i=Math.floor(n),r=Math.ceil(n);return i===r?e[i]:e[i]+(e[r]-e[i])*(n-i)}function Jl(e){const t=e.interpolation??"step",n=e.outsideDomain??"omit",i=function(e){const t=(e??Hl).map(e=>{const t=_l(e);if(null==t||0>t||t>1)throw new RangeError("physicsReferenceEnvelope quantiles must be finite values from 0 to 1; received "+e);return Ul(t)});return Array.from(new Set(t)).sort((e,t)=>e-t)}(e.quantiles),r=function(e){if(Array.isArray(e)){if(e.length>Gl)throw new RangeError(`physicsReferenceEnvelope sampleAt exceeds ${Gl} points`);return Array.from(new Set(e.map(_l).filter(e=>null!=e).map(Ul))).sort((e,t)=>e-t)}const t=e,n=_l(t.start),i=_l(t.end),r=_l(t.step);if(null==n||null==i||null==r||0>=r||n>i)throw new RangeError("physicsReferenceEnvelope sampleAt requires finite start/end values with end >= start and step > 0");const o=Math.floor((i-n)/r)+1;if(o>Gl)throw new RangeError(`physicsReferenceEnvelope sampleAt exceeds ${Gl} points`);const s=[],a=1e-10*Math.max(1,Math.abs(i),Math.abs(n));for(let e=0;o>e;e+=1){const t=n+e*r;if(t>i+a)break;s.push(Ul(Math.min(t,i)))}if(s.length&&a>=Math.abs(s[s.length-1]-i)||s.push(Ul(i)),s.length>Gl)throw new RangeError(`physicsReferenceEnvelope sampleAt exceeds ${Gl} points`);return Array.from(new Set(s)).sort((e,t)=>e-t)}(e.sampleAt),o=e.runs.map(t=>Kl(t.samples,t.id,e.timeAccessor,e.valueAccessor));return{points:r.map(e=>{const r=o.map(i=>Ql(i,e,t,n)).filter(e=>null!=e).sort((e,t)=>e-t),s={};for(const e of i)s[e]=r.length?Zl(r,e):null;return{time:e,count:r.length,min:r.length?r[0]:null,max:r.length?r[r.length-1]:null,median:r.length?Zl(r,.5):null,quantiles:s}}),quantiles:i,interpolation:t,outsideDomain:n,runCount:e.runs.length}}function ed(e,t){return e.quantiles.length?"lower"===t?e.quantiles[0]:e.quantiles[e.quantiles.length-1]:"lower"===t?"min":"max"}function td(e,t){if("min"===t||"median"===t||"max"===t)return e[t];const n=_l(t);if(null==n||0>n||n>1)throw new RangeError("comparePhysicsTrace quantile selectors must be from 0 to 1; received "+t);const i=Ul(n);if(!Object.prototype.hasOwnProperty.call(e.quantiles,i))throw Error(`comparePhysicsTrace could not find quantile ${i} in the reference envelope`);return e.quantiles[i]??null}function nd(e,t,n){return t>e?"below":e>n?"above":"inside"}function id(e,t){const n=Math.max(0,t.time-e.time);if(0>=n||null==e.value||null==e.lower||null==e.upper||null==t.value||null==t.lower||null==t.upper)return{below:0,inside:0,above:0,observed:0};const i=e.value-e.lower,r=t.value-t.lower,o=e.value-e.upper,s=t.value-t.upper,a=[0,1];for(const[e,t]of[[i,r],[o,s]])(0>e&&t>0||e>0&&0>t)&&a.push(-e/(t-e));a.sort((e,t)=>e-t);let c=0,l=0,d=0;for(let i=0;a.length-1>i;i+=1){const r=a[i],o=a[i+1];if(r>=o)continue;const s=(r+o)/2,u=(o-r)*n,h=nd(e.value+(t.value-e.value)*s,e.lower+(t.lower-e.lower)*s,e.upper+(t.upper-e.upper)*s);"below"===h?c+=u:"above"===h?d+=u:l+=u}return{below:c,inside:l,above:d,observed:n}}function rd(e,t,n={}){const i=n.interpolation??t.interpolation,r=n.outsideDomain??t.outsideDomain,o=Kl(e,n.traceId??"trace",n.timeAccessor,n.valueAccessor),s=n.lower??ed(t,"lower"),a=n.upper??ed(t,"upper"),c=t.points.map(e=>{const t=Ql(o,e.time,i,r),n=td(e,s),c=td(e,a);if(null!=n&&null!=c&&n>c)throw new RangeError("comparePhysicsTrace lower band exceeds upper band at time "+e.time);return{time:e.time,value:t,lower:n,upper:c,status:null==t||null==n||null==c?"unobserved":nd(t,n,c)}});let l=0,d=0,u=0,h=0,p=null,f=0,m=null;for(const e of c){if("below"===e.status?l+=1:"inside"===e.status?d+=1:"above"===e.status&&(u+=1),null==e.value||null==e.lower||null==e.upper)continue;const t=Math.max(0,e.value-e.upper),n=Math.max(0,e.lower-e.value);t>h&&(h=t,p=e.time),n>f&&(f=n,m=e.time)}let y=0,g=0,x=0,b=0;for(let e=0;c.length-1>e;e+=1){const t=c[e],n=c[e+1],r=Math.max(0,n.time-t.time);if(r>0){if("linear"===i){const e=id(t,n);y+=e.below,g+=e.inside,x+=e.above,b+=e.observed;continue}"unobserved"!==t.status&&(b+=r,"below"===t.status?y+=r:"above"===t.status?x+=r:g+=r)}}const v=c[0]?.time,w=c[c.length-1]?.time,k=null==v||null==w?0:Math.max(0,w-v);return{points:c,sampleCount:c.length,observedSamples:l+d+u,belowSamples:l,insideSamples:d,aboveSamples:u,totalDuration:k,observedDuration:b,unobservedDuration:Math.max(0,k-b),belowDuration:y,insideDuration:g,aboveDuration:x,peakExcess:h,peakExcessAt:p,peakDeficit:f,peakDeficitAt:m}}function od(e){return{id:e,furthestStageIndex:-1,visitedStageIds:[],visitsByStage:{},firstEnteredAt:{},lastEnteredAt:{},regressionCount:0}}function sd(e){const t=Array.from(new Set(e.bodyIds??[]));return{stages:e.stages.map(e=>({...e})),bodyIds:t,entities:Object.fromEntries(t.map(e=>[e,od(e)]))}}function ad(e,t,n={}){if("region-enter"!==t.type)return e;const i=function(e,t){const n=t.stageId?.(e);if(n)return n;const i=e.region.metadata;if(i&&"object"==typeof i){const e=i.stageId;if("string"==typeof e)return e}return e.region.id}(t,n),r=e.stages.findIndex(e=>e.id===i);if(0>r)return e;const o=n.entityId?.(t)??t.bodyId;if(!o)return e;const s=e.entities[o]??od(o),a=s.currentStageId?e.stages.findIndex(e=>e.id===s.currentStageId):-1,c=!s.visitedStageIds.includes(i),l=Number(t.observation.timestamp),d=Number.isFinite(l)?l:0,u={...s,currentStageId:i,furthestStageId:r>s.furthestStageIndex?i:s.furthestStageId,furthestStageIndex:Math.max(s.furthestStageIndex,r),visitedStageIds:c?[...s.visitedStageIds,i]:s.visitedStageIds,visitsByStage:{...s.visitsByStage,[i]:(s.visitsByStage[i]??0)+1},firstEnteredAt:c?{...s.firstEnteredAt,[i]:d}:s.firstEnteredAt,lastEnteredAt:{...s.lastEnteredAt,[i]:d},regressionCount:a>=0&&a>r?s.regressionCount+1:s.regressionCount};return{...e,bodyIds:e.bodyIds.includes(o)?e.bodyIds:[...e.bodyIds,o],entities:{...e.entities,[o]:u}}}function cd(e){const t=e.bodyIds.map(t=>e.entities[t]??od(t)),n=t.length;let i=n;return e.stages.map((e,r)=>{const o=t.filter(e=>e.furthestStageIndex>=r).length,s=t.filter(t=>t.visitedStageIds.includes(e.id)).length,a=t.reduce((t,n)=>t+(n.visitsByStage[e.id]??0),0),c={id:e.id,label:e.label??e.id,reached:o,entered:s,total:n,conversion:n>0?o/n:0,fromPrevious:i>0?o/i:0,dropoff:Math.max(0,i-o),visits:a,repeatVisits:Math.max(0,a-s)};return i=o,c})}function ld(e){const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:null}function dd(e,t,n,i){const r="function"==typeof e?e(t,n):e;return Number.isFinite(r)?Number(r):i}function ud(e,t,n){return ld(e[t])??n}function hd(e,t){return"number"==typeof e?e:e?.[t]??0}function pd(e){const{band:t,idPrefix:n,plot:i,projection:r}=e,{includeBoundaryWalls:o=!0,includeInteriorWalls:s=!0,wallThickness:a=4}=t,c=function(e){const t=e.bandwidth??e.scale.bandwidth?.()??0,n=new Set;for(const i of e.values){const r=e.scale(i);Number.isFinite(r)&&(n.add(Number(r)),n.add(Number(r)+t))}return Array.from(n).sort((e,t)=>e-t)}(t);if(2>c.length)return[];const l=o?c.length-1:c.length-2,d=[];for(let e=o?0:1;l>=e;e+=1){if(!s&&e>0&&c.length-1>e)continue;const t=c[e];d.push({id:`${n}-wall-${e}`,shape:"x"===r?{type:"aabb",x:t,y:i.y+i.height/2,width:a,height:i.height}:{type:"aabb",x:i.x+i.width/2,y:t,width:i.width,height:a}})}return d}function fd(e){const{plot:t,idPrefix:n="physics-scale",bounds:i={},xBins:r,xBands:o,yBands:s}=e,a=[];if(!1!==i&&a.push(...Qi(t,{idPrefix:n,...i})),r){const{idPrefix:e,yTop:i,yBottom:o,...s}=r;a.push(...Zi({...s,idPrefix:e??n+"-xbin",yTop:i??t.y,yBottom:o??t.y+t.height}))}return o&&a.push(...pd({band:o,idPrefix:o.idPrefix??n+"-xband",plot:t,projection:"x"})),s&&a.push(...pd({band:s,idPrefix:s.idPrefix??n+"-yband",plot:t,projection:"y"})),a}function md(e){const{plot:t,rows:n,columns:i=n+1,pegRadius:r=3,idPrefix:o="galton-peg",yStart:s=t.y+.18*t.height,yEnd:a=t.y+.58*t.height,stagger:c=!0,restitution:l=.2,friction:d=.04}=e,u=Math.max(0,Math.floor(n)),h=Math.max(1,Math.floor(i));if(0===u)return[];const p=u>1?(a-s)/(u-1):0,f=t.width/h,m=[];for(let e=0;u>e;e+=1){const n=c&&e%2==1?f/2:0;for(let i=0;h>i;i+=1){const a=t.x+f*(i+.5)+n;t.x+r>a||a>t.x+t.width-r||m.push({id:`${o}-${e}-${i}`,shape:{type:"aabb",x:a,y:s+e*p,width:2*r,height:2*r},restitution:l,friction:d})}}return m}function yd(e,t={}){const{idPrefix:n="physics-token",radius:i=5,shape:r,mass:o,vx:s,vy:a,spawnAt:c,seed:l=1,jitter:d,datum:u}=t,h=ei(l),p=hd(d,"x"),f=hd(d,"y");return e.map((e,l)=>{const d=dd(t.x,e,l,ud(e,"x",0)),m=dd(t.y,e,l,ud(e,"y",0)),y=dd(i,e,l,5),g="function"==typeof r?r(e,l):r??{type:"circle",radius:y};return{id:`${n}-${e.index??l}`,x:d+(h()-.5)*p,y:m+(h()-.5)*f,vx:dd(s,e,l,0),vy:dd(a,e,l,0),mass:dd(o,e,l,1),spawnAt:dd(c,e,l,void 0),shape:g,datum:u?u(e,l):e.datum??e}}).map(e=>{if(Number.isFinite(e.spawnAt))return e;const{spawnAt:t,...n}=e;return n})}function gd(e,t={}){const{idPrefix:n="sediment",collider:i=!0,colliderThickness:r=1,restitution:o=.05,friction:s=.2,...a}=t,c=Ni(e,a),l=i?c.filter(e=>e.height>0).map(e=>({id:`${n}-${e.binId}`,shape:{type:"aabb",x:e.x+e.width/2,y:e.y+r/2,width:e.width,height:r},restitution:o,friction:s})):[];return{columns:c,colliders:l}}function xd(e,t={}){const{timeAccessor:n="arrivalTime",timeScale:i=1,startAt:r=0,rebase:o=!0,sort:s=!0}=t,a=e.map((e,t)=>({spawn:e,time:function(e,t,n){return ld("function"==typeof n?n(e,t):e[n]??e.datum?.[n])}(e,t,n)??e.spawnAt??t})),c=a.length?Math.min(...a.map(e=>e.time)):0;return{initialSpawns:a.map(({spawn:e,time:t})=>({...e,spawnAt:r+(o?t-c:t)})).sort((e,t)=>s?(e.spawnAt??0)-(t.spawnAt??0):0),initialSpawnPacing:{pacing:"arrival",startAt:r,timeAccessor:"spawnAt",timeScale:i}}}var bd=require("react");function vd(e,t,n={}){const i=new Set,r=[...e.get(t)??[]];let o=0;for(;r.length>o;){const t=r[o];if(o+=1,!i.has(t)){i.add(t);for(const n of e.get(t)??[])r.push(n)}}return n.includeStart&&i.add(t),i}function wd(e,t,n){return gc(n,e,t)}function kd(e,t){return t>e?-1:e>t?1:0}function Md(e,t){return`dependency:${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Sd(e,t){return`socket:${encodeURIComponent(e)}:${t}`}function Id(e){const t=Number(e);return Number.isFinite(t)?Math.max(0,Math.min(1,t)):0}function jd(e){const t=[],n=new Map,i=[],r=new Set;e.data.forEach((o,s)=>{const a=(wd(o,s,e.taskIDAccessor)??"")+"";if(!a)return void t.push({code:"duplicate-task-id",message:`Task row ${s} has an empty id.`,taskIDs:[]});if(n.has(a))return void t.push({code:"duplicate-task-id",message:`Task id "${a}" occurs more than once.`,taskIDs:[a]});const c=(wd(o,s,e.laneAccessor)??"Unassigned")+"";r.has(c)||(r.add(c),i.push(c));const l=wd(o,s,e.dependencyAccessor)??[],d=Array.from(new Set(Array.from(l,e=>e+""))).sort(kd),u=wd(o,s,e.blockerAccessor),h=wd(o,s,e.statusAccessor)??(u?"blocked":"waiting");n.set(a,{id:a,label:(wd(o,s,e.labelAccessor)??a)+"",lane:c,laneIndex:0,level:0,index:s,datum:o,dependencyIDs:d,incomingEdgeIDs:[],outgoingEdgeIDs:[],socketIDs:[],start:wd(o,s,e.startAccessor),end:wd(o,s,e.endAccessor),progress:Id(wd(o,s,e.progressAccessor)),status:h,completionTime:wd(o,s,e.completionTimeAccessor),blockerReason:u||void 0,milestone:!!wd(o,s,e.milestoneAccessor)})});const o=e.laneOrder?[...e.laneOrder,...i.filter(t=>!e.laneOrder?.includes(t))]:i,s=new Map(o.map((e,t)=>[e,t]));for(const e of n.values())e.laneIndex=s.get(e.lane)??0;const a=new Map,c=new Map;for(const e of n.keys())a.set(e,[]),c.set(e,[]);const l=[],d=[...n.values()].sort((e,t)=>e.index-t.index);for(const e of d)e.dependencyIDs.forEach((i,r)=>{const o=n.get(i);if(!o)return void t.push({code:"missing-dependency",message:`Task "${e.id}" depends on missing task "${i}".`,taskIDs:[e.id,i]});const s={id:Md(i,e.id),sourceID:i,targetID:e.id,sourceIndex:o.index,targetIndex:e.index,socketID:Sd(e.id,r),socketIndex:r};l.push(s),a.get(e.id)?.push(s),c.get(i)?.push(s),e.incomingEdgeIDs.push(s.id),e.socketIDs.push(s.socketID),o.outgoingEdgeIDs.push(s.id)});for(const e of a.values())e.sort((e,t)=>kd(e.sourceID,t.sourceID)),e.forEach((e,t)=>{e.socketIndex=t,e.socketID=Sd(e.targetID,t)});for(const e of c.values())e.sort((e,t)=>kd(e.targetID,t.targetID));for(const e of n.values()){const t=a.get(e.id)??[];e.incomingEdgeIDs=t.map(e=>e.id),e.socketIDs=t.map(e=>e.socketID),e.outgoingEdgeIDs=(c.get(e.id)??[]).map(e=>e.id)}const u=new Map,h=new Map;for(const e of n.keys())u.set(e,a.get(e)?.length??0),h.set(e,0);const p=[...n.keys()].filter(e=>0===u.get(e)).sort(kd);let f=0;for(;p.length;){const e=p.shift();f+=1;for(const t of c.get(e)??[]){const n=Math.max(h.get(t.targetID)??0,(h.get(e)??0)+1);h.set(t.targetID,n);const i=(u.get(t.targetID)??0)-1;if(u.set(t.targetID,i),0===i){const e=p.findIndex(e=>e>t.targetID);0>e?p.push(t.targetID):p.splice(e,0,t.targetID)}}}if(f!==n.size){const e=[...n.keys()].filter(e=>(u.get(e)??0)>0).sort(kd);t.push({code:"cycle",message:`Dependency graph contains a cycle involving: ${e.join(", ")}.`,taskIDs:e})}let m=0;const y=[...n.values()].sort((e,t)=>e.index-t.index);for(const e of y)e.level=h.get(e.id)??0,m=Math.max(m,e.level);return{nodes:y,edges:l,byID:n,incoming:a,outgoing:c,lanes:o,maxLevel:m,diagnostics:t,valid:0===t.length}}function Ad(e,t,n={}){const i=Math.max(240,t.width),r=Math.max(220,t.height),o=t.paddingX??48,s=t.paddingTop??48,a=t.paddingBottom??44,c=Math.max(70,(i-2*o)/Math.max(1,e.lanes.length)),l=Math.max(76,(r-s-a)/Math.max(1,e.maxLevel+1)),d=Math.min(n.taskWidth??112,Math.max(58,.78*c)),u=Math.min(n.taskHeight??58,.64*l),h=n.socketRadius??5,p=Math.max(1,Math.round(n.gutterCount??3)),f=new Map;for(const t of e.nodes){const e=`${t.laneIndex}:${t.level}`,n=f.get(e)??[];n.push(t),f.set(e,n)}for(const e of f.values())e.sort((e,t)=>kd(e.id,t.id));const m=e.nodes.map(e=>{const t=f.get(`${e.laneIndex}:${e.level}`)??[e],n=Math.max(0,t.findIndex(t=>t.id===e.id));return{taskID:e.id,lane:e.lane,laneIndex:e.laneIndex,level:e.level,x:o+c*(e.laneIndex+.5),y:s+l*(e.level+.5)+(n-(t.length-1)/2)*Math.min(18,.3*u),width:d,height:u}}),y=new Map(m.map(e=>[e.taskID,e])),g=[],x=[];e.edges.forEach((t,n)=>{const i=y.get(t.sourceID),r=y.get(t.targetID);if(!i||!r)return;const o=e.incoming.get(t.targetID)??[],s=Math.min(.72*r.width,14*Math.max(1,o.length-1)),a=o.length>1?r.x-s/2+s*t.socketIndex/(o.length-1):r.x,c=r.y-r.height/2-h-2;g.push({id:t.socketID,edgeID:t.id,taskID:r.taskID,index:t.socketIndex,x:a,y:c,radius:h});const l={x:i.x,y:i.y+i.height/2+3},d=Math.min(c-10,l.y+.48*Math.max(18,c-l.y)+7*(n%p-(p-1)/2));var u;x.push({edgeID:t.id,sourceID:t.sourceID,targetID:t.targetID,socketID:t.socketID,points:(u=[l,{x:l.x,y:d},{x:a,y:d},{x:a,y:c}],u.filter((e,t)=>{const n=u[t-1];return!n||n.x!==e.x||n.y!==e.y}))})});const b=new Map(g.map(e=>[e.id,e])),v=new Map(x.map(e=>[e.edgeID,e]));return{tasks:m,sockets:g,routes:x,taskByID:y,socketByID:b,routeByEdgeID:v}}function Cd(e,t,n="all"){const i=Array.from(new Set(t)).sort(kd),r=new Set,o=()=>i.every(e=>r.has(e));return{taskID:e,mode:n,incomingEdgeIDs:i,deliver:e=>i.includes(e)?(r.add(e),o()):o(),reset:(e=[])=>{r.clear();for(const t of e)i.includes(t)&&r.add(t)},isSatisfied:o,getSnapshot:()=>({taskID:e,mode:n,incomingEdgeIDs:[...i],deliveredEdgeIDs:[...r].sort(kd),satisfied:o()})}}function Rd(e){return e instanceof Date?e.getTime():Number(e)}function Pd(e,t){const n=Rd("object"!=typeof t||t instanceof Date?t:t.currentTime),i=e.map((e,t)=>({event:e,index:t,time:Rd(e.at)})).filter(e=>Number.isFinite(e.time)&&n>=e.time).sort((e,t)=>e.time-t.time||e.index-t.index),r=new Set,o=new Map,s=new Set,a=new Set;for(const{event:e}of i)"task-completed"===e.type?(r.add(e.taskID),o.delete(e.taskID)):"task-blocked"===e.type?o.set(e.taskID,e.reason):"task-unblocked"===e.type?o.delete(e.taskID):"dependency-delivered"===e.type?s.add(e.edgeID):"task-armed"===e.type&&a.add(e.taskID);return{currentTime:n,appliedEvents:i.map(e=>e.event),completedTaskIDs:r,blockedByTaskID:o,deliveredEdgeIDs:s,armedTaskIDs:a}}function Dd(e,t,n={}){const i=new Set(n.completedTaskIDs??[]),r=[...vd(function(e,t){const n=new Map;for(const t of e)n.set(t.id,new Set);for(const e of t)n.has(e.source)||n.set(e.source,new Set),n.has(e.target)||n.set(e.target,new Set),n.get(e.source).add(e.target);return n}(e.nodes,e.edges.map(e=>({source:e.sourceID,target:e.targetID}))),t)].map(t=>e.byID.get(t)).filter(e=>null!=e).filter(e=>!(n.isComplete?n.isComplete(e):i.has(e.id)||"done"===e.status)).sort((e,t)=>e.index-t.index),o=Array.from(new Set(r.map(e=>e.lane)));return{blockerID:t,downstreamTaskCount:r.length,affectedLaneCount:o.length,downstreamTaskIDs:r.map(e=>e.id),affectedLanes:o}}var $d=[];function Bd(e,t=0){if(e instanceof Date)return e.getTime();const n=Number(e);return Number.isFinite(n)?n:t}function Td(e){if(null==e.completionTime)return null;const t=Bd(e.completionTime,NaN);return Number.isFinite(t)?t:null}function Nd(e,t,n,i){const r=new Set;for(const o of e.nodes){const s=e.incoming.get(o.id)??[];(i.has(o.id)||!n.has(o.id)&&s.every(e=>t.has(e.id)))&&r.add(o.id)}return r}function Ed(e,t,n,i){const r=e.nodes.map(Td).filter(e=>null!=e),o=r.length?Math.min(...r)-1:0,s="replay"!==t||i?n:o,a=new Set,c=new Map;for(const n of e.nodes){const e=Td(n);(null!=e&&s>=e||"done"===n.status&&"replay"!==t)&&a.add(n.id),n.blockerReason&&!a.has(n.id)&&c.set(n.id,n.blockerReason)}const l=new Set;if("replay"!==t||i)for(const t of e.edges)a.has(t.sourceID)&&l.add(t.id);return{currentTime:s,playing:!1,completed:a,delivered:l,inFlight:new Set,armed:Nd(e,l,c,a),blockers:c,previewTaskID:null}}function Wd(e){return{...e,completed:new Set(e.completed),delivered:new Set(e.delivered),inFlight:new Set(e.inFlight),armed:new Set(e.armed),blockers:new Map(e.blockers)}}function qd(e){const t=e.datum;return"dependency-ball"===t?.kind&&Array.isArray(t.route)?t:null}function Od(e){const t=qd(e.body);if(!t||2>t.route.length)return null;const n=function(e){let t=0;for(let n=1;e.length>n;n+=1)t+=Math.hypot(e[n].x-e[n-1].x,e[n].y-e[n-1].y);return t}(t.route),i=function(e,t){let n=1/0,i=0,r=0;for(let o=1;t.length>o;o+=1){const s=t[o-1],a=t[o],c=a.x-s.x,l=a.y-s.y,d=c*c+l*l,u=Math.sqrt(d);if(0>=u)continue;const h=Math.max(0,Math.min(1,((e.x-s.x)*c+(e.y-s.y)*l)/d)),p=Math.hypot(e.x-(s.x+c*h),e.y-(s.y+l*h));n>p&&(n=p,i=r+h*u),r+=u}return i}(e.body,t.route),r=function(e,t){if(2>e.length)return{point:e[0]??{x:0,y:0},tangent:{x:0,y:1}};let n=0;for(let i=1;e.length>i;i+=1){const r=e[i-1],o=e[i],s=o.x-r.x,a=o.y-r.y,c=Math.hypot(s,a);if(c>0){if(n+c>=t){const e=Math.max(0,Math.min(1,(t-n)/c));return{point:{x:r.x+s*e,y:r.y+a*e},tangent:{x:s/c,y:a/c}}}n+=c}}const i=e[e.length-2],r=e[e.length-1],o=r.x-i.x,s=r.y-i.y,a=Math.hypot(o,s)||1;return{point:r,tangent:{x:o/a,y:s/a}}}(t.route,Math.min(n,i+22));return{x:2.5*(78*r.tangent.x-e.body.vx)+8*(r.point.x-e.body.x),y:2.5*(78*r.tangent.y-e.body.vy)+8*(r.point.y-e.body.y)}}function Fd(e,t){const n=t.points[0]??{x:0,y:0},i=t.points[1]??n,r=i.x-n.x,o=i.y-n.y,s=Math.hypot(r,o)||1;return{id:"dependency-ball:"+e.id,x:n.x,y:n.y,vx:r/s*42,vy:o/s*42,mass:.7,restitution:.02,friction:.12,bodyCollisions:!1,shape:{type:"circle",radius:5},datum:{kind:"dependency-ball",edgeID:e.id,sourceID:e.sourceID,targetID:e.targetID,route:t.points}}}var zd=require("react/jsx-runtime");function Ld({machine:e,layout:t,runtime:n,downstreamSet:i,selectedSet:r,width:o,height:s,seed:a,reduced:c,onSelectTask:l}){return(0,zd.jsxs)("svg",{"aria-hidden":"true",width:o,height:s,viewBox:`0 0 ${o} ${s}`,style:{position:"absolute",inset:0,overflow:"visible",pointerEvents:"none"},children:[(0,zd.jsx)("defs",{children:(0,zd.jsx)("filter",{id:"chain-shadow-"+a,x:"-20%",y:"-20%",width:"140%",height:"150%",children:(0,zd.jsx)("feDropShadow",{dx:"0",dy:"2",stdDeviation:"2",floodOpacity:"0.2"})})}),e.lanes.map((e,n)=>{const i=t.tasks.filter(e=>e.laneIndex===n),r=i[0]?.x??0;return(0,zd.jsxs)("g",{children:[(0,zd.jsx)("line",{x1:r,x2:r,y1:32,y2:s-24,stroke:"var(--semiotic-grid, #d7dde0)",strokeWidth:1,strokeDasharray:"3 7"}),(0,zd.jsx)("text",{x:r,y:23,textAnchor:"middle",fontSize:12,fontWeight:700,fill:"var(--semiotic-text, #243039)",children:e})]},e)}),t.routes.map(e=>{const t=n.delivered.has(e.edgeID),r=n.inFlight.has(e.edgeID),o=i.has(e.targetID)||i.has(e.sourceID),s=e.points.map(e=>`${e.x},${e.y}`).join(" ");return(0,zd.jsx)("polyline",{points:s,fill:"none",stroke:o?"var(--semiotic-highlight, #e08a1e)":t?"var(--semiotic-success, #2b8a66)":"var(--semiotic-grid, #aeb8bd)",strokeWidth:o?4:r?3:2,strokeOpacity:t||r||o?.95:.48,strokeLinecap:"round",strokeLinejoin:"round"},e.edgeID)}),t.sockets.map(e=>{const t=n.delivered.has(e.edgeID);return(0,zd.jsxs)("g",{children:[(0,zd.jsx)("circle",{cx:e.x,cy:e.y,r:e.radius+2,fill:"var(--semiotic-background, #fff)",stroke:"var(--semiotic-text, #243039)",strokeWidth:1.5}),t&&(0,zd.jsx)("circle",{cx:e.x,cy:e.y,r:e.radius-.5,fill:"var(--semiotic-success, #2b8a66)"})]},e.id)}),e.nodes.map(e=>{const o=t.taskByID.get(e.id);if(!o)return null;const s=n.completed.has(e.id),d=n.blockers.has(e.id),u=n.previewTaskID===e.id,h=r.has(e.id)||u,p=i.has(e.id),f=function(e,t){return t.completed.has(e.id)?"var(--semiotic-success, #2b8a66)":t.blockers.has(e.id)?"var(--semiotic-error, #c64035)":"in-progress"===e.status?"var(--semiotic-warning, #d18a22)":t.armed.has(e.id)?"var(--semiotic-primary, #2474a6)":"var(--semiotic-muted, #75818a)"}(e,n),m=o.x-o.width/2,y=o.y-o.height/2,g=Math.max(2,o.height*e.progress);return(0,zd.jsxs)("g",{children:[(0,zd.jsxs)("g",{style:{transform:`rotate(${s?76:0}deg)`,transformBox:"fill-box",transformOrigin:"50% 100%",transition:c?"none":"transform 520ms cubic-bezier(.2,.8,.25,1)",filter:"url(#chain-shadow-"+a+")"},children:[(0,zd.jsx)("rect",{x:m,y:y,width:o.width,height:o.height,rx:e.milestone?12:4,fill:"var(--semiotic-background, #fff)",stroke:h||p?"var(--semiotic-highlight, #e08a1e)":f,strokeWidth:h?4:p?3:2}),(0,zd.jsx)("rect",{x:m+3,y:y+o.height-g+1,width:o.width-6,height:Math.max(0,g-4),rx:2,fill:f,opacity:s?.86:.46})]}),d&&(0,zd.jsxs)("g",{opacity:u?.28:1,children:[(0,zd.jsx)("line",{x1:m-8,x2:m+14,y1:o.y+9,y2:o.y-9,stroke:"var(--semiotic-error, #c64035)",strokeWidth:7,strokeLinecap:"round"}),(0,zd.jsx)("circle",{cx:m-8,cy:o.y+9,r:3,fill:"var(--semiotic-error, #c64035)"})]}),(0,zd.jsxs)("g",{onPointerDown:()=>l(e.id),style:{cursor:"pointer",pointerEvents:"auto"},children:[(0,zd.jsx)("rect",{x:m,y:y,width:o.width,height:o.height,fill:"transparent"}),(0,zd.jsx)("text",{x:o.x,y:o.y-4,textAnchor:"middle",fontSize:10.5,fontWeight:700,fill:"var(--semiotic-text, #243039)",children:e.label.length>24?e.label.slice(0,22)+"…":e.label}),(0,zd.jsxs)("text",{x:o.x,y:o.y+12,textAnchor:"middle",fontSize:9.5,fill:"var(--semiotic-text-muted, #5f6b72)",children:[Math.round(100*e.progress),"% · ",s?"done":d?"blocked":n.armed.has(e.id)?"ready":"waiting"]})]})]},e.id)})]})}var Yd=require("react/jsx-runtime"),Hd={border:0,clip:"rect(0 0 0 0)",clipPath:"inset(50%)",height:1,margin:-1,overflow:"hidden",padding:0,position:"absolute",whiteSpace:"nowrap",width:1},Gd=(0,bd.forwardRef)(function(e,t){const{data:n,taskIDAccessor:i,labelAccessor:r,laneAccessor:o,dependencyAccessor:s,startAccessor:a,endAccessor:c,progressAccessor:l,statusAccessor:d,completionTimeAccessor:u,blockerAccessor:h,milestoneAccessor:p,mode:f="snapshot",insight:m="blocker-amplification",currentTime:y,controls:g=!1,selectedTaskIDs:x,onSelectionChange:b,onObservation:v,reducedMotion:w,seed:k=31,width:M=920,height:S=620,responsiveWidth:I,responsiveHeight:j,title:A="Dependency chain reaction",description:C,className:R,accessibleTable:P=!0,enableHover:D=!0}=e,$=(0,bd.useRef)(null),[B,T]=(0,bd.useState)([]),N=x?Array.from(x):B,E=(0,bd.useMemo)(()=>new Set(N),[N]),W=Bd(y,1/0),q="settle"===w,O=(0,bd.useMemo)(()=>jd({data:n,taskIDAccessor:i,labelAccessor:r,laneAccessor:o,dependencyAccessor:s,startAccessor:a,endAccessor:c,progressAccessor:l,statusAccessor:d,completionTimeAccessor:u,blockerAccessor:h,milestoneAccessor:p}),[n,i,r,o,s,a,c,l,d,u,h,p]),F=(0,bd.useMemo)(()=>Ad(O,{width:M,height:S}),[O,M,S]),[z,L]=(0,bd.useState)(()=>Ed(O,f,W,q)),Y=(0,bd.useRef)(z),H=(0,bd.useCallback)(e=>{Y.current=e,L(e)},[]),G=(0,bd.useCallback)(e=>v?.(e),[v]);(0,bd.useEffect)(()=>{const e=Ed(O,f,W,q);$.current?.clear(),Y.current=e,L(e)},[O,f,W,q]);const X=(0,bd.useCallback)(e=>{const t=E.has(e)?N.filter(t=>t!==e):[e];x||T(t),b?.(t)},[x,b,E,N]),_=(0,bd.useCallback)(e=>{if(q)return;const t=Wd(Y.current),n=[];for(const i of O.outgoing.get(e)??[]){if(t.delivered.has(i.id)||t.inFlight.has(i.id))continue;const e=F.routeByEdgeID.get(i.id);e&&(t.inFlight.add(i.id),n.push(Fd(i,e)))}n.length&&(H(t),$.current?.pushMany(n,{pacing:{ratePerSec:8}}))},[H,F,O,q]),V=(0,bd.useCallback)((e,t)=>{const n=O.byID.get(e),i=Y.current;if(!n||i.completed.has(e))return;const r=Wd(i);r.completed.add(e),r.blockers.delete(e),r.armed.add(e),null!=t&&(r.currentTime=t),H(r),G({type:"task-completed",taskID:e,datum:n.datum}),_(e)},[H,G,O,_]),U=(0,bd.useCallback)(e=>{const t=Wd(Y.current),n=[],i=[];for(const i of e){if(t.delivered.has(i))continue;const e=O.edges.find(e=>e.id===i);e&&(t.delivered.add(i),t.inFlight.delete(i),n.push(e))}for(const e of n){const n=O.byID.get(e.targetID);!n||t.blockers.has(n.id)||t.armed.has(n.id)||(O.incoming.get(n.id)??[]).every(e=>t.delivered.has(e.id))&&(t.armed.add(n.id),i.push(n.id))}if(n.length){H(t);for(const e of n)G({type:"dependency-delivered",sourceID:e.sourceID,targetID:e.targetID});for(const e of i)G({type:"task-armed",taskID:e})}},[H,G,O]),K=(0,bd.useCallback)((e,t)=>{const n=[],i=[];for(const e of t.readBodies()){const t=qd(e);if(!t||Y.current.delivered.has(t.edgeID))continue;const r=t.route[t.route.length-1];r&&9>=Math.hypot(e.x-r.x,e.y-r.y)&&(n.push(t.edgeID),i.push(e.id))}i.length&&t.remove(i),n.length&&U(n)},[U]),Q=(0,bd.useCallback)(()=>{const e=Wd(Y.current);for(const t of O.edges)e.completed.has(t.sourceID)&&e.delivered.add(t.id);e.inFlight.clear(),e.armed=Nd(O,e.delivered,e.blockers,e.completed),e.playing=!1,$.current?.settle(),H(e),G({type:"machine-settled"})},[H,G,O]),Z=(0,bd.useCallback)(()=>{const e=Wd(Y.current);e.playing=!1,H(e)},[H]),J=(0,bd.useCallback)(()=>{const e=Y.current,t=O.nodes.map(e=>({node:e,time:Td(e)})).filter(t=>null!=t.time&&t.time>e.currentTime&&!e.completed.has(t.node.id)).sort((e,t)=>e.time-t.time||e.node.index-t.node.index)[0];if(t)return void V(t.node.id,t.time);Z();const n=[...e.blockers.keys()].map(t=>Dd(O,t,{completedTaskIDs:e.completed})).sort((e,t)=>t.affectedLaneCount-e.affectedLaneCount||t.downstreamTaskCount-e.downstreamTaskCount);n[0]&&G({type:"machine-stalled",blockerID:n[0].blockerID,downstreamTaskCount:n[0].downstreamTaskCount,affectedLaneCount:n[0].affectedLaneCount})},[G,O,Z,V]),ee=(0,bd.useCallback)(()=>{if(q)return void Q();const e=Wd(Y.current);e.playing=!0,H(e)},[H,q,Q]);(0,bd.useEffect)(()=>{if(!z.playing||"replay"!==f||q)return;const e=window.setInterval(J,760);return()=>window.clearInterval(e)},[f,q,z.playing,J]);const te=(0,bd.useCallback)(()=>{$.current?.clear(),H(Ed(O,f,W,q))},[H,O,f,W,q]),ne=(0,bd.useCallback)(e=>{if(!O.byID.has(e))return;const t=Wd(Y.current);t.previewTaskID=e,H(t);const n=Dd(O,e,{completedTaskIDs:t.completed});G({type:"blocker-previewed",blockerID:e,downstreamTaskIDs:n.downstreamTaskIDs})},[H,G,O]),ie=(0,bd.useCallback)(()=>{const e=Wd(Y.current);e.previewTaskID=null,H(e)},[H]),re=(0,bd.useCallback)((e,t)=>{if(!O.byID.has(e))return;const n=Wd(Y.current);n.blockers.set(e,t),n.armed.delete(e),H(n)},[H,O]),oe=(0,bd.useCallback)(e=>{if(!O.byID.has(e))return;const t=Wd(Y.current);t.blockers.delete(e),(O.incoming.get(e)??[]).every(e=>t.delivered.has(e.id))&&t.armed.add(e),H(t)},[H,O]),se=(0,bd.useCallback)(e=>Dd(O,e,{completedTaskIDs:Y.current.completed}),[O]),ae=(0,bd.useCallback)(()=>{const e=Y.current;return{currentTime:e.currentTime,playing:e.playing,previewTaskID:e.previewTaskID,selectedTaskIDs:[...N],tasks:O.nodes.map(t=>({taskID:t.id,completed:e.completed.has(t.id),armed:e.armed.has(t.id),blocked:e.blockers.has(t.id),blockerReason:e.blockers.get(t.id)})),dependencies:O.edges.map(t=>({edgeID:t.id,sourceID:t.sourceID,targetID:t.targetID,state:e.delivered.has(t.id)?"delivered":e.inFlight.has(t.id)?"in-flight":"waiting"}))}},[O,N]);(0,bd.useImperativeHandle)(t,()=>({play:ee,pause:Z,step:J,reset:te,settle:Q,previewResolve:ne,clearPreview:ie,completeTask:V,blockTask:re,unblockTask:oe,getAmplification:se,getMachineState:ae}),[re,ie,se,ae,Z,V,ee,ne,te,Q,J,oe]);const ce=z.previewTaskID??N[0]??null,le=ce?Dd(O,ce,{completedTaskIDs:z.completed}):null,de=(0,bd.useMemo)(()=>new Set(le?.downstreamTaskIDs??[]),[le?.downstreamTaskIDs]),ue=(0,bd.useMemo)(()=>function(e,t,n){return e.nodes.flatMap(i=>{const r=t.taskByID.get(i.id);if(!r)return[];const o=e.incoming.get(i.id)??[],s=o.filter(e=>n.delivered.has(e.id)).length,a=n.blockers.get(i.id),c=n.completed.has(i.id)?"completed":a?"blocked: "+a:n.armed.has(i.id)?"armed":"waiting";return[{id:i.id,label:`${i.label}, ${i.lane}, ${Math.round(100*i.progress)}%, ${c}`,description:`${s} of ${o.length} prerequisites delivered.`,datum:i.datum,x:r.x,y:r.y,width:r.width,height:r.height,shape:"rect",group:i.lane}]})}(O,F,z),[F,O,z]),he=(0,bd.useMemo)(()=>(0,Yd.jsx)(Ld,{machine:O,layout:F,runtime:z,downstreamSet:de,selectedSet:E,width:M,height:S,seed:k,reduced:q,onSelectTask:X}),[de,S,F,O,q,z,k,X,E,M]),pe=(0,bd.useMemo)(()=>{const e=[...z.blockers.keys()].map(e=>Dd(O,e,{completedTaskIDs:z.completed})).sort((e,t)=>t.affectedLaneCount-e.affectedLaneCount||t.downstreamTaskCount-e.downstreamTaskCount);return e.length?e.map(e=>`${O.byID.get(e.blockerID)?.label??e.blockerID} affects ${e.downstreamTaskCount} unfinished tasks across ${e.affectedLaneCount} lanes.`).join(" "):"No explicit blockers are active."},[O,z.blockers,z.completed]),fe=(0,bd.useMemo)(()=>[{id:"chain-left",shape:{type:"segment",x1:2,y1:0,x2:2,y2:S,thickness:4}},{id:"chain-right",shape:{type:"segment",x1:M-2,y1:0,x2:M-2,y2:S,thickness:4}},{id:"chain-top",shape:{type:"segment",x1:0,y1:2,x2:M,y2:2,thickness:4}},{id:"chain-bottom",shape:{type:"segment",x1:0,y1:S-2,x2:M,y2:S-2,thickness:4}}],[S,M]),me=!0===g?["play","pause","step","reset","settle"]:g||[];return(0,Yd.jsxs)("div",O.valid?{className:R,style:{width:M,maxWidth:"100%",position:"relative"},children:[me.length>0&&(0,Yd.jsx)("div",{"aria-label":"Chain reaction replay controls",style:{display:"flex",flexWrap:"wrap",gap:6,marginBottom:8},children:me.map(e=>(0,Yd.jsx)("button",{type:"button",onClick:"play"===e?ee:"pause"===e?Z:"step"===e?J:"reset"===e?te:Q,"aria-pressed":"play"===e?z.playing:void 0,children:e[0].toUpperCase()+e.slice(1)},e))}),(0,Yd.jsx)(ts,{ref:$,size:[M,S],responsiveWidth:I,responsiveHeight:j,title:A,description:C??"Tasks are arranged by workstream and dependency depth. Balls represent satisfied prerequisites; task completion remains an explicit data event.",summary:`${pe}${le&&"blocker-amplification"===m?` Selected task reaches ${le.downstreamTaskCount} unfinished tasks across ${le.affectedLaneCount} lanes.`:""}`,accessibleTable:!1,enableHover:D,initialSpawns:$d,bodyForces:Od,bodyStyle:{fill:"var(--semiotic-accent, #f0a329)",stroke:"var(--semiotic-text, #243039)",strokeWidth:1.25},bodySemanticItems:!1,semanticItems:ue,onSemanticItemActivate:e=>e.id&&X(e.id),foregroundGraphics:()=>he,paused:q,continuous:z.inFlight.size>0,onTick:K,config:{bodyLimit:Math.max(16,O.edges.length+4),colliders:fe,settleStepLimit:2200,kernel:{seed:k,gravity:{x:0,y:7},fixedDt:1/60,cellSize:28,collisionIterations:2,velocityDamping:.992,restitution:.02,friction:.12,maxVelocity:150,sleepSpeed:1.1,sleepAfter:.8},observation:{chartType:"ChainReactionChart"}}}),P&&(0,Yd.jsxs)("table",{style:Hd,children:[(0,Yd.jsx)("caption",{children:pe}),(0,Yd.jsx)("thead",{children:(0,Yd.jsxs)("tr",{children:[(0,Yd.jsx)("th",{children:"Task"}),(0,Yd.jsx)("th",{children:"Lane"}),(0,Yd.jsx)("th",{children:"Progress"}),(0,Yd.jsx)("th",{children:"State"}),(0,Yd.jsx)("th",{children:"Waiting on"}),(0,Yd.jsx)("th",{children:"Downstream reach"})]})}),(0,Yd.jsx)("tbody",{children:O.nodes.map(e=>{const t=Dd(O,e.id,{completedTaskIDs:z.completed});return(0,Yd.jsxs)("tr",{children:[(0,Yd.jsx)("th",{scope:"row",children:e.label}),(0,Yd.jsx)("td",{children:e.lane}),(0,Yd.jsxs)("td",{children:[Math.round(100*e.progress),"%"]}),(0,Yd.jsx)("td",{children:z.completed.has(e.id)?"Completed":z.blockers.has(e.id)?"Blocked":z.armed.has(e.id)?"Armed":"Waiting"}),(0,Yd.jsx)("td",{children:z.blockers.get(e.id)??(e.dependencyIDs.filter(e=>!z.completed.has(e)).join(", ")||"None")}),(0,Yd.jsxs)("td",{children:[t.downstreamTaskCount," tasks / ",t.affectedLaneCount," lanes"]})]},e.id)})})]})]}:{className:R,role:"alert",style:{width:M,maxWidth:"100%"},children:[(0,Yd.jsx)("strong",{children:"ChainReactionChart could not compile this dependency graph."}),(0,Yd.jsx)("ul",{children:O.diagnostics.map((e,t)=>(0,Yd.jsx)("li",{children:e.message},`${e.code}-${t}`))})]})});Gd.displayName="ChainReactionChart";var Xd=ts;
2
+ var e,t=Object.create,n=Object.defineProperty,i=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,r=Object.getPrototypeOf,s=Object.prototype.hasOwnProperty,a=(e,t,r,a)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of o(t))s.call(e,c)||c===r||n(e,c,{get:()=>t[c],enumerable:!(a=i(t,c))||a.enumerable});return e},c=(e,i,o)=>(o=null!=e?t(r(e)):{},a(!i&&e&&e.__esModule?o:n(o,"default",{value:e,enumerable:!0}),e)),l={};((e,t)=>{for(var i in t)n(e,i,{get:t[i],enumerable:!0})})(l,{BuiltInPhysicsEngineAdapter:()=>Si,ChainReactionChart:()=>Fh,CollisionSwarmChart:()=>bc,CrucibleChart:()=>ph,DEFAULT_CRUCIBLE_HEIGHT:()=>Vd,DEFAULT_CRUCIBLE_OUTLETS:()=>Kd,DEFAULT_CRUCIBLE_SIZE:()=>Ud,DEFAULT_CRUCIBLE_WIDTH:()=>Xd,EventDropChart:()=>nc,GaltonBoardChart:()=>Ja,GauntletChart:()=>Ml,GuantletChart:()=>Il,PhysicalFlowChart:()=>Nl,PhysicsCustomChart:()=>mc,PhysicsPileChart:()=>rc,PhysicsPipelineStore:()=>ko,PhysicsSVGOverlay:()=>Yn,PhysicsSedimentAccumulator:()=>Ni,ProcessFlowChart:()=>Xl,StreamPhysicsFrame:()=>os,absorbRegion:()=>na,aggregateRegionCounts:()=>qs,applyCrucibleEvent:()=>Ld,arrivalReplay:()=>kd,bodiesToAnnotationAnchors:()=>Fn,bodyGroupSpec:()=>oa,buildCollisionSwarmPhysics:()=>Ps,buildCrucibleEvidence:()=>Gd,buildCrucibleInitialSpawns:()=>bu,buildCrucibleLayout:()=>au,buildCruciblePhysicsConfig:()=>hu,buildCrucibleProductEvents:()=>ih,buildCrucibleProjection:()=>Yd,buildCrucibleStateSpawns:()=>ku,buildCrucibleTerminalSpawns:()=>Mu,buildEventDropPhysics:()=>As,buildGaltonBoardPhysics:()=>Is,buildPhysicalFlowPhysics:()=>Ws,buildPhysicsAnnotationContext:()=>zn,buildPhysicsPile:()=>Rs,buildProcessFlowPhysics:()=>aa,calculateBlockerAmplification:()=>jh,capacitatedRegion:()=>ea,chargeGateRegion:()=>Qs,cloneCrucibleState:()=>Cd,collidersFromScales:()=>bd,comparePhysicsTrace:()=>cd,compileCruciblePlan:()=>Ru,compileDependencyMachine:()=>wh,compileMotionEncoding:()=>kc,compilePhysicsEncoding:()=>Ac,composePhysicsControllers:()=>Xo,composeStyleRules:()=>us,createCapacityQueueController:()=>qo,createDefaultPhysicsEngineAdapter:()=>ji,createDependencyGateController:()=>_o,createInitialCrucibleState:()=>ru,createLogicalJoin:()=>Mh,createPhysicsEncodingLayout:()=>Cc,createPortalController:()=>Vo,createProcessJourneyLedger:()=>dd,createServiceLevelController:()=>Ho,createServiceResourcePoolController:()=>Lo,crucibleBondId:()=>fu,crucibleBoundaryColliders:()=>lu,crucibleComponentBodyId:()=>pu,crucibleProductBodyId:()=>mu,crucibleProjectionRows:()=>Hd,crucibleSemanticKey:()=>Su,default:()=>zh,deriveMotionVector:()=>jc,evaluateCrucibleConservation:()=>_d,evaluatePhysicsBodyBudget:()=>qi,forceFieldRegion:()=>ia,galtonPegs:()=>xd,groupCompletionRows:()=>zs,hatchFillId:()=>re,hatchPatternDef:()=>ae,isHatchFill:()=>ie,makeRuleValueResolver:()=>ss,matchesThreshold:()=>cs,membraneRegion:()=>Ks,normalizePhysicsAnnotations:()=>Ln,opacityFromAge:()=>Ic,physicsProcessBoundaryColliders:()=>$c,physicsProcessGroupSemanticItems:()=>Bc,physicsProcessRegionSemanticItem:()=>Pc,physicsProcessStageSemanticItems:()=>Dc,physicsReferenceEnvelope:()=>id,planGauntletPropertyWork:()=>il,portalRegion:()=>ta,pressureFieldRegion:()=>Js,processChrome:()=>_l,processJourneyRows:()=>hd,processLaneWalls:()=>ra,processStageLayout:()=>Xs,processStageRegions:()=>Us,processVolumePolygons:()=>Hs,regionCountsToProjectionRows:()=>Fs,replaceGauntletNegative:()=>ol,replayCruciblePlan:()=>Cu,replayStateTransitions:()=>Sh,resolveCrucibleSelector:()=>Bd,resolveCrucibleSnapshotAt:()=>Au,resolveCrucibleTime:()=>ju,resolveMotionAccessor:()=>wc,resolveMotionAge:()=>Mc,resolveMotionVector:()=>Sc,resolveStyleRules:()=>ds,resolveSvgFill:()=>ce,routeDependencyTracks:()=>kh,routeSurfaceRegion:()=>Zs,ruleMatches:()=>ls,sedimentBake:()=>wd,sedimentHeightfield:()=>Oi,spawnFromTokens:()=>vd,stageTargetInVolume:()=>Ys,updateProcessJourney:()=>ud}),module.exports=(e=l,a(n({},"__esModule",{value:!0}),e));var d=require("react"),u=c(require("react")),h=require("react"),p=c(require("react")),m=require("react"),f=require("react"),y=require("react/jsx-runtime");function g(e){let t=null;const n=()=>(t||(t=(0,f.createContext)(null)),t),i=b(e);return[function({children:t,initialState:i}){const o=(0,f.useRef)(i),r=(0,f.useMemo)(()=>b(e,o.current),[]),s=n();return(0,y.jsx)(s.Provider,{value:r,children:t})},(e,t)=>{const o=n(),r=(0,f.useContext)(o)??i,s=(0,f.useRef)(e);s.current=e;const a=(0,f.useRef)({hasValue:!1,value:void 0}),c=(0,f.useCallback)(()=>{const e=s.current(r.getState()),n=a.current;return n.hasValue&&t&&t(n.value,e)?n.value:(a.current={hasValue:!0,value:e},e)},[r,t]),l=(0,f.useCallback)(()=>s.current(r.getState()),[r]);return(0,f.useSyncExternalStore)(r.subscribe,c,l)}]}function b(e,t){const n=new Set;let i={...e(function(e){const t=e(i);if(function(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!0;return!1}(t)){i={...i,...t};for(const e of n)e()}}),...t??{}};return{getState:()=>i,subscribe:function(e){return n.add(e),()=>{n.delete(e)}}}}function x(e){if(!e.accessibility)return e;let t=e;if(e.accessibility.colorBlindSafe&&(t={...t,colors:{...t.colors,categorical:v}}),e.accessibility.highContrast){const e="dark"===t.mode;t={...t,colors:{...t.colors,text:e?"#ffffff":"#000000",textSecondary:e?"#cccccc":"#333333",grid:e?"#666666":"#999999",border:e?"#888888":"#000000"}}}return t}var v=["#0072B2","#E69F00","#009E73","#CC79A7","#56B4E9","#D55E00","#F0E442","#000000"],w={mode:"light",colors:{primary:"#00a2ce",secondary:"#6c757d",categorical:["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],sequential:"blues",diverging:"RdBu",background:"transparent",surface:"#ffffff",text:"#333",textSecondary:"#666",grid:"#e0e0e0",border:"#ccc",selection:"#00a2ce",selectionOpacity:.15,success:"#2ca02c",danger:"#d62728",warning:"#f0ad4e",error:"#b4181b",info:"#00a2ce"},typography:{fontFamily:"sans-serif",titleSize:16,labelSize:12,tickSize:12}},k={mode:"dark",colors:{primary:"#4fc3f7",secondary:"#90a4ae",categorical:["#4fc3f7","#ffb74d","#81c784","#ef5350","#ba68c8","#a1887f","#f06292","#90a4ae","#dce775","#4dd0e1"],sequential:"blues",diverging:"RdBu",background:"#1a1a2e",surface:"#252540",text:"#e0e0e0",textSecondary:"#aaa",grid:"#333",border:"#555",selection:"#4fc3f7",selectionOpacity:.15,success:"#81c784",danger:"#ef5350",warning:"#ffb74d",error:"#d84848",info:"#4fc3f7"},typography:{fontFamily:"sans-serif",titleSize:16,labelSize:12,tickSize:12}},M={mode:"light",colors:{primary:"#0000cc",secondary:"#333333",categorical:v,sequential:"blues",diverging:"RdBu",background:"#ffffff",surface:"#ffffff",text:"#000000",textSecondary:"#333333",grid:"#999999",border:"#000000",focus:"#0000cc",selection:"#0000cc",selectionOpacity:.1,success:"#006400",danger:"#cc0000",warning:"#b15a00",error:"#8b0000",info:"#0000cc"},typography:{fontFamily:"system-ui, sans-serif",titleSize:18,labelSize:14,tickSize:12},tooltip:{background:"#000000",text:"#ffffff",borderRadius:"4px",fontSize:"14px",shadow:"0 2px 8px rgba(0, 0, 0, 0.3)"},borderRadius:"4px"};function I(e,t){if("light"===t)return w;if("dark"===t)return k;if("high-contrast"===t)return M;if("string"==typeof t)return void 0!==console&&console.warn(`[ThemeStore] Unknown theme preset "${t}". Keeping current theme.`),e;if(t.mode&&"auto"!==t.mode){const e="dark"===t.mode?k:w;return x({...e,...t,colors:{...e.colors,...t.colors||{}},typography:{...e.typography,...t.typography||{}}})}return x({...e,...t,colors:{...e.colors,...t.colors||{}},typography:{...e.typography,...t.typography||{}}})}var[S,j]=g(e=>({theme:w,setTheme(t){e(e=>({theme:I(e.theme,t)}))}})),A=require("react");function C(){const[e,t]=(0,A.useState)(()=>!("undefined"==typeof window||!window.matchMedia)&&window.matchMedia("(prefers-reduced-motion: reduce)").matches);return(0,A.useEffect)(()=>{if("undefined"==typeof window||!window.matchMedia)return;const e=window.matchMedia("(prefers-reduced-motion: reduce)");return t(e.matches),function(e,t){if("function"==typeof e.addEventListener)return e.addEventListener("change",t),()=>e.removeEventListener("change",t);const n=e;return n.addListener(t),()=>n.removeListener(t)}(e,e=>t(e.matches))},[]),e}var R=require("react");function $(e,t,n){const i=(0,R.useRef)(null),[o,r]=(0,R.useState)(null);return(0,R.useEffect)(()=>{if(!t&&!n)return;const e=i.current;if(!e)return;const o=new ResizeObserver(e=>{for(const t of e){const{width:e,height:n}=t.contentRect;r(t=>t&&t.w===e&&t.h===n?t:{w:e,h:n})}});return o.observe(e),()=>o.disconnect()},[t,n]),[i,[t&&o?o.w:e[0],n&&o?o.h:e[1]]]}var P=new WeakMap,D=0,B=!1,T=null,E=null;function N(e,t){if(!t)return t;const n=function(e){const t=e.trim();if(!t.startsWith("var(")||!t.endsWith(")"))return null;const n=t.slice(4,-1),i=n.indexOf(",");if(-1===i){const e=n.trim();return e.startsWith("--")?{name:e}:null}const o=n.slice(0,i).trim(),r=n.slice(i+1).trim();return o.startsWith("--")?{name:o,fallback:r||void 0}:null}(t);if(!n)return t;const i=()=>n.fallback?N(e,n.fallback):t,o=e.canvas;if(!o)return i();!function(){if(B)return;if("undefined"==typeof window||"undefined"==typeof document)return;B=!0;const e=()=>{D++};if("undefined"!=typeof MutationObserver&&document.documentElement&&new MutationObserver(e).observe(document.documentElement,{attributes:!0,attributeFilter:["class","style","data-theme","data-semiotic-theme"],subtree:!0}),"function"==typeof window.matchMedia)try{T=window.matchMedia("(prefers-color-scheme: dark)"),E=e,"function"==typeof T.addEventListener?T.addEventListener("change",E):"function"==typeof T.addListener&&T.addListener(E)}catch{}}();let r=P.get(o);r&&r.version===D||(r={version:D,map:new Map},P.set(o,r));const s=r.map.get(t);if(void 0!==s)return s;const a=getComputedStyle(o).getPropertyValue(n.name).trim()||i()||t;return r.map.set(t,a),a}var O=()=>"undefined"!=typeof performance?performance.now():Date.now();function W(e,t){const n=e();return Number.isFinite(n)?n:t}var q=class{constructor(e={}){this.randomSource=Math.random,this.subscribers=new Set,this.now=()=>this.advance(),this.random=()=>this.randomSource(),this.clock=e.clock??O,this.lastWallTime=W(this.clock,0),this.logicalTime=this.lastWallTime,this.pausedValue=!0===e.paused,this.visibleValue=!1!==e.visible,this.setRandomSource(e.random,e.seed)}get isActive(){return!this.pausedValue&&this.visibleValue}get paused(){return this.pausedValue}get seed(){return this.seedValue}get visible(){return this.visibleValue}configure(e){this.setClock(e.clock),this.setRandomSource(e.random,e.seed)}setPaused(e){this.pausedValue!==e&&(this.advance(),this.pausedValue=e,this.emit())}setVisible(e){this.visibleValue!==e&&(this.advance(),this.visibleValue=e,this.emit())}snapshot(){return{now:this.now(),paused:this.pausedValue,seed:this.seedValue,visible:this.visibleValue}}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}advance(){const e=W(this.clock,this.lastWallTime),t=Math.max(0,e-this.lastWallTime);return this.lastWallTime=e,this.isActive&&(this.logicalTime+=t),this.logicalTime}emit(){for(const e of this.subscribers)e()}setClock(e){const t=e??O;t!==this.clock&&(this.advance(),this.clock=t,this.lastWallTime=W(t,this.lastWallTime))}setRandomSource(e,t){const n=function(e){return"number"==typeof e&&Number.isFinite(e)?Math.trunc(e):void 0}(t);e===this.randomInput&&n===this.seedValue||(this.randomInput=e,this.seedValue=n,this.randomSource=e??(void 0===n?Math.random:function(e){let t=e>>>0;return()=>{t+=1831565813;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(n)))}},F="undefined"==typeof window?m.useEffect:m.useLayoutEffect,z={requestAnimationFrame:e=>("undefined"==typeof window?globalThis:window).requestAnimationFrame(e),cancelAnimationFrame:e=>("undefined"==typeof window?globalThis:window).cancelAnimationFrame(e)};function L(e,t,n){return"function"==typeof e?e({size:t,margin:n}):e}var Y=require("react"),H="undefined"!=typeof window?Y.useLayoutEffect:Y.useEffect,_=()=>()=>{},G=()=>!1,X=()=>!0;function V(){const e=(0,Y.useSyncExternalStore)(_,G,X);return(0,Y.useRef)(e).current}var U=require("react"),K=require("react/jsx-runtime");function Q({children:e,size:t,margin:n,overflowVisible:i=!1}){return e?(0,K.jsx)("svg",{style:{position:"absolute",left:0,top:0,width:t[0],height:t[1],pointerEvents:"none",overflow:i?"visible":void 0},children:(0,K.jsx)("g",{transform:`translate(${n.left},${n.top})`,children:e})}):null}var Z=c(require("react")),J=require("d3-shape");function ee(e){return{type:"hatch",background:e.background,stroke:e.stroke,lineWidth:e.lineWidth,spacing:e.spacing,angle:e.angle}}var te=null;var ne=require("react/jsx-runtime");function ie(e){return"object"==typeof e&&null!==e&&"hatch"===e.type}function oe(e){return["hatch",e.background??"transparent",e.stroke??"#000",e.lineWidth??1.5,e.spacing??6,e.angle??45,e.lineOpacity??1].join("|")}function re(e,t){let n=2166136261;const i=oe(t);for(let e=0;i.length>e;e++)n^=i.charCodeAt(e),n=Math.imul(n,16777619);return`${e}-hatch-${(n>>>0).toString(36)}`}var se=new Map;function ae(e,t){const{background:n="transparent",stroke:i="#000",lineWidth:o=1.5,spacing:r=6,angle:s=45,lineOpacity:a=1}=e,c=Math.max(8,Math.ceil(2*r));return(0,ne.jsxs)("pattern",{id:t,width:c,height:c,patternUnits:"userSpaceOnUse",patternTransform:0!==s?`rotate(${s})`:void 0,children:[n&&"transparent"!==n&&(0,ne.jsx)("rect",{width:c,height:c,fill:n}),(0,ne.jsx)("line",{x1:0,y1:0,x2:0,y2:c,stroke:i,strokeWidth:o,strokeOpacity:a}),(0,ne.jsx)("line",{x1:r,y1:0,x2:r,y2:c,stroke:i,strokeWidth:o,strokeOpacity:a})]},t)}function ce(e,t,n="#4e79a7"){if(ie(e)){const n=re(t,e);return{fill:`url(#${n})`,def:ae(e,n)}}return e&&"string"==typeof e?{fill:e}:{fill:n}}var le=require("d3-shape");function de(e){switch(e){case"monotoneX":return le.curveMonotoneX;case"monotoneY":return le.curveMonotoneY;case"cardinal":return le.curveCardinal;case"catmullRom":return le.curveCatmullRom;case"step":return le.curveStep;case"stepBefore":return le.curveStepBefore;case"stepAfter":return le.curveStepAfter;case"basis":return le.curveBasis;case"natural":return le.curveNatural;default:return null}}function ue(e,t,n){if(null==t)return n;if(ie(t)){const i=function(e,t){const n="undefined"!=typeof window&&window.devicePixelRatio||1,i=`${oe(e)}@${n}`,o=se.get(i);if(void 0!==o)return o;const r=function(e={},t){const{background:n="transparent",stroke:i="#000",lineWidth:o=1.5,spacing:r=6,angle:s=45}=e,a={background:n,stroke:i,lineWidth:o,spacing:r,angle:s},c=Math.max(8,Math.ceil(2*r));let l;try{l=function(e){return"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,e):(te||(te=document.createElement("canvas")),te.width=e,te.height=e,te)}(c)}catch{return ee(a)}const d=l.getContext("2d");if(!d)return ee(a);n&&"transparent"!==n?(d.fillStyle=n,d.fillRect(0,0,c,c)):d.clearRect(0,0,c,c),d.strokeStyle=i,d.lineWidth=o,d.lineCap="square";const u=s*Math.PI/180;if(45===s||-45===s){const e=s>0?1:-1;for(let t=-c;2*c>=t;t+=r)d.beginPath(),d.moveTo(t,0),d.lineTo(t+e*c,c),d.stroke()}else{d.save(),d.translate(c/2,c/2),d.rotate(u);const e=2*c;for(let t=-e;e>=t;t+=r)d.beginPath(),d.moveTo(-e,t),d.lineTo(e,t),d.stroke();d.restore()}return(t||d).createPattern(l,"repeat")}({background:e.background,stroke:e.stroke,lineWidth:e.lineWidth,spacing:e.spacing,angle:e.angle},t),s=ie(r)?null:r;return se.set(i,s),s}(t,e);return i||t.background&&N(e,t.background)||n}return"string"!=typeof t?t:N(e,t)||n}var he=[40,40],pe=[.5,.5];function me(e,t,n,i){if("none"!==e)return"color"===e||null==e?t??i:"accent"===e?n:e}var fe=require("d3-shape"),ye={circle:fe.symbolCircle,square:fe.symbolSquare,triangle:fe.symbolTriangle,diamond:fe.symbolDiamond,star:fe.symbolStar,cross:fe.symbolCross,wye:fe.symbolWye};var ge=require("react/jsx-runtime");function be(e,t="#4e79a7"){return ie(e)?e.background&&"transparent"!==e.background?e.background:t:e&&"string"==typeof e?e:t}function xe(e){const t=e.replace(/[^A-Za-z0-9_-]/g,"_");return!t||/^\d/.test(t)?"s_"+t:t}function ve(e){const t=e.filter(e=>Number.isFinite(e.offset)).map(e=>({offset:Math.max(0,Math.min(1,e.offset)),color:e.color}));return 2>t.length?null:t.map((e,t)=>(0,ge.jsx)("stop",{offset:e.offset,stopColor:e.color},t))}var we=require("react/jsx-runtime");function ke(e,t,n){if(!e||2>t.length)return null;const i=ve(e.colorStops);return i?(0,we.jsx)("linearGradient",{id:n,gradientUnits:"userSpaceOnUse",x1:t[0][0],y1:0,x2:t[t.length-1][0],y2:0,children:i}):null}function Me(e,t,n){switch(e.type){case"line":{const i=e;if(0===i.path.length)return null;const o=de(i.curve),r=o?(0,J.line)().x(([e])=>e).y(([,e])=>e).curve(o)(i.path)??"":"M"+i.path.map(([e,t])=>`${e},${t}`).join("L"),s=xe(`${n?n+"-":""}line-${t}-stroke-gradient`),a=ke(i.strokeGradient,i.path,s);return(0,we.jsxs)(Z.Fragment,{children:[a&&(0,we.jsx)("defs",{children:a}),(0,we.jsx)("path",{d:r,fill:"none",stroke:a?`url(#${s})`:i.style.stroke||"#4e79a7",strokeWidth:i.style.strokeWidth||2,strokeDasharray:i.style.strokeDasharray,opacity:i.style.opacity})]},"line-"+t)}case"area":{const i=e;if(0===i.topPath.length)return null;const o=de(i.curve),r=!o||2>i.topPath.length||2>i.bottomPath.length?`M${i.topPath.map(([e,t])=>`${e},${t}`).join("L")}L${[...i.bottomPath].reverse().map(([e,t])=>`${e},${t}`).join("L")}Z`:(0,J.area)().x(([e])=>e).y0((e,t)=>i.bottomPath[t][1]).y1(([,e])=>e).curve(o)(i.topPath)??"",s=`${n?n+"-":""}area-${t}-hatch`,a=ie(i.style.fill)?ae(i.style.fill,s):void 0,c=xe(`${n?n+"-":""}area-${t}-gradient`),l=function(e,t){const n=e.fillGradient;if(!n||"object"!=typeof n)return null;let i=1/0;for(const[,t]of e.topPath)i=Math.min(i,t);let o=-1/0;for(const[,t]of e.bottomPath)o=Math.max(o,t);if(!Number.isFinite(i)||!Number.isFinite(o))return null;const r=[];if("colorStops"in n){const e=ve(n.colorStops);if(!e)return null;r.push(...e)}else{if(!Number.isFinite(n.topOpacity)||!Number.isFinite(n.bottomOpacity))return null;r.push((0,we.jsx)("stop",{offset:0,stopColor:be(e.style.fill),stopOpacity:Math.max(0,Math.min(1,n.topOpacity))},"0")),r.push((0,we.jsx)("stop",{offset:1,stopColor:be(e.style.fill),stopOpacity:Math.max(0,Math.min(1,n.bottomOpacity))},"1"))}return(0,we.jsx)("linearGradient",{id:t,gradientUnits:"userSpaceOnUse",x1:0,y1:i,x2:0,y2:o,children:r})}(i,c),d=l?`url(#${c})`:a?`url(#${s})`:be(i.style.fill),u=l?void 0:i.style.fillOpacity??i.style.opacity??.7,h=o?(0,J.line)().x(([e])=>e).y(([,e])=>e).curve(o)(i.topPath)??"":"M"+i.topPath.map(([e,t])=>`${e},${t}`).join("L"),p=xe(`${n?n+"-":""}area-${t}-stroke-gradient`),m=ke(i.strokeGradient,i.topPath,p),f=i.style.stroke&&"none"!==i.style.stroke?(0,we.jsx)("path",{d:h,fill:"none",stroke:m?`url(#${p})`:be(i.style.stroke),strokeWidth:i.style.strokeWidth||2,opacity:i.style.opacity}):null;if(i.clipRect){const e=`${n?n+"-":""}area-clip-${t}`;return(0,we.jsxs)("g",{children:[(0,we.jsxs)("defs",{children:[l,!l&&a,m,(0,we.jsx)("clipPath",{id:e,children:(0,we.jsx)("rect",{x:i.clipRect.x,y:i.clipRect.y,width:i.clipRect.width,height:i.clipRect.height})})]}),(0,we.jsxs)("g",{clipPath:`url(#${e})`,children:[(0,we.jsx)("path",{d:r,fill:d,fillOpacity:u,opacity:l?i.style.opacity:void 0,stroke:"none"}),f]})]},"area-"+t)}return(0,we.jsxs)(Z.Fragment,{children:[(l||a||m)&&(0,we.jsxs)("defs",{children:[l,!l&&a,m]}),(0,we.jsx)("path",{d:r,fill:d,fillOpacity:u,opacity:l?i.style.opacity:void 0,stroke:"none"}),f]},"area-"+t)}case"point":{const i=e,o=`${n?n+"-":""}point-${t}-hatch`,r=ie(i.style.fill)?ae(i.style.fill,o):void 0;return(0,we.jsxs)(Z.Fragment,{children:[r&&(0,we.jsx)("defs",{children:r}),(0,we.jsx)("circle",{cx:i.x,cy:i.y,r:i.r,fill:r?`url(#${o})`:be(i.style.fill),opacity:i.style.opacity??i.style.fillOpacity??.8,stroke:i.style.stroke,strokeWidth:i.style.strokeWidth})]},"point-"+t)}case"symbol":return function(e,t){const n=function(e,t,n){if(n)return n;const i=e??"circle";return"chevron"===i?function(e){const t=1.5*function(e){return Math.sqrt(Math.max(1,e)/Math.PI)}(e),n=.92*t;return`M0,${-t}L${n},${(.78*t).toFixed(3)}L0,${(.28*t).toFixed(3)}L${-n},${(.78*t).toFixed(3)}Z`}(t):(0,fe.symbol)(ye[i]??fe.symbolCircle,Math.max(1,t))()??""}(e.symbolType,e.size,e.path);return(0,ge.jsx)("path",{d:n,transform:e.rotation?`translate(${e.x},${e.y}) rotate(${180*e.rotation/Math.PI})`:`translate(${e.x},${e.y})`,fill:e.style.fill?be(e.style.fill):"none",fillOpacity:e.style.fillOpacity,opacity:e.style.opacity,stroke:e.style.stroke,strokeWidth:e.style.strokeWidth},"symbol-"+t)}(e,t);case"glyph":return function(e,t,n,i){const o=e.glyph;if(!o?.parts?.length||0>=e.size)return null;const r=function(e,t){const[n,i]=e.viewBox??he,[o,r]=e.anchor??pe,s=i>0?i:1,a=Math.max(0,t)/s,c=(n>0?n:s)*a,l=s*a;return{width:c,height:l,scale:a,offsetX:-o*c,offsetY:-r*l}}(o,e.size);if(0>=r.scale)return null;const s=`translate(${t},${n})${e.rotation?` rotate(${180*e.rotation/Math.PI})`:""} translate(${r.offsetX},${r.offsetY}) scale(${r.scale})`,a=e.color??("string"==typeof e.style.fill?e.style.fill:void 0),c=function(e,t,n=0,i="horizontal"){const[o,r]=e.viewBox??he,s=Math.min(1,Math.max(0,n)),a=Math.min(1,Math.max(0,t));return a>s?s>0||1>a?"vertical"===i?{x:0,y:r*(1-a),width:o,height:r*(a-s)}:{x:o*s,y:0,width:o*(a-s),height:r}:null:{x:0,y:0,width:0,height:0}}(o,e.fraction??1,e.fractionStart??0,e.fractionDirection??"horizontal"),l=c?xe(i+"-clip"):void 0,d=(e.style.opacity??1)*(e._decayOpacity??1)*(e.style.fillOpacity??1),u=t=>o.parts.map((n,i)=>{const o=t?"none"===n.fill?void 0:t:me(n.fill,a,e.accent),r=t?n.stroke&&"none"!==n.stroke?t:void 0:me(n.stroke??"none",a,e.accent);return o||r?(0,ge.jsx)("path",{d:n.d,fill:o??"none",stroke:r,strokeWidth:r?n.strokeWidth??1:void 0,strokeLinecap:n.strokeLinecap,strokeLinejoin:n.strokeLinejoin,opacity:n.opacity},i):null});return(0,ge.jsxs)("g",{transform:s,opacity:1===d?void 0:d,children:[c&&l&&(0,ge.jsx)("clipPath",{id:l,children:(0,ge.jsx)("rect",{x:c.x,y:c.y,width:c.width,height:c.height})}),c&&e.ghostColor?(0,ge.jsx)("g",{children:u(e.ghostColor)}):null,c&&l?(0,ge.jsx)("g",{clipPath:`url(#${l})`,children:u()}):u()]},i)}(e,e.x,e.y,`${n??""}glyph-${e.pointId??t}`);case"rect":{const i=e,o=`${n?n+"-":""}xyrect-${t}-hatch`,r=ie(i.style.fill)?ae(i.style.fill,o):void 0;return(0,we.jsxs)(Z.Fragment,{children:[r&&(0,we.jsx)("defs",{children:r}),(0,we.jsx)("rect",{x:i.x,y:i.y,width:i.w,height:i.h,fill:r?`url(#${o})`:be(i.style.fill),opacity:i.style.opacity,stroke:i.style.stroke,strokeWidth:i.style.strokeWidth})]},"rect-"+t)}case"heatcell":{const n=e;if(n.showValues&&null!=n.value&&n.w>=20&&n.h>=20){const e=n.valueFormat?n.valueFormat(n.value):Number.isInteger(n.value)?n.value+"":100>Math.abs(n.value)?1>Math.abs(n.value)?n.value.toPrecision(3):n.value.toFixed(1):n.value.toFixed(0),[i,o,r]=function(e){if(e.startsWith("#")){let t=e.slice(1);if(3===t.length&&(t=t[0]+t[0]+t[1]+t[1]+t[2]+t[2]),6===t.length)return[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16)]}const t=e.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);return t?[+t[1],+t[2],+t[3]]:[128,128,128]}(n.fill),s=.299*i+.587*o+.114*r>128?"#000":"#fff",a=Math.max(10,Math.min(16,.3*Math.min(n.w,n.h)));return(0,we.jsxs)("g",{children:[(0,we.jsx)("rect",{x:n.x,y:n.y,width:n.w,height:n.h,fill:n.fill,stroke:n.style?.stroke,strokeWidth:n.style?.strokeWidth}),(0,we.jsx)("text",{x:n.x+n.w/2,y:n.y+n.h/2,textAnchor:"middle",dominantBaseline:"middle",fill:s,fontSize:a+"px",children:e})]},"heatcell-"+t)}return(0,we.jsx)("rect",{x:n.x,y:n.y,width:n.w,height:n.h,fill:n.fill,stroke:n.style?.stroke,strokeWidth:n.style?.strokeWidth},"heatcell-"+t)}case"candlestick":{const n=e;if(n.isRange){const e=n.dotRadius??Math.max(2,n.bodyWidth/2);return(0,we.jsxs)("g",{children:[(0,we.jsx)("line",{x1:n.x,y1:n.highY,x2:n.x,y2:n.lowY,stroke:n.wickColor,strokeWidth:n.wickWidth}),(0,we.jsx)("circle",{cx:n.x,cy:n.highY,r:e,fill:n.wickColor}),(0,we.jsx)("circle",{cx:n.x,cy:n.lowY,r:e,fill:n.wickColor})]},"candle-"+t)}const i=Math.min(n.openY,n.closeY),o=Math.max(Math.abs(n.openY-n.closeY),1),r=n.isUp?n.upColor:n.downColor;return(0,we.jsxs)("g",{children:[(0,we.jsx)("line",{x1:n.x,y1:n.highY,x2:n.x,y2:n.lowY,stroke:n.wickColor,strokeWidth:n.wickWidth}),(0,we.jsx)("rect",{x:n.x-n.bodyWidth/2,y:i,width:n.bodyWidth,height:o,fill:r,stroke:r,strokeWidth:1})]},"candle-"+t)}default:return null}}var Ie="undefined"==typeof window||"undefined"==typeof document;var Se=c(require("react")),je=["name","label","title"],Ae=["type","kind","category","group","class","status","role","shape"],Ce=["value","amount","total","count","weight","score"],Re=new Set(["x","y","z","x0","x1","y0","y1","r","cx","cy","radius","layer","row","rowindex","col","column","depth","index","order","sankeywidth","coincidentpoints","sourcelinks","targetlinks","parent","children","fx","fy","vx","vy"]);function $e(e,t){for(const n of t){const t=e.find(e=>e.lower===n);if(t)return t}}var Pe=require("react/jsx-runtime"),De={background:"var(--semiotic-tooltip-bg, rgba(0, 0, 0, 0.85))",color:"var(--semiotic-tooltip-text, white)",padding:"8px 12px",borderRadius:"var(--semiotic-tooltip-radius, 6px)",fontSize:"var(--semiotic-tooltip-font-size, 14px)",fontFamily:"var(--semiotic-font-family, inherit)",lineHeight:"1.5",boxShadow:"var(--semiotic-tooltip-shadow, 0 2px 8px rgba(0, 0, 0, 0.15))",pointerEvents:"none",maxWidth:"300px",wordWrap:"break-word"};function Be(e,t){return"function"==typeof t?t(e):e[t]}function Te(e,t){if(t)return t(e);if(null==e)return"";if("number"==typeof e){if(!Number.isFinite(e))return e+"";const t=Number.isInteger(e)?e:parseFloat(e.toPrecision(6));return Math.abs(t)>9999?t.toLocaleString():t+""}return e instanceof Date?e.toLocaleDateString():"object"==typeof e&&null!==e?void 0!==e.id?e.id+"":void 0!==e.name?e.name+"":JSON.stringify(e):e+""}function Ee(e={}){const{fields:t,title:n,format:i,style:o={},className:r=""}=e;return e=>{if(!e||"object"!=typeof e)return null;let s;const a=[];if(n){const t=Be(e,n);s=Te(t,i)}if(t&&t.length>0)t.forEach(t=>{let n,o,r;"string"==typeof t?(n=t,o=t,r=i):(n=t.label,o=t.accessor||t.key||"",r=t.format||i);const s=Be(e,o);a.push({label:n,value:Te(s,r)})});else if(!n){const t=["value","y","name","id","label"];for(const n of t)if(void 0!==e[n]){s=Te(e[n],i);break}if(!s){const t=Object.keys(e).filter(e=>!e.startsWith("_"));t.length>0&&(s=Te(e[t[0]],i))}}const c={...De,...o};return(0,Pe.jsxs)("div",{className:("semiotic-tooltip "+r).trim(),style:c,children:[s&&(0,Pe.jsx)("div",{style:{fontWeight:a.length>0?"bold":"normal"},children:s}),a.map((e,t)=>(0,Pe.jsxs)("div",{style:{marginTop:0===t&&s?"4px":0},children:[e.label&&(0,Pe.jsxs)("span",{children:[e.label,": "]}),e.value]},t))]})}}function Ne(e){if(!0!==e){if("function"==typeof e){const t=e;return e=>{let n=Array.isArray(i=!0===e?.__semioticHoverData||e&&void 0!==e.data&&"number"==typeof e.x&&"number"==typeof e.y&&e&&("node"===e.type||"edge"===e.type||void 0!==e.nodeOrEdge||void 0!==e.allSeries||void 0!==e.stats||void 0!==e.__chartType)?e.data??{}:e)?i[0]:i;var i;if(!n)return null;if(("node"===e?.nodeOrEdge&&"number"==typeof n?.x0&&"number"==typeof n?.x1||"edge"===e?.nodeOrEdge&&"number"==typeof n?.sankeyWidth)&&n.data&&"object"==typeof n.data&&(n=n.data),!n)return null;const o=t(n);return null==o?null:(0,Pe.jsx)("div",{className:"semiotic-tooltip",style:De,children:o})}}return!1!==e&&void 0!==e&&("object"==typeof e&&null!==e&&("fields"in e||"title"in e)?Ee(e):"multi"===e?("undefined"!=typeof process&&"production"!==process.env?.NODE_ENV&&console.warn('[semiotic] tooltip="multi" reached normalizeTooltip — prefer charts that set tooltipMode (LineChart, AreaChart, StackedAreaChart, DifferenceChart). Rendering MultiLineTooltip content as a fallback.'),function(e={}){const{fields:t=[],title:n,format:i,style:o={},className:r="",showLabels:s=!0,separator:a=": "}=e;return e=>{if(!e||"object"!=typeof e)return null;const c=[];if(n){const t=Be(e,n);c.push({value:Te(t,i)})}if(t&&Array.isArray(t)&&t.length>0)t.forEach(t=>{let n,o,r;"string"==typeof t?(n=t,o=t,r=i):(n=t.label,o=t.accessor||t.key||"",r=t.format||i);const a=Te(Be(e,o),r);c.push({label:s?n:void 0,value:a})});else{const t=function(e,t={}){if(!e||"object"!=typeof e)return{entries:[]};const n=t.maxEntries??6,i=!1!==t.skipPositional,o=[];for(const[t,n]of Object.entries(e)){if(t.startsWith("_"))continue;if("data"===t)continue;if(i&&Re.has(t.toLowerCase()))continue;if(null==n)continue;const e=typeof n;("string"===e||"number"===e||"boolean"===e||n instanceof Date)&&o.push({key:t,lower:t.toLowerCase(),value:n})}if(0===o.length)return{entries:[]};let r=o.findIndex(e=>je.includes(e.lower));const s=r>=0;0>r&&(r=o.findIndex(e=>"id"===e.lower)),0>r&&(r=o.findIndex(e=>"string"==typeof e.value));const a=0>r?void 0:o[r];let c=o.filter((e,t)=>t!==r);s&&(c=c.filter(e=>"id"!==e.lower));const l=$e(c,Ae),d=$e(c,Ce),u=new Set(Ae),h=new Set(Ce),p=[];l&&p.push({key:l.key,value:l.value}),d&&p.push({key:d.key,value:d.value});for(const e of c){if(p.length>=n)break;e!==l&&e!==d&&(u.has(e.lower)||h.has(e.lower)||p.push({key:e.key,value:e.value}))}return{titleKey:a?.key,title:a?.value,entries:p}}(e,{skipPositional:!1});null!=t.title&&c.push({label:void 0,value:Te(t.title,i),bold:!0}),t.entries.forEach(e=>{c.push({label:s?e.key:void 0,value:Te(e.value,i)})})}const l={...De,...o};return Array.isArray(c)&&0!==c.length?(0,Pe.jsx)("div",{className:("semiotic-tooltip semiotic-tooltip-multiline "+r).trim(),style:l,children:c.map((e,t)=>(0,Pe.jsxs)("div",{style:{marginBottom:c.length-1>t?"4px":0,fontWeight:e.bold?"bold":void 0},children:[e.label&&(0,Pe.jsxs)("strong",{children:[e.label,a]}),e.value]},t))}):null}}()):Ee())}}var Oe=require("react/jsx-runtime");function We({x:e,y:t,containerWidth:n,containerHeight:i,margin:o,children:r,className:s="stream-frame-tooltip",zIndex:a=1}){const c=Number.isFinite(e)&&Number.isFinite(t),l=Se.useRef(null),[d,u]=Se.useState(null);Se.useLayoutEffect(()=>{const e=l.current;if(!e)return;const t=()=>{const t=e.getBoundingClientRect();Number.isFinite(t.width)&&Number.isFinite(t.height)&&u(e=>e&&.5>Math.abs(e.width-t.width)&&.5>Math.abs(e.height-t.height)?e:{width:t.width,height:t.height})};if(t(),"undefined"==typeof ResizeObserver)return;const n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[s,n,i,c]);let h;h=d?`translate(${d.width+12>n-e?"calc(-100% - 12px)":"12px"}, ${d.height+12>i-t?"calc(-100% - 4px)":"4px"})`:`translate(${e>.7*n?"calc(-100% - 12px)":"12px"}, ${.3*i>t?"4px":"calc(-100% - 4px)"})`;const p=function(e){if(!Se.isValidElement(e))return!1;const t=e.type;if("string"!=typeof t&&t&&!0===t.ownsChrome)return!0;const n=e.props;if(!0===n["data-semiotic-tooltip-chrome"])return!0;if("true"===n["data-semiotic-tooltip-chrome"])return!0;const i=n.style;if(i&&"object"==typeof i){if(null!=i.background&&""!==i.background&&"transparent"!==i.background)return!0;if(null!=i.backgroundColor&&""!==i.backgroundColor&&"transparent"!==i.backgroundColor)return!0}return!1}(r),m=p?null:De;return c?(0,Oe.jsx)("div",{ref:l,className:p?s:(s+" semiotic-tooltip").trim(),style:{...m||{},position:"absolute",left:o.left+e,top:o.top+t,transform:h,pointerEvents:"none",zIndex:a,width:"max-content"},children:r}):null}var qe={names:["--semiotic-bg","--surface-1","--surface-0"],fallback:"#f8fafc"},Fe={names:["--semiotic-border","--surface-3"],fallback:"#334155"},ze={names:["--semiotic-danger","--viz-4"],fallback:"#dc2626"},Le={names:["--semiotic-focus","--accent","--viz-9"],fallback:"#f97316"},Ye={names:["--semiotic-grid","--surface-3"],fallback:"#cbd5e1"},He={names:["--semiotic-primary","--accent","--viz-5"],fallback:"#0ea5e9"},_e={names:["--semiotic-success","--viz-2"],fallback:"#22c55e"},Ge={names:["--semiotic-text","--text-primary"],fallback:"#0f172a"},Xe={names:["--semiotic-text-secondary","--text-secondary"],fallback:"#475569"},Ve={names:["--semiotic-warning","--viz-9","--viz-3"],fallback:"#f97316"};function Ue(e,t){const n=e.canvas;if("function"!=typeof getComputedStyle||!n)return t.fallback;const i=getComputedStyle(n);for(const n of t.names){const t=i.getPropertyValue(n).trim();if(t)return N(e,t)??t}return t.fallback}function Ke(e,t){const n=Math.max(0,Math.min(1,t)),i=e.trim(),o=i.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);if(o){const[,e,t,i]=o;return Ke(`#${e}${e}${t}${t}${i}${i}`,n)}const r=i.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(r){const[,e,t,i]=r;return`rgba(${parseInt(e,16)}, ${parseInt(t,16)}, ${parseInt(i,16)}, ${n})`}const s=i.match(/^rgb\s*\(\s*([^)]+?)\s*\)$/i);if(s)return`rgba(${s[1]}, ${n})`;const a=i.match(/^rgba\s*\(\s*([^,]+,\s*[^,]+,\s*[^,]+),\s*[^)]+\)$/i);return a?`rgba(${a[1]}, ${n})`:i}var Qe=c(require("react")),Ze=require("d3-scale"),Je=c(require("react")),et=16,tt=6,nt=10,it=22,ot=require("react/jsx-runtime"),rt={fill:(e,t)=>(0,ot.jsx)("rect",{style:e,width:t,height:t}),line:(e,t)=>(0,ot.jsx)("line",{style:e,x1:0,y1:0,x2:t,y2:t})};function st(e,t,n,i,o){let r;return r="function"==typeof n?n(e):(0,rt[n])(i(e,t),o),r}function at({swatchSize:e}){return(0,ot.jsx)("path",{d:`M${.25*e},${.55*e} L${.45*e},${.75*e} L${.8*e},${.3*e}`,fill:"none",stroke:"white",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"})}function ct(e,t,n){return n&&n.size>0?n.has(e.label)?1:.3:null!=t?e.label===t?1:.3:1}var lt=(e,t,n,i,o,r,s,a,c,l,d)=>{const{type:u="fill",styleFn:h,items:p}=e,m=[];let f=0;const y=!(!t&&!n),g="isolate"===l||void 0===l&&null!=o,{swatchSize:b,labelGap:x,rowHeight:v}=d;return p.forEach((e,l)=>{const d=st(e,l,u,h,b),w=ct(e,i,o),k=o&&o.size>0&&o.has(e.label);m.push((0,ot.jsxs)("g",{transform:`translate(0,${f})`,onClick:t?()=>t(e):void 0,onMouseEnter:n?()=>n(e):void 0,onMouseLeave:n?()=>n(null):void 0,tabIndex:y?a===r&&l===s?0:-1:void 0,role:y?"option":void 0,"aria-selected":y&&g?k||!1:void 0,"aria-current":y&&!g&&null!=i&&e.label===i||void 0,"aria-label":e.label,onKeyDown:y?n=>{if("Enter"!==n.key&&" "!==n.key||(n.preventDefault(),t&&t(e)),"ArrowDown"===n.key||"ArrowUp"===n.key){n.preventDefault();const e=(l+("ArrowDown"===n.key?1:-1)+p.length)%p.length;c(a,e);const t=n.currentTarget.parentElement?.children[e];t instanceof SVGElement&&t.focus()}}:void 0,onFocus:y?t=>{c(a,l),n&&n(e);const i=t.currentTarget.querySelector(".semiotic-legend-focus-ring");i&&i.setAttribute("visibility","visible")}:void 0,onBlur:y?e=>{n&&n(null);const t=e.currentTarget.querySelector(".semiotic-legend-focus-ring");t&&t.setAttribute("visibility","hidden")}:void 0,style:{cursor:y?"pointer":"default",opacity:w,transition:"opacity 150ms ease",pointerEvents:"all",outline:"none"},children:[y&&(0,ot.jsx)("rect",{className:"semiotic-legend-focus-ring",x:-2,y:-2,width:b+x+2+7*e.label.length,height:b+4,fill:"none",stroke:"var(--semiotic-focus, #005fcc)",strokeWidth:2,rx:3,visibility:"hidden"}),d,k&&(0,ot.jsx)(at,{swatchSize:b}),(0,ot.jsx)("text",{y:b/2,x:b+x,dominantBaseline:"central",style:{fontSize:"var(--semiotic-legend-font-size, 12px)"},fill:"var(--semiotic-text, #333)",children:e.label})]},"legend-item-"+l)),f+=v}),m},dt=({legendGroups:e,width:t,customClickBehavior:n,customHoverBehavior:i,highlightedCategory:o,isolatedCategories:r,focusedGroupIndex:s,focusedItemIndex:a,onFocusedIndexChange:c,legendInteraction:l,metrics:d})=>{const u=[],h=function(e,t){let n=24;return e.map(({hasLabel:e,itemCount:i})=>{n+=5;const o=n;let r;n+=8,e&&(n+=16,r=n,n+=8);const s=n;return n+=i*t+8,{lineY:o,labelY:r,itemsY:s,endY:n}})}(e.map(e=>({hasLabel:!!e.label,itemCount:e.items.length})),d.rowHeight);return e.forEach((e,p)=>{const m=h[p];u.push((0,ot.jsx)("line",{stroke:"gray",x1:0,y1:m.lineY,x2:t,y2:m.lineY},"legend-top-line legend-symbol-"+p)),e.label&&null!=m.labelY&&u.push((0,ot.jsx)("text",{y:m.labelY,className:"legend-group-label",style:{fontSize:"var(--semiotic-legend-font-size, 12px)"},fill:"var(--semiotic-text, #333)",children:e.label},"legend-text-"+p)),u.push((0,ot.jsx)("g",{className:"legend-item",transform:`translate(0,${m.itemsY})`,children:lt(e,n,i,o,r,s,a,p,c,l,d)},"legend-group-"+p))}),u},ut=({legendGroups:e,height:t,width:n,customClickBehavior:i,customHoverBehavior:o,highlightedCategory:r,isolatedCategories:s,focusedGroupIndex:a,focusedItemIndex:c,onFocusedIndexChange:l,legendInteraction:d,metrics:u})=>{let h=0;const p=[];e.forEach((e,t)=>{let m=0;e.label&&(m+=16);const f=((e,t,n,i,o,r,s,a,c,l,d,u)=>{const{type:h="fill",styleFn:p,items:m}=e,f=[],{swatchSize:y,labelGap:g,itemGap:b,rowHeight:x,align:v}=d,w=!(!t&&!n),k="isolate"===l||void 0===l&&null!=o,M=m.map(e=>y+g+7*e.label.length),I=[];let S=0,j=0;M.forEach((e,t)=>{const n=0===j?e:j+b+e;u&&u>0&&j>0&&n>u?(I.push({start:S,end:t,width:j}),S=t,j=e):j=n}),m.length>0&&I.push({start:S,end:m.length,width:j}),I.forEach((e,l)=>{let d="center"===v?Math.max(0,((u??e.width)-e.width)/2):"end"===v?Math.max(0,(u??e.width)-e.width):0;for(let u=e.start;e.end>u;u++){const e=m[u],v=st(e,u,h,p,y),I=ct(e,i,o),S=o&&o.size>0&&o.has(e.label);f.push((0,ot.jsxs)("g",{transform:`translate(${d},${l*x})`,onClick:t?()=>t(e):void 0,onMouseEnter:n?()=>n(e):void 0,onMouseLeave:n?()=>n(null):void 0,tabIndex:w?a===r&&u===s?0:-1:void 0,role:w?"option":void 0,"aria-selected":w&&k?S||!1:void 0,"aria-current":w&&!k&&null!=i&&e.label===i||void 0,"aria-label":e.label,onKeyDown:w?n=>{if("Enter"!==n.key&&" "!==n.key||(n.preventDefault(),t&&t(e)),"ArrowRight"===n.key||"ArrowLeft"===n.key){n.preventDefault();const e=(u+("ArrowRight"===n.key?1:-1)+m.length)%m.length;c(a,e);const t=n.currentTarget.parentElement?.children[e];t instanceof SVGElement&&t.focus()}}:void 0,onFocus:w?t=>{c(a,u),n&&n(e);const i=t.currentTarget.querySelector(".semiotic-legend-focus-ring");i&&i.setAttribute("visibility","visible")}:void 0,onBlur:w?e=>{n&&n(null);const t=e.currentTarget.querySelector(".semiotic-legend-focus-ring");t&&t.setAttribute("visibility","hidden")}:void 0,style:{cursor:w?"pointer":"default",opacity:I,transition:"opacity 150ms ease",pointerEvents:"all",outline:"none"},children:[w&&(0,ot.jsx)("rect",{className:"semiotic-legend-focus-ring",x:-2,y:-2,width:y+g+2+7*e.label.length,height:y+4,fill:"none",stroke:"var(--semiotic-focus, #005fcc)",strokeWidth:2,rx:3,visibility:"hidden"}),v,S&&(0,ot.jsx)(at,{swatchSize:y}),(0,ot.jsx)("text",{y:y/2,x:y+g,dominantBaseline:"central",style:{fontSize:"var(--semiotic-legend-font-size, 12px)"},fill:"var(--semiotic-text, #333)",children:e.label})]},"legend-item-"+u)),d+=M[u]+b}});const A=Math.max(0,...I.map(e=>e.width)),C=I.length;return{items:f,offset:A,totalRows:C,totalHeight:C*x}})(e,i,o,r,s,a,c,t,l,d,u,u.maxWidth??n);m+=f.offset+5,p.push({label:e.label,...f,offset:m,totalRows:f.totalRows,totalHeight:f.totalHeight}),h+=m+12});const m=u.maxWidth??n;let f=h>m?0:"center"===u.align?Math.max(0,(m-h)/2):"end"===u.align?Math.max(0,m-h):0;const y=[];return p.forEach((n,i)=>{const o=e[i];o.label&&(y.push((0,ot.jsx)("text",{transform:`translate(${f},0) rotate(90)`,textAnchor:"start",className:"legend-group-label",style:{fontSize:"var(--semiotic-legend-font-size, 12px)"},fill:"var(--semiotic-text, #333)",children:o.label},"legend-text-"+i)),f+=16),y.push((0,ot.jsx)("g",{className:"legend-item",transform:`translate(${f},0)`,children:n.items},"legend-group-"+i)),f+=n.offset+5,e[i+1]&&y.push((0,ot.jsx)("line",{stroke:"gray",x1:f,y1:-8,x2:f,y2:(n.totalHeight||t)+0+8},"legend-top-line legend-symbol-"+i)),f+=12}),(0,ot.jsx)("g",{children:y})};function ht({config:e,orientation:t="vertical",width:n=100}){const{colorFn:i,domain:o,label:r,format:s}=e,a=s||(e=>Math.round(100*e)/100+""),c="grad-legend-"+Je.useId();if("horizontal"===t){const e=12,t=Math.min(n,200),s=Math.max(0,(n-t)/2),l=[];for(let e=0;64>=e;e++){const t=e/64;l.push((0,ot.jsx)("stop",{offset:100*t+"%",stopColor:i(o[0]+t*(o[1]-o[0]))},e))}return(0,ot.jsxs)("g",{"aria-label":r||"Gradient legend",children:[(0,ot.jsx)("defs",{children:(0,ot.jsx)("linearGradient",{id:c,x1:"0%",y1:"0%",x2:"100%",y2:"0%",children:l})}),r&&(0,ot.jsx)("text",{x:s+t/2,y:-4,textAnchor:"middle",fontSize:11,fill:"var(--semiotic-text, #333)",children:r}),(0,ot.jsx)("rect",{x:s,y:0,width:t,height:e,fill:`url(#${c})`,rx:2}),(0,ot.jsx)("text",{x:s,y:e+12,textAnchor:"start",fontSize:10,fill:"var(--semiotic-text-secondary, #666)",children:a(o[0])}),(0,ot.jsx)("text",{x:s+t,y:e+12,textAnchor:"end",fontSize:10,fill:"var(--semiotic-text-secondary, #666)",children:a(o[1])})]})}const l=[];for(let e=0;64>=e;e++){const t=e/64;l.push((0,ot.jsx)("stop",{offset:100*t+"%",stopColor:i(o[1]-t*(o[1]-o[0]))},e))}return(0,ot.jsxs)("g",{"aria-label":r||"Gradient legend",children:[r&&(0,ot.jsx)("text",{x:7,y:-6,textAnchor:"middle",fontSize:11,fill:"var(--semiotic-text, #333)",children:r}),(0,ot.jsx)("defs",{children:(0,ot.jsx)("linearGradient",{id:c,x1:"0%",y1:"0%",x2:"0%",y2:"100%",children:l})}),(0,ot.jsx)("rect",{x:0,y:0,width:14,height:100,fill:`url(#${c})`,rx:2}),(0,ot.jsx)("text",{x:19,y:10,fontSize:10,fill:"var(--semiotic-text-secondary, #666)",children:a(o[1])}),(0,ot.jsx)("text",{x:19,y:100,fontSize:10,fill:"var(--semiotic-text-secondary, #666)",children:a(o[0])})]})}function pt(e){const{legendGroups:t,customClickBehavior:n,customHoverBehavior:i,highlightedCategory:o,isolatedCategories:r,legendInteraction:s,title:a="Legend",width:c=100,height:l=20,orientation:d="vertical",legendLayout:u}=e,h=function(e){const t=Math.max(1,e?.swatchSize??et),n=Math.max(t,e?.rowHeight??it);return{swatchSize:t,labelGap:Math.max(0,e?.labelGap??tt),itemGap:Math.max(0,e?.itemGap??nt),rowHeight:n,align:"left"===e?.align?"start":"right"===e?.align?"end":e?.align??"start",maxWidth:e?.maxWidth}}(u),[p,m]=Je.useState(0),[f,y]=Je.useState(0),g=Je.useCallback((e,t)=>{m(e),y(t)},[]),b="vertical"===d?dt({legendGroups:t||[],width:c,customClickBehavior:n,customHoverBehavior:i,highlightedCategory:o,isolatedCategories:r,focusedGroupIndex:p,focusedItemIndex:f,onFocusedIndexChange:g,legendInteraction:s,metrics:h}):ut({legendGroups:t||[],title:a,height:l,width:c,customClickBehavior:n,customHoverBehavior:i,highlightedCategory:o,isolatedCategories:r,focusedGroupIndex:p,focusedItemIndex:f,onFocusedIndexChange:g,legendInteraction:s,metrics:h}),x=!(!n&&!i);return(0,ot.jsxs)("g",{role:x?"listbox":void 0,"aria-multiselectable":!(!x||"isolate"!==s&&(void 0!==s||null==r))||void 0,"aria-label":"Chart legend",style:{fontFamily:"var(--semiotic-font-family, sans-serif)"},children:[void 0!==a&&""!==a&&"vertical"===d&&(0,ot.jsx)("text",{className:"legend-title",y:16,x:c/2,textAnchor:"middle",style:{fontSize:"var(--semiotic-legend-font-size, 12px)"},fill:"var(--semiotic-text, #333)",children:a}),b]})}function mt(e){return"object"==typeof e&&null!==e&&"legendGroups"in e&&Array.isArray(e.legendGroups)}var ft=require("react/jsx-runtime");function yt(e){const{legend:t,totalWidth:n,totalHeight:i,margin:o,legendPosition:r="right",legendLayout:s,title:a,legendHoverBehavior:c,legendClickBehavior:l,legendHighlightedCategory:d,legendIsolatedCategories:u,legendInteraction:h}=e;if(!t)return null;const p="top"===r||"bottom"===r,m=!!a,f=Math.max(0,n-o.left-o.right),y=Math.max(1,p?s?.maxWidth??f:100);let g,b;return"left"===r?(g=Math.max(4,o.left-y-10),b=o.top):"top"===r?(g=o.left,b=m?32:8):"bottom"===r?(g=o.left,b=i-o.bottom+38):(g=n-o.right+10,b=o.top),(0,ft.jsx)("g",{transform:`translate(${g}, ${b})`,children:(x=t,"object"==typeof x&&null!==x&&"gradient"in x?(0,ft.jsx)(ht,{config:t.gradient,orientation:p?"horizontal":"vertical",width:y}):mt(t)?(0,ft.jsx)(pt,{legendGroups:t.legendGroups,title:"",width:y,orientation:p?"horizontal":"vertical",legendLayout:s,customHoverBehavior:c,customClickBehavior:l,highlightedCategory:d,isolatedCategories:u,legendInteraction:h}):t)});var x}var gt=require("react/jsx-runtime"),bt={secondary:0,primary:3},xt=1,vt=2,wt=.6,kt="0.88em",Mt=.95,It=.72,St=.06,jt=".annotation-deferred{opacity:0;pointer-events:none;transition:opacity .12s ease}.stream-xy-frame:hover .annotation-deferred,.stream-ordinal-frame:hover .annotation-deferred,.stream-network-frame:hover .annotation-deferred,.stream-geo-frame:hover .annotation-deferred,.stream-xy-frame:focus-within .annotation-deferred,.stream-ordinal-frame:focus-within .annotation-deferred,.stream-network-frame:focus-within .annotation-deferred,.stream-geo-frame:focus-within .annotation-deferred{opacity:1;pointer-events:auto}@media (prefers-reduced-motion:reduce){.annotation-deferred{transition:none}}",At=".annotation-cohesion--layer text,.annotation-cohesion--layer tspan{fill:var(--semiotic-annotation-color,var(--semiotic-text-secondary,#666));font-style:italic}";function Ct(e){return!0===e?._annotationDeferred}function Rt(e){return"blended"===e?.cohesion||"layer"===e?.cohesion?e.cohesion:null}function $t(e){const t=e?.provenance?.confidence;return"number"==typeof t&&Number.isFinite(t)?Math.max(0,Math.min(1,t)):null}function Pt(e){return Math.max(It,Mt-e*St)}var Dt=c(require("react")),Bt=require("react/jsx-runtime");function Tt(e,t=120,n=8){if(!e)return[];const i=Math.max(1,Math.floor(t/n)),o=e.split(/\s+/),r=[];let s="";for(const e of o)s&&s.length+1+e.length>i?(r.push(s),s=e):s=s?`${s} ${e}`:e;return s&&r.push(s),r}function Et(e,t,n,i){return"curly"===e?i?`M0,0 C${.6*n},0 ${.4*n},${t/2} ${n},${t/2} C${.4*n},${t/2} ${.6*n},${t} 0,${t}`:`M0,0 C0,${.6*n} ${t/2},${.4*n} ${t/2},${n} C${t/2},${.4*n} ${t},${.6*n} ${t},0`:i?`M0,0 L${n},0 L${n},${t} L0,${t}`:`M0,0 L0,${n} L${t},${n} L${t},0`}function Nt(e,t,n,i){if(!e)return(0,Bt.jsx)("g",{className:"annotation-note"});const{label:o,title:r,orientation:s,align:a,wrap:c=120,noWrap:l}=e;if(!o&&!r)return(0,Bt.jsx)("g",{className:"annotation-note"});let d=s;d||(d=Math.abs(t)>Math.abs(n)?"leftRight":"topBottom");let u=a;u&&"dynamic"!==u||(u="topBottom"===d?0>t?"right":"left":0>n?"bottom":"top");let h="start";"topBottom"===d?"right"===u?h="end":"middle"===u&&(h="middle"):h=0>t?"end":"start";const p=16,m=r?l?[r]:Tt(r,c):[],f=o?l?[o]:Tt(o,c):[],y="leftRight"===d?"end"===h?-4:4:0;let g=0;const b=[],x=i||"var(--semiotic-annotation-color, var(--semiotic-text, #333))";e.useHTML||e.html?b.push((0,Bt.jsx)("foreignObject",{className:"annotation-note-html",x:"end"===h?y-c:"middle"===h?y-c/2:y,y:-16,width:c,height:Math.max(p,(m.length+f.length)*p+(r&&o?2:0))+p,style:{overflow:"visible"},children:(0,Bt.jsxs)("div",{xmlns:"http://www.w3.org/1999/xhtml",style:{color:x,fontSize:"12px",lineHeight:"16px",overflow:"visible",textAlign:"end"===h?"right":"middle"===h?"center":"left",whiteSpace:l?"nowrap":"normal",wordBreak:"break-word"},children:[r&&(0,Bt.jsx)("div",{className:"annotation-note-title",style:{fontWeight:"bold"},children:r}),o&&(0,Bt.jsx)("div",{className:"annotation-note-label",children:o})]})},"annotation-note-html")):(m.length>0&&(b.push((0,Bt.jsx)("text",{className:"annotation-note-title",fill:x,textAnchor:h,fontWeight:"bold",children:m.map((e,t)=>(0,Bt.jsx)("tspan",{x:y,dy:0===t?0:p,children:e},t))},"annotation-note-title")),g=m.length*p),f.length>0&&b.push((0,Bt.jsx)("text",{className:"annotation-note-label",fill:x,textAnchor:h,y:g,children:f.map((e,t)=>(0,Bt.jsx)("tspan",{x:y,dy:0===t?0:p,children:e},t))},"annotation-note-label")));let v=null;if((r||o)&&(0!==t||0!==n))if("topBottom"===d){const e=Math.min(c,120);let t=0,n=e;"end"===h?(t=-e,n=0):"middle"===h&&(t=-e/2,n=e/2),v=(0,Bt.jsx)("line",{className:"note-line",x1:t,x2:n,y1:0,y2:0,stroke:i||"var(--semiotic-text-secondary, currentColor)"})}else{const e=(m.length+f.length)*p+(f.length>0?p:0);let t=0,n=e;"bottom"===u?(t=-e,n=0):"middle"===u&&(t=-e/2,n=e/2),v=(0,Bt.jsx)("line",{className:"note-line",x1:0,x2:0,y1:t,y2:n,stroke:i||"var(--semiotic-text-secondary, currentColor)"})}const w=Math.max(0,m.length+f.length-1)*p;let k=0;return"topBottom"===d?k=0>n?-(w+2):18:"leftRight"===d&&(k="middle"===u?-(w+p+(f.length>0&&m.length>0?2:0))/2+8:"bottom"===u||0>n?-(w+2):18),(0,Bt.jsxs)("g",{className:"annotation-note",transform:`translate(${t},${n})`,children:[(0,Bt.jsx)("g",{className:"annotation-note-content",transform:0!==k?`translate(0,${k})`:void 0,children:b}),v]})}function Ot(e,t,n,i,o){const r=[];switch(e){case"callout-circle":{const e=(t?.radius||0)+(t?.radiusPadding||0);e>0&&r.push((0,Bt.jsx)("circle",{r:e,fill:"none",stroke:n||"var(--semiotic-text-secondary, currentColor)"},"subject-circle"));break}case"callout-rect":{const e=t?.width||0,i=t?.height||0;(e>0||i>0)&&r.push((0,Bt.jsx)("rect",{width:e,height:i,fill:"none",stroke:n||"var(--semiotic-text-secondary, currentColor)"},"subject-rect"));break}case"callout-custom":t?.custom&&r.push(...Array.isArray(t.custom)?t.custom:[t.custom]);break;case"xy-threshold":{const e=i||0,s=o||0;if(void 0!==t?.x){const i=(t.x||0)-e;r.push((0,Bt.jsx)("line",{x1:i,y1:(t.y1||0)-s,x2:i,y2:(t.y2||0)-s,stroke:n||"var(--semiotic-text-secondary, currentColor)",strokeDasharray:"5,5"},"threshold-line"))}else if(void 0!==t?.y){const i=(t.y||0)-s;r.push((0,Bt.jsx)("line",{x1:(t.x1||0)-e,y1:i,x2:(t.x2||0)-e,y2:i,stroke:n||"var(--semiotic-text-secondary, currentColor)",strokeDasharray:"5,5"},"threshold-line"))}else void 0!==t?.x1||void 0!==t?.x2?r.push((0,Bt.jsx)("line",{x1:(t.x1||0)-e,y1:0,x2:(t.x2||0)-e,y2:0,stroke:n||"var(--semiotic-text-secondary, currentColor)",strokeDasharray:"5,5"},"threshold-line")):void 0===t?.y1&&void 0===t?.y2||r.push((0,Bt.jsx)("line",{x1:0,y1:(t.y1||0)-s,x2:0,y2:(t.y2||0)-s,stroke:n||"var(--semiotic-text-secondary, currentColor)",strokeDasharray:"5,5"},"threshold-line"));break}case"bracket":{const e=t?.type||"curly",i=t?.width??t?.height;void 0!==i&&r.push((0,Bt.jsx)("path",{d:Et(e,i,t?.depth||30,void 0===t?.width),fill:"none",stroke:n||"var(--semiotic-text-secondary, currentColor)"},"bracket-path"));break}}return(0,Bt.jsx)("g",{className:"annotation-subject",children:r})}function Wt(e,t,n,i,o,r){const s=[];let a=0,c=0;if("callout-circle"!==o&&"label"!==o||!r?.radius){if("callout-rect"===o&&r){const n=r.width||0,i=r.height||0;if(n>0||i>0){const o=n/2,r=i/2,s=e-o,l=t-r;if(0!==s||0!==l){const e=Math.abs(s),t=Math.abs(l),d=n/2,u=i/2,h=e*u>t*d?d/e:u/t;a=o+s*h,c=r+l*h}}}else if("bracket"===o&&r){const e=r.width,t=r.height,n=r.depth||30;void 0!==e?(a=e/2,c=n):void 0!==t&&(a=n,c=t/2)}}else{const n=(r.radius||0)+(r.radiusPadding||0);if(n>0&&(0!==e||0!==t)){const i=Math.atan2(t,e);a=Math.cos(i)*n,c=Math.sin(i)*n}}const l=Math.sqrt((e-a)**2+(t-c)**2);if(l>.5){const o=i||"var(--semiotic-text-secondary, currentColor)",r="curve"===n?.type;let d=Math.atan2(t-c,e-a);if(r){const i=(a+e)/2,r=(c+t)/2,u=-(t-c)/l,h=(e-a)/l,p=(n?.curve??.25)*l,m=i+u*p,f=r+h*p;s.push((0,Bt.jsx)("path",{className:"connector-curve",d:`M${a},${c}Q${m},${f} ${e},${t}`,fill:"none",stroke:o},"connector-line")),d=Math.atan2(f-c,m-a)}else s.push((0,Bt.jsx)("line",{x1:a,y1:c,x2:e,y2:t,stroke:o},"connector-line"));if("arrow"===n?.end){const e=10,t=16/180*Math.PI;s.push((0,Bt.jsx)("path",{d:`M${a},${c}L${a+e*Math.cos(d+t)},${c+e*Math.sin(d+t)}L${a+e*Math.cos(d-t)},${c+e*Math.sin(d-t)}Z`,fill:o,stroke:"none"},"connector-arrow"))}}return(0,Bt.jsx)("g",{className:"annotation-connector",children:s})}function qt(e){const{x:t=0,y:n=0,dx:i,dy:o,nx:r,ny:s,note:a,connector:c,subject:l,type:d,color:u,className:h,disable:p,opacity:m,strokeDasharray:f,events:y={},"data-testid":g}=e,b=Array.isArray(t)?t[0]??0:t,x=Array.isArray(n)?n[0]??0:n,v=new Set(Array.isArray(p)?p:[]);let w=i||0,k=o||0;null!=r&&(w=r-b),null!=s&&(k=s-x);const M="string"==typeof d?d:"label";if("bracket"===M&&l&&0===w&&0===k)if(void 0!==l.width){w=l.width/2;const e=l.depth||30;k=e+(0>e?-5:5)}else if(void 0!==l.height){const e=l.depth||30;w=e+(0>e?-5:5),k=l.height/2}return(0,Bt.jsxs)("g",{className:("annotation "+(h||"")).trim(),transform:`translate(${b},${x})`,"data-testid":g,...null!=m&&{opacity:m},...f&&{strokeDasharray:f},...y,children:[!v.has("connector")&&Wt(w,k,c,u,M,l),!v.has("subject")&&Ot(M,l,u,b,x),!v.has("note")&&Nt(a,w,k,u)]})}function Ft(e){const{noteData:t}=e,{screenCoordinates:n}=t,i="string"==typeof t.type?t.type:"label",o=t.eventListeners||t.events||{};if(t.coordinates&&n){const e=t.nx||n[0][0]+(t.dx??0),o=t.ny||n[0][1]+(t.dy??0),r=n.map((n,r)=>{const s=Object.assign({},t,{note:0===r?t.note:{label:""},x:n[0],y:n[1],nx:e,ny:o});return(0,Bt.jsx)(qt,{"data-testid":"semiotic-annotation",...s,type:i},"multi-annotation-"+r)});return(0,Bt.jsx)("g",{children:r})}const r=t.note||{title:"none",label:t.label},s=`${r.label}-${r.title}-${t.i}`;return(0,Bt.jsx)(qt,{"data-testid":"semiotic-annotation",events:o,...t,type:i},s)}var zt=require("d3-hierarchy"),Lt=require("d3-shape"),Yt=2;function Ht(e){const t=10**Yt;return Math.round(e*t)/t}function _t(e,t=2){const n=[],i=[],o=t+1;for(let t=0;o>t;t++){let r=0;for(const[n,i]of e)null!==i&&(r+=n**t*i);n.push(r);const s=[];for(let n=0;o>n;n++){let i=0;for(const[o,r]of e)null!==r&&(i+=o**(t+n));s.push(i)}i.push(s)}i.push(n);const r=function(e,t){const n=e,i=e.length-1,o=[t];for(let e=0;i>e;e++){let t=e;for(let o=e+1;i>o;o++)Math.abs(n[e][o])>Math.abs(n[e][t])&&(t=o);for(let o=e;i+1>o;o++){const i=n[o][e];n[o][e]=n[o][t],n[o][t]=i}for(let t=e+1;i>t;t++)for(let o=i;o>=e;o--)n[o][t]-=n[o][e]*n[e][t]/n[e][e]}for(let e=i-1;e>=0;e--){let t=0;for(let r=e+1;i>r;r++)t+=n[r][e]*o[r];o[e]=(n[i][e]-t)/n[e][e]}return o}(i,o).map(Ht);return{points:e.map(([e])=>[Ht(e),Ht(r.reduce((t,n,i)=>t+n*e**i,0))]),equation:[...r].reverse()}}function Gt(e,t){const n=t.scales?.x??t.scales?.time;return n?null!=e.x?n(e.x):t.xAccessor&&null!=e[t.xAccessor]?n(e[t.xAccessor]):null:null}function Xt(e,t){const n=t.scales?.y??t.scales?.value;return n?null!=e.y?n(e.y):t.yAccessor&&null!=e[t.yAccessor]?n(e[t.yAccessor]):null:null}function Vt(e){return null==e?null:e+""}function Ut(e,t,n){return t.stickyPositionCache?.set(e,n),n}function Kt(e,t,n){const i=e.anchor||e.lifecycle?.anchor||"fixed";if("latest"===i){if(null!=e.pointId&&n.pointNodes&&n.pointNodes.length>0)for(let i=n.pointNodes.length-1;i>=0;i--){const o=n.pointNodes[i];if(o.pointId===e.pointId)return Ut(t,n,{x:o.x,y:o.y})}const i=function(e){const t=e.data;if(!t||0===t.length)return null;const n=t[t.length-1],i=e.scales?.x??e.scales?.time,o=e.scales?.y??e.scales?.value;if(!i||!o)return null;const r=n[e.xAccessor||"x"],s=n[e.yAccessor||"y"];return null==r||null==s?null:{x:i(r),y:o(s)}}(n);return i?Ut(t,n,i):null}if("semantic"===i){const i=function(e,t,n){const i=function(e){return Vt(e.provenance?.stableId??e.stableId)}(e);if(!i)return null;const o=n.pointNodes?.find(e=>Vt(e.pointId)===i);if(o)return Ut(t,n,{x:o.x,y:o.y});const r=n.data?.find(e=>function(e){return Vt(e.stableId??e.id??e.provenance?.stableId)}(e)===i);if(!r)return null;const s=Gt(r,n),a=Xt(r,n);return null==s||null==a?null:Ut(t,n,{x:s,y:a})}(e,t,n);if(i)return i}let o=null,r=null;if(null!=e.pointId&&n.pointNodes){const t=n.pointNodes.find(t=>t.pointId===e.pointId);t&&(o=t.x,r=t.y)}if(null!=o&&null!=r||(o=Gt(e,n),r=Xt(e,n)),null!=o&&null!=r)return Ut(t,n,{x:o,y:r});if("sticky"===i){const e=n.stickyPositionCache?.get(t);if(e)return e}return null}function Qt(e,t,n,i=50){return!(-i>e||e>(n.width||0)+i||-i>t||t>(n.height||0)+i)}function Zt(e){let t=1/0,n=-1/0;for(const i of e)t>i&&(t=i),i>n&&(n=i);return[t,n]}var Jt=c(require("react")),[en,tn]=g(e=>({observations:[],maxObservations:100,version:0,pushObservation(t){e(e=>{const n=e.observations;return n.push(t),n.length>e.maxObservations&&n.shift(),{version:e.version+1}})},clearObservations(){e(()=>({observations:[],version:0}))}}));function nn(e,t={}){const n=function(e){const t=e.provenance,n=e.id??e.stableId??t?.stableId;return null==n||""===n?void 0:n+""}(e);return{"data-semiotic-annotation-widget":"",...n?{"data-semiotic-annotation-id":n}:{},onClickCapture(i){const o=function(e){const t=e.nativeEvent;return"touch"===t.pointerType?"touch":0===t.detail?"keyboard":"pointer"}(i);t.onAnnotationActivate?.({annotation:e,annotationId:n,chartId:t.chartId,inputType:o}),n&&t.onObservation&&t.onObservation({type:"annotation-activate",annotationId:n,inputType:o,timestamp:Date.now(),chartType:t.chartType??"unknown",chartId:t.chartId})}}}var on=16,rn=20,sn=require("react/jsx-runtime"),an="var(--semiotic-bg, #ffffff)",cn=.85;function ln(e){const{x:t,y:n,text:i,fill:o,fontSize:r=12,fontWeight:s,fontFamily:a,textAnchor:c="start",dominantBaseline:l,background:d,className:u}=e,h=function(e){return void 0===e||!0===e||"halo"===e?{type:"halo"}:!1===e||"none"===e?null:"box"===e?{type:"box"}:{type:e.type??"halo",...e}}(d),p=e=>(0,sn.jsx)("text",{x:t,y:n,textAnchor:c,dominantBaseline:l,fill:o,fontSize:r,fontWeight:s,fontFamily:a,className:u,...e?{stroke:e.stroke,strokeWidth:e.strokeWidth,paintOrder:"stroke"}:{},children:i});if(!h)return p();if("halo"===h.type)return p({stroke:h.fill??an,strokeWidth:h.haloWidth??3});const m=h.padding??{x:6,y:3},f="number"==typeof m?m:m.x,y="number"==typeof m?m:m.y,g=function(e,t){return(e+"").length*t*.6}(i,r),b=r+2*y;let x,v;return x="middle"===c?t-g/2-f:"end"===c?t-g-f:t-f,v="middle"===l||"central"===l?n-b/2:"hanging"===l||"text-before-edge"===l?n-y:n-.8*r-y,(0,sn.jsxs)("g",{className:u,children:[(0,sn.jsx)("rect",{x:x,y:v,width:g+2*f,height:b,rx:h.radius??3,ry:h.radius??3,fill:h.fill??an,fillOpacity:h.opacity??cn,stroke:h.stroke,strokeWidth:h.strokeWidth}),p()]})}var dn=require("react/jsx-runtime"),un={linear:Lt.curveLinear,monotoneX:Lt.curveMonotoneX,monotoneY:Lt.curveMonotoneY,step:Lt.curveStep,stepAfter:Lt.curveStepAfter,stepBefore:Lt.curveStepBefore,basis:Lt.curveBasis,cardinal:Lt.curveCardinal,catmullRom:Lt.curveCatmullRom};var hn=new Set(["label","callout","callout-circle","callout-rect","text","widget"]);function pn(e){return!!e&&"object"==typeof e&&hn.has(function(e){return"string"==typeof e?.type?e.type:""}(e))}new Set(["label","callout","callout-circle","callout-rect"]);var mn=2e4,fn=1;function yn(e){return"primary"===e?.emphasis||!0===e?.defensive}function gn(e,t,n={}){return"number"==typeof n.maxAnnotations&&Number.isFinite(n.maxAnnotations)?Math.max(0,Math.floor(n.maxAnnotations)):e>0&&t>0?Math.max(1,Math.round(e*t/(n.areaPerAnnotation&&n.areaPerAnnotation>0?n.areaPerAnnotation:mn))):1/0}function bn(e){let t;const n=e?.emphasis;t="primary"===n?100:"secondary"===n?10:50;const i=e?.provenance?.confidence;switch("number"==typeof i&&Number.isFinite(i)&&(t+=15*Math.max(0,Math.min(1,i))),e?.lifecycle?.freshness){case"fresh":t+=8;break;case"aging":t+=4;break;case"stale":t+=1;break;case"expired":t-=200}return t}var xn=32,vn=6,wn=4,kn=8,Mn=72,In=30,Sn=-30,jn=8,An=480,Cn=3;var Rn={ai:"AI",agent:"agent",watcher:"watcher",system:"system",import:"imported",computed:"computed",user:"you"};function $n(e){if(!Pn(e))return e;const t=("string"==typeof e.mobileText?e.mobileText:void 0)??("string"==typeof e.shortText?e.shortText:void 0);return!t||"string"!=typeof e.label&&null!=e.label?e:{...e,label:t}}function Pn(e){return pn(e)}function Dn(e,t){if(!e)return[];const n=Math.max(1,Math.floor(t/7)),i=e.split(/\s+/).filter(Boolean),o=[];let r="";for(const e of i)r&&r.length+e.length+1>n?(o.push(r),r=e):r=r?`${r} ${e}`:e;return r&&o.push(r),o}function Bn(e,t,n,i,o){const r=e+n,s=t+i;return Math.abs(n)>Math.abs(i)?{x:0>n?r-o.width-4:r+4,y:0>i?s-o.height:s,width:o.width,height:o.height}:{x:0>n?r-o.width:r,y:0>i?s-o.height-4:s+4,width:o.width,height:o.height}}function Tn(e,t){return{x:e.x-t,y:e.y-t,width:e.width+2*t,height:e.height+2*t}}function En(e,t){return Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x))*Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y))}function Nn(e,t,n,i,o,r,s,a){const c=Tn(e,s);let l=.4*Math.hypot(t.dx,t.dy)+80*function(e,t,n,i){const o=Math.max(0,i-e.x),r=Math.max(0,i-e.y);return(o+Math.max(0,e.x+e.width-(t-i)))*e.height+(r+Math.max(0,e.y+e.height-(n-i)))*e.width}(c,o,r,a);for(const e of n)l+=12*En(c,e);for(const e of i)l+=4*En(c,e);return l}function On(e){const{annotations:t,context:n,defaultOffset:i=xn,notePadding:o=vn,markPadding:r=wn,edgePadding:s=kn,preserveManualOffsets:a=!0,routeLongConnectors:c=!0,connectorThreshold:l=Mn,density:d,progressiveDisclosure:u=!1,redundantCues:h=!1,responsive:p,mobile:m,cohesion:f,audience:y}=e,g=n.width||0,b=n.height||0,x="object"==typeof m?m:{},v=x.breakpoint??An,w=!!m&&v>=g,k=w&&!1!==x.preferShortText?t.map($n):t,M=w&&!d?{maxAnnotations:x.maxAnnotations??("callout-list"===x.strategy?1:2),minVisible:x.minVisible??1}:d,I=u||w&&(!1!==x.progressiveDisclosure||"callout-list"===x.strategy),S=w&&!p?x.responsive??{minWidth:v}:p,j=w&&!f?x.cohesion:f;if(0===k.length||0>=g||0>=b)return k.slice();const A=[],C=function(e,t){return(e.pointNodes||[]).map(e=>{const n=Math.max(1,e.r||1)+t;return{x:e.x-n,y:e.y-n,width:2*n,height:2*n}})}(n,r);let R=!1;const $=k.map((e,t)=>{if(!Pn(e))return e;const r=function(e,t,n){if("widget"===e.type&&"number"==typeof e.px&&"number"==typeof e.py)return{x:e.px,y:e.py};const i=e.pointId??e.nodeId;if(null!=i&&n.pointNodes){const e=n.pointNodes.find(e=>e.pointId===i);if(e)return{x:e.x,y:e.y}}const o=e.coordinates,r=n.scales?.geoProjection;if(Array.isArray(o)&&o.length>=2&&r){const e=o[0],t=o[1];if("number"==typeof e&&"number"==typeof t){const n=r([e,t]);if(n&&"number"==typeof n[0]&&"number"==typeof n[1])return{x:n[0],y:n[1]}}}return n.scales||"number"!=typeof e.x||"number"!=typeof e.y?Kt(e,t,n):{x:e.x,y:e.y}}(e,t,n);if(!r)return e;const d=function(e){if("widget"===e.type)return{width:"number"==typeof e.width?e.width:32,height:"number"==typeof e.height?e.height:32};const t="number"==typeof e.wrap?e.wrap:120,n=[...Dn("string"==typeof e.title?e.title:void 0,t),...Dn("string"==typeof e.label?e.label:void 0,t)],i=n.reduce((e,t)=>Math.max(e,t.length),0);return{width:Math.max(24,Math.min(t,7*i)+10),height:Math.max(18,16*n.length+6)}}(e);if(a&&("number"==typeof(u=e).dx||"number"==typeof u.dy)){const t=function(e){return"text"===e.type||"widget"===e.type?{dx:0,dy:0}:{dx:In,dy:Sn}}(e);return A.push(Tn(Bn(r.x,r.y,"number"==typeof e.dx?e.dx:t.dx,"number"==typeof e.dy?e.dy:t.dy,d),o)),e}var u;let h=null,p=1/0;for(const e of function(e){const t=1.6*e;return[{dx:e,dy:-e},{dx:-e,dy:-e},{dx:e,dy:e},{dx:-e,dy:e},{dx:e,dy:0},{dx:-e,dy:0},{dx:0,dy:-e},{dx:0,dy:e},{dx:t,dy:-t},{dx:-t,dy:-t},{dx:t,dy:t},{dx:-t,dy:t}]}(i)){const t=Nn(Bn(r.x,r.y,e.dx,e.dy,d),e,A,C,g,b,o,s);p>t&&(h=e,p=t)}if(!h)return e;const m=Tn(Bn(r.x,r.y,h.dx,h.dy,d),o);A.push(m);const f=Math.hypot(h.dx,h.dy),y=c&&f>=l&&"text"!==e.type&&"widget"!==e.type?{...e.connector||{end:"arrow"},type:"curve"}:e.connector;return R=!0,{...e,dx:h.dx,dy:h.dy,...y?{connector:y}:{}}}),P=R?$:k.slice();let D=P;if(h){let e=!1;const t=P.map(t=>{const n=function(e){return"text"!==e.type||"string"!=typeof e.color||Math.hypot("number"==typeof e.dx?e.dx:0,"number"==typeof e.dy?e.dy:0)<jn?e:{...e,_redundantConnector:!0}}(t);return n!==t&&(e=!0),n});D=e?t:P}{let e=!1;const t=D.map(t=>{if(!0!==t?.defensive)return t;const n=function(e){const t=e?.provenance;if(!t||"object"!=typeof t)return e;const n="string"==typeof t.source?Rn[t.source]??t.source:null,i="number"==typeof t.confidence&&Number.isFinite(t.confidence)?Math.round(100*Math.max(0,Math.min(1,t.confidence)))+"%":null;if(!n&&!i)return e;if(null!=e.label&&"string"!=typeof e.label)return e;const o=[n,i].filter(Boolean).join(" · "),r="string"==typeof e.label?e.label:"";return r.includes(`(${o})`)?e:{...e,label:r?`${r} (${o})`:`(${o})`}}(t);return n!==t&&(e=!0),n});D=e?t:D}const B=new Set;if(M){const e="object"==typeof M?M:{},t=function(e){if(!e)return 1;const t=function(e){const t=e?.familiarity;if(!t)return Cn;const n=Object.values(t).filter(e=>"number"==typeof e&&Number.isFinite(e));return 0===n.length?Cn:n.reduce((e,t)=>e+t,0)/n.length}(e);return t>2?4>t?1:.6:1.5}(y),n=1===t?e:{...e,maxAnnotations:Math.max(0,Math.round((e.maxAnnotations??gn(g,b,e))*t))},{deferred:i}=function(e){const{annotations:t,width:n,height:i}=e,o=Math.max(0,e.minVisible??fn),r=gn(n,i,e),s=t.map((e,t)=>{return{annotation:e,index:t,note:(n=e,pn(n))};var n}),a=s.filter(e=>e.note);if(0===a.length||r>=a.length)return{visible:t.slice(),deferred:[],budget:r};const c=a.filter(e=>yn(e.annotation)),l=a.filter(e=>!yn(e.annotation)).sort((e,t)=>bn(t.annotation)-bn(e.annotation)||e.index-t.index),d=Math.min(l.length,Math.max(Math.max(0,r-c.length),Math.max(0,o-c.length))),u=new Set([...c.map(e=>e.index),...l.slice(0,d).map(e=>e.index)]),h=[],p=[];for(const{annotation:e,index:t,note:n}of s)!n||u.has(t)?h.push(e):p.push(e);return{visible:h,deferred:p,budget:r}}({annotations:D,width:g,height:b,...n});for(const e of i)B.add(e)}if(S&&("object"==typeof S&&"number"==typeof S.minWidth?S.minWidth:An)>=g)for(const e of D)Pn(e)&&"secondary"===e.emphasis&&B.add(e);if(B.size>0)for(const e of D)!0===e?.defensive&&B.delete(e);let T;return T=0===B.size?D:I?D.map(e=>B.has(e)?{...e,_annotationDeferred:!0}:e):D.filter(e=>!B.has(e)),j?function(e,t){let n=!1;const i=e.map(e=>Pn(e)?"blended"===e.cohesion||"layer"===e.cohesion?e:(n=!0,{...e,cohesion:t}):e);return n?i:e}(T,j):T}var Wn=require("react/jsx-runtime");function qn(e){return"circle"===e.shape.type?e.shape.radius:Math.max(e.shape.width,e.shape.height)/2}function Fn(e){return e.map(e=>({pointId:e.id,x:e.x,y:e.y,r:Math.max(1,qn(e))}))}function zn(e){const{width:t,height:n,pointNodes:i=[],data:o}=e;return{scales:{x:(0,Ze.scaleLinear)().domain([0,Math.max(1,t)]).range([0,Math.max(1,t)]),y:(0,Ze.scaleLinear)().domain([0,Math.max(1,n)]).range([0,Math.max(1,n)])},width:t,height:n,frameType:"network",pointNodes:i,data:o,xAccessor:"x",yAccessor:"y"}}function Ln(e){return e?.length?e.map(e=>null!=e.pointId||null==e.bodyId?e:{...e,pointId:e.bodyId+""}):e}function Yn(e){const{width:t,height:n,totalWidth:i,totalHeight:o,margin:r,title:s,legend:a,legendHoverBehavior:c,legendClickBehavior:l,legendHighlightedCategory:d,legendIsolatedCategories:u,legendPosition:h="right",legendLayout:p,pointNodes:m=[],annotations:f,onAnnotationActivate:y,onObservation:g,chartId:b,chartType:x,autoPlaceAnnotations:v,svgAnnotationRules:w,children:k}=e,M=function(e){const t=tn(e=>e.pushObservation),n=Jt.useCallback(n=>{e.onObservation?.(n),t?.(n)},[e,t]);return Jt.useMemo(()=>({...e,onObservation:n}),[n,e])}({onAnnotationActivate:y,onObservation:g,chartId:b,chartType:x}),I=Qe.useMemo(()=>Ln(f),[f]),S=Qe.useMemo(()=>zn({width:t,height:n,pointNodes:m}),[n,m,t]),j=Qe.useMemo(()=>I&&v?On({annotations:I,context:S,..."object"==typeof v?v:{}}):I,[S,v,I]),A=Qe.useMemo(()=>function(e,t={}){return function(e,n,i){switch(e.type){case"label":case"callout":case"callout-circle":case"callout-rect":{const t=Kt(e,n,i);if(!t)return null;const{x:o,y:r}=t;if(!Qt(o,r,i))return null;const s="callout"===e.type?"callout-circle":e.type,a="callout-circle"===s?{radius:e.radius??12,radiusPadding:e.radiusPadding}:"callout-rect"===s?{width:e.width,height:e.height}:void 0;return(0,dn.jsx)(Ft,{noteData:{x:o,y:r,dx:e.dx??30,dy:e.dy??-30,note:{label:e.label,title:e.title,wrap:e.wrap||120},type:s,...a?{subject:a}:{},connector:e.connector||{end:"arrow"},color:e.color,disable:e.disable,opacity:e.opacity,strokeDasharray:e.strokeDasharray,className:e.className}},"ann-"+n)}case"x-threshold":{const t=Gt(null!=e.value?{...e,x:e.value}:e,i);if(null==t)return null;const o=e.color||"#f97316",r=e.labelPosition||"top";let s;s="bottom"===r?(i.height||0)-4:"center"===r?(i.height||0)/2:on;const a=t>.6*(i.width||0),c=a?t-4:t+4,l=a?"end":"start";return(0,dn.jsxs)("g",{opacity:e.opacity,children:[(0,dn.jsx)("line",{x1:t,y1:0,x2:t,y2:i.height||0,stroke:o,strokeWidth:e.strokeWidth||1.5,strokeDasharray:e.strokeDasharray||"6,3"}),e.label&&(0,dn.jsx)(ln,{x:c,y:s,text:e.label,textAnchor:l,fill:o,fontSize:12,fontWeight:"bold",background:e.labelBackground??"halo"})]},"ann-"+n)}case"y-threshold":{const t=Xt(null!=e.value?{...e,y:e.value}:e,i);if(null==t)return null;const o=e.color||"#f97316",r=e.labelPosition||"right";let a,c;"left"===r?(a=4,c="start"):"center"===r?(a=(i.width||0)/2,c="middle"):(a=(i.width||0)-4,c="end");const l=rn>(s=t)?Math.min((i.height||0)-4,s+on):s-4;return(0,dn.jsxs)("g",{opacity:e.opacity,children:[(0,dn.jsx)("line",{x1:0,y1:t,x2:i.width||0,y2:t,stroke:o,strokeWidth:e.strokeWidth||1.5,strokeDasharray:e.strokeDasharray||"6,3"}),e.label&&(0,dn.jsx)(ln,{x:a,y:l,text:e.label,textAnchor:c,fill:o,fontSize:12,fontWeight:"bold",background:e.labelBackground??"halo"})]},"ann-"+n)}case"enclose":{const t=(e.coordinates||[]).map(e=>({x:Gt({...e,type:"point"},i),y:Xt({...e,type:"point"},i),r:1})).filter(e=>null!=e.x&&null!=e.y);if(2>t.length)return null;const o=(0,zt.packEnclose)(t),r=e.padding||10;return(0,dn.jsxs)("g",{children:[(0,dn.jsx)("circle",{cx:o.x,cy:o.y,r:o.r+r,fill:e.fill||"none",fillOpacity:e.fillOpacity||.1,stroke:e.color||"var(--semiotic-text-secondary, #666)",strokeWidth:1.5,strokeDasharray:"4,2"}),e.label&&(0,dn.jsx)(ln,{x:o.x,y:o.y-o.r-r-4,textAnchor:"middle",fill:e.color||"var(--semiotic-text-secondary, #666)",fontSize:12,text:e.label,background:e.labelBackground??"none"})]},"ann-"+n)}case"rect-enclose":{const t=(e.coordinates||[]).map(e=>({x:Gt({...e,type:"point"},i),y:Xt({...e,type:"point"},i)})).filter(e=>null!=e.x&&null!=e.y);if(2>t.length)return null;const o=e.padding||10,r=t.map(e=>e.x),s=t.map(e=>e.y),[a,c]=Zt(r),[l,d]=Zt(s),u=a-o,h=c+o,p=l-o;return(0,dn.jsxs)("g",{children:[(0,dn.jsx)("rect",{x:u,y:p,width:h-u,height:d+o-p,fill:e.fill||"none",fillOpacity:e.fillOpacity||.1,stroke:e.color||"var(--semiotic-text-secondary, #666)",strokeWidth:1.5,strokeDasharray:"4,2"}),e.label&&(0,dn.jsx)(ln,{x:(u+h)/2,y:p-4,textAnchor:"middle",fill:e.color||"var(--semiotic-text-secondary, #666)",fontSize:12,text:e.label,background:e.labelBackground??"none"})]},"ann-"+n)}case"highlight":{const t=i.data||[],o="function"==typeof e.filter?t.filter(e.filter):e.field&&null!=e.value?t.filter(t=>t[e.field]===e.value):[],r={stroke:e.color||"#f97316",strokeWidth:2,fill:"none"};return(0,dn.jsx)("g",{children:o.map((t,n)=>{const o=Gt(t,i),s=Xt(t,i);if(null==o||null==s)return null;const a="function"==typeof e.r?e.r(t):e.r||6,c="function"==typeof e.style?e.style(t):e.style||r;return(0,dn.jsx)("circle",{cx:o,cy:s,r:a,...c},"hl-"+n)})},"ann-"+n)}case"bracket":{const t=Gt(e,i),o=Xt(e,i);return(0,dn.jsx)(Ft,{noteData:{x:t??0,y:o??0,dx:e.dx||0,dy:e.dy||0,note:{label:e.label,title:e.title,wrap:e.wrap||120},type:"bracket",subject:{type:e.bracketType||"curly",width:e.width,height:e.height,depth:e.depth||30},color:e.color}},"ann-"+n)}case"trend":{const t=i.data||[];if(2>t.length)return null;const o=i.xAccessor||"x",r=i.yAccessor||"y",s="ordinal"===i.frameType,a="horizontal"===i.projection,c=s?o:null,l=s?r:null;let d;const u=[],h=new Map;if(s&&c&&l){for(const e of t){const t=e[c];if(null==t)continue;const n=t+"";h.has(n)||(h.set(n,u.length),u.push(n))}d=t.map(e=>{const t=e[c],n=e[l];if(null==t||null==n)return null;const i=h.get(t+"");return null!=i?[i,+n]:null}).filter(e=>null!==e)}else d=t.map(e=>[e[o],e[r]]).filter(e=>null!=e[0]&&null!=e[1]);if(2>d.length)return null;const p=i.scales?.x??i.scales?.time,m=i.scales?.y??i.scales?.value;if(!p||!m)return null;const f=e=>t=>{const n=Math.max(0,Math.floor(t)),i=Math.min(u.length-1,n+1),o=t-n,r=e(u[n]);return r+(e(u[i])-r)*o},y=p,g=m;let b;if(s)if(a){const e=f(g);b=(t,n)=>[y(n),e(t)]}else{const e=f(y);b=(t,n)=>[e(t),g(n)]}else b=(e,t)=>[y(e),g(t)];const x=e.method||"linear";let v;if("loess"===x)v=function(e,t=.3){const n=e.length;if(2>n)return e.slice();const i=e.slice().sort((e,t)=>e[0]-t[0]),o=i.map(e=>e[0]),r=i.map(e=>e[1]),s=Math.max(2,Math.ceil(t*n)),a=[];for(let e=0;n>e;e++){const t=o[e],i=o.map(e=>Math.abs(e-t)),c=i.slice().sort((e,t)=>e-t)[Math.min(s-1,n-1)]||1,l=[];for(let e=0;n>e;e++){const t=0===c?0:i[e]/c;l[e]=1>t?Math.pow(1-Math.pow(t,3),3):0}let d=0,u=0,h=0,p=0,m=0;for(let e=0;n>e;e++){const t=l[e];0!==t&&(d+=t,u+=t*o[e],h+=t*r[e],p+=t*o[e]*o[e],m+=t*o[e]*r[e])}if(0===d){a.push([t,r[e]]);continue}const f=d*p-u*u;if(1e-12>Math.abs(f))a.push([t,h/d]);else{const e=(d*m-u*h)/f;a.push([t,(h-e*u)/d+e*t])}}return a}(d,e.bandwidth??.3);else{const t="polynomial"===x?_t(d,e.order||2):function(e){const t=[0,0,0,0];let n=0;for(const[i,o]of e)null!==o&&(n++,t[0]+=i,t[1]+=o,t[2]+=i*i,t[3]+=i*o);const i=n*t[2]-t[0]*t[0],o=0===i?0:Ht((n*t[3]-t[0]*t[1])/i),r=Ht(t[1]/n-o*t[0]/n);return{points:e.map(([e])=>[Ht(e),Ht(o*e+r)]),equation:[o,r]}}(d);v=t.points}const w=v.map(([e,t])=>{const[n,i]=b(e,t);return`${n},${i}`}).join(" "),k=e.color||"#6366f1",M=v[v.length-1],[I,S]=b(M[0],M[1]);return(0,dn.jsxs)("g",{children:[(0,dn.jsx)("polyline",{points:w,fill:"none",stroke:k,strokeWidth:e.strokeWidth||2,strokeDasharray:e.strokeDasharray||"6,3"}),e.label&&(0,dn.jsx)("text",{x:I+4,y:S-4,fill:k,fontSize:11,children:e.label})]},"ann-"+n)}case"band":{const t=i.scales?.y??i.scales?.value,s=t?.domain?.(),a=e.y0??s?.[0],c=e.y1??s?.[1],l=null!=a&&t?t(a):0,d=null!=c&&t?t(c):i.height||0,u=ce(e.fill,"ann-"+n,"var(--semiotic-primary, #6366f1)");return(0,dn.jsxs)("g",{opacity:e.opacity,children:[u.def&&(0,dn.jsx)("defs",{children:u.def}),(0,dn.jsx)("rect",{x:0,y:Math.min(l,d),width:i.width||0,height:Math.abs(d-l),fill:u.fill,fillOpacity:e.fillOpacity||.1}),e.label&&(0,dn.jsx)(ln,{x:(i.width||0)-4,y:(o=l,r=d,Math.max(Math.min(o,r),0)+on),textAnchor:"end",fill:e.color||"var(--semiotic-primary, #6366f1)",fontSize:11,fontWeight:"bold",text:e.label,background:e.labelBackground??"halo"})]},"ann-"+n)}case"x-band":{const t=i.scales?.x??i.scales?.time,o=t?.domain?.(),r=e.x0??o?.[0],s=e.x1??o?.[1],a=null!=r&&t?t(r):null,c=null!=s&&t?t(s):null;if(null==a||null==c)return null;const l=ce(e.fill||e.color,"ann-"+n,"var(--semiotic-primary, #6366f1)");return(0,dn.jsxs)("g",{opacity:e.opacity,children:[l.def&&(0,dn.jsx)("defs",{children:l.def}),(0,dn.jsx)("rect",{x:Math.min(a,c),y:0,width:Math.abs(c-a),height:i.height||0,fill:l.fill,fillOpacity:e.fillOpacity??.1}),e.label&&(0,dn.jsx)(ln,{x:Math.min(a,c)+4,y:on,textAnchor:"start",fill:e.color||"var(--semiotic-primary, #6366f1)",fontSize:11,fontWeight:"bold",text:e.label,background:e.labelBackground??"halo"})]},"ann-"+n)}case"envelope":{const t=i.data||[];if(2>t.length)return null;const o=i.xAccessor||"x",r=i.scales?.x??i.scales?.time,s=i.scales?.y??i.scales?.value;if(!r||!s)return null;const a=e.upperAccessor||"upperBounds",c=e.lowerAccessor||"lowerBounds",l=e.filter,d=t.filter(e=>null!=e[a]&&null!=e[c]&&!(l&&!l(e))).sort((e,t)=>e[o]-t[o]);if(2>d.length)return null;const u=un[i.curve||"linear"]||Lt.curveLinear,h=(0,Lt.area)().x(e=>r(e[o])).y0(e=>s(e[c])).y1(e=>s(e[a])).curve(u)(d);if(!h)return null;const p=e.fill||"#6366f1";return(0,dn.jsxs)("g",{children:[(0,dn.jsx)("path",{d:h,fill:p,fillOpacity:e.fillOpacity??.15,stroke:"none"}),e.label&&d.length>0&&(0,dn.jsx)("text",{x:r(d[d.length-1][o])+4,y:s(d[d.length-1][a])-4,fill:p,fontSize:11,children:e.label})]},"ann-"+n)}case"anomaly-band":{const t=i.data||[];if(2>t.length)return null;const o=i.yAccessor||"y",r=i.scales?.x??i.scales?.time,s=i.scales?.y??i.scales?.value;if(!r||!s)return null;const a=t.map(e=>e[o]).filter(e=>null!=e&&isFinite(e));if(2>a.length)return null;const c=a.reduce((e,t)=>e+t,0)/a.length,l=a.reduce((e,t)=>e+(t-c)**2,0)/a.length,d=Math.sqrt(l),u=e.threshold??2,h=c-u*d,p=!1!==e.showBand,m=e.fill||"#6366f1",f=e.fillOpacity??.1,y=e.anomalyColor||"#ef4444",g=e.anomalyRadius??6,b=s(c+u*d),x=s(h),v=t.filter(e=>{const t=e[o];return null!=t&&Math.abs(t-c)>u*d});return(0,dn.jsxs)("g",{children:[p&&(0,dn.jsx)("rect",{x:0,y:Math.min(b,x),width:i.width||0,height:Math.abs(x-b),fill:m,fillOpacity:f}),v.map((e,t)=>{const n=Gt(e,i),o=Xt(e,i);return null==n||null==o?null:(0,dn.jsx)("circle",{cx:n,cy:o,r:g,fill:y,fillOpacity:.7,stroke:y,strokeWidth:1.5},"anomaly-"+t)}),e.label&&(0,dn.jsx)("text",{x:(i.width||0)-4,y:Math.min(b,x)-4,textAnchor:"end",fill:m,fontSize:11,children:e.label})]},"ann-"+n)}case"forecast":{const t=i.data||[];if(3>t.length)return null;const o=i.xAccessor||"x",r=i.yAccessor||"y",s=i.scales?.x??i.scales?.time,a=i.scales?.y??i.scales?.value;if(!s||!a)return null;const c=t.map(e=>[e[o],e[r]]).filter(e=>null!=e[0]&&null!=e[1]&&isFinite(e[0])&&isFinite(e[1])).sort((e,t)=>e[0]-t[0]);if(3>c.length)return null;let l;if("polynomial"===(e.method||"linear")){const t=_t(c,e.order||2).equation;l=e=>t.reduce((t,n,i)=>t+n*Math.pow(e,i),0)}else{const e=c.length;let t=0,n=0,i=0,o=0;for(const[e,r]of c)t+=e,n+=r,i+=e*e,o+=e*r;const r=e*i-t*t;if(1e-12>Math.abs(r))return null;const s=(e*o-t*n)/r,a=(n-s*t)/e;l=e=>a+s*e}const d=c.length,u=c.map(([e,t])=>t-l(e)),h=u.reduce((e,t)=>e+t*t,0),p=Math.sqrt(h/Math.max(d-2,1)),m=c.reduce((e,t)=>e+t[0],0)/d,f=c.reduce((e,t)=>e+(t[0]-m)**2,0),y=e.confidence??.95,g=.99>y?.95>y?.9>y?1:1.645:1.96:2.576,b=e.steps??5,x=c[d-1][0],v=(x-c[0][0])/Math.max(d-1,1),w=[];for(let e=1;b>=e;e++)w.push(x+e*v);const k=[];for(const e of w){const t=l(e),n=p*Math.sqrt(1+1/d+(f>0?(e-m)**2/f:0))*g;k.push({x:e,yCenter:t,yUpper:t+n,yLower:t-n})}const M=`M${k.map(e=>`${s(e.x)},${a(e.yUpper)}`).join(" L")} L${k.slice().reverse().map(e=>`${s(e.x)},${a(e.yLower)}`).join(" L")} Z`,I=k.map(e=>`${s(e.x)},${a(e.yCenter)}`).join(" "),S=`${s(x)},${a(l(x))}`,j=e.strokeColor||"#6366f1";return(0,dn.jsxs)("g",{children:[(0,dn.jsx)("path",{d:M,fill:e.fill||"#6366f1",fillOpacity:e.fillOpacity??.15,stroke:"none"}),(0,dn.jsx)("polyline",{points:`${S} ${I}`,fill:"none",stroke:j,strokeWidth:e.strokeWidth??2,strokeDasharray:e.strokeDasharray??"6,3"}),e.label&&k.length>0&&(0,dn.jsx)("text",{x:s(k[k.length-1].x)+4,y:a(k[k.length-1].yCenter)-4,fill:j,fontSize:11,children:e.label})]},"ann-"+n)}case"widget":{let o,r;if(null!=e.px&&null!=e.py)o=e.px,r=e.py;else{const t=Kt(e,n,i);if(!t)return null;o=t.x,r=t.y}if(!Qt(o,r,i))return null;const s=e.dx??0,a=e.dy??0,c=e.width??32,l=e.height??32,d=e.content??(0,dn.jsx)("span",{style:{fontSize:18,cursor:"default"},title:e.label||"Info",children:"ℹ️"});return(0,dn.jsx)("foreignObject",{x:o+s-c/2,y:r+a-l/2,width:c,height:l,style:{overflow:"visible",pointerEvents:"auto"},children:(0,dn.jsx)("div",{...nn(e,t),style:{width:c,height:l,display:"flex",alignItems:"center",justifyContent:"center"},children:d})},"ann-"+n)}case"text":{const t=Kt(e,n,i);if(!t)return null;const{x:o,y:r}=t,s=o+(e.dx||0),a=r+(e.dy||0),c=e.color||"var(--semiotic-text, #333)",l=(0,dn.jsx)("text",{x:s,y:a,fill:c,fontSize:e.fontSize||11,opacity:e.opacity,strokeDasharray:e.strokeDasharray,dominantBaseline:"middle",style:{fontFamily:"inherit"},children:e.label});return!0!==e._redundantConnector?Dt.cloneElement(l,{key:"ann-text-"+n}):(0,dn.jsxs)("g",{opacity:e.opacity,strokeDasharray:e.strokeDasharray,children:[(0,dn.jsx)("line",{x1:o,y1:r,x2:s,y2:a,stroke:c,strokeWidth:1,strokeOpacity:.5,style:{pointerEvents:"none"}}),Dt.cloneElement(l,{opacity:void 0,strokeDasharray:void 0})]},"ann-text-"+n)}case"category-highlight":{const t=e.category;if(null==t)return null;const o=e=>"function"==typeof e&&"function"==typeof e.bandwidth,r=i.scales?.o,s=i.scales?.x,a=i.scales?.y,c=o(r)?r:o(s)?s:o(a)?a:null;if(!c)return null;const l=c(t+"");if(null==l)return null;const d=c.bandwidth(),u=e.color||"var(--semiotic-primary, #4589ff)",h=e.opacity??.15,p=e.label;return(0,dn.jsxs)("g",(i.projection?"vertical"===i.projection:c===s)?{children:[(0,dn.jsx)("rect",{x:l,y:0,width:d,height:i.height||0,fill:u,fillOpacity:h}),p&&(0,dn.jsx)(ln,{x:l+d/2,y:on,textAnchor:"middle",fill:u,fontSize:12,fontWeight:"bold",text:p,background:e.labelBackground??"none"})]}:{children:[(0,dn.jsx)("rect",{x:0,y:l,width:i.width||0,height:d,fill:u,fillOpacity:h}),p&&(0,dn.jsx)(ln,{x:12,y:l+d/2,dominantBaseline:"middle",fill:u,fontSize:12,fontWeight:"bold",text:p,background:e.labelBackground??"none"})]},"ann-"+n)}default:return null}var o,r,s}}(0,M),[M]),C=j?function(e,t,n,i){const o=[];return e.forEach((e,r)=>{let s;if(n){const o=n(e,r,i);s=null!=o?o:t(e,r,i)}else s=t(e,r,i);s&&o.push({node:s,annotation:e})}),function(e){const t=e.map((e,t)=>{return{p:e,i:t,emphasis:(n=e.annotation,"primary"===n?.emphasis||"secondary"===n?.emphasis?n.emphasis:null),confidence:$t(e.annotation),readingOrder:null,rank:xt};var n}),n=t.some(e=>null!=e.emphasis||null!=e.confidence),i=e.some(e=>Ct(e.annotation)),o=e.some(e=>null!=Rt(e.annotation)),r=e.some(e=>"layer"===Rt(e.annotation));if(!n&&!i&&!o)return e.map(e=>e.node);const s=t.filter(e=>null==e.emphasis&&null!=e.confidence).slice().sort((e,t)=>(t.confidence??0)-(e.confidence??0)||e.i-t.i);s.forEach((e,t)=>{e.readingOrder=t,e.rank=vt-t/Math.max(1,s.length)});for(const e of t)e.emphasis&&(e.rank=bt[e.emphasis]);const a=t.sort((e,t)=>e.rank-t.rank||e.i-t.i).map(e=>{const{p:t,i:n,emphasis:i,readingOrder:o}=e,r=Ct(t.annotation);let s=t.node;if("primary"===i||"secondary"===i||null!=o){const e=null==i&&null!=o;s=(0,gt.jsx)("g",{className:e?"annotation-emphasis annotation-emphasis--inferred":"annotation-emphasis annotation-emphasis--"+i,..."secondary"===i?{opacity:wt,fontSize:kt}:{},...e?{opacity:Pt(o),"data-annotation-reading-order":o}:{},children:t.node},"annotation-emphasis-"+n)}const a=Rt(t.annotation);return a&&(s=(0,gt.jsx)("g",{className:"annotation-cohesion--"+a,children:s},"annotation-cohesion-"+n)),r&&(s=(0,gt.jsx)("g",{className:"annotation-deferred","data-annotation-disclosure":"deferred",children:s},"annotation-deferred-"+n)),s});return i&&a.unshift((0,gt.jsx)("style",{children:jt},"annotation-disclosure-style")),r&&a.unshift((0,gt.jsx)("style",{children:At},"annotation-cohesion-style")),a}(o)}(j,A,w,S):null,R=!0===j?.some(e=>"widget"===e.type&&!0===e._annotationDeferred);return(0,Wn.jsxs)(Wn.Fragment,{children:[R?(0,Wn.jsx)("style",{children:jt},"physics-annotation-disclosure-style"):null,(0,Wn.jsxs)("svg",{className:"stream-physics-frame__overlay","data-testid":"stream-physics-overlay",role:"presentation",width:i,height:o,style:{position:"absolute",top:0,left:0,pointerEvents:"none",overflow:"visible"},children:[(0,Wn.jsxs)("g",{transform:`translate(${r.left},${r.top})`,children:[C,k]}),s&&"string"==typeof s?(0,Wn.jsx)("text",{x:i/2,y:16,textAnchor:"middle",fontWeight:600,fill:"var(--semiotic-text, #333)",className:"semiotic-chart-title",style:{fontSize:"var(--semiotic-title-font-size, 14px)"},children:s}):s?(0,Wn.jsx)("foreignObject",{x:0,y:0,width:i,height:Math.max(r.top,28),children:s}):null,a?yt({legend:a,totalWidth:i,totalHeight:o,margin:r,legendPosition:h,legendLayout:p,title:s,legendHoverBehavior:c,legendClickBehavior:l,legendHighlightedCategory:d,legendIsolatedCategories:u}):null]})]})}function Hn(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function _n(e,t){const n="sensor"===e.physics?t.sensorThickness:t.barrierThickness;return Math.max(0,Hn(e.thickness)??Hn(n)??Hn(t.thickness)??4)}var Gn=2500;function Xn(e){return"function"==typeof e}function Vn(e){return void 0===e||!1===e||!Xn(e.binAccessor)&&!Xn(e.labelAccessor)&&!Xn(e.valueAccessor)}function Un(e){if(void 0!==e){if(!1===e)return!1;if(!Vn(e))throw new TypeError("Physics worker sediment config only supports string or numeric accessors");return{binAccessor:"string"==typeof e.binAccessor?e.binAccessor:void 0,labelAccessor:"string"==typeof e.labelAccessor?e.labelAccessor:void 0,valueAccessor:"string"==typeof e.valueAccessor||"number"==typeof e.valueAccessor?e.valueAccessor:void 0,retainBodyIds:e.retainBodyIds}}}function Kn(e){if(e)return{chartId:e.chartId,chartType:e.chartType,sensors:e.sensors}}function Qn(e){return function(e){return!Xn(e?.timeAccessor)}(e)}function Zn(e={}){if(e.engine)throw new TypeError("Physics workers use the built-in kernel adapter");const{engine:t,observation:n,sediment:i,...o}=e;return{...o,observation:Kn(n),sediment:Un(i)}}var Jn={};function ei(){if("undefined"!=typeof DOMException)return new DOMException("Physics worker request aborted","AbortError");const e=Error("Physics worker request aborted");return e.name="AbortError",e}var ti=class{constructor(e=function(){const e="string"==typeof Jn.url&&Jn.url?new URL("./physicsWorker.js",Jn.url):function(e){if("undefined"!=typeof __filename){const t=__filename.replace(/\\/g,"/"),n=t.startsWith("/")?t:"/"+t;return new URL("./"+e,"file:"+n)}throw Error("Cannot resolve module worker asset: "+e)}("physicsWorker.js");return new Worker(e,{type:"module",name:"semiotic-physics"})}()){this.nextRequestId=1,this.pending=new Map,this.worker=e,this.worker.onmessage=e=>{const t=e.data,n=this.pending.get(t.requestId);n&&(this.pending.delete(t.requestId),n.cleanup(),t.ok?n.resolve(t.payload):n.reject(function(e){const t=Error(e.error.message);return t.name=e.error.name??"Error",e.error.stack&&(t.stack=e.error.stack),t}(t)))},this.worker.onerror=e=>{this.rejectAll(Error(e.message||"Physics worker failed")),this.worker.terminate()}}request(e,t){if(t?.aborted)return Promise.reject(ei());const n=this.nextRequestId;this.nextRequestId+=1;const i={command:e,requestId:n};return new Promise((e,o)=>{const r=()=>{this.pending.delete(n),t?.removeEventListener("abort",r),o(ei())},s=()=>t?.removeEventListener("abort",r);this.pending.set(n,{cleanup:s,reject:o,resolve:e}),t?.addEventListener("abort",r,{once:!0});try{this.worker.postMessage(i)}catch(e){this.pending.delete(n),s(),o(e)}})}async init(e,t,n,i){if(!Qn(n))throw new TypeError("Physics worker spawn pacing only supports string time accessors");const o=await this.request({type:"init",config:Zn(e),initialSpawns:t,initialSpawnPacing:n},i);if("frame"!==o.type)throw Error("Physics worker returned a non-frame init response");return o.frame}async restore(e,t){const n=await this.request({type:"restore",snapshot:e},t);if("frame"!==n.type)throw Error("Physics worker returned a non-frame restore response");return n.frame}async initFromSnapshot(e,t,n){const i=await this.request({type:"init",config:Zn(e),snapshot:t},n);if("frame"!==i.type)throw Error("Physics worker returned a non-frame init response");return i.frame}async enqueue(e,t,n){if(!Qn(t))throw new TypeError("Physics worker spawn pacing only supports string time accessors");const i=await this.request({type:"enqueue",spawns:e,pacing:t},n);if("frame"!==i.type)throw Error("Physics worker returned a non-frame enqueue response");return i.frame}async tick(e,t){const n=await this.request({type:"tick",deltaSeconds:e},t);if("frame"!==n.type)throw Error("Physics worker returned a non-frame tick response");return n.frame}async settle(e,t){const n=await this.request({type:"settle",maxSteps:e},t);if("frame"!==n.type)throw Error("Physics worker returned a non-frame settle response");return n.frame}async snapshot(e){const t=await this.request({type:"snapshot"},e);if("snapshot"!==t.type)throw Error("Physics worker returned a non-snapshot response");return t.snapshot}async remove(e,t){const n=await this.request({type:"remove",ids:e},t);if("removed"!==n.type)throw Error("Physics worker returned a non-remove response");return{frame:n.frame,removed:n.removed}}terminate(){this.rejectAll(Error("Physics worker terminated")),this.worker.terminate()}rejectAll(e){for(const[t,n]of this.pending)this.pending.delete(t),n.cleanup(),n.reject(e)}};function ni(e){let t=e>>>0;return function(){t=t+1831565813|0;let e=Math.imul(t^t>>>15,1|t);return e=e+Math.imul(e^e>>>7,61|e)^e,((e^e>>>14)>>>0)/4294967296}}var ii={seed:1,gravity:{x:0,y:980},fixedDt:1/120,cellSize:64,collisionIterations:6,velocityDamping:.995,sleepSpeed:8,sleepAfter:.35,restitution:.1,friction:.35,maxVelocity:1600,contactWakeSpeed:200},oi=1e-9,ri=.005;function si(e){return"circle"===e.type?{type:"circle",radius:e.radius}:{type:"aabb",width:e.width,height:e.height}}function ai(e){return"aabb"===e.type?{type:"aabb",x:e.x,y:e.y,width:e.width,height:e.height}:{type:"segment",x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2,thickness:e.thickness}}function ci(e,t,n){return Math.max(t,Math.min(n,e))}function li(e){return 0>e?-1:1}function di(e){if("circle"===e.shape.type){const t=e.shape.radius;return{minX:e.x-t,minY:e.y-t,maxX:e.x+t,maxY:e.y+t}}const t=e.shape.width/2,n=e.shape.height/2;return{minX:e.x-t,minY:e.y-n,maxX:e.x+t,maxY:e.y+n}}function ui(e){const t=e.shape;if("aabb"===t.type){const e=t.width/2,n=t.height/2;return{minX:t.x-e,minY:t.y-n,maxX:t.x+e,maxY:t.y+n}}const n=(t.thickness??0)/2;return{minX:Math.min(t.x1,t.x2)-n,minY:Math.min(t.y1,t.y2)-n,maxX:Math.max(t.x1,t.x2)+n,maxY:Math.max(t.y1,t.y2)+n}}function hi(e,t){return!(e.minX>t.maxX||t.minX>e.maxX||e.minY>t.maxY||t.minY>e.maxY)}function pi(e,t,n,i,o,r,s,a){const c=o-e,l=(n+s)/2-Math.abs(c);if(0>=l)return null;const d=r-t,u=(i+a)/2-Math.abs(d);return u>0?u>l?{nx:li(c),ny:0,penetration:l}:{nx:0,ny:li(d),penetration:u}:null}function mi(e,t,n,i,o,r,s){const a=r/2,c=s/2;let l=e-ci(e,i-a,i+a),d=t-ci(t,o-c,o+c);const u=l*l+d*d;if(u>n*n)return null;if(oi>=u){const r=Math.abs(e-(i-a)),s=Math.abs(e-(i+a)),u=Math.abs(t-(o-c)),h=Math.abs(t-(o+c)),p=Math.min(r,s,u,h);return p===r?(l=-1,d=0,{nx:l,ny:d,penetration:n+r}):p===s?(l=1,d=0,{nx:l,ny:d,penetration:n+s}):p===u?(l=0,d=-1,{nx:l,ny:d,penetration:n+u}):(l=0,d=1,{nx:l,ny:d,penetration:n+h})}const h=Math.sqrt(u);return{nx:l/h,ny:d/h,penetration:n-h}}function fi(e,t){if("circle"===e.shape.type&&"circle"===t.shape.type)return function(e,t,n,i,o,r){const s=i-e,a=o-t,c=n+r,l=s*s+a*a;if(l>=c*c)return null;if(oi>=l)return{nx:1,ny:0,penetration:c};const d=Math.sqrt(l);return{nx:s/d,ny:a/d,penetration:c-d}}(e.x,e.y,e.shape.radius,t.x,t.y,t.shape.radius);if("aabb"===e.shape.type&&"aabb"===t.shape.type)return pi(e.x,e.y,e.shape.width,e.shape.height,t.x,t.y,t.shape.width,t.shape.height);if("circle"===e.shape.type&&"aabb"===t.shape.type){const n=mi(e.x,e.y,e.shape.radius,t.x,t.y,t.shape.width,t.shape.height);return n?{nx:-n.nx,ny:-n.ny,penetration:n.penetration}:null}return"aabb"===e.shape.type&&"circle"===t.shape.type?mi(t.x,t.y,t.shape.radius,e.x,e.y,e.shape.width,e.shape.height):null}function yi(e,t){const n=t.shape;return"aabb"===n.type?"circle"===e.shape.type?mi(e.x,e.y,e.shape.radius,n.x,n.y,n.width,n.height):pi(n.x,n.y,n.width,n.height,e.x,e.y,e.shape.width,e.shape.height):function(e,t,n,i,o,r,s,a=0){const c=r-i,l=s-o,d=c*c+l*l,u=d>oi?ci(((e-i)*c+(t-o)*l)/d,0,1):0,h=n+a/2,p=e-(i+c*u),m=t-(o+l*u),f=p*p+m*m;if(f>=h*h)return null;if(oi>=f){const e=Math.sqrt(d);return e>oi?{nx:-l/e,ny:c/e,penetration:h}:{nx:1,ny:0,penetration:h}}const y=Math.sqrt(f);return{nx:p/y,ny:m/y,penetration:h-y}}(e.x,e.y,"circle"===e.shape.type?e.shape.radius:Math.sqrt(e.shape.width*e.shape.width+e.shape.height*e.shape.height)/2,n.x1,n.y1,n.x2,n.y2,n.thickness??0)}function gi(e,t){return`${e}\0${t}`}function bi(e){const t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}function xi(e){return{id:e.id,x:e.x,y:e.y,prevX:e.prevX,prevY:e.prevY,vx:e.vx,vy:e.vy,angle:e.angle,mass:e.mass,bodyCollisions:e.bodyCollisions,shape:si(e.shape),sleeping:e.sleeping,datum:e.datum,index:e.index,sleepTime:e.sleepTime,restitution:e.restitution,friction:e.friction}}function vi(e){return e&&"function"!=typeof e?{property:e.property,equals:e.equals,notEquals:e.notEquals,oneOf:e.oneOf?.slice(),notOneOf:e.notOneOf?.slice()}:e}function wi(e){return{id:e.id,shape:ai(e.shape),sensor:e.sensor,restitution:e.restitution,friction:e.friction,bodyFilter:vi(e.bodyFilter),index:e.index}}function ki(e,t){return!!t?.some(t=>Object.is(e,t))}function Mi(e,t){const n=e.bodyFilter;if(!n)return!0;if("function"==typeof n)return n(t);const i=function(e,t){if(!t)return;let n=e;for(const e of t.split(".")){if(null==n||"object"!=typeof n)return;n=n[e]}return n}(t,n.property);return!("equals"in n&&!Object.is(i,n.equals)||"notEquals"in n&&Object.is(i,n.notEquals)||n.oneOf&&!ki(i,n.oneOf)||n.notOneOf&&ki(i,n.notOneOf))}var Ii=class{constructor(e={}){this.capabilities={determinism:"strict",sensors:!0,joints:!1,ccd:!1,maxBodiesHint:5e3,worker:!1},this.bodies=new Map,this.colliders=new Map,this.springs=new Map,this.activeSensors=new Set,this.supportedThisStep=new Set,this.lastEvents=[],this.nextBodyIndex=0,this.nextColliderIndex=0,this.nextSpringIndex=0,this.options={...ii,...e},this.random=ni(this.options.seed)}init(e={}){this.options={...ii,...e},this.random=ni(this.options.seed),this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors.clear(),this.lastEvents=[],this.nextBodyIndex=0,this.nextColliderIndex=0,this.nextSpringIndex=0}spawn(e){const t={id:e.id,x:e.x,y:e.y,prevX:e.x,prevY:e.y,vx:e.vx??0,vy:e.vy??0,angle:e.angle??0,mass:Math.max(oi,e.mass??1),bodyCollisions:e.bodyCollisions??!0,shape:si(e.shape),sleeping:!1,datum:e.datum,restitution:e.restitution,friction:e.friction,index:this.nextBodyIndex,sleepTime:0};this.nextBodyIndex+=1,this.bodies.set(e.id,t)}remove(e){for(const t of e){this.bodies.delete(t);for(const e of Array.from(this.activeSensors))bi(e).bodyId===t&&this.activeSensors.delete(e)}}setColliders(e){this.colliders.clear(),this.activeSensors.clear(),this.nextColliderIndex=0;for(const t of e)this.colliders.set(t.id,{...t,shape:ai(t.shape),bodyFilter:vi(t.bodyFilter),index:this.nextColliderIndex}),this.nextColliderIndex+=1}setConstraint(e){const t=e.id??"spring-"+this.nextSpringIndex;return this.springs.set(t,{id:t,bodyId:e.bodyId,target:e.target,restLength:e.restLength??0,stiffness:e.stiffness??40,damping:e.damping??3}),this.nextSpringIndex+=1,t}removeConstraint(e){this.springs.delete(e)}applyImpulse(e,t,n){const i=this.bodies.get(e);i&&(i.vx+=t/i.mass,i.vy+=n/i.mass,this.wake(i))}step(e=this.options.fixedDt){const t=Math.max(0,e);if(this.lastEvents=[],0===t)return;const n=this.sortedBodies();for(const e of n)e.prevX=e.x,e.prevY=e.y;this.applySprings(t);const i=this.options.maxVelocity;for(const e of n)if(!e.sleeping){if(e.vx+=this.options.gravity.x*t,e.vy+=this.options.gravity.y*t,e.vx*=this.options.velocityDamping,e.vy*=this.options.velocityDamping,i>0){const t=Math.sqrt(e.vx*e.vx+e.vy*e.vy);if(t>i){const n=i/t;e.vx*=n,e.vy*=n}}e.x+=e.vx*t,e.y+=e.vy*t}this.supportedThisStep.clear();const o=this.bodyPairKeys(n),r=this.sortedColliders().filter(e=>!e.sensor);for(let e=0;this.options.collisionIterations>e;e+=1)this.resolveBodyPairs(n,o,0===e),this.resolveColliders(n,r,0===e);this.updateSensors(n),this.updateSleeping(n,t)}settle(e=1200,t=this.options.fixedDt){let n=0;for(;e>n&&!this.allSleeping();)this.step(t),n+=1;return n}readState(e=[]){e.length=0;for(const t of this.sortedBodies())e.push({id:t.id,x:t.x,y:t.y,prevX:t.prevX,prevY:t.prevY,vx:t.vx,vy:t.vy,angle:t.angle,mass:t.mass,shape:si(t.shape),sleeping:t.sleeping,datum:t.datum});return e}events(){return this.lastEvents.slice()}activeSensorPairs(){return Array.from(this.activeSensors).sort().map(bi)}allSleeping(){for(const e of this.bodies.values())if(!e.sleeping)return!1;return!0}snapshot(){return{options:{...this.options,gravity:{...this.options.gravity}},bodies:this.sortedBodies().map(xi),colliders:this.sortedColliders().map(wi),springs:Array.from(this.springs.values()).map(e=>({...e,target:{...e.target}})),activeSensors:Array.from(this.activeSensors).sort()}}restore(e){this.options={...e.options,gravity:{...e.options.gravity}},this.random=ni(this.options.seed),this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors=new Set(e.activeSensors),this.lastEvents=[],this.nextBodyIndex=0;for(const t of e.bodies){const e=xi(t);this.bodies.set(e.id,e),this.nextBodyIndex=Math.max(this.nextBodyIndex,e.index+1)}this.nextColliderIndex=0;for(const t of e.colliders){const e=wi(t);this.colliders.set(e.id,e),this.nextColliderIndex=Math.max(this.nextColliderIndex,e.index+1)}this.nextSpringIndex=0;for(const t of e.springs){this.springs.set(t.id,{...t,target:{...t.target}});const e=/^spring-(\d+)$/.exec(t.id);e&&(this.nextSpringIndex=Math.max(this.nextSpringIndex,Number(e[1])+1))}}dispose(){this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors.clear(),this.lastEvents=[]}sortedBodies(){return Array.from(this.bodies.values()).sort((e,t)=>e.index-t.index)}sortedColliders(){return Array.from(this.colliders.values()).sort((e,t)=>e.index-t.index)}applySprings(e){for(const t of Array.from(this.springs.values()).sort((e,t)=>e.id.localeCompare(t.id))){const n=this.bodies.get(t.bodyId);if(!n||n.sleeping)continue;const i="point"===t.target.type?t.target:this.bodies.get(t.target.bodyId);if(!i)continue;const o=i.x-n.x,r=i.y-n.y,s=Math.sqrt(o*o+r*r);if(oi>=s)continue;const a=o/s,c=r/s,l=(s-t.restLength)*t.stiffness+((("vx"in i?i.vx:0)-n.vx)*a+(("vy"in i?i.vy:0)-n.vy)*c)*t.damping;n.vx+=l*a*e/n.mass,n.vy+=l*c*e/n.mass}}resolveBodyPairs(e,t,n){for(const i of t){const[t,o]=i.split(":").map(Number),r=e[t],s=e[o];if(!r||!s)continue;const a=fi(r,s);a&&(this.resolveDynamicCollision(r,s,a),n&&this.lastEvents.push({type:"contact",bodyId:r.id,otherId:s.id,sensor:!1}))}}bodyPairKeys(e){const t=Math.max(1,this.options.cellSize),n=new Map;for(let i=0;e.length>i;i+=1){if(!1===e[i].bodyCollisions)continue;const o=di(e[i]),r=Math.floor(o.minX/t),s=Math.floor(o.maxX/t),a=Math.floor(o.minY/t),c=Math.floor(o.maxY/t);for(let e=r;s>=e;e+=1)for(let t=a;c>=t;t+=1){const o=`${e}:${t}`,r=n.get(o);r?r.push(i):n.set(o,[i])}}const i=new Set;for(const t of Array.from(n.keys()).sort()){const o=n.get(t)??[];o.sort((e,t)=>e-t);for(let t=0;o.length>t;t+=1)for(let n=t+1;o.length>n;n+=1){const r=o[t],s=o[n];!1!==e[r].bodyCollisions&&!1!==e[s].bodyCollisions&&hi(di(e[r]),di(e[s]))&&i.add(`${r}:${s}`)}}return Array.from(i).sort((e,t)=>{const[n,i]=e.split(":").map(Number),[o,r]=t.split(":").map(Number);return n===o?i-r:n-o})}resolveDynamicCollision(e,t,n){e.sleeping&&this.supportedThisStep.add(t.id),t.sleeping&&this.supportedThisStep.add(e.id);const i=e.sleeping?0:1/e.mass,o=t.sleeping?0:1/t.mass,r=i+o;if(oi>=r)return;const s=Math.max(0,n.penetration-ri)/r;e.x-=n.nx*s*i,e.y-=n.ny*s*i,t.x+=n.nx*s*o,t.y+=n.ny*s*o;const a=(t.vx-e.vx)*n.nx+(t.vy-e.vy)*n.ny;if(a>0)return;const c=Math.abs(a),l=-(1+Math.min(e.restitution??this.options.restitution,t.restitution??this.options.restitution))*a/r,d=l*n.nx,u=l*n.ny;e.vx-=d*i,e.vy-=u*i,t.vx+=d*o,t.vy+=u*o,this.applyFriction(e,t,n,l,i,o),c>this.options.contactWakeSpeed&&(this.wake(e),this.wake(t))}applyFriction(e,t,n,i,o,r){const s=-n.ny,a=n.nx,c=(t.vx-e.vx)*s+(t.vy-e.vy)*a,l=o+r;if(oi>=Math.abs(c)||oi>=l)return;const d=Math.max(0,Math.min(1,Math.max(e.friction??this.options.friction,t.friction??this.options.friction))),u=ci(-c/l,-i*d,i*d),h=u*s,p=u*a;e.vx-=h*o,e.vy-=p*o,t.vx+=h*r,t.vy+=p*r}resolveColliders(e,t,n){for(const i of e)for(const e of t){if(!Mi(e,i))continue;if(!hi(di(i),ui(e)))continue;const t=yi(i,e);t&&(this.resolveStaticCollision(i,e,t),this.supportedThisStep.add(i.id),n&&this.lastEvents.push({type:"contact",bodyId:i.id,otherId:e.id,sensor:!1}))}}resolveStaticCollision(e,t,n){e.x+=n.nx*Math.max(0,n.penetration-ri),e.y+=n.ny*Math.max(0,n.penetration-ri);const i=e.vx*n.nx+e.vy*n.ny;if(0>i){const o=Math.min(e.restitution??this.options.restitution,t.restitution??this.options.restitution);e.vx-=(1+o)*i*n.nx,e.vy-=(1+o)*i*n.ny;const r=-n.ny,s=n.nx,a=e.vx*r+e.vy*s,c=Math.max(0,Math.min(1,Math.max(e.friction??this.options.friction,t.friction??this.options.friction)));e.vx-=a*r*c,e.vy-=a*s*c}}updateSensors(e){const t=new Set,n=this.sortedColliders().filter(e=>e.sensor);for(const i of e){const e=di(i);for(const o of n){if(!Mi(o,i))continue;if(!hi(e,ui(o)))continue;if(!yi(i,o))continue;const n=gi(o.id,i.id);t.add(n),this.activeSensors.has(n)||this.lastEvents.push({type:"sensor-enter",bodyId:i.id,sensorId:o.id})}}for(const e of Array.from(this.activeSensors).sort()){if(t.has(e))continue;const{sensorId:n,bodyId:i}=bi(e);this.lastEvents.push({type:"sensor-exit",bodyId:i,sensorId:n})}this.activeSensors=t}updateSleeping(e,t){const n=Math.hypot(this.options.gravity.x,this.options.gravity.y)>1;for(const i of e)Math.sqrt(i.vx*i.vx+i.vy*i.vy)>=this.options.sleepSpeed||Math.sqrt((i.x-i.prevX)*(i.x-i.prevX)+(i.y-i.prevY)*(i.y-i.prevY))>=this.options.sleepSpeed*t||n&&!this.supportedThisStep.has(i.id)?i.sleeping?this.wake(i):i.sleepTime=0:(i.sleepTime+=t,i.sleeping||this.options.sleepAfter>i.sleepTime||(i.sleeping=!0,i.vx=0,i.vy=0,this.lastEvents.push({type:"sleep",bodyId:i.id})))}wake(e){e.sleeping&&this.lastEvents.push({type:"wake",bodyId:e.id}),e.sleeping=!1,e.sleepTime=0}nextRandom(){return this.random()}},Si=class{constructor(e={}){this.id="builtin",this.capabilities={...(new Ii).capabilities,engine:"builtin"},this.world=new Ii(e)}init(e={}){this.world.init(e)}spawn(e){this.world.spawn(e)}remove(e){this.world.remove(e)}setColliders(e){this.world.setColliders(e)}setConstraint(e){return this.world.setConstraint(e)}removeConstraint(e){this.world.removeConstraint(e)}applyImpulse(e,t,n){this.world.applyImpulse(e,t,n)}step(e){this.world.step(e)}settle(e,t){return this.world.settle(e,t)}readState(e){return this.world.readState(e)}events(){return this.world.events()}activeSensorPairs(){return this.world.activeSensorPairs()}allSleeping(){return this.world.allSleeping()}snapshot(){return this.world.snapshot()}restore(e){this.world.restore(e)}nextRandom(){return this.world.nextRandom()}dispose(){this.world.dispose()}};function ji(e={}){return new Si(e)}function Ai(e,t={}){return e?"function"==typeof e?e(t):(e.init(t),e):ji(t)}var Ci=["binId","targetBin","category","windowIndex","lane","group"];function Ri(e,t){if(!Number.isFinite(t))return;e.count+=1,e.total+=t,e.min=Math.min(e.min,t),e.max=Math.max(e.max,t);const n=t-e.mean;e.mean+=n/e.count,e.m2+=n*(t-e.mean)}function $i(e){return{count:e.count,total:e.total,mean:e.count>0?e.mean:0,min:e.count>0?e.min:0,max:e.count>0?e.max:0,variance:e.count>1?e.m2/(e.count-1):0}}function Pi(e){return{count:e.count,total:e.total,mean:e.mean,m2:e.variance*Math.max(0,e.count-1),min:e.count>0?e.min:1/0,max:e.count>0?e.max:-1/0}}function Di(e,t){if(null!=e[t])return e[t];const n=e.datum;return n&&"object"==typeof n?n[t]:void 0}function Bi(e,t,n){return"function"==typeof e?e(t,n):"string"==typeof e?Di(t,e):void 0}function Ti(e){if(null==e)return;const t=e+"";return t.trim()?t:void 0}function Ei(e){const t=$i(e.value);return{id:e.id,label:e.label,count:t.count,total:t.total,bodyIds:e.bodyIds.slice(),lastBodyId:e.lastBodyId,lastDatum:e.lastDatum,x:$i(e.x),y:$i(e.y),value:t}}var Ni=class{constructor(e=!1){this.bins=new Map,this.nextIndex=0,this.config=e}updateConfig(e){void 0!==e&&(this.config=e,!1===e&&this.clear())}isEnabled(){return!1!==this.config}add(e){if(!1===this.config)return null;const t=this.nextIndex;this.nextIndex+=1;const n=Ti(Bi(this.config.binAccessor,e,t))??function(e){for(const t of Ci){const n=Ti(Di(e,t));if(n)return n}return"sediment"}(e),i=Ti(Bi(this.config.labelAccessor,e,t))??n,o=function(e,t,n){if("number"==typeof e)return e;const i="function"==typeof e?e(t,n):"string"==typeof e?Di(t,e):1,o="number"==typeof i?i:Number(i);return Number.isFinite(o)?o:1}(this.config.valueAccessor,e,t),r=Math.max(0,Math.floor(this.config.retainBodyIds??12));let s=this.bins.get(n);return s||(s={id:n,label:i,bodyIds:[],x:{count:0,total:0,mean:0,m2:0,min:1/0,max:-1/0},y:{count:0,total:0,mean:0,m2:0,min:1/0,max:-1/0},value:{count:0,total:0,mean:0,m2:0,min:1/0,max:-1/0}},this.bins.set(n,s)),s.label=i,s.lastBodyId=e.id,s.lastDatum=e.datum,Ri(s.x,e.x),Ri(s.y,e.y),Ri(s.value,o),r>0&&(s.bodyIds.push(e.id),s.bodyIds.length>r&&(s.bodyIds=s.bodyIds.slice(s.bodyIds.length-r))),Ei(s)}clear(){this.bins.clear(),this.nextIndex=0}snapshot(){return Array.from(this.bins.values()).map(Ei)}restore(e=[]){this.bins.clear();for(const t of e)this.bins.set(t.id,{id:t.id,label:t.label,bodyIds:t.bodyIds.slice(),lastBodyId:t.lastBodyId,lastDatum:t.lastDatum,x:Pi(t.x),y:Pi(t.y),value:Pi(t.value)});this.nextIndex=e.reduce((e,t)=>e+t.count,0)}totals(){const e=this.snapshot();return{bins:e.length,count:e.reduce((e,t)=>e+t.count,0),total:e.reduce((e,t)=>e+t.total,0)}}};function Oi(e,t={}){const{baselineY:n=0,binWidth:i=24,gap:o=2,maxHeight:r=80,value:s="count",x:a}=t,c=Math.max(1,...e.map(e=>e[s]));return e.map((e,t)=>{const l=Math.max(0,e[s]/c*r),d=a?.(e,t)??t*(i+o);return{binId:e.id,label:e.label,index:t,count:e.count,total:e.total,x:d,y:n-l,width:i,height:l,meanX:e.x.mean,meanY:e.y.mean}})}function Wi(e){const t=Number(e);if(Number.isFinite(t)&&t>0)return Math.floor(t)}function qi(e){const t=Math.max(0,Math.floor(e.liveBodies)),n=Math.max(0,Math.floor(e.queuedBodies??0)),i=t+n,o=Wi(e.bodyLimit),r=Wi(e.engineMaxBodiesHint),s=function(e,t,n){if(!1===n)return;const i=Wi(n?.warnAt);return null!=i?i:null!=e?Math.max(1,Math.floor(.8*e)):null!=t?Math.max(1,Math.floor(.8*t)):void 0}(o,r,e.options),a=null==o?0:Math.max(0,t-o),c=a>0?"overflow":null==s||s>i?"ok":"warning";return{action:"overflow"!==c?"continue":e.sedimentEnabled?"sediment":e.evictionEnabled?"evict":"retain",bodyLimit:o,engineMaxBodiesHint:r,liveBodies:t,overflow:a,projectedBodies:i,queuedBodies:n,state:c,warnAt:s}}var Fi={bodyLimit:1/0,eviction:"oldest",fixedDt:1/120,maxDeltaSeconds:.1,maxSubsteps:8,settleStepLimit:1200,timeScale:1},zi={chartId:"physics",chartType:"physics",sensors:{},onObservation:void 0,onSimulationStateChange:void 0};function Li(e={},t=zi){return{chartId:e.chartId??t.chartId,chartType:e.chartType??t.chartType,sensors:e.sensors??t.sensors,onObservation:e.onObservation??t.onObservation,onSimulationStateChange:e.onSimulationStateChange??t.onSimulationStateChange}}function Yi(e){return{...e,shape:{...e.shape},datum:e.datum,springs:e.springs?.map(e=>({...e,target:{...e.target}}))}}function Hi(e){if(e instanceof Date){const t=e.getTime();return Number.isFinite(t)?t:void 0}const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:void 0}function _i(e,t){if(null!=e[t])return e[t];const n=e.datum;return n&&"object"==typeof n?n[t]:void 0}function Gi(e){return{...Yi(e),sequence:e.sequence,spawnAt:e.spawnAt}}function Xi(e){return e.map(e=>({...e,shape:{...e.shape},bodyFilter:e.bodyFilter&&"function"!=typeof e.bodyFilter?{...e.bodyFilter,oneOf:e.bodyFilter.oneOf?.slice(),notOneOf:e.bodyFilter.notOneOf?.slice()}:e.bodyFilter}))}function Vi(e){return!1!==e&&{...e}}function Ui(e,t){return e.spawnAt===t.spawnAt?e.sequence-t.sequence:e.spawnAt-t.spawnAt}function Ki(e){return{...e,gravity:{...e.gravity}}}function Qi(e,t,n,i){if("circle"===e.shape.type){const o=e.x-t,r=e.y-n,s=e.shape.radius+i,a=o*o+r*r;return a>s*s?null:a}const o=Math.max(Math.abs(t-e.x)-e.shape.width/2,0),r=Math.max(Math.abs(n-e.y)-e.shape.height/2,0),s=o*o+r*r;return s>i*i?null:s}function Zi(e){const t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}function Ji(e,t={}){const{idPrefix:n="plot",includeFloor:i=!0,includeCeiling:o=!1,includeLeftWall:r=!0,includeRightWall:s=!0,wallThickness:a=20,floorThickness:c=a}=t,l=[],d=e.x+e.width/2,u=e.y+e.height/2;return i&&l.push({id:n+"-floor",shape:{type:"aabb",x:d,y:e.y+e.height+c/2,width:e.width+2*a,height:c}}),o&&l.push({id:n+"-ceiling",shape:{type:"aabb",x:d,y:e.y-c/2,width:e.width+2*a,height:c}}),r&&l.push({id:n+"-left-wall",shape:{type:"aabb",x:e.x-a/2,y:u,width:a,height:e.height+2*c}}),s&&l.push({id:n+"-right-wall",shape:{type:"aabb",x:e.x+e.width+a/2,y:u,width:a,height:e.height+2*c}}),l}function eo(e){const{idPrefix:t="bin",count:n,domainStart:i,domainStep:o,xScale:r,yTop:s,yBottom:a,wallThickness:c=4,includeBoundaryWalls:l=!0,includeInteriorWalls:d=!0,closedBefore:u,lidY:h=s,lidThickness:p=Math.max(2,c)}=e,m=[],f=s+(a-s)/2,y=Math.abs(a-s),g=l?n:n-1;if(d||l)for(let e=l?0:1;g>=e;e+=1){if(!d&&e>0&&n>e)continue;const s=r(i+e*o);m.push({id:`${t}-wall-${e}`,shape:{type:"aabb",x:s,y:f,width:c,height:y}})}if(null!=u)for(let e=0;n>e;e+=1){const n=i+e*o,s=n+o;if(s>=u)continue;const a=r(n),l=r(s);m.push({id:`${t}-lid-${e}`,shape:{type:"segment",x1:Math.min(a,l)+c/2,y1:h,x2:Math.max(a,l)-c/2,y2:h,thickness:p}})}return m}var to={data:"data",domain:"domain",layout:"layout","scene-geometry":"sceneGeometry","scene-style":"sceneStyle","data-paint":"dataPaint","interaction-paint":"interactionPaint",overlay:"overlay",accessibility:"accessibility",evidence:"evidence"};function no(e,t){const n={...e};for(const e of t)n[to[e]]++;return n}function io(e,t,n){const i=new Set(t);return{changeSet:{...e,...e.keys?{keys:[...e.keys]}:{}},changed:i,revisions:no(n,i)}}var oo=class{constructor(){this.revisions={data:0,domain:0,layout:0,sceneGeometry:0,sceneStyle:0,dataPaint:0,interactionPaint:0,overlay:0,accessibility:0,evidence:0},this.latest=io({kind:"initialize"},[],this.revisions),this.listeners=new Set}get last(){return this.latest}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}record(e,t){const n=io(e,t,this.revisions);this.revisions=n.revisions,this.latest=n;for(const e of[...this.listeners])e();return n}},ro=require("d3-quadtree"),so=class{constructor(){this.maxSearchRadius=0,this.revision=-1,this.tree=null}hitTest(e,t,n,i,o,r=0){const s=this.ensure(e,t);if(!s)return null;let a=null,c=1/0;const l=Math.max(0,r)+this.maxSearchRadius,d=i-l,u=i+l,h=o-l,p=o+l;return s.visit((e,t,s,l,m)=>{if(d>l||t>u||h>m||s>p)return!0;if(e.length)return!1;let f=e;for(;f;){const e=f.data;if(e){const t=Qi(e,i,o,Math.max(0,r));null!=t&&(c>t||t===c&&n.indexOf(e.id)>n.indexOf(a?.id??""))&&(a=e,c=t)}f=f.next}return!1}),a}ensure(e,t){if(this.tree&&this.revision===t)return this.tree;const n=e.readState();return 0===n.length?(this.tree=null,this.maxSearchRadius=0,this.revision=t,null):(this.maxSearchRadius=n.reduce((e,t)=>Math.max(e,function(e){return"circle"===e.shape.type?e.shape.radius:Math.hypot(e.shape.width,e.shape.height)/2}(t)),0),this.tree=(0,ro.quadtree)().x(e=>e.x).y(e=>e.y).addAll(n),this.revision=t,this.tree)}},ao=["data","scene-geometry","data-paint","accessibility","evidence"],co=["scene-geometry","data-paint","accessibility","evidence"],lo=["overlay","accessibility","evidence"],uo=(e,t)=>({retainedData:e,invalidations:t}),ho=["layout","scene-geometry","data-paint","overlay","accessibility","evidence"],po=["scene-geometry","data-paint","accessibility","evidence"],mo=[],fo={engine:uo("rebuild",["scene-geometry","data-paint","accessibility","evidence"]),kernel:uo("preserve",po),colliders:uo("preserve",po),sediment:uo("preserve",po),bodyBudget:uo("preserve",ho),bodyLimit:uo("preserve",ho),eviction:uo("preserve",ho),fixedDt:uo("preserve",mo),maxDeltaSeconds:uo("preserve",mo),maxSubsteps:uo("preserve",mo),settleStepLimit:uo("preserve",mo),timeScale:uo("preserve",mo),observation:uo("preserve",mo)},yo=uo("preserve",ho);function go(e){let t="preserve";const n=new Set;for(const i of e){const e=fo[i]??yo;"rebuild"===e.retainedData&&(t="rebuild");for(const t of e.invalidations)n.add(t)}return{retainedData:t,invalidations:n}}var bo=["seed","fixedDt","cellSize","collisionIterations","velocityDamping","sleepSpeed","sleepAfter","restitution","friction","maxVelocity","contactWakeSpeed"];function xo(e,t){return e===t||!(!e||!t)&&e.gravity?.x===t.gravity?.x&&e.gravity?.y===t.gravity?.y&&bo.every(n=>e[n]===t[n])}function vo(e,t,n,i){return e||!t?"paused":n||!i?"running":"settled"}var wo=class{constructor(){this.seconds=0,this.speed=8,this.scratch=[]}setKernelOptions(e){this.speed=function(e){const t=e?.sleepSpeed;return"number"==typeof t&&Number.isFinite(t)&&t>0?t:8}(e)}reset(){this.seconds=0}isAtRest(){return this.seconds>=.6}refresh(e,t,n){if(n>0)return void(this.seconds=0);const i=e.readState(this.scratch),o=this.speed*this.speed;let r=!0;for(const e of i)if(!e.sleeping&&e.vx*e.vx+e.vy*e.vy>=o){r=!1;break}this.seconds=r?this.seconds+Math.max(0,t):0}},ko=class{constructor(e={}){this.activeSensorPairs=new Set,this.accumulator=0,this.bodyBudgetObservationKey="ok",this.bodySpatialIndex=new so,this.elapsedSeconds=0,this.liveBodyOrder=[],this.nextSequence=0,this.paused=!1,this.queue=[],this.revision=0,this.updateResults=new oo,this.simulationState="settled",this.visible=!0,this.quiescence=new wo;const{bodyBudget:t,colliders:n,engine:i,kernel:o,observation:r,sediment:s,...a}=e;this.config={...Fi,...a},this.configInput={...e},this.bodyBudget=t??{},this.engineInput=i,this.observation=Li(r),this.sediment=new Ni(s??!1),this.world=Ai(i,{fixedDt:this.config.fixedDt,...o}),this.quiescence.setKernelOptions(o),n&&this.world.setColliders(Xi(n))}updateConfig(e){const t=function(e,t){return Object.keys(e).filter(n=>"kernel"===n?!xo(e.kernel,t.kernel):e[n]!==t[n])}(e,this.configInput),{colliders:n,bodyBudget:i,engine:o,kernel:r,observation:s,sediment:a,...c}=e;if(this.config={...this.config,...c},void 0!==i&&(this.bodyBudget=i,!1===i&&(this.bodyBudgetObservationKey="ok")),o&&o!==this.engineInput){const e=this.world.snapshot();this.world.dispose(),this.engineInput=o,this.world=Ai(o,e.options),this.world.restore(e),this.revision+=1}if(r&&!xo(r,this.configInput.kernel)){const e=this.world.snapshot(),t={...e.options,...r,gravity:{...e.options.gravity,...r.gravity}};this.world.restore({...e,options:t}),this.quiescence.setKernelOptions(t),this.revision+=1}s&&(this.observation=Li(s,this.observation)),this.sediment.updateConfig(a),n&&(this.world.setColliders(Xi(n)),this.revision+=1),this.configInput={...this.configInput,...e};const l=go(t);this.updateResults.record({kind:"config",keys:t},l.invalidations)}updateConfigWithResult(e){return this.updateConfig(e),this.updateResults.last}setColliders(e){this.world.setColliders(Xi(e)),this.revision+=1,this.updateResults.record({kind:"config",keys:["colliders"]},go(["colliders"]).invalidations)}enqueue(e,t){const n=Array.isArray(e)?e:[e],i=t?function(e,t={}){const n=Hi(t.startAt)??0,i=t.pacing??"immediate";if("arrival"===i){const i=e.map((e,n)=>function(e,t,n){return"function"==typeof n?Hi(n(e,t)):"string"==typeof n?Hi(_i(e,n)):Hi(e.spawnAt)??Hi(_i(e,"arrivalTime"))??Hi(_i(e,"timestamp"))??Hi(_i(e,"time"))??Hi(_i(e,"eventTime"))}(e,n,t.timeAccessor)),o=i.filter(e=>null!=e),r=o.length>0?Math.min(...o):0,s=Hi(t.timeScale)??1,a=s>0?s:1;return e.map((e,t)=>{const o=i[t],s=null==o?0:Math.max(0,o-r);return{...Yi(e),spawnAt:n+s/a}})}if("object"==typeof i){const t=Hi(i.ratePerSec);if(t&&t>0)return e.map((e,i)=>({...Yi(e),spawnAt:n+i/t}))}return e.map(e=>({...Yi(e),spawnAt:n}))}(n,{...t,startAt:t.startAt??this.elapsedSeconds}):n;for(const e of i)this.queue.push({...Yi(e),sequence:this.nextSequence,spawnAt:e.spawnAt??this.elapsedSeconds}),this.nextSequence+=1;this.queue.sort(Ui),i.length>0&&(this.revision+=1),this.updateResults.record({kind:"enqueue",count:i.length},i.length?ao:[])}enqueueWithResult(e,t){return this.enqueue(e,t),this.updateResults.last}spawnNow(e){this.spawnOne(Yi(e)),this.nextSequence+=1,this.observeBodyBudget(),this.evictOverflow(),this.revision+=1,this.updateResults.record({kind:"enqueue",count:1},ao)}materializeDueSpawns(){const e=this.revision,t=[],n=[];return this.spawnDue(t,n),0===t.length||(this.observeBodyBudget(n),this.evictOverflow(n),this.syncSimulationState(n),this.revision+=1,this.updateResults.record({kind:"enqueue",count:t.length},this.revision!==e?ao:[])),t}clear(){const e=this.world.snapshot().options;this.world.init({...e,fixedDt:this.config.fixedDt}),this.activeSensorPairs.clear(),this.liveBodyOrder=[],this.queue=[],this.accumulator=0,this.elapsedSeconds=0,this.nextSequence=0,this.quiescence.reset(),this.sediment.clear(),this.bodyBudgetObservationKey="ok",this.revision+=1,this.syncSimulationState(),this.updateResults.record({kind:"clear"},ao)}tick(e){const t=this.revision,n=[],i=[],o=[],r=[],s=[];if(this.paused||!this.visible){const e=this.result(0,n,i,o,r,s,!1);return this.updateResults.record({kind:"tick",count:0},[]),e}const a=Math.max(0,Math.min(e,this.config.maxDeltaSeconds))*this.config.timeScale;this.elapsedSeconds+=a,this.spawnDue(n,s);const c=this.observeBodyBudget(s),l=this.evictOverflow(s);i.push(...l.evicted),o.push(...l.sedimented),this.syncSimulationState(s),this.accumulator+=a;let d=0;for(;this.accumulator>=this.config.fixedDt&&this.config.maxSubsteps>d;){this.world.step(this.config.fixedDt);const e=this.world.events();r.push(...e),this.observeKernelEvents(e,s),this.observeSensorTransitions(s),this.accumulator-=this.config.fixedDt,d+=1}d===this.config.maxSubsteps&&(this.accumulator=Math.min(this.accumulator,this.config.fixedDt)),this.quiescence.refresh(this.world,a,n.length),(d>0||n.length>0||i.length>0||o.length>0||r.length>0)&&(this.revision+=1);const u=this.result(d,n,i,o,r,s,void 0,c);return this.updateResults.record({kind:"tick",count:d},this.revision!==t?n.length||i.length||o.length?ao:co:[]),u}settle(e=this.config.settleStepLimit){const t=this.revision;this.spawnDue([],[]);const n=this.world.settle(e,this.config.fixedDt);return n>0&&(this.revision+=1),this.syncSimulationState(),this.updateResults.record({kind:"settle",count:n},this.revision!==t?co:[]),n}settleWithObservations(e=this.config.settleStepLimit){const t=this.revision,n=[],i=[],o=[],r=[],s=[];if(this.paused||!this.visible){const e=this.result(0,n,i,o,r,s,!1);return this.updateResults.record({kind:"settle",count:0},[]),e}this.spawnDue(n,s);const a=this.observeBodyBudget(s),c=this.evictOverflow(s);i.push(...c.evicted),o.push(...c.sedimented),this.syncSimulationState(s);let l=0;for(n.length>0&&this.quiescence.reset();e>l&&!this.atRest();){this.world.step(this.config.fixedDt);const e=this.world.events();r.push(...e),this.observeKernelEvents(e,s),this.observeSensorTransitions(s),l+=1,this.quiescence.refresh(this.world,this.config.fixedDt,0)}(l>0||n.length>0||i.length>0||o.length>0||r.length>0)&&(this.revision+=1);const d=this.result(l,n,i,o,r,s,void 0,a);return this.updateResults.record({kind:"settle",count:l},this.revision!==t?n.length||i.length||o.length?ao:co:[]),d}readBodies(e=[]){return this.world.readState(e)}readSediment(){return this.sediment.snapshot()}bodyBudgetStatus(){return this.evaluateBodyBudget()}sedimentTotals(){return this.sediment.totals()}sedimentHeightfield(e={}){return Oi(this.readSediment(),e)}hitTest(e,t,n=0){return this.bodySpatialIndex.hitTest(this.world,this.revision,this.liveBodyOrder,e,t,n)}events(){return this.world.events()}allSleeping(){return this.world.allSleeping()}atRest(){return this.world.allSleeping()||this.quiescence.isAtRest()}hasPendingWork(){return this.queue.length>0||!this.atRest()}queueSize(){return this.queue.length}liveBodyCount(){return this.liveBodyOrder.length}elapsed(){return this.elapsedSeconds}recordObservation(e){const{timestamp:t,chartType:n,chartId:i,...o}=e,r={...o,timestamp:t??this.elapsedSeconds,chartType:n??this.observation.chartType,chartId:i??this.observation.chartId};return this.emitObservation(r),this.updateResults.record({kind:"update",count:1},["evidence"]),r}getLastUpdateResult(){return this.updateResults.last}getUpdateSnapshot(){return this.updateResults.last}subscribeUpdateResult(e){return this.updateResults.subscribe(e)}version(){return this.revision}setPaused(e){const t=this.paused!==e;this.paused=e,this.syncSimulationState(),this.updateResults.record({kind:"pause"},t?lo:[])}setVisible(e){const t=this.visible!==e;this.visible=e,this.syncSimulationState(),this.updateResults.record({kind:"visibility"},t?lo:[])}remove(e){const t=new Set(e),n=new Set(this.liveBodyOrder),i=new Set(this.queue.map(e=>e.id));this.queue=this.queue.filter(e=>!t.has(e.id)),this.liveBodyOrder=this.liveBodyOrder.filter(e=>!t.has(e)),this.world.remove(e),this.removeActiveSensorPairsForBodies(t);const o=e.filter(e=>n.has(e)||i.has(e));return o.length>0&&(this.revision+=1,this.syncSimulationState()),this.updateResults.record({kind:"remove",keys:o,count:o.length},o.length?ao:[]),o}setConstraint(e){const t=this.world.setConstraint(e);return this.revision+=1,this.updateResults.record({kind:"constraint",keys:[t]},co),t}removeConstraint(e){this.world.removeConstraint(e),this.revision+=1,this.updateResults.record({kind:"constraint",keys:[e]},co)}applyImpulse(e,t,n){this.world.applyImpulse(e,t,n),this.revision+=1,this.updateResults.record({kind:"impulse",keys:[e]},co)}nextRandom(){return this.world.nextRandom()}controls(){return e=this,{applyImpulse:(t,n,i)=>e.applyImpulse(t,n,i),clear:()=>e.clear(),hitTest:(t,n,i)=>e.hitTest(t,n,i),pause:()=>e.setPaused(!0),push:(t,n)=>e.enqueue(t,n),pushMany:(t,n)=>e.enqueue(t,n),bodyBudgetStatus:()=>e.bodyBudgetStatus(),readBodies:t=>e.readBodies(t),readSediment:()=>e.readSediment(),recordObservation:t=>e.recordObservation(t),remove:t=>e.remove(t),restore:t=>e.restore(t),resume:()=>e.setPaused(!1),settle:t=>e.settle(t),settleWithObservations:t=>e.settleWithObservations(t),snapshot:()=>e.snapshot(),sedimentHeightfield:t=>e.sedimentHeightfield(t),sedimentTotals:()=>e.sedimentTotals(),step:t=>e.tick(t)};var e}snapshot(){const e=this.world.snapshot();return{accumulator:this.accumulator,activeSensorPairs:Array.from(this.activeSensorPairs).sort(),bodyBudget:Vi(this.bodyBudget),config:{...this.config,kernel:Ki(e.options)},elapsedSeconds:this.elapsedSeconds,paused:this.paused,queue:this.queue.map(Gi),revision:this.revision,sediment:this.readSediment(),simulationState:this.simulationState,liveBodyOrder:this.liveBodyOrder.slice(),visible:this.visible,world:e}}restore(e){this.config={bodyLimit:e.config.bodyLimit,eviction:e.config.eviction,fixedDt:e.config.fixedDt,maxDeltaSeconds:e.config.maxDeltaSeconds,maxSubsteps:e.config.maxSubsteps,settleStepLimit:e.config.settleStepLimit,timeScale:e.config.timeScale},this.configInput={...e.config,bodyBudget:Vi(e.bodyBudget??{}),kernel:Ki(e.world.options)},this.bodyBudget=Vi(e.bodyBudget??{}),this.bodyBudgetObservationKey="ok",this.quiescence.setKernelOptions(e.world.options),this.quiescence.reset(),this.activeSensorPairs=new Set(e.activeSensorPairs),this.accumulator=e.accumulator,this.elapsedSeconds=e.elapsedSeconds,this.paused=e.paused,this.queue=e.queue.map(Gi).sort(Ui),this.revision=e.revision,this.sediment.restore(e.sediment??[]),this.simulationState=e.simulationState??vo(e.paused,e.visible,e.queue.length>0,e.world.bodies.every(e=>e.sleeping)),this.liveBodyOrder=e.liveBodyOrder.slice(),this.visible=e.visible,this.nextSequence=this.queue.reduce((e,t)=>Math.max(e,t.sequence),-1)+1,this.world.restore(e.world),this.updateResults.record({kind:"restore"},ao)}spawnDue(e,t){for(;this.queue.length>0&&this.elapsedSeconds>=this.queue[0].spawnAt;){const n=this.queue.shift();if(!n)return;this.spawnOne(n,t),e.push(n.id)}}spawnOne(e,t){this.liveBodyOrder=this.liveBodyOrder.filter(t=>t!==e.id),this.removeActiveSensorPairsForBodies(new Set([e.id])),this.world.spawn(e),this.liveBodyOrder.push(e.id);for(const t of e.springs??[])this.world.setConstraint({...t,bodyId:e.id});const n=this.world.readState().find(t=>t.id===e.id);this.emitObservation({type:"physics-spawn",timestamp:this.elapsedSeconds,chartType:this.observation.chartType,chartId:this.observation.chartId,bodyId:e.id,datum:n?.datum??e.datum,x:n?.x??e.x,y:n?.y??e.y},t)}result(e,t,n,i,o,r,s,a=this.evaluateBodyBudget()){this.syncSimulationState(r);const c=this.world.allSleeping();return{budget:a,elapsedSeconds:this.elapsedSeconds,evicted:n,events:o,observations:r,queueSize:this.queue.length,revision:this.revision,shouldContinue:s??(this.queue.length>0||!this.atRest()),sleeping:c,sedimented:i,spawned:t,steps:e}}observeKernelEvents(e,t){!function(e,t,n){if(0===t.length)return;const i=new Map(e.readState().map(e=>[e.id,e]));for(const e of t){if("sleep"!==e.type)continue;const t=i.get(e.bodyId);n.emit({type:"physics-settle",timestamp:n.elapsedSeconds,chartType:n.observation.chartType,chartId:n.observation.chartId,bodyId:e.bodyId,datum:t?.datum,x:t?.x,y:t?.y})}}(this.world,e,this.observationContext(t))}observeSensorTransitions(e){this.activeSensorPairs=function(e,t,n){const i=new Set(e.activeSensorPairs().map(e=>`${e.sensorId}\0${e.bodyId}`));if(0===i.size&&0===t.size)return i;const o=new Map(e.readState().map(e=>[e.id,e])),r=(e,t)=>{const{sensorId:i,bodyId:r}=Zi(t),s=n.observation.sensors[i],a=o.get(r);n.emit({type:"enter"===e?s?.enterType??"physics-bin-enter":s?.exitType??"physics-bin-exit",timestamp:n.elapsedSeconds,chartType:n.observation.chartType,chartId:n.observation.chartId,bodyId:r,datum:a?.datum,x:a?.x,y:a?.y,sensorId:i,binId:s?.binId??i})};for(const e of Array.from(i).sort())t.has(e)||r("enter",e);for(const e of Array.from(t).sort())i.has(e)||r("exit",e);return i}(this.world,this.activeSensorPairs,this.observationContext(e))}removeActiveSensorPairsForBodies(e){!function(e,t){for(const n of e)t.has(Zi(n).bodyId)&&e.delete(n)}(this.activeSensorPairs,e)}observationContext(e){return{elapsedSeconds:this.elapsedSeconds,observation:this.observation,emit:t=>this.emitObservation(t,e)}}emitObservation(e,t){t?.push(e),this.observation.onObservation?.(e)}evaluateBodyBudget(){return qi({bodyLimit:this.config.bodyLimit,engineMaxBodiesHint:this.world.capabilities.maxBodiesHint,evictionEnabled:!1!==this.config.eviction,liveBodies:this.liveBodyOrder.length,queuedBodies:this.queue.length,sedimentEnabled:this.sediment.isEnabled(),options:this.bodyBudget})}observeBodyBudget(e){const t=this.evaluateBodyBudget();if("ok"===t.state||!1===this.bodyBudget)return this.bodyBudgetObservationKey="ok",t;const n=`${t.state}:${t.action}`;return n===this.bodyBudgetObservationKey||(this.bodyBudgetObservationKey=n,this.emitObservation({type:"overflow"===t.state?"physics-budget-overflow":"physics-budget-warning",timestamp:this.elapsedSeconds,chartType:this.observation.chartType,chartId:this.observation.chartId,budgetAction:t.action,bodyLimit:t.bodyLimit,engineMaxBodiesHint:t.engineMaxBodiesHint,liveBodies:t.liveBodies,overflow:t.overflow,projectedBodies:t.projectedBodies,queuedBodies:t.queuedBodies,warnAt:t.warnAt},e)),t}syncSimulationState(e){const t=vo(this.paused,this.visible,this.queue.length>0,this.atRest());if(t===this.simulationState)return;const n=this.simulationState;this.simulationState=t,function(e,t,n){n.observation.onSimulationStateChange?.(t,e),"running"!==t&&"settled"!==t||n.emit({type:"running"===t?"sim-active":"sim-idle",timestamp:n.elapsedSeconds,chartType:n.observation.chartType,chartId:n.observation.chartId,simulationState:t,previousSimulationState:e})}(n,t,this.observationContext(e))}evictOverflow(e){const{evicted:t,sedimented:n,liveBodyOrder:i}=function(e,t,n,i,o,r){const s={evicted:[],sedimented:[],liveBodyOrder:o};if(!1===n)return s;const a=Math.max(0,Math.floor(i));if(!Number.isFinite(a))return s;const c=o.length-a;if(0>=c)return s;const l=function(e,t,n){if("sleeping-first"!==t)return n.slice();const i=new Map(e.readState().map(e=>[e.id,e.sleeping])),o=[],r=[];for(const e of n)i.get(e)?o.push(e):r.push(e);return[...o,...r]}(e,n,o),d=l.slice(0,c);if(0===d.length)return s;const u=function(e,t,n,i){const o=new Map(e.readState().map(e=>[e.id,e])),r=[];for(const e of n){const n=o.get(e);if(!n)continue;const s=t.add(n);s&&(r.push(e),i.emit({type:"physics-sediment",timestamp:i.elapsedSeconds,chartType:i.observation.chartType,chartId:i.observation.chartId,bodyId:e,datum:n.datum,x:n.x,y:n.y,binId:s.id,count:s.count,total:s.total}))}return r}(e,t,d,r);e.remove(d);const h=new Set(d);return{evicted:d,sedimented:u,liveBodyOrder:o.filter(e=>!h.has(e))}}(this.world,this.sediment,this.config.eviction,this.config.bodyLimit,this.liveBodyOrder,this.observationContext(e));return t.length>0&&(this.liveBodyOrder=i,this.removeActiveSensorPairsForBodies(new Set(t))),{evicted:t,sedimented:n}}};function Mo(e,t,n){const i=new ko(e);return t?.length&&(i.enqueue(t,n),i.materializeDueSpawns()),i}function Io(){return"undefined"!=typeof performance?performance.now():Date.now()}var So=c(require("react-dom/server"));function jo(e=[]){return e.map(e=>({id:e.id,label:e.label,count:e.count,...null!=e.secondary?{secondary:e.secondary}:{},...e.secondaryLabel?{secondaryLabel:e.secondaryLabel}:{},...null!=e.observed?{observed:e.observed}:{}}))}var Ao={fill:"#4e79a7",stroke:"#172033",strokeWidth:1,opacity:.85};function Co(e){const t=e.datum;if(t&&"object"==typeof t){const e=t.label??t.name??t.id;if(null!=e&&""!==e)return e+""}return e.id}function Ro(e,t){const n="function"==typeof t?t(e):t;return{...Ao,...n??{}}}function $o(e,t={}){const n=e.settle(t.maxSteps),i=e.readBodies(),o=e.snapshot(),r=function(e,t={}){return e.map(e=>function(e,t={}){const n=function(e){return e.datum&&"object"==typeof e.datum?e.datum:null}(e),i={label:t.getBodyLabel?.(e)??Co(e)},o={style:Ro(e,t.bodyStyle),datum:n,accessibleDatum:n,accessibility:i,_transitionKey:e.id};return"aabb"===e.shape.type?{type:"rect",x:e.x-e.shape.width/2,y:e.y-e.shape.height/2,w:e.shape.width,h:e.shape.height,...o}:{type:"point",x:e.x,y:e.y,r:e.shape.radius,pointId:e.id,...o}}(e,t))}(i,t),s=function(e,t={}){const n=t.bodies??function(e){return e.world.bodies.map(e=>({id:e.id,x:e.x,y:e.y,prevX:e.prevX,prevY:e.prevY,vx:e.vx,vy:e.vy,angle:e.angle,mass:e.mass,shape:{...e.shape},sleeping:e.sleeping,datum:e.datum}))}(e),i=n.filter(e=>e.sleeping).length;return{bodyCount:n.length,sleepingCount:i,settled:"settled"===e.simulationState&&0===e.queue.length&&i===n.length,stepsRun:Math.max(0,Math.floor(t.stepsRun??0)),seed:e.world.options.seed,binCounts:jo(t.projectionRows)}}(o,{bodies:i,projectionRows:t.projectionRows,stepsRun:n});return{snapshot:o,bodies:i,sceneNodes:r,evidence:s,stepsRun:n}}var Po=require("react/jsx-runtime"),Do={top:0,right:0,bottom:0,left:0};function Bo(e,t,n){return"function"==typeof e?e({size:t,margin:n}):e}function To(e,t){if("function"==typeof t){const n=t(e);return Number.isFinite(n)&&n>0?Number(n):1}const n=e.datum;if(t&&n&&"object"==typeof n){const e=Number(n[t]);if(Number.isFinite(e)&&e>0)return e}const i=Number(n?.work??n?.reviewWork??n?.value);return Number.isFinite(i)&&i>0?i:1}function Eo(e,t){if("function"==typeof t){const n=t(e);if(null!=n&&(n+"").length>0)return n+""}else if(t){const n=Oo(e.datum,t),i=Oo(e,t),o=n??i;if(null!=o&&(o+"").length>0)return o+""}return e.id}function No(e,t){if(0===e.length)return 0;if(1===e.length)return e[0];const n=Math.max(0,Math.min(1,t))*(e.length-1),i=Math.floor(n);return e[i]+(e[Math.ceil(n)]-e[i])*(n-i)}function Oo(e,t){if(!t)return;let n=e;for(const e of t.split(".")){if(null==n||"object"!=typeof n)return;n=n[e]}return n}function Wo(e,t){if(!t)return!0;if("function"==typeof t)return t(e);const n=Oo(e,t.property);return!("equals"in t&&!Object.is(n,t.equals)||"notEquals"in t&&Object.is(n,t.notEquals)||t.oneOf&&!t.oneOf.some(e=>Object.is(n,e))||t.notOneOf&&t.notOneOf.some(e=>Object.is(n,e)))}function qo(e){const t=e.regionId,n=Math.max(0,e.unitsPerSecond),i=e.queueLayout??"lane",o=e.queueSlotSpacing??14,r=e.queueStiffness??.35,s=Number.isFinite(e.maxQueue)?Math.max(0,Math.floor(Number(e.maxQueue))):1/0,a=Math.max(.25,e.metricWindowSeconds??30),c=Math.max(1/60,e.snapshotIntervalSeconds??.25),l=e.releaseImpulse??{x:90,y:0},d=new Map,u=new Map,h=new Map,p=new Map,m=new Map,f=new Map,y=new Map,g=[];let b=0,x=new Map,v=new Map,w=0,k=0,M=0,I=null,S=0,j=0,A=0,C=0,R=0,$=0,P=0,D=0,B=0,T=0,E=0,N=0,O=-1,W=!1;function q(e,n){const i=n(e);return!!i&&i.activeRegionIds.includes(t)}function F(){N+=1}function z(e){return{bodyId:e.bodyId,jobId:e.jobId,visitId:e.visitId,visit:e.visit,regionId:t,work:e.total,queuedAt:e.queuedAt}}function L(n,i,o,r){const s={bodyId:n.id,jobId:i.jobId,visitId:i.visitId,visit:i.visit,remaining:i.work,total:i.work,queuedAt:i.queuedAt,sequence:r};return d.set(i.jobId,s),y.delete(n.id),f.set(n.id,i.jobId),j+=1,A+=i.work,F(),function(n,i,o){const r=z(i);e.onQueued?.(n,r),o.controls.recordObservation({type:"physics-capacity-queued",bodyId:n.id,datum:n.datum,x:n.x,y:n.y,regionId:t,work:i.total,jobId:i.jobId,visitId:i.visitId,visit:i.visit,queuedAt:i.queuedAt,queueDepth:d.size})}(n,s,o),s}function Y(e){if(d.size>=s||0===u.size)return;const t=Array.from(u.values()).sort((e,t)=>e.sequence-t.sequence);for(const n of t){if(d.size>=s)break;const t=m.get(n.jobId);t&&h.has(n.jobId)?(u.delete(n.jobId),y.delete(n.bodyId),L(t,n,e,n.sequence)):u.delete(n.jobId)}}function H(){let e=0;for(const t of d.values())e+=t.remaining;return e}function _(){B=Math.max(B,d.size),T=Math.max(T,H())}function G(){const e=M-a,t=Math.max(0,Math.min(a,M-(I??M)));let i=0,o=0,r=0,s=0,c=0;for(const t of g){if(e>t.end)continue;i+=t.arrivals,o+=t.arrivalWork,r+=t.completions,s+=t.completedWork;const n=t.end-t.start;c+=n>0&&e>t.start?t.processedWork*Math.min(1,Math.max(0,t.end-e)/n):t.processedWork}const l=t>0?o/t:0;return{seconds:t,arrivals:i,arrivalWork:o,completions:r,completedWork:s,processedWork:c,arrivalsPerSecond:t>0?i/t:0,throughputPerSecond:t>0?r/t:0,utilization:t>0&&n>0?Math.max(0,Math.min(1,c/(n*t))):0,pressure:n>0?l/n:0}}return{id:e.id??"capacity-queue:"+t,continuous:!1!==e.continuous,tick:i=>{const o=i.controls.readBodies(),r=new Map,j=new Map;for(const t of o){if(r.set(t.id,t),!q(t.id,i.getRegionState))continue;if(!Wo(t,e.bodyFilter))continue;const n=Eo(t,e.jobKey),o=j.get(n)??[];o.push(t),j.set(n,o)}const A=Number.isFinite(i.dt)?Math.max(0,i.dt):0;if(!W){const e=Number.isFinite(i.elapsed)?Math.max(0,i.elapsed):A;M=Math.max(0,e-A),W=!0}const B=M,T=B+A;M=T,I=null==I?B:Math.min(I,B);const N={start:B,end:T,arrivals:0,arrivalWork:0,completions:0,completedWork:0,processedWork:0},H=new Map;for(const[e,t]of j){const n=h.get(e)?.bodyId,i=t.find(e=>e.id===n)??t[0];H.set(e,i),m.set(e,i)}for(const[n,o]of h){if(H.has(n))continue;const s=d.get(n),a=r.get(o.bodyId)??m.get(n);if(s){d.delete(n),f.delete(s.bodyId),P+=1,D+=s.remaining,F();const r={...z(s),abandonedAt:M,remainingWork:s.remaining,queueSeconds:Math.max(0,M-s.queuedAt)};a&&e.onAbandoned?.(a,r),i.controls.recordObservation({type:"physics-capacity-abandoned",bodyId:o.bodyId,datum:a?.datum,x:a?.x,y:a?.y,regionId:t,work:s.total,remainingWork:s.remaining,jobId:n,visitId:s.visitId,visit:s.visit,queuedAt:s.queuedAt,abandonedAt:M,queueSeconds:r.queueSeconds,queueDepth:d.size})}u.delete(n),y.delete(o.bodyId),h.delete(n),m.delete(n)}for(const[n,o]of H){if(h.has(n))continue;const r=(p.get(n)??0)+1;p.set(n,r);const a=To(o,e.unitAccessor),c={bodyId:o.id,jobId:n,visitId:`${t}:${n}:${r}`,visit:r,regionId:t,work:a,queuedAt:M};h.set(n,c),S+=1,N.arrivals+=1,N.arrivalWork+=a;const l=b++;if(s>d.size)L(o,c,i,l);else{const s={...c,blockedAt:M,sequence:l};u.set(n,s),y.set(o.id,n),$+=1,F(),e.onBlocked?.(o,s),i.controls.recordObservation({type:"physics-capacity-blocked",bodyId:o.id,datum:o.datum,x:o.x,y:o.y,regionId:t,work:a,jobId:n,visitId:c.visitId,visit:r,queuedAt:M,blockedAt:M,queueDepth:d.size,blockedDepth:u.size})}}Y(i),_();const G=Array.from(d.values()).sort((e,t)=>e.sequence-t.sequence);let X=n*A;for(const n of G){if(0>=X)break;const o=Math.min(n.remaining,X);if(n.remaining-=o,X-=o,C+=o,N.processedWork+=o,n.remaining>1e-6)continue;d.delete(n.jobId),f.delete(n.bodyId),k+=1,R+=n.total,N.completions+=1,N.completedWork+=n.total;const s=Math.max(0,M-n.queuedAt);E+=s,F();const a=r.get(n.bodyId);if(!a)continue;i.controls.applyImpulse(n.bodyId,l.x??0,l.y??0);const c={...z(n),completedAt:M,queueSeconds:s};e.onProcessed?.(a,c),i.controls.recordObservation({type:"physics-capacity-processed",bodyId:n.bodyId,datum:a.datum,x:a.x,y:a.y,regionId:t,work:n.total,jobId:n.jobId,visitId:n.visitId,visit:n.visit,queuedAt:n.queuedAt,completedAt:M,queueSeconds:s,queueDepth:d.size})}Y(i),_(),function(){const e=Array.from(d.values()).sort((e,t)=>e.sequence-t.sequence);x=new Map(e.map((e,t)=>[e.bodyId,t]));const t=Array.from(u.values()).sort((e,t)=>e.sequence-t.sequence);v=new Map(t.map((e,t)=>[e.bodyId,t])),w=e.length}(),function(e){(e.end>e.start||e.arrivals>0||e.completions>0||e.processedWork>0)&&g.push(e);const t=M-a;for(;g.length>0&&t>g[0].end;)g.shift()}(N);const V=Math.floor(M/c);V!==O&&(O=V,F())},getSnapshot:()=>{const e=H(),i=function(){let e=0;for(const t of u.values())e+=t.work;return e}(),o=d.size,r=Array.from(d.values()).map(e=>Math.max(0,M-e.queuedAt)).sort((e,t)=>e-t),s=r.reduce((e,t)=>e+t,0);return{regionId:t,queueDepth:o,processedCount:k,unitsPerSecond:n,remainingWork:e,meanRemainingWork:o>0?e/o:0,waitingWork:e+i,blockedDepth:u.size,blockedWork:i,arrivalCount:S,admittedCount:j,admittedWork:A,processedWork:C,completedWork:R,blockedCount:$,abandonedCount:P,abandonedWork:D,peakQueueDepth:B,peakRemainingWork:T,queueAge:{count:r.length,meanSeconds:r.length>0?s/r.length:0,p50Seconds:No(r,.5),p95Seconds:No(r,.95),oldestSeconds:r.at(-1)??0},meanCompletedQueueSeconds:k>0?E/k:0,window:G(),simulatedAt:M,metricRevision:N}},bodyForce:e=>{if("none"===i)return null;const n=f.get(e.body.id),s=y.get(e.body.id),a=n?d.get(n):void 0,c=s?u.get(s):void 0;if(!a&&!c)return null;const l=a?x.get(e.body.id):v.get(e.body.id);if(null==l)return null;let h;const p=e.regions;if(p)for(let e=0;p.length>e;e+=1)if(p[e].id===t){const t=p[e].shape;t&&"aabb"===t.type&&(h=t);break}return h?{x:((c?h.x-.44*h.width:h.x-.22*h.width-l*(.15*o))-e.body.x)*r,y:(h.y-(l-((c?u.size:w)-1)/2)*o/Math.max(1,Math.sqrt(c?u.size:w))-e.body.y)*r*.85}:{x:8*-Math.sign(e.body.vx||1),y:0}}}}function Fo(e,t){if(!t)return;let n=e;for(const e of t.split(".")){if(null==n||"object"!=typeof n)return;n=n[e]}return n}function zo(e,t){if(!t)return!0;if("function"==typeof t)return t(e);const n=Fo(e,t.property);return!("equals"in t&&!Object.is(n,t.equals)||"notEquals"in t&&Object.is(n,t.notEquals)||t.oneOf&&!t.oneOf.some(e=>Object.is(n,e))||t.notOneOf&&t.notOneOf.some(e=>Object.is(n,e)))}function Lo(e){const t=e.resources.map(e=>({...e,bodyId:e.bodyId??e.id})),n=new Map(t.map(e=>[e.bodyId,e])),i=new Map,o=new Map,r=e.assignmentForce??.45,s=e.returnForce??.35,a=e.caseAttraction??.08,c=e.assignmentOffset??{x:0,y:0};let l=new Map,d=0,u=0;return{id:e.id??"service-resource-pool",continuous:!0,assign:e=>{const n=i.get(e);if(n)return n;const r=t.find(e=>!o.has(e.id));if(!r)return null;const s={resourceId:r.id,resourceBodyId:r.bodyId,caseBodyId:e,assignedAt:d};return i.set(e,s),o.set(r.id,s),u+=1,s},release:e=>{const t=i.get(e);return!!t&&(i.delete(e),o.delete(t.resourceId),u+=1,!0)},getAssignment:e=>i.get(e),tick:e=>{d=Math.max(d,e.elapsed),l=new Map(e.controls.readBodies().map(e=>[e.id,e]));for(const[e,t]of i)l.has(e)&&l.has(t.resourceBodyId)||(i.delete(e),o.delete(t.resourceId),u+=1)},getSnapshot:()=>({total:t.length,available:t.length-o.size,assigned:o.size,assignments:Array.from(i.values()),simulatedAt:d,metricRevision:u}),bodyForce:e=>{const t=n.get(e.body.id);if(t){const n=o.get(t.id),i=n?l.get(n.caseBodyId):void 0,a=n?r:s;return{x:((i?i.x+(c.x??0):t.home.x)-e.body.x)*a,y:((i?i.y+(c.y??0):t.home.y)-e.body.y)*a}}const d=i.get(e.body.id);if(!d||0>=a)return null;const u=l.get(d.resourceBodyId);return u?{x:(u.x-e.body.x)*a,y:(u.y-e.body.y)*a}:null}}}function Yo(e,t){const n="function"==typeof t.deadlineAccessor?t.deadlineAccessor(e):Fo(e.datum,t.deadlineAccessor)??Fo(e,t.deadlineAccessor);return Number.isFinite(Number(n))?Math.max(0,Number(n)):0}function Ho(e){const t=new Map;let n=0,i=0;function o(n){t.set(n.bodyId,n),i+=1,e.onStateChange?.({...n})}function r(e){const i=t.get(e);return!(!i||null!=i.completedAt||(o({...i,completedAt:n,state:"unhappy"===i.state?"resolved-unhappy":"resolved"}),0))}return{id:e.id??"service-level",continuous:!0,protect:e=>{const i=t.get(e);return!(!i||null!=i.completedAt||"unhappy"===i.state||(o({...i,state:"protected",protectedAt:n}),0))},complete:r,getCase:e=>t.get(e),tick:i=>{n=Math.max(n,i.elapsed);for(const s of i.controls.readBodies()){if(!zo(s,e.bodyFilter))continue;if(!t.has(s.id)){const t=Yo(s,e);o({bodyId:s.id,openedAt:n,deadlineAt:n+t,state:"waiting"})}const a=t.get(s.id);a&&null==a.completedAt&&(e.completionRegionId&&i.getRegionState(s.id)?.activeRegionIds.includes(e.completionRegionId)?r(s.id):"waiting"!==a.state||a.deadlineAt>n||o({...a,state:"unhappy"}))}},getSnapshot:()=>{const e=Array.from(t.values()),o=t=>e.filter(e=>e.state===t).length;return{total:e.length,waiting:o("waiting"),protected:o("protected"),unhappy:o("unhappy"),resolved:o("resolved"),resolvedUnhappy:o("resolved-unhappy"),simulatedAt:n,metricRevision:i}}}}function _o(e){const t=new Set;let n=0,i=0,o=0,r=!1;return{id:e.id??"dependency-gate:"+e.regionId,continuous:!0,tick:s=>{n=Math.max(n,s.elapsed);const a=r;var c;c=n,r=e.isOpen?e.isOpen(c):null!=e.opensAt&&c>=e.opensAt;const l=s.controls.readBodies(),d=new Map(l.map(e=>[e.id,e]));for(const n of l){const i=s.getRegionState(n.id)?.activeRegionIds.includes(e.regionId);i&&zo(n,e.bodyFilter)&&(r||t.has(n.id)||(t.add(n.id),o+=1,e.onHeld?.(n)))}if(r&&!a){for(const n of t){const t=d.get(n);t&&(s.controls.applyImpulse(n,e.releaseImpulse?.x??86,e.releaseImpulse?.y??0),i+=1,e.onReleased?.(t))}t.clear(),o+=1}for(const e of t)d.has(e)||(t.delete(e),o+=1)},getSnapshot:()=>({regionId:e.regionId,isOpen:r,blocked:t.size,released:i,simulatedAt:n,metricRevision:o}),bodyForce:n=>{if(r||!t.has(n.body.id))return null;const i=n.regions?.find(t=>t.id===e.regionId),o=i?.shape;if(!o||"aabb"!==o.type)return{x:.8*-n.body.vx,y:.8*-n.body.vy};const s=e.holdForce??.4;return{x:(o.x-n.body.x)*s-.45*n.body.vx,y:(o.y-n.body.y)*s-.45*n.body.vy}}}}function Go(e,t){return e||t?{x:(e?.x??0)+(t?.x??0),y:(e?.y??0)+(t?.y??0)}:null}function Xo(e){if(!e?.length)return null;const t=e.slice(),n=t.some(e=>!1!==e.continuous);return{controllers:t,continuous:n,onTick:(e,n,i)=>{const o={result:e,controls:n,dt:i.dt,elapsed:i.elapsed,getRegionState:i.getRegionState};for(const e of t)e.tick(o)},bodyForce:e=>{let n=null;for(const i of t)i.bodyForce&&(n=Go(n,i.bodyForce(e)));return n}}}function Vo(e){const t=new Set,n=e.impulse??{x:-60,y:0};return{id:e.id??"portal:"+e.fromRegionId,continuous:!0===e.continuous,tick:i=>{const o=i.controls.readBodies();for(const r of o){const o=i.getRegionState(r.id),s=o?.activeRegionIds.includes(e.fromRegionId);s?t.has(r.id)||(t.add(r.id),i.controls.applyImpulse(r.id,n.x??0,n.y??0),e.onPortal?.(r)):t.delete(r.id)}}}}var Uo=require("react");function Ko(){return"undefined"==typeof document||!document.hidden}var Qo=require("react/jsx-runtime"),Zo="var(--semiotic-focus, #005fcc)";function Jo({active:e,hoverPoint:t,margin:n,size:i,shape:o="circle",width:r,height:s,pathData:a}){if(!e||!t)return null;const c=t.x+n.left,l=t.y+n.top;let d;if("geoarea"!==o&&"path"!==o||!a)if("rect"===o&&null!=r&&null!=s){const e=Math.max(r,4),t=Math.max(s,4);d=(0,Qo.jsx)("rect",{x:c-e/2-3,y:l-t/2-3,width:e+6,height:t+6,rx:3,fill:"none",stroke:Zo,strokeWidth:2,strokeDasharray:"4,2"})}else d=(0,Qo.jsx)("circle","wedge"===o?{cx:c,cy:l,r:12,fill:"none",stroke:Zo,strokeWidth:2.5,strokeDasharray:"6,3"}:{cx:c,cy:l,r:8,fill:"none",stroke:Zo,strokeWidth:2,strokeDasharray:"4,2"});else d=(0,Qo.jsx)("g",{transform:`translate(${n.left},${n.top})`,children:(0,Qo.jsx)("path",{d:a,fill:"none",stroke:Zo,strokeWidth:2.5,strokeDasharray:"6,3"})});return(0,Qo.jsx)("svg",{style:{position:"absolute",left:0,top:0,width:i[0],height:i[1],pointerEvents:"none",zIndex:2},"aria-hidden":"true",children:d})}var er=require("react"),tr={sceneGeometry:0,layout:0,domain:0};function nr(e){const{domain:t,layout:n,sceneGeometry:i}=e.revisions;return{domain:t,layout:n,sceneGeometry:i}}function ir(e,t){return{sceneGeometry:Math.max(e.sceneGeometry,t.sceneGeometry),layout:Math.max(e.layout,t.layout),domain:Math.max(e.domain,t.domain)}}var or="production"!==process.env.NODE_ENV,rr={revisions:tr,signature:"",sawSignals:!1,wasUnconsumed:!1,warnUnconsumed:!1},sr=class{constructor(e="scene host"){this.hostName=e,this.lastConsumed=tr,this.lastObserved=tr,this.lastDuplicateWarning="",this.lastUnconsumedWarning=""}observeUpdateResult(e){or&&(this.lastObserved=ir(this.lastObserved,nr(e)))}beforeCompute(e,t){if(!or)return rr;const n=ir(nr(e),this.lastObserved),i=function(e){return`${e.sceneGeometry}|${e.layout}|${e.domain}`}(n),o=!((r=n).sceneGeometry===(s=this.lastConsumed).sceneGeometry&&r.layout===s.layout&&r.domain===s.domain);var r,s;return{revisions:n,signature:i,sawSignals:e.changed.has("scene-geometry")||e.changed.has("layout")||e.changed.has("domain"),wasUnconsumed:o,warnUnconsumed:!t&&o&&this.lastUnconsumedWarning!==i}}afterCompute(e,t,n){if(or){if(t&&e.wasUnconsumed&&(this.lastConsumed=e.revisions),e.warnUnconsumed&&!t)return console.warn(`[semiotic] ${this.hostName} observed scene-affecting revisions without a scene rebuild: ${e.signature}.`),void(this.lastUnconsumedWarning=e.signature);t&&e.sawSignals&&!e.wasUnconsumed&&!n&&this.lastDuplicateWarning!==e.signature?(console.warn(`[semiotic] ${this.hostName} performed scene rebuild with unchanged scene revisions: ${e.signature}.`),this.lastDuplicateWarning=e.signature):t&&!e.sawSignals&&(this.lastDuplicateWarning="")}}},ar=(0,er.memo)(function({store:e,diagnostics:t}){return(0,er.useEffect)(()=>{const n=()=>t.observeUpdateResult(e.getUpdateSnapshot());return n(),e.subscribeUpdateResult(n)},[t,e]),null}),cr=(c(require("react")),c(require("react"))),lr=(require("react/jsx-runtime"),cr.createContext(null)),dr=require("react/jsx-runtime"),ur={position:"absolute",width:1,height:1,overflow:"hidden",clip:"rect(0,0,0,0)",whiteSpace:"nowrap",border:0};function hr({hoverPoint:e}){let t="";if(e){const n=e.data||e;t="object"==typeof n?"Data point: "+Object.entries(n).filter(([,e])=>"object"!=typeof e&&"function"!=typeof e).map(([e,t])=>`${e}: ${t}`).join(", "):"Data point: "+n}return(0,dr.jsx)("div",{"aria-live":"polite","aria-atomic":"true",style:ur,children:t})}var pr=require("react/jsx-runtime");function mr({summary:e}){return e?(0,pr.jsx)("div",{role:"note",style:ur,children:e}):null}function fr({tableId:e}){return(0,pr.jsx)("a",{href:"#"+e,style:ur,onClick:t=>{t.preventDefault();const n=document.getElementById(e);n&&requestAnimationFrame(()=>n.focus())},onFocus:e=>{Object.assign(e.currentTarget.style,{position:"absolute",width:"auto",height:"auto",overflow:"visible",clip:"auto",whiteSpace:"normal",padding:"4px 8px",background:"var(--semiotic-bg, #fff)",color:"var(--semiotic-text, #000)",border:"2px solid var(--semiotic-focus, #005fcc)",borderRadius:"4px",zIndex:"10",fontSize:"12px",top:"4px",left:"4px"})},onBlur:e=>{const t=e.currentTarget;t.removeAttribute("style"),Object.assign(t.style,ur)},children:"Skip to data table"})}function yr(e,t,n){const i=function(e,t){if(null==t)return;const n=ue(e,t,"");return""===n?void 0:n}(e,n.fill)??"#4e79a7",o=n.stroke,r=n.strokeWidth??0,s=n.opacity??1,a=n.fillOpacity??1,c=function(e,t){const n=t.mark;if(n)return n;const i=e.datum,o=i?.__physicsMark??i?.mark;return"circle"===o||"halo"===o||"faceted"===o||"pill"===o||"diamond"===o||"square"===o?o:"circle"===e.shape.type?"circle":"square"}(t,n),l="circle"===t.shape.type?n.r??t.shape.radius:Math.max(t.shape.width,t.shape.height)/2;if(e.save(),e.globalAlpha*=s,e.beginPath(),"pill"===c||"square"===c||"aabb"===t.shape.type){const n="pill"===c?2.4*l:"aabb"===t.shape.type?t.shape.width:1.7*l,i="pill"===c?1.35*l:"aabb"===t.shape.type?t.shape.height:1.7*l,o=t.x-n/2,r=t.y-i/2,s="pill"===c?i/2:Math.min(4,n/4);e.moveTo(o+s,r),e.arcTo(o+n,r,o+n,r+i,s),e.arcTo(o+n,r+i,o,r+i,s),e.arcTo(o,r+i,o,r,s),e.arcTo(o,r,o+n,r,s),e.closePath()}else if("diamond"===c)e.moveTo(t.x,t.y-l),e.lineTo(t.x+l,t.y),e.lineTo(t.x,t.y+l),e.lineTo(t.x-l,t.y),e.closePath();else if("faceted"===c){const n=6;for(let i=0;n>i;i+=1){const o=2*Math.PI*i/n-Math.PI/2,r=t.x+Math.cos(o)*l,s=t.y+Math.sin(o)*l;0===i?e.moveTo(r,s):e.lineTo(r,s)}e.closePath()}else e.arc(t.x,t.y,l,0,2*Math.PI);i&&(e.save(),e.globalAlpha*=a,e.fillStyle=i,e.fill(),e.restore()),"halo"===c&&(e.beginPath(),e.arc(t.x,t.y,1.35*l,0,2*Math.PI),e.strokeStyle=o??i,e.lineWidth=Math.max(1.5,r||1.5),e.globalAlpha*=.55,e.stroke(),e.globalAlpha/=.55),o&&r>0&&(e.strokeStyle=o,e.lineWidth=r,n.strokeDasharray&&e.setLineDash(n.strokeDasharray.split(/[,\s]+/).map(e=>Number(e)).filter(e=>Number.isFinite(e))),e.stroke()),e.restore()}function gr(e){return"circle"===e.shape.type?e.shape.radius:Math.max(e.shape.width,e.shape.height)/2}function br(e){return e.sensorId??"stream-region-"+e.id}function xr(e){const t=br(e),n={bodyFilter:e.bodyFilter,friction:e.friction,restitution:e.restitution};if("boundary"===e.collider&&"aabb"===e.shape.type){const i=e.colliderThickness??8,o=e.shape.x-e.shape.width/2,r=e.shape.x+e.shape.width/2,s=e.shape.y-e.shape.height/2,a=e.shape.y+e.shape.height/2;return[{...n,id:t+"-top",shape:{type:"segment",x1:o,y1:s,x2:r,y2:s,thickness:i}},{...n,id:t+"-right",shape:{type:"segment",x1:r,y1:s,x2:r,y2:a,thickness:i}},{...n,id:t+"-bottom",shape:{type:"segment",x1:r,y1:a,x2:o,y2:a,thickness:i}},{...n,id:t+"-left",shape:{type:"segment",x1:o,y1:a,x2:o,y2:s,thickness:i}}]}return e.collider?[{...n,id:t+"-collider",shape:e.shape}]:[]}function vr(e){if(e)return{activeRegionIds:Array.from(e.activeRegionIds),regionIds:Array.from(e.regionIds),charges:{...e.charges},attributes:{...e.attributes},energy:e.energy}}function wr(e,t){const n="function"==typeof e?e(t):e;if(!n)return null;const i=Number(n.x??0),o=Number(n.y??0);return Number.isFinite(i)||Number.isFinite(o)?{x:Number.isFinite(i)?i:0,y:Number.isFinite(o)?o:0}:null}function kr(e){if(!1===e.semanticItem)return null;const t=e.shape,n=e.semanticItem??{},i="aabb"===t.type?{id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"region",x:t.x,y:t.y,width:t.width,height:t.height}:{id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"region",x:(t.x1+t.x2)/2,y:(t.y1+t.y2)/2,pathData:`M ${t.x1} ${t.y1} L ${t.x2} ${t.y2}`};return{...i,...n,id:n.id??i.id}}function Mr(e){return e.some(e=>null!=e.force||null!=e.damping||null!=e.impulseOnEnter||null!=e.impulseOnExit)}function Ir(e,t){const n="function"==typeof e?e(t):e;if(!n)return null;const i=Number(n.x??0),o=Number(n.y??0);return Number.isFinite(i)||Number.isFinite(o)?{x:Number.isFinite(i)?i:0,y:Number.isFinite(o)?o:0}:null}var Sr=[];function jr(e){const t=e.store.controls(),n=e.store.snapshot(),i=Math.max(0,e.result.steps*(n.config.fixedDt||1/60)),o=function(e,t,n,i){const o=Number.isFinite(i)?Math.max(0,i):0;if(0>=o||!Mr(t))return!1;const r=new Map(t.map(e=>[e.id,e])),s=e.readBodies();let a=!1;for(const t of s){const i=n.get(t.id);if(!i||!i.activeRegionIds.size)continue;const s=vr(i);if(s)for(const n of i.activeRegionIds){const i=r.get(n);if(!i)continue;const c=wr(i.force,{body:t,region:i,regionState:s}),l=Number(i.damping??0),d=(c?.x??0)*o-(Number.isFinite(l)?t.vx*l*o:0),u=(c?.y??0)*o-(Number.isFinite(l)?t.vy*l*o:0);(d||u)&&(e.applyImpulse(t.id,d,u),a=!0)}}return a}(t,e.regionEffects,e.regionState,i),r=function(e,t,n,i,o,r){const s=Number.isFinite(r)?Math.max(0,r):0;if(0>=s||!t)return!1;const a=new Map(n.map(e=>[e.id,e])),c=e.readBodies();let l=!1;for(let n=0;c.length>n;n+=1){const r=c[n],d=i.get(r.id),u=vr(d);let h=Sr;if(d&&d.activeRegionIds.size>0){const e=[];for(const t of d.activeRegionIds){const n=a.get(t);n&&e.push(n)}h=e}const p=Ir(t,{body:r,bodies:c,index:n,regionState:u,regions:h,simulationState:o});if(!p)continue;const m=(p.x??0)*s,f=(p.y??0)*s;(m||f)&&(e.applyImpulse(r.id,m,f),l=!0)}return l}(t,e.bodyForces,e.regionEffects,e.regionState,n.simulationState,i);return e.composed&&e.composed.onTick(e.result,t,{dt:i,elapsed:e.result.elapsedSeconds,getRegionState:t=>vr(e.regionState.get(t))}),e.onTick?.(e.result,t),{regionEffectsApplied:o,bodyForcesApplied:r,snapshot:n}}function Ar(e,t,n,i,o,r,s,a,c,l){const d=function(e,t){return!!t?.isActive&&(t.predicate?.(e)??!0)}(e,o),u={selected:d,simulationState:t,regionState:r,regions:s},h="function"==typeof n?n(e,u):n,p=s.reduce((t,n)=>n.bodyStyle?{...t,..."function"==typeof n.bodyStyle?n.bodyStyle(e,u):n.bodyStyle}:t,{}),m=d?"function"==typeof i?i(e,u):i:void 0;return{fill:l?.color??a,stroke:l?.stroke??c,strokeWidth:l?.strokeWidth??1,opacity:l?.opacity??.9,...h,...p,...m}}var Cr=require("react"),Rr=c(require("react")),$r=require("react/jsx-runtime"),Pr={border:0,clip:"rect(0 0 0 0)",height:1,margin:-1,overflow:"hidden",padding:0,position:"absolute",whiteSpace:"nowrap",width:1},Dr="semiotic-accessible-data-table",Br=Dr+" semiotic-accessible-data-table-hidden",Tr=Dr+" semiotic-accessible-data-table-visible",Er={position:"absolute",top:0,left:0,right:0,zIndex:"var(--semiotic-data-table-z-index, var(--semiotic-overlay-z-index, 20))",padding:"14px 16px 12px",borderBottom:"1px solid var(--semiotic-data-table-border, var(--semiotic-border, #e0e0e0))",fontFamily:"var(--semiotic-font-family, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif)",fontSize:13,lineHeight:1.5,color:"var(--semiotic-data-table-text, var(--semiotic-text, #333))",background:"var(--semiotic-data-table-bg, var(--semiotic-surface, var(--semiotic-bg, #fff)))",borderRadius:"var(--semiotic-border-radius, 0px) var(--semiotic-border-radius, 0px) 0 0"},Nr={marginBottom:8,paddingRight:28,color:"var(--semiotic-data-table-muted-text, var(--semiotic-text-secondary, #666))",fontSize:12,letterSpacing:"0.01em"},Or={position:"absolute",top:10,right:10,width:22,height:22,display:"flex",alignItems:"center",justifyContent:"center",border:"1px solid var(--semiotic-data-table-border, var(--semiotic-border, #e0e0e0))",background:"var(--semiotic-data-table-bg, var(--semiotic-surface, var(--semiotic-bg, #fff)))",cursor:"pointer",color:"var(--semiotic-data-table-muted-text, var(--semiotic-text-secondary, #666))",fontSize:13,lineHeight:1,padding:0,borderRadius:"var(--semiotic-border-radius, 4px)"},Wr={width:"100%",borderCollapse:"collapse",fontSize:12,marginTop:4,fontVariantNumeric:"tabular-nums"},qr={textAlign:"left",padding:"5px 10px",borderBottom:"2px solid var(--semiotic-data-table-border, var(--semiotic-border, #e0e0e0))",fontWeight:600,fontSize:11,textTransform:"uppercase",letterSpacing:"0.04em",color:"var(--semiotic-data-table-muted-text, var(--semiotic-text-secondary, #666))"},Fr={padding:"4px 10px",borderBottom:"1px solid var(--semiotic-data-table-border, var(--semiotic-border, #e0e0e0))"},zr={textAlign:"left",fontSize:11,color:"var(--semiotic-data-table-muted-text, var(--semiotic-text-secondary, #666))",marginBottom:4,fontStyle:"italic"},Lr={marginTop:8,padding:"4px 10px",fontSize:12,cursor:"pointer",border:"1px solid var(--semiotic-data-table-border, var(--semiotic-border, #e0e0e0))",borderRadius:"var(--semiotic-border-radius, 4px)",background:"var(--semiotic-data-table-bg, var(--semiotic-surface, var(--semiotic-bg, #fff)))",color:"var(--semiotic-data-table-text, var(--semiotic-text, #333))",fontFamily:"inherit"};function Yr(e){return null==e?null:"string"==typeof e||"number"==typeof e||"boolean"==typeof e?e+"":null}function Hr(e){return{__semioticHoverData:!0,body:e,data:e.datum??e,id:e.id,type:"body",x:e.x,y:e.y}}function _r(e){if("circle"===e.shape.type){const t=Math.max(4,2*e.shape.radius);return{height:t,shape:"circle",width:t}}return{height:e.shape.height,shape:"rect",width:e.shape.width}}function Gr(e){const t=e.datum;if(t&&"object"==typeof t){const e=t.label??t.name??t.id;if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e+""}return e.id}function Xr(e){const t=Vr(e.datum??e);return t.length?t.map(([e,t])=>`${e}: ${t}`).join(", "):"Physics body "+e.id}function Vr(e){return e&&"object"==typeof e?Object.entries(e).map(([e,t])=>{if(e.startsWith("_"))return null;const n=Yr(t);return null==n?null:[e,n]}).filter(e=>null!=e).slice(0,8):[]}function Ur({hover:e}){const t=Vr(e.data);return(0,$r.jsxs)("div",{className:"semiotic-tooltip",style:De,children:[(0,$r.jsx)("div",{style:{fontWeight:700,marginBottom:t.length?4:0},children:e.id}),t.map(([e,t])=>(0,$r.jsxs)("div",{children:[(0,$r.jsxs)("span",{style:{opacity:.72},children:[e,": "]}),(0,$r.jsx)("span",{children:t})]},e))]})}function Kr(e){return e.datum&&"object"==typeof e.datum?Object.entries(e.datum).map(([e,t])=>{const n=Yr(t);return null==n?null:`${e}: ${n}`}).filter(e=>null!=e).slice(0,8).join(", "):""}function Qr(e){const t=[`${e.length} semantic item${1===e.length?"":"s"}.`],n=new Map;for(const t of e)t.group&&n.set(t.group,(n.get(t.group)??0)+1);return n.size&&t.push(Array.from(n).map(([e,t])=>`${e}: ${t}`).join(", ")),t.join(" ")}function Zr(e){const{chartTitle:t,items:n,tableId:i}=e,[o,r]=Rr.useState(!1),[s,a]=Rr.useState(5),c=cr.useContext(lr),l=c?.visible??!1,d=o||l,u=Rr.useRef(null),h="Data summary for "+(t??"physics chart");Rr.useEffect(()=>{d||a(5)},[d]);const p=Rr.useCallback(e=>{e.target===e.currentTarget&&(o||l||r(!0))},[o,l]),m=Rr.useCallback(e=>{l||u.current?.contains(e.relatedTarget)||r(!1)},[l]);if(!n.length)return(0,$r.jsx)("span",{id:i,tabIndex:-1,style:Pr});if(!d)return(0,$r.jsx)("div",{id:i,className:Br,role:"region","aria-label":h,tabIndex:-1,style:Pr,onFocus:p,children:(0,$r.jsxs)("button",{type:"button",onClick:()=>r(!0),children:["View data summary (",n.length," semantic items)"]})});const f=Math.min(s,n.length),y=n.slice(0,f),g=n.length-f;return(0,$r.jsxs)("div",{ref:u,id:i,className:Tr,role:"region","aria-label":h,tabIndex:-1,onBlur:m,style:Er,children:[(0,$r.jsx)("button",{type:"button",className:"semiotic-accessible-data-table-close","aria-label":"Close data summary",onClick:()=>{l&&c&&c.setVisible(!1),r(!1)},style:Or,children:"×"}),(0,$r.jsx)("div",{className:"semiotic-accessible-data-table-summary",role:"note",style:Nr,children:Qr(n)}),(0,$r.jsxs)("table",{className:"semiotic-accessible-data-table-table",role:"table","aria-label":"Semantic items for "+(t??"physics chart"),style:Wr,children:[(0,$r.jsx)("caption",{className:"semiotic-accessible-data-table-caption",style:zr,children:g>0?`First ${f} of ${n.length} semantic items`:`All ${n.length} semantic items`}),(0,$r.jsx)("thead",{children:(0,$r.jsxs)("tr",{children:[(0,$r.jsx)("th",{scope:"col",style:qr,children:"Item"}),(0,$r.jsx)("th",{scope:"col",style:qr,children:"Description"}),(0,$r.jsx)("th",{scope:"col",style:qr,children:"Group"}),(0,$r.jsx)("th",{scope:"col",style:qr,children:"Position"}),(0,$r.jsx)("th",{scope:"col",style:qr,children:"Data"})]})}),(0,$r.jsx)("tbody",{children:y.map((e,t)=>(0,$r.jsxs)("tr",{children:[(0,$r.jsx)("th",{scope:"row",style:Fr,children:e.label}),(0,$r.jsx)("td",{style:Fr,children:e.description??e.label}),(0,$r.jsx)("td",{style:Fr,children:e.group??""}),(0,$r.jsxs)("td",{style:Fr,children:[Math.round(e.x),", ",Math.round(e.y)]}),(0,$r.jsx)("td",{style:Fr,children:Kr(e)})]},e.id??`${e.label}-${t}`))})]}),g>0?(0,$r.jsxs)("button",{type:"button",className:"semiotic-accessible-data-table-show-more",onClick:()=>a(e=>e+25),style:Lr,children:["Show ",Math.min(25,g)," more"," ",1===g?"row":"rows"," (",g," remaining)"]}):null]})}Ur.ownsChrome=!0;var Jr=require("react/jsx-runtime"),es=[640,360],ts={top:0,right:0,bottom:0,left:0},ns=new Set(["ArrowRight","ArrowLeft","ArrowUp","ArrowDown","Home","End","PageUp","PageDown"]),is="StreamPhysicsFrame",os=(0,h.memo)((0,h.forwardRef)(function(e,t){const{accessibleTable:n=!0,annotations:i,onAnnotationActivate:o,autoPlaceAnnotations:r,background:s,backgroundGraphics:a,bodySemanticItemLimit:c=200,bodySemanticItems:l=!1,bodySemanticUpdateMs:d=200,bodyForces:f,bodyStyle:y,chartId:g,className:b,frameScheduler:x,clock:v,random:w,seed:k,color:M,config:I,controllers:S,continuous:A=!1,description:R,emphasis:P,chartMode:B,enableHover:T=!0,foregroundGraphics:E,hoverRadius:N=16,initialSpawns:O,initialSpawnPacing:W,legend:_,legendClickBehavior:G,legendHighlightedCategory:X,legendHoverBehavior:K,legendIsolatedCategories:Z,legendLayout:J,legendPosition:ee,margin:te,onClick:ne,onObservation:ie,onRegionEvent:oe,onSimulationExecutionChange:re,onBodyHover:se,onBodyPointerDown:ae,onSemanticItemActivate:ce,onSemanticItemFocus:le,onTick:de,opacity:ue,paused:he=!1,regionEffects:pe=[],responsiveHeight:me,responsiveWidth:fe,selectedBodyStyle:ye={stroke:"#111827",strokeWidth:2,opacity:1},selection:ge,semanticItems:be=[],simulationExecution:xe="auto",size:ve=es,stroke:we,strokeWidth:ke,summary:Se,suspendWhenHidden:je=!0,svgAnnotationRules:Ae,title:Ce,tooltipContent:Re,workerBodyThreshold:$e=Gn,renderBody:Pe,beforePaint:De,afterPaint:Be}=e,Te=u.useMemo(()=>({color:M,stroke:we,strokeWidth:ke,opacity:ue}),[M,ue,we,ke]),Ee=(0,h.useRef)(ie);Ee.current=ie;const Ne=(0,h.useRef)(g);Ne.current=g;const Oe=(0,h.useRef)(new Map),Qe=(0,h.useRef)(pe);Qe.current=pe;const Ze=(0,h.useRef)(f);Ze.current=f;const Je=(0,h.useRef)(de);Je.current=de;const et=u.useMemo(()=>Xo(S),[S]),tt=(0,h.useRef)(et);tt.current=et;const nt=A||!!et?.continuous,it=(0,h.useRef)(nt);it.current=nt;const ot=u.useMemo(()=>{if(!f&&!et?.bodyForce)return f;if(!et?.bodyForce)return f;if(!f)return et.bodyForce;const e=et.bodyForce;return t=>{const n="function"==typeof f?f(t):f,i="function"==typeof e?e(t):e;return n||i?{x:(n?.x??0)+(i?.x??0),y:(n?.y??0)+(i?.y??0)}:null}},[f,et]);Ze.current=ot;const rt=u.useMemo(()=>new Map(pe.map(e=>[br(e),e])),[pe]),st=u.useMemo(()=>new Map(pe.map(e=>[e.id,e])),[pe]),at=u.useMemo(()=>pe.map(kr).filter(e=>null!=e),[pe]),[ct,lt]=u.useState([]),dt=u.useMemo(()=>ct.length||at.length?[...be,...ct,...at]:be,[ct,at,be]),ut=u.useMemo(()=>Mr(pe),[pe]),ht=!!ot,pt=(0,h.useRef)(null),mt=(0,h.useRef)(v??Io);mt.current=v??Io;const ft=(0,h.useCallback)((e,t,n)=>{const i=pt.current;if(!i||!n)return!1;const o=i.readBodies().find(t=>t.id===e),r=vr(Oe.current.get(e));if(!o||!r)return!1;const s=wr(n,{body:o,region:t,regionState:r});return!(!s||!s.x&&!s.y||(i.applyImpulse(e,s.x??0,s.y??0),0))},[]),yt=(0,h.useCallback)((e,t,n)=>{if(!n.bodyId)return;const i=vr(Oe.current.get(n.bodyId));if(!i)return;const o={bodyId:n.bodyId,datum:n.datum,observation:n,region:t,regionState:i,type:e};"region-enter"===e?t.onEnter?.(o):t.onExit?.(o),oe?.(o)},[oe]),gt=(0,h.useCallback)(e=>{const t=e.sensorId?rt.get(e.sensorId):void 0;if(!t||!e.bodyId)return;const n=function(e,t){let n=e.get(t);return n||(n={activeRegionIds:new Set,attributes:{},charges:{},energy:0,regionIds:new Set},e.set(t,n)),n}(Oe.current,e.bodyId),i=pt.current?.readBodies().find(t=>t.id===e.bodyId),o=vr(n),r=i&&o?{body:i,region:t,regionState:o}:null;if("physics-proximity-enter"===e.type){if(n.activeRegionIds.add(t.id),n.regionIds.add(t.id),n.energy+=t.energyDelta??0,r){!function(e,t,n){const i="function"==typeof e.attributes?e.attributes(t):e.attributes;i&&(n.attributes={...n.attributes,...i})}(t,r,n);const e=function(e,t){return void 0!==e.charge?"function"==typeof e.charge?e.charge(t):e.charge:"charge-gate"===e.kind?1:void 0}(t,r);void 0!==e&&(n.charges[t.id]=e)}ft(e.bodyId,t,t.impulseOnEnter),yt("region-enter",t,e)}else"physics-proximity-exit"===e.type&&(n.activeRegionIds.delete(t.id),ft(e.bodyId,t,t.impulseOnExit),yt("region-exit",t,e))},[ft,yt,rt]),bt=u.useMemo(()=>{if(!i?.length)return[];const e=i.filter(e=>"barrier"===e.physics||"sensor"===e.physics);return e.length?function(e=[],t={}){const n=t.idPrefix?t.idPrefix+"-":"",i=[];for(const o of e){if("barrier"!==o.physics&&"sensor"!==o.physics)continue;const e=o.axis??t.defaultAxis??"x",r=_n(o,t),s=o.colliderId??`${n}${o.id}`;let a;if("x"===e){const e=Hn(o.x),n=Hn(o.y1)??Hn(t.plotBounds?.y)??Hn(o.y),i=Hn(o.y2)??(t.plotBounds?t.plotBounds.y+t.plotBounds.height:void 0)??Hn(o.y);if(null==e||null==n||null==i)continue;a={type:"segment",x1:e,y1:n,x2:e,y2:i,thickness:r}}else{const e=Hn(o.y),n=Hn(o.x1)??Hn(t.plotBounds?.x)??Hn(o.x),i=Hn(o.x2)??(t.plotBounds?t.plotBounds.x+t.plotBounds.width:void 0)??Hn(o.x);if(null==e||null==n||null==i)continue;a={type:"segment",x1:n,y1:e,x2:i,y2:e,thickness:r}}i.push({id:s,shape:a,sensor:"sensor"===o.physics,..."barrier"!==o.physics||null==o.restitution&&null==t.barrierRestitution?{}:{restitution:Hn(o.restitution)??Hn(t.barrierRestitution)},..."barrier"!==o.physics||null==o.friction&&null==t.barrierFriction?{}:{friction:Hn(o.friction)??Hn(t.barrierFriction)}})}return i}(e,{idPrefix:g?g+"-ann":"physics-ann",plotBounds:{x:0,y:0,width:ve?.[0]??es[0],height:ve?.[1]??es[1]}}):[]},[i,g,ve]),xt=u.useMemo(()=>{const e=void 0===k||void 0!==I?.kernel?.seed?I:{...I,kernel:{...I?.kernel,seed:k}},t=pe.flatMap(e=>[{id:br(e),sensor:!0,shape:e.shape,bodyFilter:e.bodyFilter,friction:e.friction,restitution:e.restitution},...xr(e)]),n=Object.fromEntries(pe.map(e=>[br(e),{binId:e.binId??e.id,enterType:"physics-proximity-enter",exitType:"physics-proximity-exit"}])),i=e?.observation,o=pe.length>0;return o||t.length>0||bt.length>0||null!=g||i?{...e,colliders:[...e?.colliders??[],...t,...bt],observation:{...i,chartId:g??i?.chartId,chartType:i?.chartType??is,sensors:{...i?.sensors??{},...n},onObservation:e=>{o&&gt(e),i?.onObservation?.(e)}}}:e},[bt,g,I,gt,pe,k]);if(!pt.current){const e=Mo(xt,O,W);e.setPaused(he),je&&e.setVisible(Ko()),pt.current=e}const vt=(0,h.useRef)(-1),wt=(0,h.useRef)(null),kt=(0,h.useRef)(!0),Mt=(0,er.useRef)(new sr("StreamPhysicsFrame")),It=(0,h.useRef)(""),St=(0,h.useId)().replace(/:/g,""),jt=(0,h.useRef)(!1),At=(0,h.useRef)(!1),Ct=(0,h.useRef)(0),Rt=(0,h.useRef)(!1),$t=(0,h.useRef)(null),Pt=(0,h.useRef)(!1),Dt=function(e){const t=C(),n=(0,m.useRef)(t);n.current=t;const[i,o]=$(e.sizeProp,e.responsiveWidth,e.responsiveHeight),r=!!e.title,s=!!e.legend&&"top"===e.legendPosition,a=(0,m.useMemo)(()=>function(e,t,n=!1){const i=n?t?58:34:t?36:0;return i>e.top?{...e,top:i}:e}({...e.marginDefault,...e.userMargin},r,s),[e.marginDefault,e.userMargin,r,s]),c=o[0]-a.left-a.right,l=o[1]-a.top-a.bottom,d=L(e.foregroundGraphics,o,a),u=L(e.backgroundGraphics,o,a),h=j(e=>e.theme),{transition:f,introEnabled:y}=function(e,t){if(!1===e)return{transition:void 0,introEnabled:!1};const n="undefined"!=typeof window&&window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;return{transition:e?!0===e?{duration:300}:{duration:e.duration??300,easing:"linear"===e.easing?"linear":"ease-out"}:t,introEnabled:!(n||!e||!0!==e&&!1===e.intro)}}(e.animate,e.transitionProp),g="semiotic-table-"+p.useId(),b=(0,m.useRef)(null);if(!b.current){const t=!e.suspendWhenHidden||"undefined"==typeof document||!document.hidden;b.current=new q({clock:e.clock,random:e.random,seed:e.seed,paused:e.paused,visible:t})}const x=b.current;x.configure({clock:e.clock,random:e.random,seed:e.seed});const v=(0,m.useRef)(null),w=(0,m.useRef)(e.frameScheduler??z);w.current=e.frameScheduler??z;const k=(0,m.useRef)(null),M=(0,m.useRef)(!1),I=(0,m.useRef)(()=>{}),S=(0,m.useCallback)(()=>{if(null!==v.current||M.current)return;const e=w.current;let t=!1,n=!1;const i=e.requestAnimationFrame(()=>{t=!0;const e=!n;e&&(M.current=!0),v.current=null,k.current=null;try{I.current()}finally{e&&(M.current=!1)}});n=!0,t||(v.current=i,k.current=e)},[]),A=(0,m.useCallback)(()=>{null!==v.current&&((k.current??w.current).cancelAnimationFrame(v.current),v.current=null,k.current=null)},[]);F(()=>{x.setPaused(!0===e.paused)},[x,e.paused]),(0,m.useEffect)(()=>{if(!e.suspendWhenHidden||"undefined"==typeof document)return void x.setVisible(!0);const t=()=>x.setVisible(!document.hidden);return t(),document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)},[x,e.suspendWhenHidden]),(0,m.useEffect)(()=>()=>{A()},[A]);const R=(0,m.useRef)(()=>{}),P=(0,m.useRef)(()=>{}),B=(0,m.useRef)(null),T=(0,m.useRef)(null),E=(0,m.useRef)(null),N=(0,m.useCallback)(()=>{const e=B.current;B.current=null,e&&R.current(e)},[]),O=(0,m.useCallback)(e=>{if(B.current={clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType},null===T.current){const e=w.current;let t=!1;const n=e.requestAnimationFrame(()=>{t=!0,T.current=null,E.current=null,N()});t||(T.current=n,E.current=e)}},[N]),W=(0,m.useCallback)(()=>{B.current=null,null!==T.current&&((E.current??w.current).cancelAnimationFrame(T.current),T.current=null,E.current=null),P.current()},[]);(0,m.useEffect)(()=>()=>{B.current=null,null!==T.current&&((E.current??w.current).cancelAnimationFrame(T.current),T.current=null,E.current=null)},[]);const Y=e.themeDirtyRef;return F(()=>{Y&&(D++,Y.current=!0,S())},[h,S,Y]),{reducedMotion:t,reducedMotionRef:n,responsiveRef:i,size:o,margin:a,adjustedWidth:c,adjustedHeight:l,resolvedForeground:d,resolvedBackground:u,currentTheme:h,transition:f,introEnabled:y,tableId:g,frameRuntime:x,rafRef:v,renderFnRef:I,scheduleRender:S,cancelRender:A,hoverHandlerRef:R,hoverLeaveRef:P,onPointerMove:O,onPointerLeave:W}}({sizeProp:ve,responsiveWidth:fe,responsiveHeight:me,userMargin:te,marginDefault:ts,foregroundGraphics:E,backgroundGraphics:a,frameScheduler:x,clock:v,random:w,seed:k,paused:he,suspendWhenHidden:je}),{margin:Bt,rafRef:Tt,reducedMotionRef:Et,renderFnRef:Nt,cancelRender:Ot,resolvedBackground:Wt,resolvedForeground:qt,responsiveRef:Ft,scheduleRender:zt,size:Lt,frameRuntime:Yt}=Dt,Ht=(0,h.useRef)(Yt.now);Ht.current=Yt.now;const _t=function(){const[e,t]=(0,Y.useState)(!1);return H(()=>{t(!0)},[]),e}(),Gt=V(),[Xt,Vt]=u.useState(null),[Ut,Kt]=u.useState(null),Qt=(0,h.useRef)(null),Zt=(0,h.useRef)(0),Jt=(0,h.useRef)(new Map),en=St+"-physics-live",tn=(0,h.useCallback)((e,t,n=!1)=>{if(!l)return void lt(e=>e.length?[]:e);const i=Ht.current();if(!n&&d>0&&d>i-Zt.current)return;Zt.current=i;const o=function(e,t,n,i){if(!n)return[];const o=Math.max(0,Math.floor(i));if(!o)return[];const r=[];for(let i=0;e.length>i&&o>r.length;i+=1){const o=e[i],s="function"==typeof n?n(o,{index:i,simulationState:t}):void 0;if(!1===s)continue;const a=_r(o);r.push({datum:o.datum??o,description:Xr(o),group:"body",label:Gr(o),...a,...s??{},bodyId:s?.bodyId??o.id,id:s?.id??"body:"+o.id,x:s?.x??o.x,y:s?.y??o.y})}return r}(e,t,l,c);lt(e=>function(e,t){if(e.length!==t.length)return!0;for(let n=0;e.length>n;n+=1){const i=e[n],o=t[n];if(i.id!==o.id||i.label!==o.label||i.description!==o.description||i.group!==o.group||i.bodyId!==o.bodyId||Math.round(i.x)!==Math.round(o.x)||Math.round(i.y)!==Math.round(o.y))return!0}return!1}(e,o)?o:e)},[c,l,d]),nn=(0,h.useCallback)(e=>{if(!dt.length)return;const t=Math.max(0,Math.min(e,dt.length-1));vt.current=t;const n=dt[t];if(Qt.current=n.bodyId??null,Vt(n),le?.(n),n.bodyId&&pt.current){const e=pt.current.readBodies().find(e=>e.id===n.bodyId);if(e){const t=Hr(e);Kt(t),se?.(e,t)}}},[dt,se,le]),on=(0,h.useCallback)(()=>{vt.current=-1,Qt.current=null,Vt(null),le?.(null)},[le]),rn=function({onObservationRef:e,chartIdRef:t,wallClockRef:n}){return(0,Cr.useCallback)((i,o)=>{const r=e.current;if(!r)return;const s={timestamp:n.current(),chartType:"StreamPhysicsFrame",chartId:t.current};r("hover"===i||"click"===i?{...s,type:i,datum:o?.datum??{},x:o?.x??0,y:o?.y??0}:"focus"===i?{...s,type:i,datum:o?.datum??{},inputType:"touch"===o?.inputType?"pointer":o?.inputType??"keyboard"}:"activate"===i?{...s,type:i,datum:o?.datum??{},inputType:o?.inputType??"keyboard"}:{...s,type:i})},[t,e,n])}({onObservationRef:Ee,chartIdRef:Ne,wallClockRef:mt}),sn=(0,h.useCallback)(()=>{Kt(e=>e?(se?.(null,null),rn("hover-end"),null):e)},[rn,se]),an=(0,h.useCallback)(e=>{if(!T||!pt.current)return;const t=e.currentTarget.getBoundingClientRect(),n=pt.current.hitTest(e.clientX-t.left,e.clientY-t.top,N);if(!n)return void sn();const i=Hr(n);Kt(e=>e&&e.id===i.id&&e.x===i.x&&e.y===i.y?e:(se?.(n,i),rn("hover",{datum:n.datum,x:n.x,y:n.y}),i))},[sn,rn,T,N,se]),cn=(0,h.useCallback)(e=>{on();const t=pt.current,n=e.currentTarget.getBoundingClientRect(),i=e.clientX-n.left,o=e.clientY-n.top,r=t?t.hitTest(i,o,Math.max(16,N)):null;ae?.(r,e),r?(rn("click",{datum:r.datum,x:r.x,y:r.y}),rn("activate",{datum:r.datum,inputType:"touch"===e.pointerType?"touch":"pointer"}),ne?.(r.datum??null,{x:r.x,y:r.y,body:r})):(rn("click-end"),ne?.(null,{x:i,y:o,body:null}),sn())},[sn,on,rn,N,ae,ne]);(0,h.useEffect)(()=>{if(!dt.length)return void on();const e=vt.current;if(dt.length>e){if(e>=0){const t=dt[e];if(Qt.current=t.bodyId??null,Vt(e=>null!=e&&e.id===t.id&&Math.round(e.x)===Math.round(t.x)&&Math.round(e.y)===Math.round(t.y)?e:t),t.bodyId&&pt.current){const e=pt.current.readBodies().find(e=>e.id===t.bodyId);if(e){const t=Hr(e);Kt(e=>e?.id===t.id&&Math.round(e.x)===Math.round(t.x)&&Math.round(e.y)===Math.round(t.y)?e:t)}}}}else nn(dt.length-1)},[dt,on,nn]),(0,h.useEffect)(()=>{T||sn()},[sn,T]);const ln=(0,h.useCallback)(e=>{if(function(e){const t=e.target;return t instanceof Element&&t!==e.currentTarget&&null!=t.closest("button, a[href], input, select, textarea, summary, [contenteditable='true'], [role='button'], [role='link'], [role='checkbox'], [role='radio'], [role='switch']")}(e))return;if(!dt.length)return;if("Escape"===e.key)return e.preventDefault(),void on();if(("Enter"===e.key||" "===e.key)&&vt.current>=0){e.preventDefault();const t=dt[vt.current];return rn("activate",{datum:t.datum??{id:t.id,label:t.label},inputType:"keyboard"}),void ce?.(t)}if(!ns.has(e.key))return;e.preventDefault();const t=vt.current;if(0>t){nn(0);const e=dt[0];return void rn("focus",{datum:e.datum??{id:e.id,label:e.label},inputType:"keyboard"})}const n=Math.max(1,Math.floor(.1*dt.length));let i=t;if("Home"===e.key?i=0:"End"===e.key?i=dt.length-1:"PageDown"===e.key?i=Math.min(dt.length-1,t+n):"PageUp"===e.key?i=Math.max(0,t-n):"ArrowRight"===e.key||"ArrowDown"===e.key?i=Math.min(dt.length-1,t+1):"ArrowLeft"!==e.key&&"ArrowUp"!==e.key||(i=Math.max(0,t-1)),nn(i),i!==t){const e=dt[i];rn("focus",{datum:e.datum??{id:e.id,label:e.label},inputType:"keyboard"})}},[on,rn,nn,ce,dt]),[dn,un]=u.useState([]),hn=(0,h.useRef)(0),pn=!!i?.length&&i.some(e=>null!=e.pointId||null!=e.bodyId||"latest"===e.anchor),{canvasRef:mn}=function(e,t){return function(e){const{cancelRender:t,dirtyRef:n,frameRuntime:i,manageFrameRuntime:o,scheduleRender:r}=e,s=(0,U.useRef)(null),a=(0,U.useRef)(null),c=(0,U.useRef)(!1);return function(e){const{hydrated:t,wasHydratingFromSSR:n,storeRef:i,dirtyRef:o,renderFnRef:r,cancelRender:s,cleanup:a}=e;H(()=>{const e=i.current;t&&n&&e?.cancelIntroAnimation?.(),!n&&e?.sceneNodes&&e.sceneNodes.length>0&&e?.markStylePaintPending?e.markStylePaintPending():o.current=!0,s?.(),r.current()},[t,n]);const c=(0,Y.useRef)(a);c.current=a,(0,Y.useEffect)(()=>()=>c.current?.(),[])}({hydrated:e.hydrated,wasHydratingFromSSR:e.wasHydratingFromSSR,storeRef:e.storeRef,dirtyRef:e.dirtyRef,renderFnRef:e.renderFnRef,cancelRender:e.cancelRender,cleanup:e.cleanup}),(0,U.useEffect)(()=>{if(!1!==o)return i.subscribe(()=>{i.isActive?(n.current=!0,r()):t()})},[t,n,i,o,r]),(0,U.useEffect)(()=>{!c.current&&(c.current=!0,e.skipInitialCanvasPaintInvalidation)||(e.dirtyRef.current=!0,e.scheduleRender())},e.canvasPaintDependencies),{canvasRef:s,interactionCanvasRef:a}}({...t,renderFnRef:e.renderFnRef,scheduleRender:e.scheduleRender,cancelRender:e.cancelRender,frameRuntime:e.frameRuntime})}(Dt,{hydrated:_t,wasHydratingFromSSR:Gt,storeRef:pt,dirtyRef:kt,manageFrameRuntime:!1,skipInitialCanvasPaintInvalidation:!0,canvasPaintDependencies:[s,a,zt]}),fn=(0,h.useCallback)(()=>{const e=mn.current,t=pt.current;if(!e||!t)return;const n=Mt.current.beforeCompute(t.getLastUpdateResult(),!1),i=function(){if("undefined"==typeof window)return 1;const e=window.devicePixelRatio||1,t=function(){if("undefined"==typeof window)return!1;const e="function"==typeof window.matchMedia&&window.matchMedia("(pointer: coarse)").matches,t=768>Math.min(window.innerWidth||1/0,window.innerHeight||1/0);return e||t}()?2:3;return Math.max(1,Math.min(e,t))}(),o=function(e,t,n,i){const o=e.getContext("2d");if(!o)return null;const r=Math.round(t[0]*i),s=Math.round(t[1]*i),a=r/t[0],c=s/t[1],l=t[0]+"px",d=t[1]+"px";return e.style.width!==l&&(e.style.width=l),e.style.height!==d&&(e.style.height=d),e.width===r&&e.height===s||(e.width=r,e.height=s),o.setTransform(a,0,0,c,0,0),o.translate(n.left,n.top),o}(e,Lt,Bt,i);if(!o)return void Mt.current.afterCompute(n,!1,!1);const r=function(e){const t=Ue(e,He),n=Ue(e,ze),i=Ue(e,Ve),o=Ue(e,_e),r=Ue(e,Fe),s=Ue(e,qe),a=Ue(e,Ge),c=Ue(e,Xe),l=Ue(e,Le),d=Ue(e,Ye);return{annotationBackground:Ke(s,.94),annotationStroke:r,annotationText:a,background:s,border:r,closedWindowFill:Ke(n,.08),closedWindowStroke:Ke(n,.55),danger:n,focus:l,grid:d,gutterFill:Ke(c,.14),lateFill:i,openWindowFill:Ke(t,.07),openWindowStroke:Ke(t,.3),primary:t,selectedFill:i,selectedStroke:l,success:o,text:a,textSecondary:c,warning:i}}(o);o.clearRect(-Bt.left,-Bt.top,Lt[0],Lt[1]),a||"transparent"===s||(o.fillStyle=s??r.background,o.fillRect(-Bt.left,-Bt.top,Lt[0],Lt[1]));const c=t.snapshot(),l=t.readBodies();if(tn(l,c.simulationState),pn){const e=Ht.current();if(e-hn.current>=100){hn.current=e;const t=Fn(l);un(e=>e.length===t.length&&e.every((e,n)=>e.pointId===t[n].pointId&&Math.round(e.x)===Math.round(t[n].x)&&Math.round(e.y)===Math.round(t[n].y))?e:t)}}De&&(o.save(),De(o,l),o.restore());for(const e of l){const t=Oe.current.get(e.id),n=t?Array.from(t.activeRegionIds).map(e=>st.get(e)).filter(e=>null!=e):[],i=Ar(e,c.simulationState,y,ye,ge,vr(t),n,r.primary,r.text,Te);Pe?(o.save(),Pe(o,e,i),o.restore()):yr(o,e,i)}Be&&(o.save(),Be(o,l),o.restore()),function(e,t,n){let i=!1;for(const[o,r]of t){const s=Math.min(1,Math.max(0,(n-r.startedAt)/r.durationMs));if(s>=1){t.delete(o);continue}i=!0;const a=1-Math.pow(1-s,3),{body:c}=r,l=r.scale>0?r.scale:1,d=(r.radius+28*a)*l,u=1-s;e.save(),e.globalAlpha*=u,e.strokeStyle=r.color,e.fillStyle=r.color,e.lineWidth=Math.max(.5,(2.4*u+.4)*l),e.beginPath(),e.arc(c.x,c.y,d,0,2*Math.PI),e.stroke(),e.globalAlpha*=.18,e.beginPath(),e.arc(c.x,c.y,.52*d,0,2*Math.PI),e.fill(),e.restore(),e.save(),e.globalAlpha*=u,e.strokeStyle=r.color,e.lineWidth=Math.max(.5,1.8*l);for(let t=0;8>t;t+=1){const n=t*(Math.PI/4)+1.4*s,i=(r.radius+5+12*a)*l,o=(r.radius+12+34*a)*l;e.beginPath(),e.moveTo(c.x+Math.cos(n)*i,c.y+Math.sin(n)*i),e.lineTo(c.x+Math.cos(n)*o,c.y+Math.sin(n)*o),e.stroke()}e.restore()}}(o,Jt.current,Ht.current()),Mt.current.afterCompute(n,!0,!1),kt.current=!1},[mn,Mt,Lt,Bt,a,s,tn,pn,De,Be,y,ye,ge,Te,Pe,st]),yn=(0,h.useCallback)((e,t)=>{const n=pt.current,i=`${xe}:${e}:${t??""}`;It.current!==i&&(It.current=i,re?.({execution:e,liveBodies:n?.liveBodyCount()??0,queuedBodies:n?.queueSize()??0,reason:t,requested:xe}))},[re,xe]),gn=(0,h.useCallback)((e,t=!0)=>{Ct.current+=1,jt.current=!1,Rt.current=!1,Pt.current=!1,$t.current?.terminate(),$t.current=null,t&&yn("sync",e)},[yn]),bn=(0,h.useCallback)(()=>_t?"undefined"==typeof window||"undefined"==typeof Worker?"worker unavailable":ut?"runtime region effects require sync":ht?"body forces require sync":et?"physics controllers require sync":function(e){return!e||!e.engine&&Vn(e.sediment)&&(!(t=e.colliders)||t.every(e=>{const t=e.bodyFilter;return!t||"function"!=typeof t}));var t}(xt??{})?Qn(W)?At.current?"worker fallback":null:"spawn pacing is not worker-cloneable":"config is not worker-cloneable":"hydrating",[xt,et,ht,ut,_t,W]),xn=(0,h.useCallback)(()=>{const e=pt.current,t=bn();if(!e||t)return{reason:t,useWorker:!1};const n=e.liveBodyCount(),i=e.queueSize(),o=function(e,t,n=0,i=Gn){return"sync"!==e&&("worker"===e||t+n>=i)}(xe,n,i,$e);return{reason:o?"worker"===xe?"forced worker":"body threshold":"below threshold",useWorker:o}},[xe,$e,bn]),vn=(0,h.useCallback)(e=>{const t=pt.current;return t&&e.snapshot?(t.restore(e.snapshot),kt.current=!0,t):t},[]),wn=(0,h.useCallback)((e,t=!0)=>{const n=vn(e);if(!n)return;t&&de?.(e.result,n.controls()),fn();const i=n.snapshot();!e.result.shouldContinue&&Jt.current.size<=0||i.paused||!i.visible||Et.current||zt()},[vn,de,fn,Et,zt]),kn=(0,h.useCallback)(e=>{At.current=!0,gn("worker failed: "+((e instanceof Error?e.message:e+"")||"unknown error"))},[gn]),Mn=(0,h.useCallback)(()=>{const e=pt.current;if(!e)return!1;const t=xn();if(!t.useWorker)return jt.current||Pt.current?gn(t.reason??"sync fallback"):yn("sync",t.reason??"sync"),!1;if(jt.current||Pt.current)return!0;const n=$t.current??new ti;$t.current=n,Pt.current=!0;const i=Ct.current+1;return Ct.current=i,n.initFromSnapshot(xt??{},e.snapshot()).then(e=>{if(Ct.current!==i)return;Pt.current=!1,jt.current=!0,At.current=!1,vn(e),yn("worker",t.reason??"worker"),fn();const n=pt.current?.snapshot();e.result.shouldContinue&&n&&!n.paused&&n.visible&&!Et.current&&(wt.current=null,zt())}).catch(e=>{Ct.current===i&&kn(e)}),!0},[vn,xt,kn,fn,Et,yn,zt,gn,xn]),In=(0,h.useCallback)(e=>"frame"===e.type||"removed"===e.type?e.frame:null,[]),Sn=(0,h.useCallback)((e,t=!0)=>{const n=$t.current;if(!n||!jt.current)return;const i=Ct.current;n.request(e).then(e=>{if(Ct.current!==i)return;const n=In(e);n&&wn(n,t)}).catch(kn)},[wn,In,kn]),jn=(0,h.useCallback)(()=>{const e=pt.current;if(!e)return;const t=Mn(),n=e.snapshot(),i=nt||ht||ut||!!et;n.paused||!n.visible||!e.hasPendingWork()&&!i||Et.current?Nt.current():t&&Pt.current||zt()},[et,nt,ht,ut,Et,Nt,zt,Mn]),An=(0,h.useCallback)(()=>{Ot(),Tt.current=null;const e=pt.current;if(!e)return;if(jt.current&&$t.current){if(Rt.current)return;let t=0;if(!Et.current){const e=Ht.current();t=null!==wt.current?(e-wt.current)/1e3:0,wt.current=e}const n=$t.current,i=Ct.current;return Rt.current=!0,void(Et.current?n.settle():n.tick(t)).then(e=>{Rt.current=!1,Ct.current===i&&wn(e)}).catch(n=>{if(Rt.current=!1,Ct.current!==i)return;kn(n);const o=Et.current?e.settleWithObservations():e.tick(t);jr({store:e,result:o,regionEffects:Qe.current,regionState:Oe.current,bodyForces:Ze.current,composed:tt.current,onTick:Je.current}),fn()})}let t;if(Et.current)t=e.settleWithObservations();else{const n=Ht.current(),i=null!==wt.current?(n-wt.current)/1e3:0;wt.current=n,t=e.tick(i)}const n=tt.current,{regionEffectsApplied:i,bodyForcesApplied:o,snapshot:r}=jr({store:e,result:t,regionEffects:Qe.current,regionState:Oe.current,bodyForces:Ze.current,composed:n,onTick:Je.current});fn(),(it.current||t.shouldContinue||i||o||n||Jt.current.size>0)&&!r.paused&&r.visible&&!Et.current&&zt()},[wn,kn,fn,Ot,zt,Et,Tt]);Nt.current=An,(0,h.useEffect)(()=>{At.current=!1,(jt.current||Pt.current)&&gn("config changed",!1),pt.current?.updateConfig(xt??{}),jn()},[xt,gn]),(0,h.useEffect)(()=>{At.current=!1,jn()},[_t,xe,$e]),function({cancelRender:e,frameRuntime:t,lastFrameTimeRef:n,paused:i,postWorkerCommand:o,requestRender:r,storeRef:s,suspendWhenHidden:a}){const c=(0,Uo.useRef)(o);c.current=o;const l=(0,Uo.useRef)(r);l.current=r,(0,Uo.useEffect)(()=>{const o=s.current;o&&(t.setPaused(i),o.setPaused(i),i&&(n.current=null,e()),c.current({type:"setPaused",paused:i},!1),l.current())},[e,t,i]),(0,Uo.useEffect)(()=>{if(!a){const e=s.current;return t.setVisible(!0),void(e&&!e.snapshot().visible&&(e.setVisible(!0),c.current({type:"setVisible",visible:!0},!1),l.current()))}if("undefined"==typeof document)return;const i=()=>{const i=s.current;if(!i)return;const o=Ko();t.setVisible(o),i.setVisible(o),o||(n.current=null,e()),c.current({type:"setVisible",visible:o},!1),l.current()};return i(),document.addEventListener("visibilitychange",i),()=>document.removeEventListener("visibilitychange",i)},[e,t,a])}({cancelRender:Ot,frameRuntime:Yt,lastFrameTimeRef:wt,paused:he,postWorkerCommand:Sn,requestRender:jn,storeRef:pt,suspendWhenHidden:je}),(0,h.useEffect)(()=>()=>gn("unmount",!1),[gn]),(0,h.useEffect)(()=>{fn()},[fn]),(0,h.useImperativeHandle)(t,()=>({...pt.current.controls(),applyImpulse:(e,t,n)=>{pt.current.applyImpulse(e,t,n),Sn({type:"applyImpulse",id:e,ix:t,iy:n}),jn()},clear:()=>{pt.current.clear(),Oe.current.clear(),Jt.current.clear(),Sn({type:"clear"}),jn()},clearRegionState:e=>{e?Oe.current.delete(e):Oe.current.clear(),jn()},getData:()=>pt.current.readBodies(),getRegionState:e=>e?vr(Oe.current.get(e)):function(e){const t={};return e.forEach((e,n)=>{const i=vr(e);i&&(t[n]=i)}),t}(Oe.current),getStore:()=>pt.current,pause:()=>{Yt.setPaused(!0),wt.current=null,Ot(),pt.current.setPaused(!0),Sn({type:"setPaused",paused:!0},!1),jn()},push:(e,t)=>{pt.current.enqueue(e,t),Qn(t)?Sn({type:"enqueue",spawns:[e],pacing:t}):(jt.current||Pt.current)&&gn("spawn pacing is not worker-cloneable"),jn()},pushMany:(e,t)=>{pt.current.enqueue(e,t),Qn(t)?Sn({type:"enqueue",spawns:e,pacing:t}):(jt.current||Pt.current)&&gn("spawn pacing is not worker-cloneable"),jn()},popBodies:(e,t={})=>{const n=pt.current,i=new Map(n.readBodies().map(e=>[e.id,e])),o=n.remove(e),r=Ht.current();for(const e of o){const n=i.get(e);n&&(Oe.current.delete(e),Jt.current.set(e,{body:n,color:t.color??"#f59e0b",durationMs:Math.max(120,t.durationMs??520),radius:t.radius??gr(n),scale:null!=t.scale&&t.scale>0?t.scale:1,startedAt:r}),Qt.current===e&&(Qt.current=null,Vt(null)),Kt(t=>t?.id===e?null:t))}return o.length&&(Sn({type:"remove",ids:o}),jn()),o},remove:e=>{const t=pt.current.remove(e);for(const t of e)Oe.current.delete(t);return Sn({type:"remove",ids:e}),jn(),t},restore:e=>{pt.current.restore(e),Oe.current.clear(),Jt.current.clear(),Sn({type:"restore",snapshot:e},!1),jn()},resume:()=>{Yt.setPaused(!1),wt.current=null,pt.current.setPaused(!1),Sn({type:"setPaused",paused:!1},!1),jn()},settle:e=>{const t=pt.current.settle(e);return Sn({type:"settle",maxSteps:e}),jn(),t},settleWithObservations:e=>{const t=pt.current.settleWithObservations(e);return Sn({type:"settle",maxSteps:e}),jn(),t},step:e=>{const t=pt.current,n=t.tick(e);return jr({store:t,result:n,regionEffects:Qe.current,regionState:Oe.current,bodyForces:Ze.current,composed:tt.current,onTick:Je.current}),Sn({type:"tick",deltaSeconds:e}),fn(),n}}),[Ot,Yt,fn,Sn,jn,gn]);const Cn=Ie||!_t&&Gt,Rn=["stream-physics-frame",B?"stream-physics-frame--mode-"+B:null,P?"stream-physics-frame--emphasis-"+P:null,b].filter(Boolean).join(" "),$n=R??("string"==typeof Ce?Ce:void 0)??"Physics chart",Pn=St+"-physics-table",Dn=Math.max(1,Lt[0]-Bt.left-Bt.right),Bn=Math.max(1,Lt[1]-Bt.top-Bt.bottom),Tn=T&&Ut?Re?Re(Ut):(0,Jr.jsx)(Ur,{hover:Ut}):null,En=Tn&&Ut?(0,Jr.jsx)(We,{x:Ut.x-Bt.left,y:Ut.y-Bt.top,containerWidth:Math.max(1,Lt[0]-Bt.left-Bt.right),containerHeight:Math.max(1,Lt[1]-Bt.top-Bt.bottom),margin:Bt,className:"stream-physics-tooltip",children:Tn}):null;if(Cn){const e=pt.current??Mo(xt,O,W),t="string"==typeof Ce?Ce:void 0,{svg:n}=function(e,t={}){const{width:n=640,height:i=360,title:o,description:r,background:s,backgroundGraphics:a,className:c,foregroundGraphics:l,idPrefix:d="physics",margin:u,renderBodySVG:h,...p}=t,m=$o(e,p),f={...Do,...u},y=[n,i],g=Bo(a,y,f),b=Bo(l,y,f),x=function(e){const t=e.replace(/[^A-Za-z0-9_-]/g,"_");return!t||/^\d/.test(t)?"physics-"+t:t}(d),v=o?x+"-title":void 0,w=r?x+"-desc":void 0,k=[v,w].filter(Boolean).join(" ")||void 0;return{svg:So.renderToStaticMarkup((0,Po.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",className:c??"stream-physics-frame",width:n,height:i,viewBox:`0 0 ${n} ${i}`,role:"img","aria-labelledby":k,children:[o&&(0,Po.jsx)("title",{id:v,children:o}),r&&(0,Po.jsx)("desc",{id:w,children:r}),!a&&s&&"transparent"!==s?(0,Po.jsx)("rect",{x:0,y:0,width:n,height:i,fill:s}):null,g,(0,Po.jsx)("g",{id:x+"-data-area",children:m.sceneNodes.map((e,t)=>{const n=m.bodies[t];return(n&&h?h(n,e.style??{},t,x):void 0)??Me(e,t,x)})}),b]})),scene:m,evidence:m.evidence}}(e,{width:Lt[0],height:Lt[1],title:t,description:R,background:a||"transparent"===s?void 0:s,backgroundGraphics:Wt,className:"stream-physics-frame__svg",foregroundGraphics:qt,idPrefix:"physics-"+St,margin:Bt});return(0,Jr.jsxs)("div",{ref:Ft,className:Rn,"data-semiotic-mode":B,role:"img","aria-label":$n,style:{width:Lt[0],height:Lt[1]},children:[(0,Jr.jsx)(mr,{summary:Se}),(0,Jr.jsx)("div",{dangerouslySetInnerHTML:{__html:n}})]})}return(0,Jr.jsxs)("div",{ref:Ft,className:Rn,"data-semiotic-mode":B,role:"group","aria-label":$n,"aria-describedby":Xt?en:void 0,tabIndex:0,style:{position:"relative",width:Lt[0],height:Lt[1]},onKeyDown:ln,children:["production"!==process.env.NODE_ENV&&pt.current&&(0,Jr.jsx)(ar,{store:pt.current,diagnostics:Mt.current}),n?(0,Jr.jsx)(fr,{tableId:Pn}):null,n?(0,Jr.jsx)(Zr,{chartTitle:"string"==typeof Ce?Ce:$n,items:dt,tableId:Pn}):null,(0,Jr.jsx)(mr,{summary:Se}),(0,Jr.jsx)(hr,{hoverPoint:Ut}),(0,Jr.jsx)("div",{id:en,"aria-live":"polite","aria-atomic":"true",style:Pr,children:Xt?Xt.description??Xt.label:""}),(0,Jr.jsxs)("div",{role:"img","aria-label":$n,style:{position:"relative",width:"100%",height:"100%"},children:[(0,Jr.jsx)(Q,{size:Lt,margin:Bt,children:Wt}),(0,Jr.jsx)("canvas",{ref:mn,width:Lt[0],height:Lt[1],"aria-hidden":"true",style:{position:"absolute",left:0,top:0,display:"block"},onPointerDown:cn,onPointerMove:T?an:void 0,onPointerLeave:T?sn:void 0}),qt,(0,Jr.jsx)(Yn,{width:Dn,height:Bn,totalWidth:Lt[0],totalHeight:Lt[1],margin:Bt,title:Ce,legend:_,legendPosition:ee,legendLayout:J,legendHoverBehavior:K,legendClickBehavior:G,legendHighlightedCategory:X,legendIsolatedCategories:Z,pointNodes:dn,annotations:i,onAnnotationActivate:o,onObservation:ie,chartId:g,chartType:is,autoPlaceAnnotations:r,svgAnnotationRules:Ae}),(0,Jr.jsx)(Jo,{active:null!=Xt,hoverPoint:Xt?{x:Xt.x,y:Xt.y}:null,margin:Bt,size:Lt,shape:Xt?.shape,width:Xt?.width,height:Xt?.height,pathData:Xt?.pathData}),En]})]})}));os.displayName="StreamPhysicsFrame";var rs=os;function ss(e){if(null==e)return()=>{};const t="function"==typeof e?e:t=>t[e];return e=>as(t(e))}function as(e){if("number"==typeof e)return Number.isFinite(e)?e:void 0;if("string"==typeof e&&""!==e.trim()){const t=Number(e);return Number.isFinite(t)?t:void 0}}function cs(e,t,n){const i=null!=e.axis?n[e.axis]:null!=e.field?t[e.field]:n.value;if(void 0!==e.eq&&i!==e.eq)return!1;if(void 0!==e.ne&&i===e.ne)return!1;if(void 0!==e.in&&!e.in.includes(i))return!1;if(void 0===e.gt&&void 0===e.gte&&void 0===e.lt&&void 0===e.lte&&void 0===e.within&&void 0===e.outside)return!0;const o=as(i);if(void 0===o)return!1;if(void 0!==e.gt&&e.gt>=o)return!1;if(void 0!==e.gte&&e.gte>o)return!1;if(void 0!==e.lt&&o>=e.lt)return!1;if(void 0!==e.lte&&o>e.lte)return!1;if(void 0!==e.within){const[t,n]=e.within;if(t>o||o>n)return!1}if(void 0!==e.outside){const[t,n]=e.outside;if(o>=t&&n>=o)return!1}return!0}function ls(e,t,n){const i=e.when;return void 0===i||!0===i||!1!==i&&("function"==typeof i?i(t,n):cs(i,t,n))}function ds(e,t,n){if(!t||0===t.length)return{};let i={};for(const o of t){if(!ls(o,e,n))continue;const t="function"==typeof o.style?o.style(e,n):o.style;t&&(i={...i,...t})}return i}function us(e,t,n,i=e=>e){const o=e??(()=>({}));return t&&0!==t.length?(e,r)=>{const s=i(e),a={...o(e,r)};return Object.assign(a,ds(s,t,n(s,r))),a}:o}function hs(e){const[t,n]=e,i=160>t||116>n,o=i?Math.min(12,Math.max(2,.08*t)):32,r=i?Math.min(8,Math.max(2,.12*n)):24,s=i?r:34;return{width:t,height:n,plot:{x:o,y:r,width:Math.max(1,t-2*o),height:Math.max(1,n-r-s)}}}function ps(e){const t=(e??"")+"";if(!t)return"#4e79a7";const n=["#4e79a7","#59a14f","#e15759","#f28e2b","#76b7b2","#edc948","#b07aa1","#ff9da7"];let i=0;for(let e=0;t.length>e;e+=1)i=31*i+t.charCodeAt(e)>>>0;return n[i%n.length]}function ms(e,t="#4e79a7",n){const i=n?.styleRules,o=!!i&&i.length>0,r=o?ss(n?.valueAccessor):void 0;return n=>{const s=n.datum,a=s&&e?"function"==typeof e?e(s,0):s[e]:void 0,c={fill:null==a?t:ps(a),stroke:"#111827",strokeWidth:1,opacity:.9};return o&&s&&Object.assign(c,ds(s,i,{value:r?r(s):void 0,category:null==a?void 0:a+""})),c}}function fs(e,t,n,i){return{fixedDt:1/120,maxSubsteps:8,colliders:t,observation:{chartType:n},kernel:{seed:e,gravity:{x:0,y:760},cellSize:36,collisionIterations:6,velocityDamping:.995,restitution:.08,friction:.4,sleepSpeed:8,sleepAfter:.6,...i}}}function ys(e,t,n){if(!e.length)return[];const i=hs(t),o=i.plot.width/Math.max(1,e.length),r=Math.max(1,...e.map(e=>e.value)),s=.62*i.plot.height,a=i.plot.y+i.plot.height;return e.map((e,t)=>{const c=Math.max(8,e.value/r*s),l=`${n} ${e.label}: ${e.value}${null==e.secondary?"":`, ${e.secondary} secondary`}`;return{id:`${n}-${e.label}`,label:l,description:l,datum:e,x:i.plot.x+(t+.5)*o,y:a-c/2,shape:"rect",width:Math.max(12,.58*o),height:c,group:n}})}function gs(e,t,n){return"function"==typeof n?n(e,t):e[n]}function bs(e){if(e instanceof Date){const t=e.getTime();return Number.isFinite(t)?t:null}const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:null}function xs(e,t,n){return Math.max(t,Math.min(n,e))}function vs(e,t){const n=bs(e);return null!=n&&n>0?n:t}function ws(e){return((e??"unknown")+"").trim().replace(/[^A-Za-z0-9_-]+/g,"_")||"unknown"}function ks(e){let t=e>>>0;return()=>{t+=1831565813;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}var Ms=require("d3-scale");function Is(e){const{data:t,valueAccessor:n,bins:i,ballRadius:o,seed:r,size:s,valueExtent:a}=e,c=hs(s),l=t.map((e,t)=>bs(gs(e,t,n))).filter(e=>null!=e),d=function(e){if(!e)return;const t=bs(e[0]),n=bs(e[1]);return null!=t&&null!=n?t>n?[n,t]:[t,n]:void 0}(a),u=d?.[0]??(l.length?Math.min(...l):0),h=d?.[1]??(l.length?Math.max(...l):1),p=h===u?1:h-u,m=(0,Ms.scaleLinear)().domain([0,i]).range([c.plot.x,c.plot.x+c.plot.width]),f=Array.from({length:i},()=>0),y=[];t.forEach((e,t)=>{const r=bs(gs(e,t,n));if(null==r)return;const s=Math.max(0,Math.min(i-1,Math.floor((r-u)/p*i)));f[s]+=1,y.push({id:(e.id??"galton-"+t)+"",x:m(s+.5),y:c.plot.y+o+2,vx:8*(t%5-2),vy:0,mass:1,shape:{type:"circle",radius:o},datum:{...e,value:r,bin:s}})});const g=c.plot.y+c.plot.height;return{config:fs(r,[...Ji({x:c.plot.x,y:c.plot.y,width:c.plot.width,height:c.plot.height},{idPrefix:"galton",wallThickness:20,floorThickness:20}),...eo({idPrefix:"galton-bin",count:i,domainStart:0,domainStep:1,xScale:m,yTop:c.plot.y-400,yBottom:g,wallThickness:6})],"GaltonBoardChart"),initialSpawns:y,initialSpawnPacing:{pacing:{ratePerSec:55}},projectionRows:f.map((e,t)=>({label:t+1+"",value:e})),metadata:{kind:"galton-board",bins:i,plot:c.plot,valueExtent:[u,h]}}}var Ss=require("d3-scale");function js(e){const{count:t,idPrefix:n,wallThickness:i,xScale:o,yBottom:r,yTop:s,yTopForIndex:a}=e;return Array.from({length:t+1},(e,t)=>{const c=Math.min(r-1,a?.(t)??s),l=Math.max(1,r-c);return{id:`${n}-wall-${t}`,shape:{type:"aabb",x:o(t),y:c+l/2,width:i,height:l}}})}function As(e){const{data:t,timeAccessor:n,arrivalAccessor:i,windows:o,watermark:r,ballRadius:s,seed:a,size:c,timeExtent:l,timeScale:d=1}=e,u=hs(c),h=t.map((e,t)=>bs(gs(e,t,n))).filter(e=>null!=e),p=bs(l?.[0]),m=bs(l?.[1]),f=h.length?Math.min(...h):0,y=h.length?Math.max(...h):f+o.size,g=Math.min(p??f,f),b=Math.max(m??y,y),x=Math.floor(g/o.size)*o.size,v=Math.max(1,Math.ceil((b-x+o.size)/o.size)),w=h.length?Math.max(...h):0,k="function"==typeof r?r(w):bs(r?.value)??w-(r?.delay??o.size),M=Math.max(0,Math.min(v,Array.from({length:v},(e,t)=>t).reduce((e,t)=>x+(t+1)*o.size>k?e:e+1,0))),I=function(e,t){const n=Math.max(5*t,Math.min(92,.13*e.plot.width));return{gutter:{x:e.plot.x,y:e.plot.y,width:n,height:e.plot.height},windowPlot:{x:e.plot.x+n,y:e.plot.y,width:Math.max(40,e.plot.width-n),height:e.plot.height},wallTop:e.plot.y+.48*e.plot.height}}(u,s),S=x+v*o.size,j=(0,Ss.scaleLinear)().domain([x,S]).range([I.windowPlot.x,I.windowPlot.x+I.windowPlot.width]),A=Array.from({length:v},()=>({value:0,secondary:0})),C=[];t.forEach((e,t)=>{const r=bs(gs(e,t,n));if(null==r)return;const a=bs(gs(e,t,i))??r,c=Math.max(0,Math.min(v-1,Math.floor((r-x)/o.size))),l=k>=x+(c+1)*o.size;A[c].value+=l?0:1,A[c].secondary+=l?1:0,C.push({id:(e.id??"event-"+t)+"",x:Math.max(I.windowPlot.x+s,Math.min(I.windowPlot.x+I.windowPlot.width-s,j(r))),y:u.plot.y+s+2,vx:8*(t%3-1),vy:0,mass:1,friction:.02,spawnAt:a,shape:{type:"circle",radius:s},datum:{...e,eventTime:r,arrivalTime:a,windowIndex:c,late:l}})});const R=u.plot.y+u.plot.height,$=function(e,t){const n=Math.max(0,Math.min(e.windowCount,e.closedWindowCount));if(!n)return[];const i=e.windowStart,o=e.windowStart+e.windowCount*e.windowSize,r=(0,Ss.scaleLinear)().domain([i,o]).range([e.windowPlot.x,e.windowPlot.x+e.windowPlot.width]),s=r(e.windowStart+n*e.windowSize),a=e.windowPlot.x,c=t+Math.max(18,Math.min(.3*e.windowPlot.height,s-a)),l=e=>s===a?t:c+(e-a)/(s-a)*(t-c),d=[];for(let t=0;n>t;t+=1){const n=e.windowStart+t*e.windowSize,i=n+e.windowSize,o=r(n),s=r(i);d.push({id:"eventdrop-lid-"+t,windowIndex:t,x1:o,y1:l(o),x2:s,y2:l(s)})}return d}({closedWindowCount:M,gutter:I.gutter,plot:u.plot,windowCount:v,windowPlot:I.windowPlot,windowSize:o.size,windowStart:x},u.plot.y+.28*u.plot.height);return{config:fs(a,[...Ji({x:u.plot.x,y:u.plot.y,width:u.plot.width,height:u.plot.height},{idPrefix:"eventdrop",wallThickness:20,floorThickness:20}),...js({idPrefix:"eventdrop-window",count:v,xScale:e=>j(x+e*o.size),yTop:I.wallTop,yTopForIndex:e=>{const t=(e=>{if(0>e||e>M)return null;const t=0===e?$[0]?.y1:$[e-1]?.y2??$[e]?.y1;return"number"==typeof t&&Number.isFinite(t)?t:null})(e);return null==t?I.wallTop:t+1.25*s},yBottom:R,wallThickness:6}),...$.map(e=>({id:e.id,shape:{type:"segment",x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2,thickness:Math.max(4,.42*s)},friction:.02,restitution:.01}))],"EventDropChart",{friction:.08}),initialSpawns:C,initialSpawnPacing:{pacing:"arrival",timeAccessor:e=>e.datum?.arrivalTime,timeScale:d},projectionRows:A.map((e,t)=>({label:`${x+t*o.size}-${x+(t+1)*o.size}`,value:e.value,secondary:e.secondary})),metadata:{kind:"event-drop",closedWindowCount:M,gutter:I.gutter,lidSegments:$,lateCount:A.reduce((e,t)=>e+t.secondary,0),plot:u.plot,windowPlot:I.windowPlot,watermarkValue:k,windowCount:v,windowSize:o.size,windowStart:x}}}function Cs(e,t,n){const i=e.width/Math.max(1,t),o=Math.max(2,2*n),r=Math.min(.7*i,Math.max(3.2*o,o+8)),s=Math.max(1,Math.floor(r/o));return{laneWidth:i,tubeWidth:r,ballDiameter:o,perRow:s,centerX:t=>e.x+(t+.5)*i,pileHeight:e=>Math.ceil(Math.max(0,e)/s)*o}}function Rs(e){const{data:t,categoryAccessor:n,valueAccessor:i,unitValue:o,ballRadius:r,seed:s,size:a}=e,c=vs(o,1),l=hs(a),d=[],u=new Map,h=new Map,p=[];function m(e){let t=u.get(e);return null==t&&(t=d.length,d.push(e),u.set(e,t)),t}t.forEach((e,t)=>{m((gs(e,t,n)??"unknown")+"")});const f=Math.max(1,d.length),y=Cs(l.plot,f,r),g=Math.max(0,y.tubeWidth/2-r-1),b=d.map(()=>[]);t.forEach((e,t)=>{const o=(gs(e,t,n)??"unknown")+"",s=m(o),a=i?bs(gs(e,t,i)):1,d=Math.max(0,Math.round((a??0)/c)),u=y.centerX(s);for(let n=0;d>n;n+=1){const i=h.get(o)??0,a=y.perRow>1?((y.perRow>1?i%y.perRow:0)/(y.perRow-1)*2-1)*g:0;h.set(o,i+1),b[s].push({id:`${(e.id??"pile-"+t)+""}-${n}`,x:u+a,y:l.plot.y+r+2,vx:(n%3-1)*r/2,vy:0,mass:1,shape:{type:"circle",radius:r},datum:{...e,category:o,unitIndex:n}})}});const x=b.reduce((e,t)=>Math.max(e,t.length),0);for(let e=0;x>e;e+=1)for(const t of b)t.length>e&&p.push(t[e]);const v=l.plot.y+l.plot.height,w=[...Ji({x:l.plot.x,y:l.plot.y,width:l.plot.width,height:l.plot.height},{idPrefix:"pile",wallThickness:20,floorThickness:20})],k=l.plot.y-400;for(let e=0;f>e;e+=1){const t=y.centerX(e);for(const n of[-1,1])w.push({id:`pile-tube-${e}-${0>n?"l":"r"}`,shape:{type:"aabb",x:t+n*y.tubeWidth/2,y:(k+v)/2,width:6,height:v-k}})}return{config:fs(s,w,"PhysicsPileChart"),initialSpawns:p,initialSpawnPacing:{pacing:{ratePerSec:20}},projectionRows:d.map(e=>({label:e,value:h.get(e)??0}))}}var $s=require("d3-scale");function Ps(e){const{data:t,xAccessor:n,groupAccessor:i,radiusAccessor:o,pointRadius:r,seed:s,size:a,xExtent:c,collisionIterations:l,settle:d}=e,u=hs(a),h=ks(s),p=[],m=[],f=new Map;t.forEach((e,t)=>{const s=bs(gs(e,t,n));if(null==s)return;const a=i?(gs(e,t,i)??"All")+"":"All",c=o?bs(gs(e,t,o)):null,l=xs(null!=c&&c>0?c:r,2,18);!function(e){let t=f.get(e);null==t&&(t=m.length,m.push(e),f.set(e,t))}(a),p.push({datum:e,index:t,value:s,group:a,radius:l})});const y=p.map(e=>e.value),g=c?bs(c[0]):null,b=c?bs(c[1]):null,x=y.length?Math.min(...y):0,v=y.length?Math.max(...y):1;let w=g??x,k=b??v;if(w===k&&(w-=.5,k+=.5),w>k){const e=k;k=w,w=e}const M=Math.max(r,...p.map(e=>e.radius)),I=u.plot.x+M+8,S=u.plot.x+u.plot.width-M-8,j=(0,$s.scaleLinear)().domain([w,k]).range([I,S]),A=Math.max(1,m.length),C=Math.min(Math.max(28,3*M),u.plot.height/4),R=u.plot.y+C,$=Math.max(0,u.plot.y+u.plot.height-C-R),P=e=>{const t=f.get(e)??0;return 1===A?u.plot.y+.54*u.plot.height:R+t/(A-1)*$},D=new Map,B=p.map((e,t)=>{D.set(e.group,(D.get(e.group)??0)+1);const n=j(e.value),i=P(e.group),o=(h()-.5)*e.radius*1.6,r=(h()-.5)*e.radius*1.6;return{id:(e.datum.id??"collision-swarm-"+t)+"",x:d?n+o:xs(n+(t%9-4)*e.radius*2.5,I,S),y:d?i+r:u.plot.y-18-t%12*e.radius,vx:d?0:22*(h()-.5),vy:d?0:24+18*h(),mass:1,shape:{type:"circle",radius:e.radius},datum:{...e.datum,xValue:e.value,group:e.group,radius:e.radius,targetX:n,targetY:i},springs:[{target:{type:"point",x:n,y:i},restLength:0,stiffness:34,damping:5.5}]}});return{config:fs(s,Ji({x:u.plot.x,y:u.plot.y,width:u.plot.width,height:u.plot.height},{idPrefix:"collision-swarm",includeCeiling:!1,wallThickness:20,floorThickness:20}),"CollisionSwarmChart",{gravity:{x:0,y:0},cellSize:Math.max(24,4*M),collisionIterations:Math.max(1,Math.round(l??6)),velocityDamping:.992,restitution:.02,friction:.18,sleepSpeed:3,sleepAfter:.5}),initialSpawns:B,projectionRows:m.map(e=>({label:e,value:D.get(e)??0})),metadata:{kind:"collision-swarm",xExtent:[w,k],xRange:[I,S],groups:m.map(e=>({label:e,y:P(e),count:D.get(e)??0})),plot:u.plot}}}function Ds(e){if(Array.isArray(e)&&e.length>=2){const t=bs(e[0]),n=bs(e[1]);return null!=t&&null!=n?{x:t,y:n}:null}if(e&&"object"==typeof e){const t=e,n=bs(t.x),i=bs(t.y);return null!=n&&null!=i?{x:n,y:i}:null}return null}function Bs(e){return Array.isArray(e)?e.map(Ds).filter(e=>null!=e):[]}function Ts(e,t,n){return"normalized"===n?{x:t.plot.x+e.x*t.plot.width,y:t.plot.y+e.y*t.plot.height}:{x:xs(e.x,t.plot.x,t.plot.x+t.plot.width),y:xs(e.y,t.plot.y,t.plot.y+t.plot.height)}}function Es(e){let t=0;for(let n=1;e.length>n;n+=1)t+=Math.hypot(e[n].x-e[n-1].x,e[n].y-e[n-1].y);return t}function Ns(e,t){if(0===e.length)return{x:0,y:0};if(1===e.length)return{...e[0]};const n=xs(t,0,1)*Es(e);let i=0;for(let t=1;e.length>t;t+=1){const o=e[t-1],r=e[t],s=Math.hypot(r.x-o.x,r.y-o.y);if(s>0){if(i+s>=n){const e=(n-i)/s;return{x:o.x+(r.x-o.x)*e,y:o.y+(r.y-o.y)*e}}i+=s}}return{...e[e.length-1]}}function Os(e,t){const n=Ns(e,Math.max(0,t-.02)),i=Ns(e,Math.min(1,t+.02)),o=i.x-n.x,r=i.y-n.y,s=Math.hypot(o,r)||1;return{x:o/s,y:r/s}}function Ws(e){const{coordinateMode:t,flowSpeed:n,links:i,maxParticles:o,nodeIdAccessor:r,nodeXAccessor:s,nodeYAccessor:a,nodes:c,particleRadius:l,particleRate:d,pathAccessor:u,pathConstraint:h="path",reducedMotion:p,seed:m,size:f,sourceAccessor:y,targetAccessor:g,throughputAccessor:b}=e,x=hs(f),v=ks(m),w=new Map,k=new Map,M=[];function I(e){if(e&&"object"==typeof e){const t=e;if("function"==typeof r){const e=r(t,0);if(null!=e)return e+""}if("string"==typeof r&&null!=t[r])return t[r]+"";if(null!=t.id)return t.id+""}return(e??"unknown")+""}c.forEach((e,t)=>{const n=(gs(e,t,r)??e.id??t)+"",i=bs(gs(e,t,s)),o=bs(gs(e,t,a));if(null!=i&&null!=o){const e={x:i,y:o};w.set(n,e),M.push(e)}k.set(n,(e.label??e.name??n)+"")});const S=[];i.forEach((e,t)=>{const n=I(gs(e,t,y)),i=I(gs(e,t,g)),o=Math.max(0,bs(gs(e,t,b))??0),r=Bs(u?gs(e,t,u):void 0),s=r.length?r:Bs(e.path??e.points??e.route);s.forEach(e=>M.push(e)),S.push({id:(e.id??`physical-flow-${n}-${i}-${t}`)+"",link:e,index:t,source:n,target:i,throughput:o,rawPath:s})});const j=(C=M,"normalized"===(A=t)||"pixels"===A?A:C.length>0&&C.every(e=>!(0>e.x||e.x>1||0>e.y||e.y>1))?"normalized":"pixels");var A,C;const R=new Map;for(const[e,t]of w)R.set(e,Ts(t,x,j));const $=[];for(const e of S){let t=e.rawPath.map(e=>Ts(e,x,j));if(2>t.length){const n=R.get(e.source),i=R.get(e.target);n&&i&&(t=[n,i])}else R.has(e.source)||R.set(e.source,t[0]),R.has(e.target)||R.set(e.target,t[t.length-1]);t.length>=2&&e.throughput>0&&(k.has(e.source)||k.set(e.source,e.source),k.has(e.target)||k.set(e.target,e.target),$.push({...e,path:t,packetCount:0}))}const P=vs(d,.12),D=Math.max(1,Math.round(o)),B=$.map(e=>Math.max(1,Math.round(e.throughput*P))),T=B.reduce((e,t)=>e+t,0),E=T>D?D/T:1;$.forEach((e,t)=>{e.packetCount=Math.max(1,Math.floor(B[t]*E))});let N=$.reduce((e,t)=>e+t.packetCount,0);for(;N>D;){const e=$.reduce((e,t,n)=>t.packetCount>1&&(-1===e||t.packetCount>$[e].packetCount)?n:e,-1);if(-1===e)break;$[e].packetCount-=1,N-=1}const O=new Map,W=new Map,q=[],F=vs(n,90),z=vs(l,4);$.forEach((e,t)=>{O.set(e.target,(O.get(e.target)??0)+e.throughput),W.set(e.source,(W.get(e.source)??0)+e.throughput);const n=Es(e.path);for(let i=0;e.packetCount>i;i+=1){const o=(i+.5)/e.packetCount,r=p?o:xs(.12+.84*o+.04*(v()-.5),.04,.98),s=p?r:Math.max(0,r-(.18+.12*v())),a=Ns(e.path,s),c=Ns(e.path,r),l=Os(e.path,s),d={x:-l.y,y:l.x},u=(v()-.5)*z*1.5;q.push({id:`${e.id}-packet-${i}`,x:a.x+d.x*u,y:a.y+d.y*u,vx:p?0:l.x*F+10*(v()-.5),vy:p?0:l.y*F+10*(v()-.5),mass:.8,spawnAt:p?0:.04*t+i/32,shape:{type:"circle",radius:z},datum:{...e.link,source:e.source,target:e.target,throughput:e.throughput,packetIndex:i,packetCount:e.packetCount,routeProgress:r,flowPath:e.path,flowPathLength:n,flowRouteId:e.id,flowSpeed:F,sourceLabel:k.get(e.source)??e.source,targetLabel:k.get(e.target)??e.target},springs:"none"!==h&&p?[{target:{type:"point",x:c.x,y:c.y},restLength:.7*z,stiffness:26,damping:4.25}]:void 0})}});const L=Math.max(18,5*z),Y=Array.from(R,([e,t])=>({nodeId:e,label:k.get(e)??e,sensorId:"physical-flow-node-"+ws(e),point:t})),H=Y.map(e=>({id:e.sensorId,sensor:!0,shape:{type:"aabb",x:e.point.x,y:e.point.y,width:L,height:L}})),_=Object.fromEntries(Y.map(e=>[e.sensorId,{binId:e.label,enterType:"physics-proximity-enter",exitType:"physics-proximity-exit"}])),G=fs(m,[...Ji({x:x.plot.x,y:x.plot.y,width:x.plot.width,height:x.plot.height},{idPrefix:"physical-flow",wallThickness:18,floorThickness:18}),...H],"PhysicalFlowChart",{gravity:{x:0,y:0},cellSize:Math.max(24,7*z),collisionIterations:3,velocityDamping:.994,restitution:.01,friction:.16,sleepSpeed:2.5,sleepAfter:.7});G.bodyLimit=D,G.eviction="oldest",G.observation={...G.observation,sensors:_};const X=Array.from(R,([e,t])=>({id:e,label:k.get(e)??e,x:t.x,y:t.y,sensorId:"physical-flow-node-"+ws(e),incoming:O.get(e)??0,outgoing:W.get(e)??0})),V=$.map(e=>({id:e.id,source:e.source,target:e.target,sourceLabel:k.get(e.source)??e.source,targetLabel:k.get(e.target)??e.target,throughput:e.throughput,packetCount:e.packetCount,path:e.path}));return{config:G,initialSpawns:q,projectionRows:X.filter(e=>e.incoming>0||e.outgoing>0).map(e=>({label:e.label,value:e.incoming,secondary:e.outgoing})),metadata:{kind:"physical-flow",coordinateMode:j,particleCount:q.length,totalThroughput:$.reduce((e,t)=>e+t.throughput,0),plot:x.plot,nodes:X,links:V}}}function qs(e,t){if("region-enter"!==t.type)return e;const n=t.region.id,i=e[n]??{id:n,label:t.region.label??n,count:0,bodyIds:[]};if(i.bodyIds.includes(t.bodyId))return e;const o=[...i.bodyIds,t.bodyId];return{...e,[n]:{...i,count:o.length,bodyIds:o}}}function Fs(e,t){return(t??Object.keys(e)).map(t=>e[t]).filter(e=>null!=e).map(e=>({label:e.label??e.id,value:e.count}))}function zs(e,t){const n=t instanceof Set?t:new Set(t);return e.map(e=>{const t=e.bodyIds??[],i=t.filter(e=>!n.has(e)),o=t.length-i.length,r=e.completion?.mode??"allMembersAbsorbed",s=e.completion?.valueByBodyId,a=e=>{const t=s?.[e];return Number.isFinite(t)&&Number(t)>=0?Number(t):1},c=t.reduce((e,t)=>e+a(t),0),l=t.reduce((e,t)=>e+(n.has(t)?a(t):0),0),d=e.completion?.threshold,u="threshold"===r?Number.isFinite(d)&&Number(d)>=0?Number(d):c:void 0;return{id:e.id,label:e.label??e.id,mode:r,complete:t.length>0&&("anyAbsorbed"===r?o>0:"threshold"===r?l>=(u??c):0===i.length),absorbed:o,total:t.length,absorbedValue:l,totalValue:c,threshold:u,missing:i}})}function Ls(e,t,n){return Math.max(t,Math.min(n,e))}function Ys(e,t,n={}){const i=n.random??Math.random,o=e.stages.find(e=>e.id===t)??e.stages[e.stages.length-1],r=Ls(n.along??.5,.05,.95),s=n.jitterX??0,a=n.padY??20,c=o.x0+(o.x1-o.x0)*r+(2*i()-1)*s,l=Math.min(1,o.width/2),d=Ls(c,o.x0+l,o.x1-l),u=e.boundaryY(d,"top")+a,h=e.boundaryY(d,"bottom")-a;return{x:d,y:h>u?u+i()*Math.max(1,h-u):e.midY}}function Hs(e){return"bowtie"===e.shape?[{id:"incoming",role:"incoming",points:[[e.left,e.topY],[e.centerLeft,e.pinchTop],[e.centerLeft,e.pinchBottom],[e.left,e.bottomY]]},{id:"center",role:"center",points:[[e.centerLeft,e.pinchTop],[e.centerRight,e.pinchTop],[e.centerRight,e.pinchBottom],[e.centerLeft,e.pinchBottom]]},{id:"outgoing",role:"outgoing",points:[[e.centerRight,e.pinchTop],[e.right,e.topY],[e.right,e.bottomY],[e.centerRight,e.pinchBottom]]}]:[{id:"volume",role:"volume",points:[[e.left,e.topY],[e.right,"funnel"===e.shape?e.pinchTop:e.topY],[e.right,"funnel"===e.shape?e.pinchBottom:e.bottomY],[e.left,e.bottomY]]}]}function _s(e,t,n){return Math.max(t,Math.min(n,e))}function Gs(e,t,n,i,o,r={}){return{id:e,friction:r.friction,restitution:r.restitution,bodyFilter:r.bodyFilter,shape:{type:"segment",x1:t,y1:n,x2:i,y2:o,thickness:r.thickness??8}}}function Xs(e){const t=e.shape??"lane",n=Math.max(1,Math.round(e.width)),i=Math.max(1,Math.round(e.height)),o=e.padX??46,r=e.padY??72,s=o,a=n-o,c=r,l=i-Math.max(24,Math.round(.45*r)),d=(c+l)/2,u=Math.max(1,l-c),h=_s(e.pinchRatio??.18,.06,.5),p=Number(e.pinchHeightOffset??0),m=Number.isFinite(p)?p:0,f=_s(u*h+m,.06*u,.5*u),y=f/2,g=d-y,b=d+y,x=e.idPrefix??"process",v=e.friction??.58,w=e.restitution??.18,k=e.wallThickness??8,M=e.stages;if(!M.length)throw Error("processStageLayout requires at least one stage");const I=_s(e.centerStageIndex??Math.floor(M.length/2),0,M.length-1),S=function(e){const t=e.reduce((e,t)=>e+(t.share??1),0);return t>0?t:e.length}(M),j=a-s;let A=s;const C=M.map((e,t)=>{const n=A,i=t===M.length-1?a:A+(e.share??1)/S*j;return A=i,{id:e.id,label:e.label,description:e.description,kind:e.kind??"stage",index:t,x0:n,x1:i,x:(n+i)/2,width:i-n,y:d,height:u}}),R=C[I],$=R.x0,P=R.x1,D=(e,n)=>{if("lane"===t)return"top"===n?c:l;if("funnel"===t){const t=_s((e-s)/Math.max(1,a-s),0,1);return"top"===n?c+(g-c)*t:l+(b-l)*t}if($>=e){const t=_s((e-s)/Math.max(1,$-s),0,1);return"top"===n?c+(g-c)*t:l+(b-l)*t}if(P>=e)return"top"===n?g:b;const i=_s((e-P)/Math.max(1,a-P),0,1);return"top"===n?g+(c-g)*i:b+(l-b)*i},B=C.map(e=>{const t=Math.min(D(e.x0,"top"),D(e.x1,"top")),n=Math.max(D(e.x0,"bottom"),D(e.x1,"bottom"));return{...e,y:(t+n)/2,height:Math.max(1,n-t)}}),T={thickness:k,friction:v,restitution:w},E=[];"lane"===t?E.push(Gs(x+"-top",s,c,a,c,T),Gs(x+"-bottom",s,l,a,l,T),Gs(x+"-left",s,c,s,l,{...T,thickness:Math.max(6,k-2)}),Gs(x+"-right",a,c,a,l,{...T,thickness:Math.max(6,k)})):"funnel"===t?E.push(Gs(x+"-top",s,c,a,g,T),Gs(x+"-bottom",s,l,a,b,T),Gs(x+"-left",s,c,s,l,{...T,thickness:Math.max(6,k-2)}),Gs(x+"-right",a,g,a,b,{...T,thickness:Math.max(6,k)})):E.push(Gs(x+"-left-top",s,c,$,g,T),Gs(x+"-left-bottom",s,l,$,b,T),Gs(x+"-center-top",$,g,P,g,T),Gs(x+"-center-bottom",$,b,P,b,T),Gs(x+"-right-top",P,g,a,c,T),Gs(x+"-right-bottom",P,b,a,l,T),Gs(x+"-left",s,c,s,l,{...T,thickness:Math.max(6,k-2)}),Gs(x+"-right",a,c,a,l,{...T,thickness:Math.max(6,k)}));const N=e.membraneDampingScale??.5,O=s,W=Math.max(1,("bowtie"===t?$:a)-O),q=(e.membranes??[]).map(e=>{const t=O+_s(e.offset,0,1)*W,n=e.width??18+18*e.cost,i=u-16,o=d+.25*(e.wobble??0);return{...e,x:t,y:o,width:n,height:i}}),F=!1===e.includeMembraneRegions?[]:q.map(e=>Ks({id:e.id,label:e.label??e.id,description:e.description??(e.label??e.id)+" is a permeable region. It taxes energy and damps velocity while bodies overlap it.",x:e.x,y:e.y,width:e.width,height:e.height,cost:e.cost,dampingScale:e.dampingScale??N,bodyStyle:e.bodyStyle,metadata:e.metadata,semanticItem:e.semanticItem,color:e.color}));return{shape:t,width:n,height:i,padX:o,padY:r,left:s,right:a,topY:c,bottomY:l,midY:d,centerLeft:$,centerRight:P,pinchHeight:f,pinchTop:g,pinchBottom:b,stages:B,membranes:q,colliders:E,regionEffects:F,boundaryY:D}}function Vs(e){return{id:e.id,label:e.label,description:e.description,kind:e.kind,shape:(t=e.x,n=e.y,i=e.width,o=e.height,{type:"aabb",x:t,y:n,width:i,height:o}),bodyFilter:e.bodyFilter,collider:e.collider,colliderThickness:e.colliderThickness,friction:e.friction,restitution:e.restitution,semanticItem:e.semanticItem,metadata:e.metadata,bodyStyle:e.bodyStyle,attributes:e.attributes,onEnter:e.onEnter,onExit:e.onExit};var t,n,i,o}function Us(e,t={}){const n=t.idPrefix??"stage",i=Math.max(0,t.insetX??0),o=Math.max(0,t.insetY??1);return e.stages.map(e=>{const r="function"==typeof t.metadata?t.metadata(e):t.metadata??{};return{...Vs({id:n?`${n}:${e.id}`:e.id,label:e.label??e.id,description:e.description,kind:"region",x:e.x,y:e.y,width:Math.max(1,e.width-2*i),height:Math.max(1,e.height-2*o),bodyFilter:t.bodyFilter,semanticItem:t.semanticItem,attributes:{primitive:"processStage",stageId:e.id,stageIndex:e.index},metadata:{...r,primitive:"processStage",stageId:e.id,stageIndex:e.index}})}})}function Ks(e){const t=e.dampingScale??.5,n=e.energyScale??1,i=_s(e.cost,0,2);return{...Vs({...e,kind:e.kind??"membrane",attributes:{primitive:"membrane",membraneCost:i,..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),damping:i*t,energyDelta:-i*n}}function Qs(e){return{...Vs({...e,kind:e.kind??"charge-gate",attributes:{primitive:"chargeGate",..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),charge:e.charge??!0,energyDelta:e.energyDelta,impulseOnEnter:e.impulseOnEnter}}function Zs(e){const t="number"==typeof e.force?{x:e.force,y:0}:e.force??{x:12,y:0};return{...Vs({...e,kind:e.kind??"force-field",attributes:{primitive:"routeSurface",..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),force:t,damping:e.damping??.015}}function Js(e){const t=e.pressure??e.occupancy??0,n=e.baseDamping??.08,i=e.dampingPerUnit??.12,o=e.energyPerUnit??0;return{...Vs({...e,kind:e.kind??"membrane",attributes:{primitive:"pressureField",pressure:t,..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),damping:n+t*i,energyDelta:o?-t*o:void 0,force:e.force}}function ea(e){const t="number"==typeof e.force?{x:e.force,y:0}:e.force;return{...Vs({...e,kind:e.kind??"force-field",attributes:{primitive:"capacitatedSensor",capacity:e.capacity,unitsPerSecond:e.unitsPerSecond??e.capacity,..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),force:t,damping:e.damping,charge:e.charge??e.capacity}}function ta(e){return{...Vs({...e,kind:e.kind??"force-field",attributes:{primitive:"portal",targetStage:e.targetStage,..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),force:e.force,impulseOnEnter:e.impulseOnEnter,damping:e.damping??.08}}function na(e){const t="number"==typeof e.force?{x:e.force,y:0}:e.force??{x:24,y:0};return{...Vs({...e,kind:e.kind??"sink",attributes:{primitive:"absorb",..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),force:t,damping:e.damping??.02,charge:e.charge??"absorbed"}}function ia(e){return{...Vs({...e,kind:e.kind??"force-field",attributes:{primitive:"forceField",..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),force:e.force,damping:e.damping,energyDelta:e.energyDelta}}function oa(e){const t=e.x??e.anchor?.x??0,n=e.y??e.anchor?.y??0;return{id:e.id,label:e.label,description:e.description,group:e.group,bodyIds:e.bodyIds,datum:e.datum,state:e.state,x:t,y:n,width:e.width,height:e.height,anchor:e.anchor??{x:t,y:n},completion:e.completion,tether:e.tether,semanticItem:e.semanticItem}}function ra(e){const t=e.idPrefix??"lane",n={thickness:e.thickness??8,friction:e.friction??.5,restitution:e.restitution??.16},i=[Gs(t+"-top",e.left,e.top,e.right,e.top,n),Gs(t+"-bottom",e.left,e.bottom,e.right,e.bottom,n)];return e.openEnds||i.push(Gs(t+"-left",e.left,e.top,e.left,e.bottom,n),Gs(t+"-right",e.right,e.top,e.right,e.bottom,n)),i}function sa(e,t=12){return"number"==typeof e?{x:e,y:0}:e&&"object"==typeof e?{x:Number.isFinite(e.x)?Number(e.x):t,y:Number.isFinite(e.y)?Number(e.y):0}:{x:t,y:0}}function aa(e){const t=e.stages;if(!t.length)throw Error("buildProcessFlowPhysics requires at least one stage");const n=e.size,i=hs(n),o=xs(e.ballRadius??6,2,18),r=e.seed??1,s=ks(r),a=e.idAccessor,c=e.stageAccessor??"stage",l=e.groupBy,d=e.groupLabelAccessor,u=e.workAccessor,h=e.radiusAccessor,p=e.groupCompletion??(l?"allAbsorbed":"none"),m=e.springStiffness??.28,f=e.springDamping??.72,y=!0===e.settle,g=t.map(e=>({id:e.id,label:e.label??e.id,description:e.description,share:e.share})),b=Xs({width:n[0],height:n[1],shape:"lane",padX:Math.max(28,i.plot.x),padY:Math.max(36,i.plot.y+8),stages:g,idPrefix:"process-flow",includeMembraneRegions:!1,friction:.48,restitution:.14}),x=new Map(b.stages.map((e,t)=>[e.id,t])),v=new Map(b.stages.map(e=>[e.id,e])),w=b.stages[0].id,k=b.stages[0],M=new Set(t.filter(e=>e.absorb).map(e=>e.id)),I=t.map(e=>{const t=v.get(e.id)??k;return function(e,t){const n={id:"process-stage-"+e.id,label:e.label??e.id,description:e.description,x:t.x,y:t.y,width:Math.max(12,.92*t.width),height:Math.max(40,.88*t.height),semanticItem:!1,attributes:{stageId:e.id}};if(e.absorb)return na({...n,kind:e.kind??"sink",force:sa(e.force,28),damping:e.damping??.04,charge:"absorbed",attributes:{...n.attributes,primitive:"absorb"}});if(e.portal){const t=e.portal.force??e.force??{x:-40,y:0};return ta({...n,kind:e.kind??"force-field",force:sa(t,-40),damping:e.damping??.1,targetStage:e.portal.targetStageId,attributes:{...n.attributes,primitive:"portal",targetStage:e.portal.targetStageId}})}if(e.capacity){const t=Math.max(.1,e.capacity.unitsPerSecond);return ea({...n,kind:e.kind??"force-field",capacity:t,unitsPerSecond:t,force:sa(e.force,10+.8*t),damping:e.damping??Math.max(.04,.32-.01*t),attributes:{...n.attributes,unitAccessor:e.capacity.unitAccessor,reviewerCapacity:t}})}if(e.pressure){const t="object"==typeof e.pressure&&e.pressure?e.pressure:{};return Js({...n,kind:e.kind??"membrane",pressure:t.pressure,occupancy:t.occupancy,baseDamping:t.baseDamping??e.damping??.1,dampingPerUnit:t.dampingPerUnit??.1,energyPerUnit:t.energyPerUnit??0,force:sa(e.force,8),attributes:{...n.attributes,primitive:"pressureField"}})}return null!=e.force||null!=e.damping?Zs({...n,kind:e.kind??"force-field",force:sa(e.force,14),damping:e.damping??.02,attributes:{...n.attributes,primitive:"routeSurface"}}):ia({...n,kind:e.kind??"force-field",force:{x:10,y:0},damping:.02,attributes:{...n.attributes,primitive:"forceField"}})}(e,{x:t.x,y:b.midY,width:t.width,height:b.bottomY-b.topY})});I.unshift(Zs({id:"process-flow-route",label:"process route",description:"Baseline conveyor along the process lane.",x:(b.left+b.right)/2,y:b.midY,width:b.right-b.left,height:b.bottomY-b.topY-12,force:8,damping:.012,semanticItem:!1}));const S=new Map;for(const e of b.stages)S.set(e.id,0);const j=[];e.data.forEach((e,t)=>{const n=(a?gs(e,t,a)??e.id??"process-flow-"+t:e.id??"process-flow-"+t)+"",i=(gs(e,t,c)??w)+"",r=x.has(i)?i:w;S.set(r,(S.get(r)??0)+1);const s=l?(gs(e,t,l)??"")+"":void 0,p=s&&d?(gs(e,t,d)??s)+"":s,m=u?bs(gs(e,t,u))??1:1,f=h?bs(gs(e,t,h)):null,y=xs(null!=f&&f>0?f:o,2,18);j.push({datum:e,id:n,stageId:r,groupId:s||void 0,groupLabel:p||void 0,work:m,radius:y,index:t})});const A=new Map,C=new Map;for(const e of j){if(!e.groupId)continue;const t=A.get(e.groupId)??[];t.push(e.id),A.set(e.groupId,t),e.groupLabel&&C.set(e.groupId,e.groupLabel)}const R=xs(e.groupAnchorAlong??.55,.15,.9),$=b.left+(b.right-b.left)*R,P=Array.from(A.keys()),D=P.map((e,n)=>{const i=A.get(e)??[],o=P.length>1?b.topY+28+n/Math.max(1,P.length-1)*(b.bottomY-b.topY-56):b.midY;return oa({id:e,label:C.get(e)??e,bodyIds:i,anchor:{x:$,y:o},x:$,y:o,completion:"allAbsorbed"===p?{mode:"allMembersAbsorbed",targetZone:t.find(e=>e.absorb)?.id??"merged"}:void 0,tether:{stiffness:.06,visible:!0,restLength:18}})}),B=zs(D,j.filter(e=>M.has(e.stageId)).map(e=>e.id)),T=new Map(D.map(e=>[e.id,e])),E=j.map((e,t)=>{const n=v.get(e.stageId)??k,i=n.x+(s()-.5)*Math.min(24,.2*n.width),o=b.boundaryY(i,"top")+e.radius+10,r=b.boundaryY(i,"bottom")-e.radius-10,a=r>o?o+s()*Math.max(1,r-o):b.midY,c=y?i:b.left+18+t%7*4,l=y?a:b.midY+(s()-.5)*(b.bottomY-b.topY)*.35,d=[{target:{type:"point",x:i,y:a},restLength:.45*e.radius,stiffness:m,damping:f}];if(e.groupId){const t=T.get(e.groupId);t?.anchor&&!M.has(e.stageId)&&d.push({target:{type:"point",x:t.anchor.x,y:t.anchor.y},restLength:t.tether?.restLength??22,stiffness:t.tether?.stiffness??.05,damping:.8})}return{id:e.id,x:c,y:l,vx:y?0:40+40*s(),vy:y?0:20*(s()-.5),mass:1,shape:{type:"circle",radius:e.radius},spawnAt:y?0:.03*t,springs:d,datum:{...e.datum,id:e.id,stage:e.stageId,groupId:e.groupId,groupLabel:e.groupLabel,work:e.work,__processFlow:!0}}}),N={kernel:{seed:r,gravity:{x:e.gravityX??22,y:e.gravityY??0},restitution:.14,friction:.48,velocityDamping:.988,maxVelocity:420,sleepSpeed:8,sleepAfter:.9,collisionIterations:4},colliders:b.colliders,fixedDt:1/60,maxSubsteps:8},O=b.stages.map(e=>({label:e.label??e.id,value:S.get(e.id)??0})),W=t.map(e=>{const t=v.get(e.id)??k;return{id:e.id,label:e.label??e.id,x:t.x,width:t.width,count:S.get(e.id)??0,capacity:e.capacity?.unitsPerSecond,absorb:!0===e.absorb,portalTarget:e.portal?.targetStageId}});return{config:N,initialSpawns:E,initialSpawnPacing:y?void 0:{pacing:"arrival",timeAccessor:"spawnAt",timeScale:1},projectionRows:O,metadata:{kind:"process-flow",plot:i.plot,volume:b,stages:W,groups:D,groupCompletion:B,regionEffects:I}}}var ca=require("react");function la(e,t){if(!t?.length)return[e];const n=t.filter(t=>{if(t.id===e||t.id.startsWith(e+"-"))return!0;const n=t.datum;return!(!n||"object"!=typeof n||null==n.id)&&n.id+""===e}).map(e=>e.id);return n.length?n:[e]}function da(e,t,n){if("function"==typeof n)return n(e,t)+"";if("string"==typeof n){const t=e[n];if(null!=t)return t+""}return null!=e&&"object"==typeof e&&"id"in e&&null!=e.id?e.id+"":"physics-row-"+t}function ua(e,t){const n=e?.getData().find(e=>e.id===t),i=n?.datum;if(i&&"object"==typeof i)return i}function ha(e,t){const{frameRef:n,spawnDatum:i,seedRows:o,idAccessor:r,bodyIdsForSeed:s,seedSpawns:a}=t,c=(0,ca.useRef)(new Map),l=(0,ca.useRef)(new Map),d=(0,ca.useRef)(""),u=o?o.map((e,t)=>da(e,t,r)).join("\0"):"";if(u!==d.current&&(d.current=u,o))for(let e=0;o.length>e;e+=1){const t=o[e],n=da(t,e,r);c.current.set(n,t),l.current.set(n,s?.(t,n,e)??la(n,a))}(0,ca.useImperativeHandle)(e,()=>{const e=c.current,t=l.current;function o(e,t){const n=i(e,t);return{datumId:n.datumId||da(e,t,r),spawns:n.spawns.map(e=>({...e,spawnAt:void 0}))}}function s(i){const o=[];for(const{datum:n,result:r}of i)e.set(r.datumId,n),t.set(r.datumId,r.spawns.map(e=>e.id)),o.push(...r.spawns);if(!o.length)return;const r=n.current;r?(r.pushMany(o),r.step(0)):"production"!==process.env.NODE_ENV&&console.warn("[semiotic/physics] push() called before the physics frame mounted (loading/empty early-return). Omit data for push mode and ensure the chart is mounted.")}function a(i){const o=e.get(i);if(o)return o;const r=t.get(i)??[i];for(const o of r){const r=ua(n.current,o);if(r)return e.set(i,r),t.has(i)||t.set(i,[o]),r}}return{push:t=>{s([{datum:t,result:o(t,e.size)}])},pushMany:t=>{const n=e.size;s(t.map((e,t)=>({datum:e,result:o(e,n+t)})))},remove:i=>{const o=Array.isArray(i)?i:[i],r=[],s=[];for(const n of o){const i=a(n);i&&r.push(i),e.delete(n),s.push(...t.get(n)??[n]),t.delete(n)}return s.length&&n.current?.remove(s),r},update:(i,r)=>{const c=Array.isArray(i)?i:[i],l=[];for(const i of c){const c=a(i);if(!c)continue;l.push(c);const d=t.get(i)??[i];n.current?.remove(d),e.delete(i),t.delete(i);const u=r(c);s([{datum:u,result:o(u,e.size)}])}return l},clear:()=>{e.clear(),t.clear(),d.current="",n.current?.clear()},getData:()=>{const t=n.current;if(!t)return Array.from(e.values());const i=t.getData().map(e=>e.datum).filter(e=>!!e&&"object"==typeof e);return i.length?i:Array.from(e.values())},getScales:()=>null,getCustomLayout:()=>n.current?.snapshot()??null,popBodies:(e,t)=>n.current?.popBodies(e,t)??[]}},[n,r,i])}var pa=require("react"),ma=c(require("react")),fa=require("react/jsx-runtime");function ya({componentName:e,message:t,diagnosticHint:n,width:i,height:o}){return(0,fa.jsx)("div",{role:"alert",style:{width:i,height:Math.max(o,120),display:"flex",alignItems:"center",justifyContent:"center",border:"1px dashed rgba(128, 128, 128, 0.4)",borderRadius:8,background:"rgba(128, 128, 128, 0.04)",padding:24,boxSizing:"border-box"},children:(0,fa.jsxs)("div",{style:{textAlign:"center",maxWidth:400},children:[(0,fa.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"rgba(128, 128, 128, 0.7)",marginBottom:6,fontFamily:"monospace"},children:e}),(0,fa.jsx)("div",{style:{fontSize:14,color:"rgba(128, 128, 128, 0.9)",lineHeight:1.5},children:t}),n&&(0,fa.jsx)("div",{"data-testid":"semiotic-diagnostic-hint",style:{marginTop:10,padding:"8px 12px",background:"rgba(128, 128, 128, 0.06)",borderRadius:4,fontSize:12,color:"rgba(128, 128, 128, 0.8)",fontFamily:"monospace",textAlign:"left",whiteSpace:"pre-wrap",lineHeight:1.6},children:n})]})})}var ga=require("react/jsx-runtime"),ba=class extends ma.Component{constructor(e){super(e),this.state={error:null}}static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){this.props.onError?.(e,t)}render(){if(this.state.error){const{fallback:e}=this.props,t=this.state.error;return"function"==typeof e?e(t):void 0!==e?e:(0,ga.jsx)(ya,{componentName:"ChartErrorBoundary",message:t.message||"An unexpected error occurred while rendering this chart.",width:600,height:400})}return this.props.children}},xa=require("react/jsx-runtime");function va({componentName:e,width:t,height:n,children:i}){return(0,xa.jsx)(ba,{fallback:i=>(0,xa.jsx)(ya,{componentName:e,message:i.message,width:t,height:n}),children:i})}"undefined"!=typeof process&&process;var wa={display:"flex",alignItems:"center",justifyContent:"center",color:"var(--semiotic-text-secondary, #666)",fontSize:13,fontFamily:"inherit",border:"1px dashed var(--semiotic-border, #ddd)",borderRadius:4,boxSizing:"border-box"},ka={background:"var(--semiotic-border, #e0e0e0)",borderRadius:2};function Ma(e){return[parseInt(e.slice(1,3),16),parseInt(e.slice(3,5),16),parseInt(e.slice(5,7),16)]}function Ia(e,t,n){const i=e=>e.toString(16).padStart(2,"0");return`#${i(e)}${i(t)}${i(n)}`}function Sa(e){const t=e.map(Ma),n=t.length-1;return e=>{if(0>=e){const[e,n,i]=t[0];return Ia(e,n,i)}if(e>=1){const[e,i,o]=t[n];return Ia(e,i,o)}const i=e*n,o=Math.floor(i),r=i-o,[s,a,c]=t[o],[l,d,u]=t[o+1];return Ia(Math.round(s+(l-s)*r),Math.round(a+(d-a)*r),Math.round(c+(u-c)*r))}}require("react"),require("d3-scale");var ja=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],Aa=Sa(["#f7fbff","#deebf7","#c6dbef","#9ecae1","#6baed6","#4292c6","#2171b5","#08519c","#08306b"]),Ca=Sa(["#fff5f0","#fee0d2","#fcbba1","#fc9272","#fb6a4a","#ef3b2c","#cb181d","#a50f15","#67000d"]),Ra=Sa(["#f7fcf5","#e5f5e0","#c7e9c0","#a1d99b","#74c476","#41ab5d","#238b45","#006d2c","#00441b"]),$a=Sa(["#fff5eb","#fee6ce","#fdd0a2","#fdae6b","#fd8d3c","#f16913","#d94801","#a63603","#7f2704"]),Pa=Sa(["#fcfbfd","#efedf5","#dadaeb","#bcbddc","#9e9ac8","#807dba","#6a51a3","#54278f","#3f007d"]),Da=Sa(["#ffffff","#f0f0f0","#d9d9d9","#bdbdbd","#969696","#737373","#525252","#252525","#000000"]),Ba={blues:Aa,reds:Ca,greens:Ra,viridis:Sa(["#440154","#482878","#3e4989","#31688e","#26828e","#1f9e89","#35b779","#6ece58","#b5de2b","#fde725"]),oranges:$a,purples:Pa,greys:Da,plasma:Sa(["#0d0887","#41049d","#6a00a8","#8f0da4","#b12a90","#cb4679","#e16462","#f1844b","#fca636","#fcce25","#f0f921"]),inferno:Sa(["#000004","#160b39","#420a68","#6a176e","#932667","#bc3754","#dd513a","#f3771a","#fca50a","#f6d746","#fcffa4"]),magma:Sa(["#000004","#140e36","#3b0f70","#641a80","#8c2981","#b73779","#de4968","#f7705c","#fe9f6d","#fecf92","#fcfdbf"]),cividis:Sa(["#00224e","#123570","#3b496c","#575d6d","#707173","#8a8678","#a59c74","#c3b369","#e1cc55","#fee838","#ffea46"]),turbo:Sa(["#23171b","#4a58dd","#3f9ee9","#46c7af","#7eed5a","#cdf134","#fbb91f","#f56918","#c52f06","#7a0403"])},Ta=(Sa(["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#f7f7f7","#d1e5f0","#92c5de","#4393c3","#2166ac","#053061"]),Sa(["#8e0152","#c51b7d","#de77ae","#f1b6da","#fde0ef","#f7f7f7","#e6f5d0","#b8e186","#7fbc41","#4d9221","#276419"]),Sa(["#40004b","#762a83","#9970ab","#c2a5cf","#e7d4e8","#f7f7f7","#d9f0d3","#a6dba0","#5aae61","#1b7837","#00441b"]),Sa(["#543005","#8c510a","#bf812d","#dfc27d","#f6e8c3","#f5f5f5","#c7eae5","#80cdc1","#35978f","#01665e","#003c30"]),Sa(["#a50026","#d73027","#f46d43","#fdae61","#fee090","#ffffbf","#e0f3f8","#abd9e9","#74add1","#4575b4","#313695"]),Sa(["#a50026","#d73027","#f46d43","#fdae61","#fee08b","#ffffbf","#d9ef8b","#a6d96a","#66bd63","#1a9850","#006837"]),Sa(["#9e0142","#d53e4f","#f46d43","#fdae61","#fee08b","#ffffbf","#e6f598","#abdda4","#66c2a5","#3288bd","#5e4fa2"]),{category10:ja,tableau10:["#4e79a7","#f28e2c","#e15759","#76b7b2","#59a14f","#edc949","#af7aa1","#ff9da7","#9c755f","#bab0ab"],set3:["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5","#d9d9d9","#bc80bd","#ccebc5","#ffed6f"],...Ba}),Ea=ja;function Na(e,t){if(null==t||!Object.prototype.hasOwnProperty.call(e,t))return;const n=e[t];return"string"==typeof n&&n.length>0?n:void 0}function Oa(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}var Wa={enabled:!0,tapToSelect:!0,tapToLockTooltip:!0,clearSelection:"backgroundTap",targetSize:44,snap:"nearestDatum",brushHandleSize:44,standardControls:!1,enabled:!1,tapToSelect:!1,tapToLockTooltip:!1};function qa(e,t={}){const n=t.mobileSemantics?.interaction,i="number"==typeof n?.targetSize?n.targetSize:"number"==typeof t.mobileSemantics?.minimumHitTarget?t.mobileSemantics.minimumHitTarget:void 0,o="mobile"===t.mode||"number"==typeof t.width&&480>=t.width,r=!!n||void 0!==i,s=e&&"object"==typeof e?e:void 0;if(!1===e||!1===s?.enabled||void 0===e&&!o&&!r)return Wa;const a=s??{};return{enabled:!0,tapToSelect:a.tapToSelect??!0,tapToLockTooltip:a.tapToLockTooltip??!0,clearSelection:a.clearSelection??"backgroundTap",targetSize:a.targetSize??i??44,snap:a.snap??"nearestDatum",brushHandleSize:a.brushHandleSize??44,standardControls:a.standardControls??!1}}var Fa={primary:{width:600,height:400,showAxes:!0,showGrid:!1,enableHover:!0,showLegend:void 0,showLabels:void 0,marginDefaults:{top:50,bottom:60,left:70,right:40}},context:{width:400,height:250,showAxes:!1,showGrid:!1,enableHover:!1,showLegend:!1,showLabels:!1,marginDefaults:{top:10,bottom:10,left:10,right:10}},sparkline:{width:120,height:24,showAxes:!1,showGrid:!1,enableHover:!1,showLegend:!1,showLabels:!1,marginDefaults:{top:2,bottom:2,left:0,right:0}},mobile:{width:390,height:300,showAxes:!0,showGrid:!1,enableHover:!0,showLegend:!1,showLabels:!0,marginDefaults:{top:28,bottom:42,left:44,right:16}}};function za(e,t,n){if(!1!==t)return e;const i={...e};return"horizontal"===n?i.left=Math.min(i.left,15):i.bottom=Math.min(i.bottom,15),i}function La(e,t,n){return function(e,t,n){const i=Fa[e||"primary"],o=e&&"primary"!==e||!n?.width?i.width:n.width,r=e&&"primary"!==e||!n?.height?i.height:n.height,s=function(e,t,n=e.responsiveRules){if(!Array.isArray(n)||0===n.length)return{props:e,matches:[]};const i=n.map((e,t)=>({rule:e,index:t})).filter(e=>function(e,t){const{when:n}=e,i=t.width,o=t.height,r=function(e){if("number"==typeof e.height&&e.height>0)return e.width/e.height}(t),s=function(e){if("number"==typeof e.height&&e.height>0)return e.height>e.width?"portrait":"landscape"}(t);return!("number"==typeof n.minWidth&&n.minWidth>i||"number"==typeof n.maxWidth&&i>n.maxWidth||"number"==typeof n.minHeight&&("number"!=typeof o||n.minHeight>o)||"number"==typeof n.maxHeight&&("number"!=typeof o||o>n.maxHeight)||"number"==typeof n.minAspectRatio&&("number"!=typeof r||n.minAspectRatio>r)||"number"==typeof n.maxAspectRatio&&("number"!=typeof r||r>n.maxAspectRatio)||n.orientation&&s!==n.orientation)}(e.rule,t)).sort((e,t)=>("number"==typeof e.rule.priority?e.rule.priority:e.index)-("number"==typeof t.rule.priority?t.rule.priority:t.index));return{props:i.reduce((e,t)=>function(e,t){const n={...e,...t};for(const i of["margin","frameProps","mobileSemantics","style"])Oa(e[i])&&Oa(t[i])&&(n[i]={...e[i],...t[i]});return"string"==typeof e.className&&"string"==typeof t.className&&(n.className=`${e.className} ${t.className}`),n}(e,t.rule.transform),e),matches:i}}({...t,mode:e},{width:t.width??o,height:t.height??r}).props,a=s.mode||e||"primary",c=Fa[a],l="context"===a||"sparkline"===a,d="primary"===a&&n?.width?n.width:c.width;return{mode:a,width:s.width??d,height:s.height??("primary"===a&&n?.height?n.height:c.height),showAxes:s.showAxes??c.showAxes,showGrid:s.showGrid??c.showGrid,enableHover:s.enableHover??(!!s.linkedHover||c.enableHover),showLegend:s.showLegend??c.showLegend,showLabels:s.showLabels??c.showLabels,title:l?void 0:s.title,description:s.description,summary:s.summary,accessibleTable:s.accessibleTable,xLabel:l?void 0:s.xLabel,yLabel:l?void 0:s.yLabel,categoryLabel:l?void 0:s.categoryLabel,valueLabel:l?void 0:s.valueLabel,marginDefaults:za(c.marginDefaults,s.showCategoryTicks,s.orientation),compactMode:l,mobileInteraction:qa(s.mobileInteraction,{mode:a,width:s.width??d,mobileSemantics:s.mobileSemantics}),mobileSemantics:s.mobileSemantics}}(e,t,n)}var Ya=require("react/jsx-runtime"),Ha=new Set(["sample","mechanical"]);function _a(e,t,n,i){const[o,r]=(0,pa.useState)(0),s=(0,pa.useRef)(null),a=(0,pa.useRef)(!1),c=function(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0?e:null}(t),l=(0,pa.useRef)(c),d=(0,pa.useRef)(!!n),u=(0,pa.useRef)(i);l.current=c,d.current=!!n,u.current=i;const h=(0,pa.useCallback)(()=>{null!=s.current&&(clearTimeout(s.current),s.current=null)},[]),p=(0,pa.useCallback)(()=>{h();const e=l.current;null!=e&&!d.current&&a.current&&(s.current=setTimeout(()=>{s.current=null,a.current=!1,u.current?.(),r(e=>e+1)},e))},[h]);(0,pa.useEffect)(()=>{null==c||n?h():a.current&&p()},[h,c,n,p]),(0,pa.useEffect)(()=>h,[h]);const m=e?.observation?.onSimulationStateChange,f=(0,pa.useCallback)((e,t)=>{if(m?.(e,t),"running"===e)return a.current=!1,void h();"settled"===e&&"running"===t&&(a.current=!0,p())},[h,m,p]);return{config:(0,pa.useMemo)(()=>null==c?e:{...e,observation:{...e?.observation,onSimulationStateChange:f}},[e,c,f]),rerunKey:o}}function Ga(e,t,n){const i=n?.hasSimulationMode?function(e){const t=e=>"string"==typeof e&&Ha.has(e);return e.simulationMode?{chartMode:t(e.mode)?void 0:e.mode,simulationMode:e.simulationMode}:t(e.mode)?{chartMode:void 0,simulationMode:e.mode}:{chartMode:e.mode,simulationMode:"sample"}}({mode:e.mode,simulationMode:e.simulationMode}):{chartMode:"sample"===e.mode||"mechanical"===e.mode?void 0:e.mode,simulationMode:"sample"},o=La(i.chartMode,{width:e.width,height:e.height,enableHover:e.enableHover,title:e.title,description:e.description,summary:e.summary,accessibleTable:e.accessibleTable,mobileInteraction:e.mobileInteraction,mobileSemantics:e.mobileSemantics,responsiveRules:e.responsiveRules},{width:t[0],height:t[1]}),r=e.size?.[0],s=e.size?.[1],a=t[0],c=t[1],l=(0,pa.useMemo)(()=>{return e=[a,c],(null!=r&&null!=s?[r,s]:void 0)??[o.width??e[0],o.height??e[1]];var e},[c,a,o.height,o.width,s,r]),d=o.compactMode?"sparkline"===i.chartMode?{top:2,right:2,bottom:2,left:2}:{top:8,right:8,bottom:8,left:8}:{top:0,right:0,bottom:0,left:0};const u=e.showProjection??!o.compactMode,h=e.showChrome??!o.compactMode,p=Ka(e.tooltip,void 0),m=void 0!==p.enableHover?p.enableHover:o.enableHover,f=o.compactMode?o.title:o.title??e.title,y=[e.className,i.chartMode&&"primary"!==i.chartMode?"semiotic-physics--"+i.chartMode:null].filter(Boolean).join(" ")||void 0;return{chartMode:i.chartMode,simulationMode:i.simulationMode,resolved:o,chartSize:l,margin:d,showProjection:u,showChrome:h,enableHover:m,title:f,description:o.description??e.description,summary:o.summary??e.summary,accessibleTable:o.accessibleTable??e.accessibleTable,className:y,compactMode:o.compactMode,mobileInteraction:o.mobileInteraction,mobileSemantics:o.mobileSemantics}}function Xa(e){const[t,n]=e.size,i=function(e,t,n,i){if(!e)return null;if(!1===i)return null;if(null!=i)return(0,xa.jsx)("div",{style:{width:t,height:n,display:"flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box"},children:i});const o=Math.min(5,Math.floor(n/40)),r=Math.max(8,Math.floor(n/(3*o))),s=Math.max(6,Math.floor(n/(2.5*o))),a=Math.floor((n-(o*(r+s)-s))/2);return(0,xa.jsx)("div",{style:{width:t,height:n,position:"relative",overflow:"hidden",border:"1px solid var(--semiotic-border, #e0e0e0)",borderRadius:4,boxSizing:"border-box"},children:Array.from({length:o},(e,n)=>(0,xa.jsx)("div",{className:"semiotic-loading-bar",style:{...ka,position:"absolute",top:a+n*(r+s),left:Math.floor(.1*t),width:30+(37*n+13)%50+"%",height:r,opacity:.5+n%2*.2}},n))})}(e.loading,t,n,e.loadingContent);return i||function(e,t,n,i){return!1===i||null==e||Array.isArray(e)&&e.length>0?null:Array.isArray(e)?(0,xa.jsx)("div",{style:{...wa,width:t,height:n},children:i||"No data available"}):null}(e.data,t,n,e.emptyContent)}function Va(e,t,n){return(0,Ya.jsx)(va,{componentName:e,width:t[0],height:t[1],children:n})}function Ua(e,t){return e?t?n=>(0,Ya.jsxs)(Ya.Fragment,{children:["function"==typeof e?e(n):e,"function"==typeof t?t(n):t]}):e:t}function Ka(e,t){return!1===e?{enableHover:!1}:{enableHover:t?.enableHover,tooltipContent:Ne(e)||t?.tooltipContent}}function Qa(e,t,n,i){return{accessibleTable:i?.accessibleTable??e.accessibleTable??t?.accessibleTable,annotations:e.annotations??t?.annotations,autoPlaceAnnotations:e.autoPlaceAnnotations??t?.autoPlaceAnnotations,background:e.background??t?.background,chartId:e.chartId??t?.chartId,chartMode:i?.chartMode??t?.chartMode,className:i?.className??e.className??t?.className,color:e.color??t?.color,description:i?.description??e.description??t?.description,emphasis:e.emphasis??t?.emphasis,enableHover:i?.enableHover??t?.enableHover,hoverRadius:e.hoverRadius??t?.hoverRadius,legend:e.legend??t?.legend,legendLayout:e.legendLayout??t?.legendLayout,legendPosition:e.legendPosition??t?.legendPosition,margin:i?.margin??t?.margin,onClick:null!=e.onClick?(t,n)=>{t&&e.onClick?.(t,{x:n.x,y:n.y})}:t?.onClick,onObservation:e.onObservation??t?.onObservation,onAnnotationActivate:t?.onAnnotationActivate,opacity:e.opacity??t?.opacity,semanticItems:t?.semanticItems??n,stroke:e.stroke??t?.stroke,strokeWidth:e.strokeWidth??t?.strokeWidth,summary:i?.summary??e.summary??t?.summary,svgAnnotationRules:e.svgAnnotationRules??t?.svgAnnotationRules,title:i?.title??e.title??t?.title}}var Za=require("react/jsx-runtime"),Ja=(0,d.forwardRef)(function(e,t){const{data:n,valueAccessor:i="value",styleRules:o,bins:r=21,ballRadius:s,colorBy:a,branchProbability:c=.5,emptyContent:l,frameProps:u,loading:h,loadingContent:p,mechanicalCount:m,paused:f,pegRows:y,referenceLines:g,rerunMS:b,responsiveHeight:x,responsiveWidth:v,seed:w=1,valueExtent:k}=e,M=Ga(e,[700,420],{hasSimulationMode:!0}),{chartSize:I,simulationMode:S,showProjection:j,className:A,title:C,chartMode:R,margin:$,enableHover:P,description:D,summary:B,accessibleTable:T}=M,E=s??("sparkline"===R?1.5:"context"===R?4:6),N=(0,d.useRef)(null),O=Math.max(1,Math.round(y??r-1)),W=(0,d.useMemo)(()=>"mechanical"===S?[0,O]:function(e){if(!e)return;const t=Number(e[0]),n=Number(e[1]);return Number.isFinite(t)&&Number.isFinite(n)?t>n?[n,t]:[t,n]:void 0}(k),[O,S,k]),q=(0,d.useMemo)(()=>"mechanical"===S?function(e){const t=Math.max(2,Math.round(e.bins)),n=Math.max(1,Math.round(e.pegRows??t-1)),i=Math.max(1,Math.round(e.count??Math.max(64,4*t))),o=xs(Number.isFinite(e.branchProbability)?e.branchProbability??.5:.5,0,1),r=ks(e.seed??1),s=e.idPrefix??"mechanical";return Array.from({length:i},(e,t)=>{let i=0;for(let e=0;n>e;e+=1)r()<o&&(i+=1);const a=n/2;return{id:`${s}-${t}`,value:i,mechanical:!0,pegRows:n,branchProbability:o,pathRights:i,side:a>i?"left":i>a?"right":"center"}})}({bins:r,branchProbability:c,count:m,pegRows:O,seed:w}):n??[],[r,c,n,m,O,w,S]),F=(0,d.useMemo)(()=>Is({data:q,valueAccessor:i,bins:r,ballRadius:E,seed:w,size:I,valueExtent:W}),[r,q,I,E,W,w,i]),z=_a(F.config,b,f);ha(t,{frameRef:N,spawnDatum:(0,d.useCallback)((e,t)=>{const n=Is({data:[e],valueAccessor:i,bins:r,ballRadius:E,seed:w+t+1,size:I,valueExtent:W}).initialSpawns[0]??{id:(e.id??"galton-push-"+t)+"",x:hs(I).plot.x,y:hs(I).plot.y,mass:1,shape:{type:"circle",radius:E},datum:e};return{datumId:(e.id??n.id)+"",spawns:[n]}},[r,I,E,W,w,i]),seedRows:q,seedSpawns:F.initialSpawns});const L="mechanical"===S&&null==a?"side":a,Y=(0,d.useMemo)(()=>ms(L,"#4e79a7",{styleRules:o,valueAccessor:i}),[L,o,i]),H=(0,d.useMemo)(()=>ys(F.projectionRows,I,"bin"),[I,F.projectionRows]),_=Xa({data:"mechanical"===S?q:n,emptyContent:l,loading:h,loadingContent:p,size:I});if(_)return _;const G=function(e,t,n,i,o){const r=Array.isArray(o)?o:o?[o]:[];if(!1!==n||0!==r.length)return({size:o})=>{const s=[Number(o[0])||700,Number(o[1])||420],a=hs(s),c=Math.max(2,Math.round(t)),l=a.plot.width/c,d=a.plot.y+a.plot.height,u=Math.max(1,...e.map(e=>e.value)),h=!1!==n,[p,m]=i?.valueExtent??[0,c],f=m===p?1:m-p,y=e.map((e,t)=>{const n=d-e.value/u*a.plot.height*.9;return`${0===t?"M":"L"} ${(a.plot.x+(t+.5)*l).toFixed(1)} ${n.toFixed(1)}`}).join(" ");return(0,Za.jsxs)("svg",{"aria-hidden":"true","data-testid":"galton-board-structure-overlay",width:s[0],height:s[1],viewBox:`0 0 ${s[0]} ${s[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[h?(0,Za.jsxs)(Za.Fragment,{children:[Array.from({length:c+1},(e,t)=>{const n=a.plot.x+t*l;return(0,Za.jsx)("line",{"data-testid":"galton-board-bin-wall",x1:n,x2:n,y1:a.plot.y,y2:d,stroke:"var(--semiotic-border, #d1d5db)",strokeOpacity:.28,strokeWidth:1},"bin-wall-"+t)}),(0,Za.jsx)("line",{x1:a.plot.x,x2:a.plot.x+a.plot.width,y1:d,y2:d,stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:1.5}),(0,Za.jsx)("path",{d:y,fill:"none",stroke:"var(--semiotic-accent, #4e79a7)",strokeOpacity:.7,strokeWidth:2,strokeLinejoin:"round"}),e.map((e,t)=>e.value>0?(0,Za.jsx)("text",{x:a.plot.x+(t+.5)*l,y:Math.max(a.plot.y+10,d-e.value/u*a.plot.height*.9-6),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:e.value},`${e.label}-${t}`):null)]}):null,r.map((e,t)=>{const n=Number(e.value);if(!Number.isFinite(n))return null;const i=a.plot.x+Math.max(0,Math.min(1,(n-p)/f))*a.plot.width,o=e.color??"var(--semiotic-warning, #f28e2b)",r="bottom"===e.labelPosition?Math.min(s[1]-8,d+16):a.plot.y+16;return(0,Za.jsxs)("g",{className:e.className,"data-testid":"galton-board-reference-line",children:[(0,Za.jsx)("line",{x1:i,x2:i,y1:a.plot.y+8,y2:d-4,stroke:o,strokeDasharray:e.strokeDasharray??"6 5",strokeWidth:e.strokeWidth??2}),null==e.label?null:(0,Za.jsx)("text",{x:Math.min(a.plot.x+a.plot.width-4,i+6),y:r,fill:o,fontSize:10,fontWeight:700,children:e.label})]},`galton-reference-${t}-${n}`)})]})}}(F.projectionRows,r,j,F.metadata,g),X=Ka(e.tooltip,u),V=Qa(e,u,H,{chartMode:R,className:A,title:C,description:D,summary:B,accessibleTable:T,enableHover:P,margin:$});return Va("GaltonBoardChart",I,(0,Za.jsx)(rs,{...u,...X,...V,ref:N,config:z.config,foregroundGraphics:Ua(G,u?.foregroundGraphics),initialSpawns:F.initialSpawns,initialSpawnPacing:F.initialSpawnPacing,paused:f,responsiveHeight:x,responsiveWidth:v,size:I,bodyStyle:Y},z.rerunKey))}),ec=require("react"),tc=require("react/jsx-runtime"),nc=(0,ec.forwardRef)(function(e,t){const{arrivalAccessor:n="arrivalTime",ballRadius:i=7,colorBy:o,styleRules:r,data:s,emptyContent:a,frameProps:c,loading:l,loadingContent:d,paused:u,responsiveHeight:h,responsiveWidth:p,seed:m=1,timeAccessor:f="time",timeExtent:y,timeScale:g=1,watermark:b,windows:x={size:10}}=e,v=Ga(e,[760,360]),{chartSize:w,showProjection:k,className:M,title:I,chartMode:S,margin:j,enableHover:A,description:C,summary:R,accessibleTable:$}=v,P=(0,ec.useRef)(null),D=(0,ec.useMemo)(()=>s??[],[s]),B=(0,ec.useMemo)(()=>As({data:D,timeAccessor:f,arrivalAccessor:n,windows:x,watermark:b,ballRadius:i,seed:m,size:w,timeExtent:y,timeScale:g}),[n,i,w,D,m,f,y,g,b,x]),T=B.metadata;ha(t,{frameRef:P,spawnDatum:(0,ec.useCallback)((e,t)=>{const o=T?function(e,t,n,i){const o=bs(gs(e,t,i.timeAccessor));if(null==o)return null;const r=bs(gs(e,t,i.arrivalAccessor))??o,{windowPlot:s,windowStart:a,windowCount:c,windowSize:l,watermarkValue:d}=n,u=a+c*l,h=(0,Ss.scaleLinear)().domain([a,u]).range([s.x,s.x+s.width]),p=Math.max(0,Math.min(c-1,Math.floor((o-a)/l))),m=d>=a+(p+1)*l,{ballRadius:f}=i;return{id:(e.id??"event-push-"+t)+"",x:Math.max(s.x+f,Math.min(s.x+s.width-f,h(o))),y:s.y+f+2,vx:8*(t%3-1),vy:0,mass:1,friction:.02,shape:{type:"circle",radius:f},datum:{...e,eventTime:o,arrivalTime:r,windowIndex:p,late:m}}}(e,t,T,{timeAccessor:f,arrivalAccessor:n,ballRadius:i}):null,r=o??{id:(e.id??"event-push-"+t)+"",x:hs(w).plot.x,y:hs(w).plot.y,mass:1,shape:{type:"circle",radius:i},datum:e};return{datumId:(e.id??r.id)+"",spawns:[r]}},[n,i,w,T,f]),seedRows:D,seedSpawns:B.initialSpawns});const E=(0,ec.useMemo)(()=>ms(o,"#4e79a7",{styleRules:r,valueAccessor:f}),[o,r,f]),N=(0,ec.useMemo)(()=>function(e,t,n){if(!t)return ys(e,n,"window");const i=t.windowPlot.width/Math.max(1,e.length),o=Math.max(1,...e.map(e=>e.value+(e.secondary??0))),r=.62*t.windowPlot.height,s=t.windowPlot.y+t.windowPlot.height;return e.map((e,n)=>{const a=Math.max(8,(e.value+(e.secondary??0))/o*r),c=`window ${e.label}: ${e.value} on time${e.secondary?`, ${e.secondary} late`:""}`;return{id:"window-"+e.label,label:c,description:c,datum:e,x:t.windowPlot.x+(n+.5)*i,y:s-a/2,shape:"rect",width:Math.max(12,.58*i),height:a,group:"window"}})}(B.projectionRows,T,w),[w,B.projectionRows,T]),O=Xa({data:s,emptyContent:a,loading:l,loadingContent:d,size:w});if(O)return O;const W=function(e,t,n){if(!1!==n&&t)return({size:n})=>{const i=[Number(n[0])||760,Number(n[1])||360],o=hs(i),r=Math.max(1,t.windowCount),s=t.plot??o.plot,a=t.gutter??{x:s.x,y:s.y,width:0,height:s.height},c=t.windowPlot??s,l=c.width/r,d=s.y+s.height,u=s.y+.48*s.height,h=t.lidSegments[0]?.y1??u,p=t.windowStart,m=t.windowStart+r*t.windowSize,f=c.x+Math.max(0,Math.min(1,m===p?0:(t.watermarkValue-p)/(m-p)))*c.width;return(0,tc.jsxs)("svg",{"aria-hidden":"true","data-testid":"event-drop-window-overlay",width:i[0],height:i[1],viewBox:`0 0 ${i[0]} ${i[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[(0,tc.jsx)("rect",{x:s.x,y:s.y,width:s.width,height:s.height,fill:"none",stroke:"var(--semiotic-border, #d1d5db)",strokeOpacity:.7,strokeWidth:1}),a.width>0?(0,tc.jsxs)("g",{children:[(0,tc.jsx)("rect",{x:a.x,y:h,width:a.width,height:d-h,fill:"var(--semiotic-negative, #e15759)",fillOpacity:.07,stroke:"var(--semiotic-border, #d1d5db)",strokeOpacity:.55,strokeWidth:1}),(0,tc.jsx)("text",{x:a.x+a.width/2,y:h-8,textAnchor:"middle",fill:"var(--semiotic-negative, #e15759)",fontSize:10,fontWeight:700,children:"gutter"})]}):null,Array.from({length:r},(n,o)=>{const r=e[o],s=c.x+o*l,a=t.closedWindowCount>o,h=r?.secondary??0;return(0,tc.jsxs)("g",{children:[(0,tc.jsx)("rect",{x:s,y:u,width:l,height:d-u,fill:a?"var(--semiotic-negative, #e15759)":"var(--semiotic-accent, #4e79a7)",fillOpacity:a?.08:.06,stroke:"var(--semiotic-border, #d1d5db)",strokeOpacity:.68,strokeWidth:1}),a?t.lidSegments.filter(e=>e.windowIndex===o).map(e=>(0,tc.jsx)("line",{x1:e.x1,x2:e.x2,y1:e.y1,y2:e.y2,stroke:"var(--semiotic-negative, #e15759)",strokeOpacity:.78,strokeWidth:2,strokeLinecap:"round"},e.id)):null,(0,tc.jsxs)("text",{x:s+l/2,y:u-8,textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:[r?.value??0,h?` / ${h} late`:""]}),(0,tc.jsx)("text",{x:s+l/2,y:Math.min(i[1]-8,d+16),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:r?.label??""})]},"window-"+o)}),t.lidSegments.filter(e=>null==e.windowIndex).map(e=>(0,tc.jsx)("line",{x1:e.x1,x2:e.x2,y1:e.y1,y2:e.y2,stroke:"var(--semiotic-negative, #e15759)",strokeOpacity:.62,strokeWidth:2,strokeLinecap:"round"},e.id)),(0,tc.jsx)("line",{x1:s.x,x2:s.x+s.width,y1:d,y2:d,stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:1.5}),(0,tc.jsx)("line",{"data-testid":"event-drop-watermark",x1:f,x2:f,y1:s.y+8,y2:d,stroke:"var(--semiotic-warning, #f28e2b)",strokeDasharray:"5 4",strokeWidth:2}),(0,tc.jsxs)("text",{x:Math.min(s.x+s.width-4,f+6),y:s.y+16,fill:"var(--semiotic-warning, #f28e2b)",fontSize:10,fontWeight:700,children:["watermark ",Math.round(100*t.watermarkValue)/100]}),t.lateCount>0?(0,tc.jsxs)("text",{x:a.x+a.width/2,y:s.y+32,textAnchor:"middle",fill:"var(--semiotic-negative, #e15759)",fontSize:10,fontWeight:700,children:[t.lateCount," late"]}):null]})}}(B.projectionRows,B.metadata,k),q=Ka(e.tooltip,c),F=Qa(e,c,N,{chartMode:S,className:M,title:I,description:C,summary:R,accessibleTable:$,enableHover:A,margin:j});return Va("EventDropChart",w,(0,tc.jsx)(rs,{...c,...q,...F,ref:P,config:B.config,foregroundGraphics:Ua(W,c?.foregroundGraphics),initialSpawns:B.initialSpawns,initialSpawnPacing:B.initialSpawnPacing,paused:u,responsiveHeight:h,responsiveWidth:p,size:w,bodyStyle:E}))}),ic=require("react"),oc=require("react/jsx-runtime"),rc=(0,ic.forwardRef)(function(e,t){const{ballRadius:n=8,categoryAccessor:i="category",colorBy:o,data:r,emptyContent:s,frameProps:a,loading:c,loadingContent:l,mechanicalCategories:d,mechanicalCount:u,paused:h,responsiveHeight:p,responsiveWidth:m,seed:f=1,unitValue:y=1,valueAccessor:g,styleRules:b}=e,x=Ga(e,[700,380],{hasSimulationMode:!0}),{chartSize:v,simulationMode:w,showProjection:k,className:M,title:I,chartMode:S,margin:j,enableHover:A,description:C,summary:R,accessibleTable:$}=x,P=(0,ic.useRef)(null),D="mechanical"===w&&null==g?"value":g,B=(0,ic.useMemo)(()=>"mechanical"===w?function(e={}){const t=(e.categories?.length?e.categories:["Intake","Review","Build","Ship"]).map(e=>(e+"").trim()).filter(Boolean),n=t.length?t:["Intake"],i=Math.max(n.length,Math.round(e.count??Math.max(48,12*n.length))),o=vs(e.unitValue,1),r=ks(e.seed??1),s=e.idPrefix??"mechanical-pile",a=n.map(()=>.65+.9*r()),c=a.reduce((e,t)=>e+t,0)||1,l=i-n.length,d=a.map(e=>e/c*l),u=d.map(e=>1+Math.floor(e));let h=i-u.reduce((e,t)=>e+t,0);const p=d.map((e,t)=>({index:t,fraction:e-Math.floor(e)})).sort((e,t)=>t.fraction-e.fraction);for(let e=0;h>0;e=(e+1)%p.length)u[p[e].index]+=1,h-=1;return n.map((e,t)=>({id:`${s}-${t}`,category:e,value:u[t]*o,mechanical:!0,unitCount:u[t],unitValue:o,share:u[t]/i}))}({categories:d,count:u,seed:f,unitValue:y}):r??[],[r,d,u,f,w,y]),T=(0,ic.useMemo)(()=>Rs({data:B,categoryAccessor:i,valueAccessor:D,unitValue:y,ballRadius:n,seed:f,size:v}),[n,i,v,B,D,f,y]);ha(t,{frameRef:P,spawnDatum:(0,ic.useCallback)((e,t)=>{const o=Rs({data:[e],categoryAccessor:i,valueAccessor:D,unitValue:y,ballRadius:n,seed:f+t+1,size:v}),r={id:(e.id??"pile-push-"+t)+"",x:hs(v).plot.x,y:hs(v).plot.y,mass:1,shape:{type:"circle",radius:n},datum:e},s=o.initialSpawns.length?o.initialSpawns:[r];return{datumId:(e.id??s[0].id)+"",spawns:s}},[n,i,v,D,f,y]),seedRows:B,seedSpawns:T.initialSpawns});const E="mechanical"===w&&null==o?"category":o,N=(0,ic.useMemo)(()=>ms(E,"#4e79a7",{styleRules:b,valueAccessor:g}),[E,b,g]),O=(0,ic.useMemo)(()=>ys(T.projectionRows,v,"category"),[v,T.projectionRows]),W=Xa({data:"mechanical"===w?B:r,emptyContent:s,loading:c,loadingContent:l,size:v});if(W)return W;const q=function(e,t,n){if(!1!==n&&0!==e.length)return({size:n})=>{const i=[Number(n[0])||700,Number(n[1])||380],o=hs(i),r=Cs(o.plot,e.length,t),s=o.plot.y+o.plot.height;return(0,oc.jsxs)("svg",{"aria-hidden":"true","data-testid":"physics-pile-projection-overlay",width:i[0],height:i[1],viewBox:`0 0 ${i[0]} ${i[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[(0,oc.jsx)("line",{x1:o.plot.x,x2:o.plot.x+o.plot.width,y1:s,y2:s,stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:1}),e.map((e,t)=>{const n=Math.min(o.plot.height,r.pileHeight(e.value)),a=r.tubeWidth,c=r.centerX(t),l=s-n;return(0,oc.jsxs)("g",{children:[(0,oc.jsx)("rect",{x:c-a/2,y:l,width:a,height:n,rx:3,fill:"var(--semiotic-accent, #4e79a7)",fillOpacity:.08,stroke:"var(--semiotic-accent, #4e79a7)",strokeOpacity:.42,strokeWidth:1,strokeDasharray:"4 3"}),(0,oc.jsx)("text",{x:c,y:Math.max(o.plot.y+12,l-6),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:11,fontWeight:700,children:e.value}),(0,oc.jsx)("text",{x:c,y:Math.min(i[1]-8,s+16),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:e.label})]},`${e.label}-${t}`)})]})}}(T.projectionRows,n,k),F=Ka(e.tooltip,a),z=Qa(e,a,O,{chartMode:S,className:M,title:I,description:C,summary:R,accessibleTable:$,enableHover:A,margin:j});return Va("PhysicsPileChart",v,(0,oc.jsx)(rs,{...a,...F,...z,ref:P,config:T.config,foregroundGraphics:Ua(q,a?.foregroundGraphics),initialSpawns:T.initialSpawns,initialSpawnPacing:T.initialSpawnPacing,paused:h,responsiveHeight:p,responsiveWidth:m,size:v,bodyStyle:N}))}),sc=require("react"),ac=Object.freeze([]);function cc(e){if(!e)return ac;let t=!1;for(let n=0;e.length>n;n++){const i=e[n];if(null==i||"object"!=typeof i){t=!0;break}}if(!t)return e;const n=[];for(const t of e)null!=t&&"object"==typeof t&&n.push(t);return n}var lc=require("d3-scale");function dc(e,t){const n=t&&"object"==typeof t&&!Array.isArray(t)?t:void 0;return 0===e.length?e=>n&&Na(n,e)||"#4e79a7":t=>{if(n){const e=Na(n,t);if(e)return e}let i=0;for(let e=0;t.length>e;e++)i=31*i+t.charCodeAt(e)|0;return e[Math.abs(i)%e.length]??"#4e79a7"}}function uc(e,t){const n=t.config??{},i=(t.sensors??[]).map(e=>({...e,sensor:!0})),o=[...t.colliders??[],...i],r=[...e.colliders??[],...n.colliders??[],...o];return{...e,...n,observation:{...e.observation,...n.observation},...r.length>0&&{colliders:r}}}function hc(e){const t=function(e,t,n){const i=e?.observation;return{...e,observation:{...i,chartId:t??i?.chartId??"physics-custom",chartType:i?.chartType??"PhysicsCustomChart",onObservation:n??i?.onObservation}}}(e.config,e.chartId,e.onObservation),n=function(e,t,n=Ea){if(e&&"object"==typeof e&&!Array.isArray(e)){const t=Object.values(e).filter(e=>"string"==typeof e&&e.length>0);if(t.length>0)return t}if(Array.isArray(e)&&e.length>0)return e;if("string"==typeof e){const t=Ta[e];if(Array.isArray(t)&&t.length>0)return t}return t&&t.length>0?t:n}(e.colorScheme,e.themeCategorical,ja),i=hs(e.size),o={data:e.data,scales:{x:(0,lc.scaleLinear)().domain(e.xExtent??[0,1]).range([i.plot.x,i.plot.x+i.plot.width]),y:(0,lc.scaleLinear)().domain(e.yExtent??[0,1]).range([i.plot.y+i.plot.height,i.plot.y])},dimensions:i,theme:{semantic:e.semantic,categorical:[...n]},resolveColor:dc(n,e.colorScheme),config:e.layoutConfig??{},world:new ko(t)},r=e.skipLayout?{}:e.layout(o)??{},s=function(e,t){if(!t?.length)return e;const n=new Map;for(const e of t){const{bodyId:t,...i}=e,o=n.get(t)??[];o.push(i),n.set(t,o)}return e.map(e=>{const t=n.get(e.id);return t?.length?{...e,springs:[...e.springs??[],...t]}:e})}([...r.initialSpawns??r.bodies??[]],r.constraints);return{config:uc(t,r),context:o,initialSpawnPacing:r.initialSpawnPacing,initialSpawns:s,result:r}}var pc=require("react/jsx-runtime"),mc=(0,sc.forwardRef)(function(e,t){const{chartId:n,color:i,colorBy:o,colorScheme:r,config:s,controllers:a,data:c,emptyContent:l,frameProps:d={},layout:u,layoutConfig:h,loading:p,loadingContent:m,onObservation:f,opacity:y,paused:g,spawnDatum:b,stroke:x,strokeWidth:v,title:k,xExtent:M,yExtent:I}=e,S=Ga(e,[700,380]),{chartSize:A,className:C,title:R,chartMode:$,margin:P,enableHover:D,description:B,summary:T,accessibleTable:E}=S,N=(0,sc.useRef)(null),O=(0,sc.useRef)(null),W=(0,sc.useRef)(""),q=Xa({data:c,emptyContent:l,loading:p,loadingContent:m,size:A}),F=null!=q,z=(0,sc.useMemo)(()=>cc(c??[]),[c]),L=j(e=>e.theme),Y=(0,sc.useMemo)(()=>function(e){if(!e?.colors)return;const t=e.colors;return{primary:t.primary,secondary:t.secondary||t.primary,surface:t.surface||t.background,success:t.success,danger:t.danger,warning:t.warning,error:t.error,info:t.info,text:t.text,textSecondary:t.textSecondary,border:t.border,grid:t.grid}}(L)??{},[L]),H=L?.colors?.categorical??w.colors.categorical,_=(0,sc.useMemo)(()=>[A[0],A[1],z.length,z.map((e,t)=>(e.id??t)+"").join("|"),M?.join(",")??"",I?.join(",")??""].join("::"),[A,z,M,I]),G=(0,sc.useMemo)(()=>hc({chartId:n,colorScheme:r,config:s,data:z,layout:u,layoutConfig:h,onObservation:f,semantic:Y,skipLayout:F,size:A,themeCategorical:H,xExtent:M,yExtent:I}),[n,A,r,s,u,h,f,z,Y,F,H,M,I]);W.current===_&&null!=O.current||(W.current=_,O.current=G.initialSpawns);const X=O.current,V=(0,sc.useMemo)(()=>{const e=[...G.result.controllers??[],...a??[],...d.controllers??[]];return e.length?e:void 0},[d.controllers,a,G.result.controllers]),U=(0,sc.useMemo)(()=>{const e=[...G.result.regionEffects??[],...d.regionEffects??[]];return e.length?e:void 0},[d.regionEffects,G.result.regionEffects]),K=(0,sc.useCallback)(e=>{const t=e.datum,n=t&&o?function(e,t,n){return"function"==typeof n?n(e,0):e[n]}(t,0,o)+"":e.id;return{fill:i??G.context.resolveColor(n,t),stroke:x??"#111827",strokeWidth:v??1,opacity:y??.9}},[i,o,y,G.context,x,v]);ha(t,{frameRef:N,spawnDatum:(0,sc.useCallback)((e,t)=>{const i=e;if(b)return function(e,t,n){return Array.isArray(n)?{datumId:(e.id??n[0]?.id??"physics-custom-"+t)+"",spawns:n}:"spawns"in n?n:{datumId:(e.id??n.id??"physics-custom-"+t)+"",spawns:[n]}}(e,t,b(i,t,G.context));const o=hc({chartId:n,colorScheme:r,config:s,data:[i],layout:u,layoutConfig:h,onObservation:f,semantic:Y,size:A,themeCategorical:H,xExtent:M,yExtent:I}),a=o.initialSpawns.length?o.initialSpawns:[{id:(e.id??"physics-custom-"+t)+"",x:o.context.dimensions.plot.x+o.context.dimensions.plot.width/2,y:o.context.dimensions.plot.y+12,mass:1,shape:{type:"circle",radius:5},datum:e}];return{datumId:(e.id??a[0].id)+"",spawns:a}},[n,A,r,s,b,u,h,f,G.context,Y,H,M,I]),seedRows:z,seedSpawns:X});const Q=(0,sc.useCallback)((e,t)=>{d.onBodyPointerDown?.(e,t)},[d]);if(q)return q;const Z=Ka(e.tooltip,d),J=Qa(e,d,G.result.semanticItems,{chartMode:$,className:C,title:R??k,description:B,summary:T,accessibleTable:E,enableHover:D,margin:P});return Va("PhysicsCustomChart",A,(0,pc.jsx)(rs,{...d,...Z,...J,ref:N,backgroundGraphics:Ua(d.backgroundGraphics,G.result.backgroundOverlays),bodyForces:G.result.bodyForces??d.bodyForces,bodyStyle:G.result.bodyStyle??d.bodyStyle??K,config:G.config,controllers:V,foregroundGraphics:Ua(d.foregroundGraphics,G.result.overlays),initialSpawnPacing:G.initialSpawnPacing,initialSpawns:X,onBodyPointerDown:Q,paused:g,regionEffects:U,responsiveHeight:e.responsiveHeight,responsiveWidth:e.responsiveWidth,selectedBodyStyle:G.result.selectedBodyStyle??d.selectedBodyStyle,size:A}))});mc.displayName="PhysicsCustomChart";var fc=require("react"),yc=require("react/jsx-runtime");function gc(e){return e.toLocaleString(void 0,Math.abs(e)>=1e3||.01>Math.abs(e)?{maximumFractionDigits:0}:{maximumFractionDigits:2})}var bc=(0,fc.forwardRef)(function(e,t){const{colorBy:n,styleRules:i,collisionIterations:o,data:r,emptyContent:s,frameProps:a,groupAccessor:c,loading:l,loadingContent:d,paused:u,pointRadius:h,radiusAccessor:p,rerunMS:m,responsiveHeight:f,responsiveWidth:y,seed:g=1,settle:b,xAccessor:x="x",xExtent:v}=e,w=Ga(e,[700,360]),{chartSize:k,showProjection:M,className:I,title:S,chartMode:j,margin:A,enableHover:C,description:R,summary:$,accessibleTable:P}=w,D=h??("sparkline"===j?2:"context"===j?4:5),B=(0,fc.useRef)(null),T=(0,fc.useMemo)(()=>r??[],[r]),E=(0,fc.useMemo)(()=>Ps({data:T,xAccessor:x,groupAccessor:c,radiusAccessor:p,pointRadius:D,seed:g,size:k,xExtent:v,collisionIterations:o,settle:b}),[T,k,o,c,D,p,g,b,x,v]),N=_a(E.config,m,u);ha(t,{frameRef:B,spawnDatum:(0,fc.useCallback)((e,t)=>{const n=Ps({data:[e],xAccessor:x,groupAccessor:c,radiusAccessor:p,pointRadius:D,seed:g+t+1,size:k,xExtent:v,collisionIterations:o,settle:b}).initialSpawns[0]??{id:(e.id??"collision-swarm-push-"+t)+"",x:hs(k).plot.x,y:hs(k).plot.y,mass:1,shape:{type:"circle",radius:D},datum:e};return{datumId:(e.id??n.id)+"",spawns:[n]}},[k,o,c,D,p,g,b,x,v]),seedRows:T,seedSpawns:E.initialSpawns});const O=n??c,W=(0,fc.useMemo)(()=>ms(O,"#4e79a7",{styleRules:i,valueAccessor:x}),[O,i,x]),q=Xa({data:r,emptyContent:s,loading:l,loadingContent:d,size:k});if(q)return q;const F=function(e,t){if(!1!==t&&e)return({size:t})=>{const n=[Number(t[0])||700,Number(t[1])||360],i=hs(n),o=i.plot.y+i.plot.height,[r,s]=e.xExtent,a=r+(s-r)/2,c=[{label:gc(r),x:e.xRange[0]},{label:gc(a),x:e.xRange[0]+(e.xRange[1]-e.xRange[0])/2},{label:gc(s),x:e.xRange[1]}];return(0,yc.jsxs)("svg",{"aria-hidden":"true","data-testid":"collision-swarm-projection-overlay",width:n[0],height:n[1],viewBox:`0 0 ${n[0]} ${n[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[e.groups.map(e=>(0,yc.jsxs)("g",{children:[(0,yc.jsx)("line",{x1:i.plot.x,x2:i.plot.x+i.plot.width,y1:e.y,y2:e.y,stroke:"var(--semiotic-border, #d1d5db)",strokeDasharray:"3 5",strokeWidth:1}),(0,yc.jsx)("text",{x:i.plot.x+4,y:e.y-7,fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:e.label}),(0,yc.jsxs)("text",{x:i.plot.x+i.plot.width-4,y:e.y-7,textAnchor:"end",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:["n=",e.count]})]},e.label)),(0,yc.jsx)("line",{x1:e.xRange[0],x2:e.xRange[1],y1:o,y2:o,stroke:"var(--semiotic-text-secondary, #555)",strokeWidth:1}),c.map(e=>(0,yc.jsxs)("g",{children:[(0,yc.jsx)("line",{x1:e.x,x2:e.x,y1:o,y2:o+5,stroke:"var(--semiotic-text-secondary, #555)",strokeWidth:1}),(0,yc.jsx)("text",{x:e.x,y:Math.min(n[1]-8,o+18),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:e.label})]},`${e.label}-${e.x}`))]})}}(E.metadata,M),z=function(e){if(!e)return[];const t=Math.max(24,e.xRange[1]-e.xRange[0]),n=e.xRange[0]+t/2;return e.groups.map(e=>{const i=`${e.label} lane: ${e.count} points`;return{id:"collision-swarm-"+e.label,label:i,description:i,datum:e,x:n,y:e.y,shape:"rect",width:t,height:28,group:"lane"}})}(E.metadata),L=Ka(e.tooltip,a),Y=Qa(e,a,z,{chartMode:j,className:I,title:S,description:R,summary:$,accessibleTable:P,enableHover:C,margin:A});return Va("CollisionSwarmChart",k,(0,yc.jsx)(rs,{...a,...L,...Y,ref:B,config:N.config,foregroundGraphics:Ua(F,a?.foregroundGraphics),initialSpawns:E.initialSpawns,paused:u,responsiveHeight:f,responsiveWidth:y,size:k,bodyStyle:W},N.rerunKey))}),xc={fresh:1,aging:1.5,stale:3};function vc(e,t,n={}){return Number.isFinite(t)&&t>0?Number.isNaN(e)?"fresh":e===1/0?"expired":0>e||t*(n.fresh??xc.fresh)>e?"fresh":t*(n.aging??xc.aging)>e?"aging":t*(n.stale??xc.stale)>e?"stale":"expired":"fresh"}function wc(e,t,n){if(null!=e)return"function"==typeof e?e(t,n):"object"==typeof e&&null!==e&&"constant"in e?e.constant:t[e]}function kc(e){const{data:t,encoding:n}=e,i=[],o=new Map;return t.forEach((e,t)=>{const r=wc(n.id,e,t);if(null==r||""===r)throw Error(`[semiotic] Motion encoding row ${t} resolved an empty id.`);const s=r+"";if(o.has(s))throw Error(`[semiotic] Duplicate motion encoding id "${s}".`);const a=wc(n.process?.group,e,t),c=wc(n.process?.stage,e,t),l=wc(n.accessible?.group,e,t)??(null!=a?a+"":null!=c?c+"":void 0),d={};for(const i of Object.keys(n.evidence??{}))d[i]=wc(n.evidence?.[i],e,t);const u={id:s,datum:e,time:{arrival:wc(n.time?.arrival,e,t),basis:n.time?.basis,unit:n.time?.unit},placement:{x:wc(n.placement?.x,e,t),y:wc(n.placement?.y,e,t),lane:wc(n.placement?.lane,e,t),space:n.placement?.space},kinematics:{velocityX:wc(n.kinematics?.velocityX,e,t),velocityY:wc(n.kinematics?.velocityY,e,t),space:n.kinematics?.space},process:{group:a,stage:c,target:wc(n.process?.target,e,t),work:wc(n.process?.work,e,t)},evidence:d,accessible:{description:wc(n.accessible?.description,e,t),group:l,label:wc(n.accessible?.label,e,t)??s}};i.push(u),o.set(s,u)}),{rows:i,byId:o}}function Mc(e){const t=e.now-e.arrival;return{age:t,progress:Number.isFinite(t)&&Number.isFinite(e.ttl)&&e.ttl>0?Math.max(0,t)/e.ttl:t===1/0&&Number.isFinite(e.ttl)&&e.ttl>0?1/0:0,lifecycle:vc(t,e.ttl,e.thresholds)}}function Ic(e){const t=Math.max(0,Math.min(1,e.minOpacity??.1));if(Number.isNaN(e.age))return 1;if(e.age===1/0)return t;if(!Number.isFinite(e.extent)||0>=e.extent)return 1;const n=Math.max(0,e.age);if("step"===e.type)return(e.threshold??.5*e.extent)>n?1:t;if("exponential"===e.type){const i=e.halfLife??e.extent/2;return t+Math.pow(.5,n/(i>0?i:e.extent/2))*(1-t)}return t+Math.max(0,Math.min(1,1-n/e.extent))*(1-t)}function Sc(e,t){const n=Number.isFinite(e)?e:0,i=Number.isFinite(t)?t:0;return{velocityX:n,velocityY:i,speed:Math.hypot(n,i),direction:Math.atan2(i,n)}}function jc(e,t,n){return Number.isFinite(n)&&n>0?Sc((t.x-e.x)/n,(t.y-e.y)/n):Sc(0,0)}function Ac(e){const{data:t,encoding:n,defaults:i={},scales:o}=e,r=kc({data:t,encoding:n}),s=[],a=new Map,c=[],l=[],d=new Map;return r.rows.forEach((e,t)=>{const{id:r,datum:u}=e,h=Math.max(0,wc(n.appearance?.size,u,t)??i.size??6),p=wc(n.appearance?.shape,u,t)??i.shape??{type:"circle",radius:h},m=e.placement.x??i.x??0,f=e.placement.y??i.y??0,y=o?.x?o.x(m):m,g=o?.y?o.y(f):f,b=wc(n.appearance?.color,u,t)??i.color,x=wc(n.appearance?.opacity,u,t)??i.opacity,v=wc(n.appearance?.stroke,u,t)??i.stroke,w=wc(n.appearance?.strokeWidth,u,t)??i.strokeWidth,k=wc(n.time?.spawnAt,u,t)??e.time.arrival,M=e.kinematics.velocityX,I=e.kinematics.velocityY,S=wc(n.dynamics?.mass,u,t)??i.mass??1,j=wc(n.dynamics?.friction,u,t),A=wc(n.dynamics?.restitution,u,t),C=wc(n.dynamics?.bodyCollisions,u,t),R={id:r,x:y,y:g,mass:S,shape:{...p},datum:u,...null!=k&&{spawnAt:k},...null!=M&&{vx:M},...null!=I&&{vy:I},...null!=j&&{friction:j},...null!=A&&{restitution:A},...null!=C&&{bodyCollisions:C}},$={...null!=b&&{fill:b},...null!=x&&{opacity:x},...null!=v&&{stroke:v},...null!=w&&{strokeWidth:w}},P={id:r,datum:u,appearance:{color:b,opacity:x,shape:p,size:h,stroke:v,strokeWidth:w},placement:{x:y,y:g,lane:e.placement.lane,space:n.placement?.space??"world"},time:{arrival:k,spawnAt:k,basis:n.time?.basis??"simulation",unit:n.time?.unit},kinematics:{velocityX:M,velocityY:I,space:n.kinematics?.space??"world"},dynamics:{bodyCollisions:C,friction:j,mass:S,restitution:A},process:e.process,evidence:e.evidence,accessible:e.accessible,spawn:R};s.push(P),a.set(r,P),c.push(R),d.set(r,$),l.push({id:r,bodyId:r,label:e.accessible.label,description:e.accessible.description,datum:u,x:y,y:g,group:e.accessible.group})}),{rows:s,byId:a,spawns:c,semanticItems:l,bodyStyle:e=>d.get(e.id)??{}}}function Cc(e){return t=>{const n=Ac({data:t.data,encoding:e.encoding,defaults:e.defaults,scales:t.scales}),i=e.extend?.(t,n)??{};return{...i,initialSpawns:n.spawns,bodyStyle:n.bodyStyle,semanticItems:[...n.semanticItems,...i.semanticItems??[]]}}}var Rc=require("react");function $c(e,t={}){const n=t.id??"physics-process-boundary",i={bodyFilter:t.bodyFilter,friction:t.friction,restitution:t.restitution};if("segment"===e.type)return[{...i,id:n,shape:e}];const o=t.thickness??8,r=e.x-e.width/2,s=e.x+e.width/2,a=e.y-e.height/2,c=e.y+e.height/2;return[{...i,id:n+"-top",shape:{type:"segment",x1:r,y1:a,x2:s,y2:a,thickness:o}},{...i,id:n+"-right",shape:{type:"segment",x1:s,y1:a,x2:s,y2:c,thickness:o}},{...i,id:n+"-bottom",shape:{type:"segment",x1:s,y1:c,x2:r,y2:c,thickness:o}},{...i,id:n+"-left",shape:{type:"segment",x1:r,y1:c,x2:r,y2:a,thickness:o}}]}function Pc(e){if(!1===e.semanticItem)return null;const t=e.semanticItem??{},n=e.shape,i="aabb"===n.type?{id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"region",x:n.x,y:n.y,width:n.width,height:n.height}:{id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"region",x:(n.x1+n.x2)/2,y:(n.y1+n.y2)/2,pathData:`M ${n.x1} ${n.y1} L ${n.x2} ${n.y2}`};return{...i,...t,id:t.id??i.id}}function Dc(e){return e.map(e=>({id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"stage",x:e.x??0,y:e.y??0,width:e.width,height:e.height}))}function Bc(e){return e.flatMap(e=>{if(!1===e.semanticItem)return[];const t=e.semanticItem??{},n={id:e.id,label:e.label??e.id,description:e.description,datum:e.datum,group:e.group??e.state??"body group",x:e.x??0,y:e.y??0,width:e.width,height:e.height};return[{...n,...t,id:t.id??n.id}]})}var Tc="gauntlet-core",Ec="gauntlet-positive",Nc="gauntlet-negative";function Oc(e){const t=Hc(e);return[{id:"gauntlet-left",restitution:.12,friction:.42,shape:{type:"segment",x1:t.left,y1:t.top,x2:t.left,y2:e.floorY,thickness:t.thickness}},{id:"gauntlet-ceiling",restitution:.12,friction:.42,shape:{type:"segment",x1:t.left,y1:t.top,x2:e.width-t.rightInset,y2:t.top,thickness:t.thickness}},{id:"gauntlet-floor",restitution:.12,friction:.42,shape:{type:"segment",x1:t.left,y1:e.floorY,x2:e.width-t.rightInset,y2:e.floorY,thickness:t.thickness}},{id:"gauntlet-right",restitution:.12,friction:.42,shape:{type:"segment",x1:e.width-t.rightInset,y1:t.top,x2:e.width-t.rightInset,y2:e.floorY,thickness:t.thickness}}]}function Wc(e,t,n,i){return n?"function"==typeof n?n(e,t):e[n]??i:i}function qc(e){return e?.label??e?.id??"property"}function Fc(e){return`gauntlet:${e}:core`}function zc(e,t){return`gauntlet:${e}:positive:${t}`}function Lc(e,t,n){return`gauntlet:${e}:negative:${t}:${n}`}var Yc={left:28,top:76,rightInset:30,thickness:8};function Hc(e){const t=e.height??e.floorY+36;if(e.width>=220&&t>=160)return Yc;const n=Math.max(1,Math.min(e.width,t)),i=Math.max(2,.04*e.width);return{left:i,top:Math.max(2,.08*t),rightInset:i,thickness:Math.max(1,Math.min(4,.04*n))}}function _c(e){return Math.max(.12,Math.min(1,e.width/500,(e.height??e.floorY+36)/260))}function Gc(e,t,n,i){const o=Hc(i),r=Math.max(2,n+2),s=o.top+o.thickness/2+r,a=i.floorY-r,c=(e,t,n)=>t>n?(t+n)/2:Math.max(t,Math.min(n,e));return{x:c(e,o.left+o.thickness/2+r,i.width-o.rightInset-o.thickness/2-r),y:c(t,s,a)}}function Xc(e){return{graveyardX:e.graveyardX,graveyardY:e.graveyardY,routeY:e.routeY,socketX:e.socketX,socketY:e.routeY-4,startX:e.startX,startY:e.routeY}}function Vc(e,t,n,i){const o=Xc(n),r=i?.(e,t,n)??{};return{...o,...r,startY:r.startY??r.routeY??o.startY,socketY:r.socketY??r.routeY??o.socketY,graveyardY:r.graveyardY??o.graveyardY}}function Uc(e,t,n=1){const i=[...e].sort((e,t)=>e.localeCompare(t)),o=Math.max(0,i.indexOf(t));return{angle:.82*-Math.PI+(i.length>1?o/(i.length-1):.5)*Math.PI*.64,index:o,radius:(48+o%2*6)*n}}function Kc(e,t,n){const i=e.activePositiveIds.reduce((e,n)=>e+(t.get(n)?.value??1),0),o=e.missingPositiveIds.length+e.poppedPositiveIds.length,r=e.negativeIds.reduce((e,t)=>e+(n.get(t)?.load??1),0);return Math.max(0,Math.min(100,75+3*i-8*r-1.2*e.delay-5*o))}function Qc(e,t,n,i,o){const r=Wc(e,t,n.idAccessor,null!=e.id?e.id+"":"project-"+t)+"",s=i.map(e=>e.id),a=[...Wc(e,t,n.positiveAccessor,s)],c=[...Wc(e,t,n.negativeAccessor,[])].filter(e=>o.has(e));return{id:r,activePositiveIds:a,datum:e,delay:0,eventsApplied:[],eventHistory:[],killed:!1,metrics:{...Wc(e,t,n.metricsAccessor,{})},missingPositiveIds:s.filter(e=>!a.includes(e)),negativeIds:c,outcome:"in_process",poppedPositiveIds:[],poppedNegativeIds:[],startedAt:Math.max(0,Number(Wc(e,t,n.startTimeAccessor,0))||0),stage:"project filed",viability:Wc(e,t,n.initialViability,100)}}function Zc(e,t,n,i,o,r,s){const a=_c(n),c=Math.max(3,28*a),l=i.startX,d=i.startY+(i.startY===n.routeY?38*t*a:0),u=s?.(e,t,n,i)??{},h=u.x??l,p=u.y??d,m={__gauntlet:!0,kind:Tc,projectId:e.id,sourceDatum:e.datum},f=[{...u,id:Fc(e.id),x:h,y:p,vx:u.vx??42,vy:u.vy??0,mass:u.mass??7,bodyCollisions:u.bodyCollisions??!0,shape:u.shape??{type:"circle",radius:c},spawnAt:u.spawnAt??e.startedAt,datum:m}],y=Gc(h,p,u.shape&&"radius"in u.shape&&Number(u.shape.radius)||c,n);f[0].x=y.x,f[0].y=y.y;for(const t of e.activePositiveIds){const i=o.get(t);if(!i)continue;const r=Uc(e.activePositiveIds,t,a),s=i.radius??Math.max(2,10*a),c=Gc(y.x+Math.cos(r.angle)*r.radius,y.y+Math.sin(r.angle)*r.radius,s,n);f.push({id:zc(e.id,t),x:c.x,y:c.y,vx:18*Math.cos(r.angle),vy:18*Math.sin(r.angle),mass:i.mass??.75,bodyCollisions:!1,shape:{type:"circle",radius:s},spawnAt:u.spawnAt??e.startedAt,datum:{__gauntlet:!0,kind:Ec,projectId:e.id,property:i,sourceDatum:e.datum},springs:!1===i.spring?[]:[{target:{type:"body",bodyId:Fc(e.id)},stiffness:.56,damping:.9,restLength:Math.max(6,(52+r.index%2*4)*a),...i.spring??{}}]})}return e.negativeIds.forEach((t,i)=>{const o=r.get(t);o&&f.push(Jc(e,o,i,y.x,y.y,n,u.spawnAt??e.startedAt))}),f}function Jc(e,t,n,i,o,r,s){const a=_c(r),c=t.radius??Math.max(2,7.2*a),l=Gc(i+(n%4*12-12)*a,o+(54+12*Math.floor(n/4))*a,c,r);return{id:Lc(e.id,t.id,n),x:l.x,y:l.y,vx:10,vy:6,mass:t.mass??.72,bodyCollisions:!1,shape:{type:"circle",radius:c},spawnAt:s,datum:{__gauntlet:!0,kind:Nc,projectId:e.id,property:t,sourceDatum:e.datum},springs:!1===t.spring?[]:[{target:{type:"body",bodyId:Fc(e.id)},stiffness:.62,damping:.92,restLength:Math.max(6,(52+n%4*3)*a),...t.spring??{}}]}}function el(e){return e?Array.isArray(e)?[...e]:Object.entries(e).flatMap(([e,t])=>Array.from({length:Math.max(0,Math.round(Number(t)||0))},()=>e)):[]}function tl(e,t){return t?Array.isArray(t)?[...t]:t.ids?[...t.ids]:t.candidates?t.candidates.filter(t=>e.includes(t)).slice(0,t.count??1):[]:[]}function nl(e,t){return tl(e.activePositiveIds,t.popPositive)}function il(e){const t=Number(e.budget),n=Number.isFinite(t)?Math.max(0,t):0,i=e.properties instanceof Map?e.properties:new Map(e.properties.map(e=>[e.id,e])),o=e.candidates?new Set(e.candidates):null,r=e.attachedIds.map((e,t)=>{const n=i.get(e),o=Number(n?.work??1),r=Number(n?.priority??t);return{id:e,index:t,priority:Number.isFinite(r)?r:t,work:Number.isFinite(o)&&o>0?o:1}}).filter(e=>!o||o.has(e.id)).sort((e,t)=>e.priority-t.priority||e.index-t.index),s=[],a=[];let c=0;for(const e of r)c+e.work>n+Number.EPSILON?a.push(e.id):(s.push(e.id),c+=e.work);return{ids:s,used:c,budget:n,remaining:Math.max(0,n-c),skippedIds:a}}function ol(e,t){if(!t.from||!t.to||t.from===t.to)return{};const n=Math.max(0,Math.floor(Number(t.count??1)||0)),i=e.negativeIds.filter(e=>e===t.from).length,o=Math.min(n,i);return o?{addNegative:{[t.to]:o},popNegative:{ids:Array.from({length:o},()=>t.from)}}:{}}function rl(e,t){const n=tl(e.negativeIds,t.popNegative);if(!n.length)return[];const i=new Map;for(const e of n)i.set(e,(i.get(e)??0)+1);const o=[];return e.negativeIds.forEach((e,t)=>{const n=i.get(e)??0;n>0&&(o.push({propertyId:e,index:t}),i.set(e,n-1))}),o}function sl(e,t,n){if(t.when&&!t.when(n))return e;let i={...e};const o=nl(i,t);o.length&&(i={...i,activePositiveIds:i.activePositiveIds.filter(e=>!o.includes(e)),poppedPositiveIds:Array.from(new Set([...i.poppedPositiveIds,...o]))});const r=rl(i,t);if(r.length){const e=new Set(r.map(e=>e.index));i={...i,negativeIds:i.negativeIds.filter((t,n)=>!e.has(n)),poppedNegativeIds:[...i.poppedNegativeIds,...r.map(e=>e.propertyId)]}}const s=el(t.addPositive);s.length&&(i={...i,activePositiveIds:Array.from(new Set([...i.activePositiveIds,...s])),missingPositiveIds:i.missingPositiveIds.filter(e=>!s.includes(e))});const a=el(t.addNegative);if(a.length&&(i={...i,negativeIds:[...i.negativeIds,...a]}),t.delayDelta&&(i={...i,delay:i.delay+t.delayDelta}),t.metricsDelta){const e={...i.metrics};for(const[n,i]of Object.entries(t.metricsDelta))e[n]=Number(e[n]??0)+i;i={...i,metrics:e}}return t.viabilityDelta&&(i={...i,viability:i.viability+t.viabilityDelta}),t.stage&&(i={...i,stage:t.stage}),t.outcome&&(i={...i,outcome:t.outcome}),i}function al(e,t){return{id:e.id,label:e.label??e.id,summary:e.summary??t.find(e=>e.summary)?.summary,time:e.time}}function cl(e,t){return e.eventsApplied.includes(t.id)?e:{...e,eventsApplied:[...e.eventsApplied,t.id],eventHistory:[...e.eventHistory??[],t],lastEvent:t,stage:t.label??e.stage}}function ll(e,t){const n=e.datum;return!(!n?.__gauntlet||n.projectId!==t||n.kind!==Nc)}function dl(e){const t=e.id.slice(e.id.lastIndexOf(":")+1),n=Number(t);return Number.isFinite(n)?n:-1}function ul(e,t){return 2>Math.hypot(e.vx,e.vy)&&4>Math.hypot(t.x,t.y)?null:t}var hl=require("react/jsx-runtime");function pl(e){const t=e.data;return t?.__gauntlet?(0,hl.jsxs)("div",{className:"semiotic-tooltip",style:{background:"var(--semiotic-tooltip-bg, rgba(15, 23, 42, 0.94))",color:"var(--semiotic-tooltip-text, #f8fafc)",padding:"8px 12px",borderRadius:6,boxShadow:"var(--semiotic-tooltip-shadow, 0 8px 24px rgba(0,0,0,0.35))",maxWidth:280},children:[(0,hl.jsx)("strong",{children:t.kind===Tc?"string"==typeof t.sourceDatum?.label?t.sourceDatum.label:t.projectId:qc(t.property)}),(0,hl.jsx)("div",{children:t.kind===Ec?"Positive property":t.kind===Nc?"Negative property":"Project core"})]}):null}function ml(e,t,n){const i=t.datum;if(!i?.__gauntlet)return;const o="circle"===t.shape.type?t.shape.radius:8;if(e.save(),e.translate(t.x,t.y),i.kind===Tc)e.fillStyle=fl(e,n.fill,"#0f766e"),e.strokeStyle=fl(e,n.stroke,"#f8fafc"),e.lineWidth=2.4,e.beginPath(),e.arc(0,0,o,0,2*Math.PI),e.fill(),e.stroke();else{const t=i.property;e.fillStyle=fl(e,n.fill??t?.color,"#38bdf8"),e.strokeStyle=fl(e,n.stroke,"#0f172a"),e.lineWidth=1.1,e.beginPath(),i.kind===Nc?e.rect(-o,-o,2*o,2*o):e.arc(0,0,o,0,2*Math.PI),e.fill(),e.stroke(),e.fillStyle=fl(e,"var(--semiotic-background, #07111f)","#07111f"),e.font=`900 ${i.kind===Nc?9:8}px system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,e.textAlign="center",e.textBaseline="middle",e.fillText(t?.short??t?.id?.slice(0,1).toUpperCase()??"?",0,.5)}e.restore()}function fl(e,t,n){if("string"!=typeof t)return n;if("function"!=typeof getComputedStyle||!e.canvas)return t||n;const i=t.startsWith("var(")?t.match(/var\((--[^,\s)]+)/)?.[1]:t.startsWith("--")?t:null;return i?getComputedStyle(e.canvas).getPropertyValue(i).trim()||n:t||n}function yl({layout:e,compact:t,showLabels:n}){const i=t?Math.round(.14*e.height):Math.max(80,e.routeY-180),o=t?Math.max(6,Math.round(.72*e.height)):Math.min(360,e.height-170);return(0,hl.jsx)(hl.Fragment,{children:e.gates.map(r=>(0,hl.jsxs)("g",{children:[(0,hl.jsx)("rect",{x:r.x-r.width/2,y:i,width:r.width,height:o,rx:t?2:12,fill:r.color??"var(--semiotic-accent, #38bdf8)",fillOpacity:.1,stroke:r.color??"var(--semiotic-accent, #38bdf8)",strokeDasharray:"5 5",strokeOpacity:.7}),n?(0,hl.jsx)("text",{x:r.x,y:Math.max(64,e.routeY-196),fill:"var(--semiotic-text-secondary, #64748b)",fontSize:10,fontWeight:800,textAnchor:"middle",children:r.label??r.id}):null]},r.id))})}function gl({layout:e,states:t,compact:n=!1}){return n?(0,hl.jsx)("svg",{"aria-hidden":"true",viewBox:`0 0 ${e.width} ${e.height}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:(0,hl.jsx)(yl,{layout:e,compact:!0,showLabels:!1})}):(0,hl.jsxs)("svg",{"aria-hidden":"true",viewBox:`0 0 ${e.width} ${e.height}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[(0,hl.jsx)("path",{d:`M ${e.startX-42} ${e.routeY} C ${.24*e.width} ${e.routeY-70}, ${.42*e.width} ${e.routeY+78}, ${.58*e.width} ${e.routeY} S ${.78*e.width} ${e.routeY-82}, ${e.socketX+36} ${e.routeY}`,fill:"none",stroke:"var(--semiotic-accent, #38bdf8)",strokeDasharray:"18 12",strokeLinecap:"round",strokeOpacity:.45,strokeWidth:7}),(0,hl.jsx)("line",{x1:Math.round(.06*e.width),x2:Math.round(.94*e.width),y1:e.crashY,y2:e.crashY,stroke:"var(--semiotic-negative, #ef4444)",strokeDasharray:"3 7",strokeOpacity:.64}),(0,hl.jsx)("text",{x:Math.round(.07*e.width),y:e.crashY-8,fill:"var(--semiotic-negative, #ef4444)",fontSize:9,fontWeight:800,children:"CRASH LINE"}),(0,hl.jsx)(yl,{layout:e,compact:!1,showLabels:!0}),(0,hl.jsxs)("g",{children:[(0,hl.jsx)("rect",{x:e.socketX-52,y:e.routeY-56,width:104,height:112,rx:13,fill:"var(--semiotic-positive, #22c55e)",fillOpacity:.12,stroke:"var(--semiotic-positive, #22c55e)",strokeWidth:1.5}),(0,hl.jsx)("text",{x:e.socketX,y:e.routeY-72,fill:"var(--semiotic-text-secondary, #64748b)",fontSize:10,fontWeight:800,textAnchor:"middle",children:"SOCKET"})]}),(0,hl.jsxs)("g",{children:[(0,hl.jsx)("rect",{x:e.graveyardX-82,y:e.graveyardY-34,width:164,height:58,rx:11,fill:"var(--semiotic-negative, #ef4444)",fillOpacity:.16,stroke:"var(--semiotic-negative, #ef4444)",strokeOpacity:.7}),(0,hl.jsx)("text",{x:e.graveyardX,y:e.graveyardY-8,fill:"var(--semiotic-negative, #ef4444)",fontSize:10,fontWeight:800,textAnchor:"middle",children:"GRAVEYARD"}),(0,hl.jsx)("text",{x:e.graveyardX,y:e.graveyardY+12,fill:"var(--semiotic-text-secondary, #64748b)",fontSize:9,fontWeight:700,textAnchor:"middle",children:t.some(e=>e.killed)?"lift shut off":"too heavy or too small"})]})]})}function bl(e){const t=e.datum;return!!t?.__gauntlet&&(t.kind===Tc?{label:t.projectId+" project core",group:"project",description:"Project core carrying positive and negative properties."}:{label:`${qc(t.property)} ${t.kind===Ec?"positive":"negative"} property`,group:t.kind===Ec?"positive property":"negative property",description:`${qc(t.property)} attached to ${t.projectId}.`})}function xl({states:e,layout:t}){const n=function(e){return e.map(e=>({label:e.id,value:Math.max(0,Number(e.viability)||0),outcome:e.outcome||e.stage||"in-process"}))}(e);if(!n.length)return null;const i=Math.max(1,...n.map(e=>e.value)),o=Math.max(40,(t.width-80)/n.length);return(0,hl.jsxs)("svg",{"aria-hidden":"true","data-testid":"gauntlet-projection-overlay",width:t.width,height:t.height,viewBox:`0 0 ${t.width} ${t.height}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[(0,hl.jsx)("text",{x:36,y:18,fill:"var(--semiotic-text-secondary, #64748b)",fontSize:9,fontWeight:800,children:"SETTLED · viability / outcome"}),n.map((e,t)=>{const n=40+t*o,r=Math.max(2,e.value/i*28),s=/kill|crash|block|grave/i.test(e.outcome);return(0,hl.jsxs)("g",{children:[(0,hl.jsx)("rect",{x:n+.18*o,y:28-r+22,width:Math.max(10,.45*o),height:r,rx:2,fill:s?"var(--semiotic-danger, #ef4444)":"var(--semiotic-success, #16a34a)",fillOpacity:.35,stroke:s?"var(--semiotic-danger, #ef4444)":"var(--semiotic-success, #16a34a)",strokeOpacity:.55,strokeWidth:1}),(0,hl.jsx)("text",{x:n+.4*o,y:62,textAnchor:"middle",fill:"var(--semiotic-text-secondary, #64748b)",fontSize:9,fontWeight:700,children:e.label})]},e.label)})]})}var vl=require("react/jsx-runtime"),wl=require("react"),kl=[],Ml=(0,Rc.forwardRef)(function(e,t){const{bodyGroups:n,coreBody:i,coreForceMode:o="route",crashDetection:r=!0,crashOffset:s=30,data:a,emptyContent:c,events:l,frameProps:d={},gates:u,initialSpawnPacing:h,loading:p,loadingContent:m,negativeProperties:f,onCapacityChange:y,onClick:g,onStateChange:b,outcome:x,paused:v,positiveProperties:w=kl,projectPlacement:k,rerunMS:M,responsiveHeight:I,responsiveWidth:S,showTethers:j=!0,terminalBehavior:A="outcome",viability:C}=e,R=(0,Rc.useRef)(null),$=(0,Rc.useMemo)(()=>({idAccessor:e.idAccessor,initialViability:e.initialViability,metricsAccessor:e.metricsAccessor,negativeAccessor:e.negativeAccessor,positiveAccessor:e.positiveAccessor,startTimeAccessor:e.startTimeAccessor}),[e.idAccessor,e.initialViability,e.metricsAccessor,e.negativeAccessor,e.positiveAccessor,e.startTimeAccessor]),P=Ga(e,[900,520]),{chartSize:D,showProjection:B,showChrome:T,className:E,title:N,chartMode:O,margin:W,enableHover:q,description:F,summary:z,accessibleTable:L}=P,Y=Xa({data:a,emptyContent:c,loading:p,loadingContent:m,size:D}),H=(0,Rc.useMemo)(()=>cc(a??[]),[a]),_=(0,Rc.useMemo)(()=>H.map((e,t)=>Wc(e,t,$.idAccessor,null!=e.id?e.id+"":"project-"+t)+"").join("|"),[H,$.idAccessor]),G=(0,Rc.useMemo)(()=>new Map(w.map(e=>[e.id,e])),[w]),X=(0,Rc.useMemo)(()=>new Map(f.map(e=>[e.id,e])),[f]),V=(0,Rc.useMemo)(()=>function(e,t,n){const[i,o]=e,r=220>i||160>o,s=Math.round(.48*o),a=r?o-Math.max(3,Math.min(12,.1*o)):o-36,c=(t??[]).filter(e=>!1!==e.enabled),l=Math.max(1,c.length),d=.22*i,u=l>1?(.78*i-d)/(l-1):0,h=r?Math.max(Math.round(.12*i),.08*i+6):Math.max(Math.round(.14*i),110);return{crashY:a-(r?Math.min(n,Math.max(3,.22*o)):n),floorY:a,gates:c.map((e,t)=>({...e,id:e.id,x:e.x??Math.round(d+t*u),width:e.width??Math.max(r?8:54,Math.round(.07*i))})),graveyardX:Math.round(i*(r?.72:.84)),graveyardY:a-4,height:o,routeY:s,socketX:Math.round(i*(r?.82:.92)),startX:h,width:i}}(D,u,s),[D,s,u]),U=(0,Rc.useMemo)(()=>new Map(V.gates.map(e=>[e.id,e])),[V.gates]),K=(0,Rc.useMemo)(()=>V.gates.map(e=>({kind:"force-field",damping:.035,force:{x:12,y:0},semanticItem:!1,...e.regionEffect,id:"gauntlet-gate-"+e.id,label:e.label??e.id,description:e.description,bodyFilter:e.capacity?{property:"datum.kind",equals:Tc}:e.regionEffect?.bodyFilter,shape:{type:"aabb",x:e.x,y:V.routeY,width:e.capacity?e.capacity.sensorWidth??Math.max(220>V.width?12:96,e.width*(220>V.width?2:6)):Math.max(e.width,220>V.width?10:54),height:Math.max(4,Math.min(360,V.height-(160>V.height?8:170)))}})),[V.gates,V.height,V.routeY,V.width]),[Q,Z]=(0,Rc.useState)(()=>H.map((e,t)=>{const n=Qc(e,t,$,w,X);return{...n,viability:C?.(n,{negativeProperties:X,positiveProperties:G})??Kc(n,G,X)}})),J=(0,Rc.useRef)(Q),ee=(0,Rc.useRef)(0),te=(0,Rc.useRef)(new Map),ne=(0,Rc.useRef)([]),ie=(0,Rc.useRef)(y);ie.current=y;const oe=(0,Rc.useRef)(H);oe.current=H;const re=(0,Rc.useRef)(b);re.current=b;const se=(0,Rc.useRef)({negativeById:X,positiveById:G,positiveProperties:w,stateAccessors:$,viability:C});se.current={negativeById:X,positiveById:G,positiveProperties:w,stateAccessors:$,viability:C};const ae=(0,Rc.useCallback)((e,t,n=0)=>{const i=se.current,o=Qc(e,t,i.stateAccessors,i.positiveProperties,i.negativeById);return i.stateAccessors.startTimeAccessor||(o.startedAt=Math.max(0,n)),{...o,viability:i.viability?.(o,{negativeProperties:i.negativeById,positiveProperties:i.positiveById})??Kc(o,i.positiveById,i.negativeById)}},[]),ce=(0,Rc.useCallback)(()=>{te.current.clear(),ne.current=[],ee.current=0;const e=oe.current.map((e,t)=>ae(e,t));J.current=e,Z(e)},[ae]),le=_a((0,Rc.useMemo)(()=>({fixedDt:1/60,maxSubsteps:8,kernel:{gravity:{x:0,y:0},restitution:.16,friction:.44,velocityDamping:.982,maxVelocity:520,sleepAfter:.8,sleepSpeed:7,...d.config?.kernel??{}},colliders:[...Oc(V),...d.config?.colliders??[]]}),[d.config?.colliders,d.config?.kernel,V]),M,v,ce),de=(0,Rc.useMemo)(()=>function(e){const{dataKey:t,gates:n,statesRef:i,processedGateVisitsRef:o}=e;return n.flatMap(e=>e.capacity&&e.capacity.unitsPerSecond>0?[qo({id:`gauntlet-capacity-${t}-${e.id}`,regionId:"gauntlet-gate-"+e.id,unitsPerSecond:e.capacity.unitsPerSecond,bodyFilter:{property:"datum.kind",equals:Tc},maxQueue:e.capacity.maxQueue,queueLayout:e.capacity.queueLayout,queueSlotSpacing:e.capacity.queueSlotSpacing,queueStiffness:e.capacity.queueStiffness??24,releaseImpulse:{x:36,y:0},unitAccessor:t=>{const n=t.datum,o=n?.sourceDatum,r=e.capacity?.unitAccessor,s=i.current.find(e=>e.id===n?.projectId);let a;"function"==typeof r?a=s?r(s):void 0:r&&(a=o?.[r]);const c=Number(a??o?.reviewWork??o?.work??s?.metrics.reviewWork??o?.points);return Number.isFinite(c)&&c>0?c:1},onProcessed:t=>{const n=t.datum;if(!n?.projectId)return;const i=`${n.projectId}:${e.id}`;o.current.set(i,(o.current.get(i)??0)+1)}})]:[])}({dataKey:`${_}:${le.rerunKey}`,gates:V.gates,statesRef:J,processedGateVisitsRef:te}),[_,V.gates,le.rerunKey]),ue=(0,Rc.useMemo)(()=>[...de,...d.controllers??[]],[de,d.controllers]);(0,Rc.useEffect)(()=>{te.current.clear(),ne.current=[],ee.current=0;const e=oe.current.map((e,t)=>ae(e,t));J.current=e,Z(e)},[ae,_]),(0,Rc.useEffect)(()=>{J.current=Q,re.current?.(Q)},[Q]);const he=(0,Rc.useCallback)(e=>[...("function"==typeof l?l(e,V):l)??[]].sort((e,t)=>e.time-t.time),[l,V]),pe=(0,Rc.useCallback)((e,t,n)=>{if(!t.gateId||!U.get(t.gateId)?.capacity)return!0;const i=Number(t.gateVisit),o=Number.isFinite(i)&&i>0?Math.floor(i):n.filter(e=>e.gateId===t.gateId).findIndex(e=>e.id===t.id)+1;return o>0&&(te.current.get(`${e.id}:${t.gateId}`)??0)>=o},[U]),me=(0,Rc.useCallback)(()=>{if(!de.length)return;const e=de.flatMap(e=>{const t=e.getSnapshot?.();return t?[t]:[]});var t,n;(t=ne.current).length===(n=e).length&&t.every((e,t)=>{const i=n[t];return!!i&&e.regionId===i.regionId&&e.queueDepth===i.queueDepth&&e.blockedDepth===i.blockedDepth&&e.processedCount===i.processedCount&&e.metricRevision===i.metricRevision})||(ne.current=e,ie.current?.(e))},[de]),fe=(0,Rc.useMemo)(()=>Q.flatMap((e,t)=>{const n=Vc(e,t,V,k);return Zc(e,t,V,n,G,X,i)}),[i,V,X,G,k,Q]),ye=(0,Rc.useCallback)((e,t)=>{let n=!1;const i=J.current.map(i=>{if(i.id!==e)return i;const o=t(i);return n=n||o!==i,o});n&&(J.current=i,Z(i))},[]);(0,Rc.useImperativeHandle)(t,()=>function(e){const{statesRef:t,setStates:n,elapsedRef:i,frameRef:o,layout:r,projectPlacement:s,positiveById:a,negativeById:c,coreBody:l,createState:d}=e;return{push:e=>{const u=d(e,t.current.length,i.current),h=Vc(u,t.current.length,r,s),p=Zc(u,t.current.length,r,h,a,c,l),m=[...t.current,u];t.current=m,n(m),o.current?.pushMany(p),o.current?.step(0)},pushMany:e=>{const u=[...t.current],h=[],p=i.current;e.forEach(e=>{const t=d(e,u.length,p),n=Vc(t,u.length,r,s);h.push(...Zc(t,u.length,r,n,a,c,l)),u.push(t)}),t.current=u,n(u),h.length&&o.current?.pushMany(h),o.current?.step(0)},remove:e=>{const i=Array.isArray(e)?e:[e],r=[],s=[];for(const e of i){const n=t.current.find(t=>t.id===e);n&&(r.push(n.datum),s.push(Fc(n.id),...n.activePositiveIds.map(e=>zc(n.id,e))),n.negativeIds.forEach((e,t)=>{s.push(Lc(n.id,e,t))}))}return t.current=t.current.filter(e=>!i.includes(e.id)),n(t.current),o.current?.remove(s),r},update:(e,u)=>{const h=Array.isArray(e)?e:[e],p=[];for(const e of h){const n=t.current.find(t=>t.id===e);if(!n)continue;const h=t.current.findIndex(t=>t.id===e);p.push(n.datum);const m=u(n.datum),f=d(m,0>h?t.current.length:h,n.startedAt??i.current),y=Vc(f,0>h?t.current.length:h,r,s);o.current?.remove([Fc(n.id),...n.activePositiveIds.map(e=>zc(n.id,e)),...n.negativeIds.map((e,t)=>Lc(n.id,e,t))]),o.current?.pushMany(Zc(f,0>h?t.current.length:h,r,y,a,c,l)),t.current=t.current.map(t=>t.id===e?f:t)}return n(t.current),p},clear:()=>{t.current=[],n([]),o.current?.clear()},getData:()=>t.current.map(e=>e.datum),getScales:()=>null,getCustomLayout:()=>o.current?.snapshot()??null,popBodies:(e,t)=>o.current?.popBodies(e,t)??[]}}({statesRef:J,setStates:Z,elapsedRef:ee,frameRef:R,layout:V,projectPlacement:k,positiveById:G,negativeById:X,coreBody:i,createState:ae}),[i,ae,V,X,G,k]);const ge="sparkline"===O?.22:"mobile"===O?.55:1,be=(0,Rc.useCallback)((e,t,n)=>{!function(e){const{project:t,effect:n,controls:i,layout:o,positiveById:r,negativeById:s,coreBody:a,popBodies:c,popScale:l}=e,d=i.readBodies().find(e=>e.id===Fc(t.id)),u=i.readBodies(),h=d?.x??o.startX,p=d?.y??o.routeY,m=function(e,t){let n=-1;for(const i of t)ll(i,e.id)&&(n=Math.max(n,dl(i)));return Math.max(e.negativeIds.length,n+1)}(t,u),f=el(n.addNegative).flatMap((e,n)=>{const i=s.get(e);return i?[Jc(t,i,m+n,h,p,o)]:[]}),y=el(n.addPositive).flatMap(e=>{if(!r.get(e)||t.activePositiveIds.includes(e))return[];const n={...Xc(o),routeY:p,socketY:p,startX:h,startY:p};return Zc({...t,activePositiveIds:[e],negativeIds:[]},0,o,n,r,s,a).filter(e=>e.id.includes(":positive:"))});(f.length||y.length)&&i.pushMany([...f,...y]);const g=nl(t,n);for(const e of g){const n=r.get(e);c([zc(t.id,e)],{color:n?.popColor??n?.color,durationMs:900,radius:(n?.radius??10)+3,scale:l})}const b=rl(t,n),x=function(e,t,n){const i=t.filter(t=>ll(t,e.id)).sort((e,t)=>dl(e)-dl(t)||e.id.localeCompare(t.id)),o=new Set;return n.map(t=>{const n=i.find(e=>!o.has(e.id)&&e.datum.property?.id===t.propertyId);return n?(o.add(n.id),n.id):Lc(e.id,t.propertyId,t.index)})}(t,u,b);b.forEach((e,t)=>{const n=s.get(e.propertyId);c([x[t]],{color:n?.popColor??n?.color,durationMs:900,radius:(n?.radius??7)+3,scale:l})})}({project:e,effect:t,controls:n,layout:V,positiveById:G,negativeById:X,coreBody:i,popBodies:(e,t)=>R.current?.popBodies(e,t),popScale:ge})},[i,V,X,G,ge]),xe=(0,Rc.useCallback)(({body:e,bodies:t})=>function(e){const{body:t,bodies:n,layout:i,states:o,projectPlacement:r,positiveById:s,negativeById:a,projectEvents:c,gateById:l,coreForceMode:d,terminalBehavior:u,elapsed:h}=e,p=t.datum;if(!p?.__gauntlet)return null;const m=o.findIndex(e=>e.id===p.projectId),f=0>m?void 0:o[m];if(!f)return null;const y=Vc(f,m,i,r),g=n.find(e=>e.id===Fc(f.id)),b=_c(i),x=f.negativeIds.reduce((e,t)=>e+(a.get(t)?.load??1),0),v=f.killed?0:58*Math.max(.25,b);if(p.kind!==Tc){if(!g)return null;let e;const o=p.property;if(o?.target){const r=n.filter(e=>{const t=e.datum;return t?.__gauntlet&&t.projectId===f.id&&t.kind===p.kind}).sort((e,t)=>(e.id+"").localeCompare(t.id+"")),s=Math.max(0,r.findIndex(e=>e.id===t.id));e=o.target({body:t,bodies:n,core:g,index:s,layout:i,placement:y,project:f})??{x:g.x,y:g.y}}else if(p.kind===Ec&&p.property){const t=Uc(f.activePositiveIds,p.property.id,b);e={x:g.x+Math.cos(t.angle)*t.radius,y:g.y+Math.sin(t.angle)*t.radius-2}}else{const i=n.filter(e=>e.datum?.kind===Nc&&e.datum.projectId===f.id).sort((e,t)=>(e.id+"").localeCompare(t.id+"")),o=Math.max(0,i.findIndex(e=>e.id===t.id)),r=Math.floor(o/4);e={x:g.x+18*(o%4-(Math.min(4,i.length-4*r)-1)/2)*b,y:g.y+(54+13*r)*b}}const r="circle"===t.shape.type?t.shape.radius:8;e=Gc(e.x,e.y,r,i);const s=Gc(t.x,t.y,r,i);if(Math.abs(s.x-t.x)>.5||Math.abs(s.y-t.y)>.5)return{x:48*(s.x-t.x)-6*t.vx,y:48*(s.y-t.y)-6*t.vy};const a=p.kind!==Ec||f.killed?0:3.2*(o?.buoyancy??o?.value??1),c=p.kind===Nc?{x:.22*(o?.pull?.x??-8),y:.22*(o?.pull?.y??22)}:{x:0,y:0};return ul(t,{x:28*(e.x-t.x)-3*(t.vx-g.vx)+c.x+.01*v,y:28*(e.y-t.y)-3*(t.vy-g.vy)+c.y-a})}if(f.killed)return ul(t,{x:44*((f.crashX??f.metrics.lastX??t.x)-t.x)-9*t.vx,y:(160+12*x)*b-1.6*t.vy});const w=c(f),k=function(e,t,n,i,o,r,s){const a=_c(n);if(t.killed)return{x:t.metrics.lastX??i.graveyardX,y:i.graveyardY};const c=o[o.length-1];if(!c)return{x:i.socketX,y:i.routeY};const l=o.find(n=>e>=n.time&&!t.eventsApplied.includes(n.id)&&!(!n.gateId||!r.get(n.gateId)?.capacity)),d=l?Math.min(e,l.time):e,u="built"===t.outcome||"built_diminished"===t.outcome;if(d>c.time+.85){if("hold-last"===s){const e=c.gateId?r.get(c.gateId):void 0;return{x:c.routeX??e?.x??i.socketX,y:c.routeY??i.routeY}}return u?{x:i.socketX,y:i.socketY}:{x:i.graveyardX,y:i.graveyardY-14}}const h=.85*t.delay+12*t.negativeIds.length+8*(t.poppedPositiveIds.length+t.missingPositiveIds.length),p=[{time:0,x:i.startX,y:i.startY},...o.map(e=>{const t=e.gateId?r.get(e.gateId):void 0;return{time:e.time,x:e.routeX??t?.x??i.startX,y:e.routeY??i.routeY+.28*Math.min(180,h)*a}})].sort((e,t)=>e.time-t.time);let m=p[0],f=p[p.length-1];for(let e=1;p.length>e;e+=1){if(p[e].time>=d){f=p[e];break}m=p[e]}const y=Math.max(0,Math.min(1,(d-m.time)/Math.max(.1,f.time-m.time))),g=y*y*(3-2*y);return{x:m.x+(f.x-m.x)*g,y:m.y+(f.y-m.y)*g+7*Math.sin(2.6*d)*a}}(Math.max(0,h-(f.startedAt??0)),f,i,y,w,l,u),M=f.activePositiveIds.reduce((e,t)=>e+(s.get(t)?.buoyancy??s.get(t)?.value??1),0);return ul(t,"net"===d?{x:15*(k.x-t.x)-1.8*t.vx+.18*v,y:1.25*(y.routeY-t.y)-1.4*t.vy+32*(x-M)}:{x:15*(k.x-t.x)-1.8*t.vx+.18*v,y:15*(k.y-t.y)-1.8*t.vy+13*x-2.2*M})}({body:e,bodies:t,layout:V,states:J.current,projectPlacement:k,positiveById:G,negativeById:X,projectEvents:he,gateById:U,coreForceMode:o,terminalBehavior:A,elapsed:ee.current}),[o,U,V,X,G,he,k,A]),ve=(0,Rc.useCallback)((e,t)=>{!function(e,t,n){const{frameProps:i,elapsedRef:o,statesRef:r,crashDetection:s,layout:a,projectEvents:c,gateById:l,capacityEventReady:d,addBodiesForEffect:u,updateProjectState:h,viability:p,positiveById:m,negativeById:f,outcome:y,reportCapacity:g}=n;i.onTick?.(e,t),o.current=e.elapsedSeconds??t.snapshot().elapsedSeconds,g();for(const e of r.current){const n=t.readBodies().find(t=>t.id===Fc(e.id));if(!n)continue;if(s&&!e.killed&&n.y+("circle"===n.shape.type?n.shape.radius:28)>=a.crashY){t.readBodies().forEach(n=>{const i=n.datum;i?.__gauntlet&&i.projectId===e.id&&t.applyImpulse(n.id,-n.vx*n.mass,0)}),h(e.id,e=>{const t={appliedAt:Math.max(0,o.current-(e.startedAt??0)),id:"gauntlet-crash-line",label:"Crash Line",summary:"The project hit the crash threshold; lift and forward motion shut off.",time:Math.max(0,o.current-(e.startedAt??0))};return{...e,crashX:n.x,eventHistory:[...e.eventHistory??[],t],killed:!0,lastEvent:t,metrics:{...e.metrics,lastX:n.x},outcome:"bad_design_crash",stage:"Crash Line",viability:Math.min(0,e.viability)}});continue}if(e.killed)continue;const i=Math.max(0,o.current-(e.startedAt??0)),r=c(e),g=r.filter(t=>i>=t.time&&!e.eventsApplied.includes(t.id)&&d(e,t,r));let b=e;for(const n of g){const o=n.gateId?l.get(n.gateId):void 0,r=n.effects??[];for(const e of r){const i={event:n,gate:o,negativeProperties:f,positiveProperties:m,project:b};e.when&&!e.when(i)||(u(b,e,t),b=sl(b,e,i))}const s={...al(n,r),appliedAt:i};b=cl(b,s),h(e.id,e=>{let t=cl(e,s);if(t===e)return e;for(const e of r)t=sl(t,e,{event:n,gate:o,negativeProperties:f,positiveProperties:m,project:t});const i=p?.(t,{negativeProperties:f,positiveProperties:m})??Kc(t,m,f);return t={...t,viability:i},n.final&&(t={...t,outcome:n.outcome??y?.(t,{layout:a,negativeProperties:f,positiveProperties:m})??(t.viability>20?"built":"approved_not_built")}),t})}}}(e,t,{frameProps:d,elapsedRef:ee,statesRef:J,crashDetection:r,layout:V,projectEvents:he,gateById:U,capacityEventReady:pe,addBodiesForEffect:be,updateProjectState:ye,viability:C,positiveById:G,negativeById:X,outcome:x,reportCapacity:me})},[be,pe,r,d,U,V,X,x,G,he,me,ye,C]),we=(0,Rc.useCallback)((e,t)=>{const n="function"==typeof d.bodyStyle?d.bodyStyle(e,t):d.bodyStyle,i=e.datum;return i?.__gauntlet?{fill:i.kind===Tc?"var(--semiotic-accent, #0f766e)":i.property?.color??"var(--semiotic-accent, #38bdf8)",stroke:i.kind===Tc?"#f8fafc":"#0f172a",opacity:.96,...n}:n??{}},[d]),ke=(0,Rc.useMemo)(()=>"function"==typeof n?n(Q,V):n??[],[n,V,Q]),Me=(0,Rc.useMemo)(()=>Bc(ke),[ke]),Ie=(0,Rc.useMemo)(()=>B?function(e,t){if(!e.length)return[];const n=Math.max(40,(t.width-80)/e.length);return e.map((e,t)=>{const i=`${e.id}: viability ${Math.round(e.viability)}, ${e.outcome||e.stage}`;return{id:"gauntlet-projection-"+e.id,label:i,description:i,datum:e,x:40+(t+.5)*n,y:28,shape:"rect",width:Math.max(16,.55*n),height:22,group:"settled projection"}})}(Q,V):[],[V,B,Q]),Se=(0,Rc.useMemo)(()=>[...Ie,...Me],[Me,Ie]),je=(0,Rc.useCallback)((e,t)=>{d.onBodyPointerDown?.(e,t)},[d]),Ae=(0,Rc.useCallback)((e,t)=>{g&&(e&&"object"==typeof e&&e.__gauntlet?g(e.sourceDatum,{x:t.x,y:t.y}):e&&g(e,{x:t.x,y:t.y}))},[g]),Ce=(0,Rc.useCallback)((e,t)=>{d.beforePaint?.(e,t),j&&function(e,t){const n=new Map(t.filter(e=>e.datum?.kind===Tc).map(e=>[e.datum.projectId,e]));e.save(),e.lineWidth=1.1,e.setLineDash([3,4]);for(const i of t){const t=i.datum;if(!t?.__gauntlet||t.kind===Tc)continue;const o=n.get(t.projectId);o&&(e.globalAlpha=t.kind===Nc?.24:.36,e.strokeStyle=t.kind===Nc?"#d94a45":"#7a8794",e.beginPath(),e.moveTo(o.x,o.y),e.lineTo(i.x,i.y),e.stroke())}e.restore()}(e,t)},[d,j]),Re=(0,Rc.useMemo)(()=>[...K,...d.regionEffects??[]],[d.regionEffects,K]);if(Y)return Y;const $e=Ka(e.tooltip,d),Pe=Qa(e,d,Se,{chartMode:O,className:E,title:N,description:F,summary:z,accessibleTable:L,enableHover:q,margin:W}),De=B?(0,vl.jsx)(xl,{states:Q,layout:V}):void 0,Be=Ua(T?(0,vl.jsx)(gl,{layout:V,states:Q,compact:P.resolved.compactMode}):void 0,d.backgroundGraphics),Te=Ua(De,d.foregroundGraphics),Ee=d.renderBody??ml,Ne=$e.tooltipContent??pl;return Va("GauntletChart",D,(0,wl.createElement)(rs,{...d,...$e,...Pe,key:`${D[0]}x${D[1]}:${_}:${le.rerunKey}`,ref:R,accessibleTable:e.accessibleTable??d.accessibleTable,backgroundGraphics:Be,bodyForces:xe,bodySemanticItems:d.bodySemanticItems??bl,bodyStyle:we,beforePaint:Ce,onClick:g?Ae:Pe.onClick,config:le.config,controllers:ue,enableHover:$e.enableHover??!0,foregroundGraphics:Te,hoverRadius:e.hoverRadius??d.hoverRadius??18,initialSpawns:fe,initialSpawnPacing:h,onBodyPointerDown:je,onTick:ve,paused:v,regionEffects:Re,renderBody:Ee,responsiveHeight:I,responsiveWidth:S,size:D,tooltipContent:Ne}))});Ml.displayName="GauntletChart";var Il=Ml,Sl=require("react"),jl=require("react/jsx-runtime");function Al(e){return e.toLocaleString(void 0,1e3>Math.abs(e)?{maximumFractionDigits:1}:{maximumFractionDigits:0})}function Cl(e){return e.map((e,t)=>`${0===t?"M":"L"} ${e.x} ${e.y}`).join(" ")}function Rl(e){if(!e||"object"!=typeof e)return null;const t=e,n=Number(t.x),i=Number(t.y);return Number.isFinite(n)&&Number.isFinite(i)?{x:n,y:i}:null}function $l(e){if(!e||"object"!=typeof e)return[];const t=e.flowPath;return Array.isArray(t)?t.map(Rl).filter(e=>null!=e):[]}function Pl(e,t){if(2>t.length)return null;let n=0;const i=[];for(let e=1;t.length>e;e+=1){const o=Math.hypot(t[e].x-t[e-1].x,t[e].y-t[e-1].y);i.push(o),n+=o}if(0>=n)return null;let o=null,r=0;for(let s=1;t.length>s;s+=1){const a=t[s-1],c=t[s],l=i[s-1];if(0>=l)continue;const d=c.x-a.x,u=c.y-a.y,h=Math.max(0,Math.min(1,((e.x-a.x)*d+(e.y-a.y)*u)/(l*l))),p={x:a.x+d*h,y:a.y+u*h},m={distance:Math.hypot(e.x-p.x,e.y-p.y),point:p,progress:(r+h*l)/n,tangent:{x:d/l,y:u/l},totalLength:n};o&&m.distance>=o.distance||(o=m),r+=l}return o}function Dl(e,t,n){if(0===e.length)return{x:0,y:0};if(1===e.length||0>=n)return{...e[0]};let i=0;const o=Math.max(0,Math.min(1,t))*n;for(let t=1;e.length>t;t+=1){const n=e[t-1],r=e[t],s=Math.hypot(r.x-n.x,r.y-n.y);if(s>0){if(i+s>=o){const e=(o-i)/s;return{x:n.x+(r.x-n.x)*e,y:n.y+(r.y-n.y)*e}}i+=s}}return{...e[e.length-1]}}function Bl(e){return"circle"===e.shape.type?e.shape.radius:Math.max(e.shape.width,e.shape.height)/2}function Tl(e,t,n){const i=Math.hypot(e,t);if(n>=i||0>=i)return[e,t];const o=n/i;return[e*o,t*o]}function El(e,t,n){const i=Pl({...e,x:t[0].x,y:t[0].y},t),o=i?.tangent??{x:t[1].x-t[0].x,y:t[1].y-t[0].y},r=Math.hypot(o.x,o.y)||1,s=o.x/r,a=o.y/r,c=Bl(e),l=function(e,t){let n=0;for(let t=0;e.length>t;t+=1)n=31*n+e.charCodeAt(t)>>>0;return(n%1e3/1e3-.5)*t*1.4}(e.id,c);return{id:e.id,x:t[0].x+-a*l,y:t[0].y+s*l,vx:s*n,vy:a*n,mass:e.mass,shape:e.shape,datum:{...e.datum&&"object"==typeof e.datum?e.datum:{},routeProgress:0}}}var Nl=(0,Sl.forwardRef)(function(e,t){const{chartId:n,colorBy:i,coordinateMode:o="auto",data:r,edges:s,emptyContent:a,flowSpeed:c=90,frameProps:l,links:d,loading:u,loadingContent:h,maxParticles:p=180,nodeIdAccessor:m="id",nodeXAccessor:f="x",nodeYAccessor:y="y",nodes:g,onObservation:b,particleRadius:x=4,particleRate:v=.16,pathAccessor:w="path",pathConstraint:k="path",paused:M,reducedMotion:I=!1,responsiveHeight:S,responsiveWidth:j,seed:A=1,showNodeLabels:C=!0,showSensors:R=!1,showStaticFlow:$=!0,sourceAccessor:P="source",styleRules:D,targetAccessor:B="target",throughputAccessor:T="value"}=e,E=Ga(e,[760,420]),{chartSize:N,className:O,title:W,chartMode:q,margin:F,enableHover:z,description:L,summary:Y,accessibleTable:H}=E,_=(0,Sl.useRef)(null),G=(0,Sl.useMemo)(()=>g??[],[g]),X=(0,Sl.useMemo)(()=>d??s??r??[],[r,s,d]),V=(0,Sl.useMemo)(()=>Ws({nodes:G,links:X,nodeIdAccessor:m,nodeXAccessor:f,nodeYAccessor:y,sourceAccessor:P,targetAccessor:B,throughputAccessor:T,pathAccessor:w,coordinateMode:o,particleRate:v,maxParticles:p,particleRadius:x,flowSpeed:c,pathConstraint:k,reducedMotion:I,seed:A,size:N}),[X,G,N,o,c,p,m,f,y,x,v,w,k,I,A,P,B,T]);ha(t,{frameRef:_,spawnDatum:(0,Sl.useCallback)((e,t)=>{const n=Ws({nodes:G,links:[e],nodeIdAccessor:m,nodeXAccessor:f,nodeYAccessor:y,sourceAccessor:P,targetAccessor:B,throughputAccessor:T,pathAccessor:w,coordinateMode:o,particleRate:v,maxParticles:p,particleRadius:x,flowSpeed:c,pathConstraint:k,reducedMotion:I,seed:A+t+1,size:N}),i={id:(e.id??"physical-flow-push-"+t)+"",x:hs(N).plot.x,y:hs(N).plot.y,mass:1,shape:{type:"circle",radius:x},datum:e},r=n.initialSpawns.length?n.initialSpawns:[i];return{datumId:(e.id??r[0].id)+"",spawns:r}},[G,N,o,c,p,m,f,y,x,v,w,k,I,A,P,B,T]),seedRows:X,seedSpawns:V.initialSpawns});const U=i??"source",K=(0,Sl.useMemo)(()=>ms(U,"#2563eb",{styleRules:D,valueAccessor:T}),[U,D,T]),Q=(0,Sl.useMemo)(()=>function(e,t,n){return{...e,observation:{...e.observation,chartId:t??e.observation?.chartId??"physical-flow",chartType:"PhysicalFlowChart",onObservation:n??e.observation?.onObservation}}}(V.config,n,b),[n,V.config,b]),Z=(0,Sl.useRef)(l?.onTick);Z.current=l?.onTick;const J=(0,Sl.useCallback)((e,t)=>{I||"none"===k||function(e,t){const n=e.readBodies(),i=[],o=[];for(const r of n){const n=$l(r.datum);if(2>n.length)continue;const s=Pl(r,n);if(!s)continue;const a=r.datum,c=Number(a?.flowSpeed),l=Number.isFinite(c)&&c>0?c:t;if(s.progress>=.985||s.distance>Math.max(90,14*Bl(r))){i.push(r.id),o.push(El(r,n,l));continue}const d=Dl(n,Math.min(1,s.progress+Math.max(.035,Math.min(.12,l/s.totalLength*.16))),s.totalLength),u=s.tangent,h=(u.x*l-r.vx)*r.mass*.16+(d.x-r.x)*r.mass*.045+(s.point.x-r.x)*r.mass*.08,p=(u.y*l-r.vy)*r.mass*.16+(d.y-r.y)*r.mass*.045+(s.point.y-r.y)*r.mass*.08,[m,f]=Tl(h,p,r.mass*l*.35);e.applyImpulse(r.id,m,f)}i.length&&e.remove(i),o.length&&e.pushMany(o)}(t,c),Z.current?.(e,t)},[c,k,I]),ee=Xa({data:null==d&&null==s&&null==r?void 0:X,emptyContent:a,loading:u,loadingContent:h,size:N});if(ee)return ee;const te=function(e,t){const{showNodeLabels:n,showSensors:i,showStaticFlow:o}=t;if(e&&(o||i))return({size:t})=>{const r=[Number(t[0])||760,Number(t[1])||420],s=Math.max(1,...e.links.map(e=>e.throughput)),a=new Set(e.nodes.map(e=>e.sensorId));return(0,jl.jsxs)("svg",{"aria-hidden":"true","data-testid":"physical-flow-static-flow-overlay",width:r[0],height:r[1],viewBox:`0 0 ${r[0]} ${r[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[o?e.links.map(e=>{const t=3+e.throughput/s*16,n=e.path[Math.floor(e.path.length/2)];return(0,jl.jsxs)("g",{children:[(0,jl.jsx)("path",{d:Cl(e.path),fill:"none",stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:t+5,strokeLinecap:"round",strokeLinejoin:"round",opacity:.26}),(0,jl.jsx)("path",{d:Cl(e.path),fill:"none",stroke:"var(--semiotic-accent, #4e79a7)",strokeWidth:t,strokeLinecap:"round",strokeLinejoin:"round",opacity:.16}),n?(0,jl.jsx)("text",{x:n.x,y:n.y-t/2-5,textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:Al(e.throughput)}):null]},e.id)}):null,e.nodes.map(e=>(0,jl.jsxs)("g",{children:[i&&a.has(e.sensorId)?(0,jl.jsx)("rect",{"data-testid":"physical-flow-sensor-overlay",x:e.x-12,y:e.y-12,width:24,height:24,rx:4,fill:"none",stroke:"var(--semiotic-warning, #f59e0b)",strokeDasharray:"3 3",strokeWidth:1.5,opacity:.88}):null,o?(0,jl.jsx)("circle",{cx:e.x,cy:e.y,r:6,fill:"var(--semiotic-bg, #fff)",stroke:"var(--semiotic-text-secondary, #555)",strokeWidth:1.2}):null,n?(0,jl.jsx)("text",{x:e.x,y:e.y-14,textAnchor:"middle",fill:"var(--semiotic-text-primary, #111827)",fontSize:11,fontWeight:800,children:e.label}):null]},e.id))]})}}(V.metadata,{showNodeLabels:C,showSensors:R,showStaticFlow:$}),ne=(ie=V.metadata)?ie.links.map(e=>{const t=e.path[Math.floor(e.path.length/2)]??e.path[0],n=`${e.sourceLabel} to ${e.targetLabel}: ${Al(e.throughput)} throughput, ${e.packetCount} packets`;return{id:e.id,label:n,description:n,datum:e,x:t?.x??0,y:t?.y??0,shape:"path",pathData:Cl(e.path),group:"flow"}}):[];var ie;const oe=Ka(e.tooltip,l),re=Qa(e,l,ne,{chartMode:q,className:O,title:W,description:L,summary:Y,accessibleTable:H,enableHover:z,margin:F});return Va("PhysicalFlowChart",N,(0,jl.jsx)(rs,{...l,...oe,...re,ref:_,config:Q,continuous:!I&&"none"!==k,foregroundGraphics:Ua(te,l?.foregroundGraphics),initialSpawns:V.initialSpawns,onTick:J,paused:M||I,responsiveHeight:S,responsiveWidth:j,simulationExecution:"none"===k?l?.simulationExecution:"sync",size:N,bodyStyle:K,workerBodyThreshold:l?.workerBodyThreshold??1/0}))});Nl.displayName="PhysicalFlowChart";var Ol=require("react"),Wl=require("react/jsx-runtime"),ql={flow:{fill:"rgba(59, 130, 246, 0.14)",stroke:"rgba(96, 165, 250, 0.7)",accent:"#60a5fa"},capacity:{fill:"rgba(251, 146, 60, 0.18)",stroke:"rgba(251, 146, 60, 0.85)",accent:"#fb923c"},portal:{fill:"rgba(244, 114, 182, 0.14)",stroke:"rgba(244, 114, 182, 0.7)",accent:"#f472b6"},absorb:{fill:"rgba(52, 211, 153, 0.18)",stroke:"rgba(52, 211, 153, 0.8)",accent:"#34d399"}},Fl=6.2;function zl(e,t,n){return Math.max(t,Math.min(n,e))}function Ll(e){return e.length*Fl}function Yl(e,t){const n=e.trim();if(t>=n.length)return n;if(1>=t)return n.slice(0,1);const i=n.split(/\s+/).filter(Boolean).map(e=>e[0]).join("").toUpperCase();return i.length>1&&t>=i.length?i:t>3?n.slice(0,Math.max(1,t-2))+"..":n.slice(0,t).toUpperCase()}function Hl(e,t,n="auto"){const i=Math.max(1,Math.floor(t/Fl)),o="compact"===n?Yl(e,i):"full"===n?e:Ll(e)>t?Yl(e,i):e;return{text:o,textLength:Ll(o)>t?Math.max(4,t):void 0}}function _l(e,t={}){const{showFlowSpine:n=!0,showStageCounts:i=!0,showCapacityBadges:o=!0,showGroupSockets:r=!0,stageLabelMode:s="auto",outlineStages:a=!1,testId:c="process-flow-chrome"}=t,{width:l,height:d,left:u,right:h,topY:p,bottomY:m,midY:f,stages:y,groups:g=[]}=e,b=m-p;return(0,Wl.jsxs)("svg",{"aria-hidden":"true","data-testid":c,"data-outline-stages":a?"true":void 0,width:l,height:d,viewBox:`0 0 ${l} ${d}`,style:{position:"absolute",inset:0,pointerEvents:"none"},className:["semiotic-process-chrome",a?"semiotic-process-chrome--outline-stages":null].filter(Boolean).join(" "),children:[(0,Wl.jsx)("defs",{children:(0,Wl.jsxs)("linearGradient",{id:"semiotic-process-floor",x1:"0",x2:"0",y1:"0",y2:"1",children:[(0,Wl.jsx)("stop",{offset:"0%",stopColor:"var(--semiotic-process-floor, var(--semiotic-bg, #0f172a))",stopOpacity:"0.2"}),(0,Wl.jsx)("stop",{offset:"100%",stopColor:"var(--semiotic-process-lane, var(--semiotic-surface, #1e293b))",stopOpacity:"0.55"})]})}),(0,Wl.jsx)("rect",{x:0,y:0,width:l,height:d,fill:"url(#semiotic-process-floor)"}),(0,Wl.jsx)("rect",{x:u-6,y:p-8,width:h-u+12,height:b+16,rx:14,fill:"var(--semiotic-process-lane, var(--semiotic-surface, #111827))",fillOpacity:.45,stroke:"var(--semiotic-process-border, var(--semiotic-border, #334155))",strokeOpacity:.95}),n?(0,Wl.jsx)("line",{x1:u+8,x2:h-8,y1:f,y2:f,stroke:"var(--semiotic-process-border, var(--semiotic-border, #475569))",strokeWidth:2,strokeDasharray:"6 8",opacity:.55}):null,y.map((e,t)=>{const n=function(e){return e.absorb?"absorb":e.portalTarget?"portal":null!=e.capacity?"capacity":"flow"}(e),r=ql[n],c=Math.max(12,e.width-8),l=zl(c-8,22,88),u=Hl(e.label,Math.max(8,l-10),s),h="none"!==s&&c-8>=22,g=function(e){if(null!=e.capacity){const t=null!=e.queueDepth?" · q "+e.queueDepth:"";return e.capacityLabel?`${e.capacityLabel}${t}`:`cap ${Number.isInteger(e.capacity)?e.capacity+"":e.capacity.toFixed(1)}${t}`}return e.absorb?"absorb":e.portalTarget?"portal":"flow"}(e),x=Hl(g,Math.max(16,c-10),"auto"),v=o&&!1!==e.showBadge&&c>=32,w=null!=e.count?`n=${e.count}${null!=e.processed?" done "+e.processed:""}`:"",k=Hl(w,Math.max(16,c-8),"auto"),M=Math.max(30,p-15),I=M-13;return(0,Wl.jsxs)("g",{"data-stage":e.id,"data-role":n,children:[(0,Wl.jsx)("rect",{className:"semiotic-process-chrome__stage-bay",x:e.x0+4,y:p+6,width:c,height:b-12,rx:10,fill:a?"none":r.fill,stroke:r.stroke,strokeWidth:a?1.85:"flow"===n?1:1.6}),y.length-1>t?(0,Wl.jsx)("polygon",{points:`${e.x1-2},${f-7} ${e.x1+8},${f} ${e.x1-2},${f+7}`,fill:r.accent,opacity:.85}):null,h?(0,Wl.jsxs)(Wl.Fragment,{children:[(0,Wl.jsx)("rect",{className:"semiotic-process-chrome__stage-label-bg",x:e.x-l/2,y:I,width:l,height:18,rx:9,fill:"var(--semiotic-bg, #0f172a)",fillOpacity:.75,stroke:r.stroke}),(0,Wl.jsxs)("text",{x:e.x,y:M,textAnchor:"middle",fill:r.accent,fontSize:10,fontWeight:800,className:"semiotic-process-chrome__stage-label",textLength:u.textLength,lengthAdjust:u.textLength?"spacingAndGlyphs":void 0,children:[(0,Wl.jsx)("title",{children:e.label}),u.text]})]}):null,v?(0,Wl.jsxs)("text",{x:e.x,y:p+22,textAnchor:"middle",fill:"var(--semiotic-process-muted, var(--semiotic-text-secondary, #94a3b8))",fontSize:9,fontWeight:700,textLength:x.textLength,lengthAdjust:x.textLength?"spacingAndGlyphs":void 0,children:[(0,Wl.jsx)("title",{children:g}),x.text]}):null,i&&null!=e.count?(0,Wl.jsxs)("text",{x:e.x,y:Math.min(d-8,m+16),textAnchor:"middle",fill:"var(--semiotic-process-text, var(--semiotic-text, #e2e8f0))",fontSize:11,fontWeight:800,textLength:k.textLength,lengthAdjust:k.textLength?"spacingAndGlyphs":void 0,children:[(0,Wl.jsx)("title",{children:w}),k.text]}):null]},e.id)}),r?g.map((e,t)=>{const n=e.total??0,i=e.absorbed??0,o=e.complete??(n>0&&i>=n),r=!o&&n>0&&i/n>=.75,s=o?"rgba(52, 211, 153, 0.35)":r?"rgba(251, 191, 36, 0.28)":"rgba(15, 23, 42, 0.75)",a=o?"#34d399":r?"#fbbf24":"var(--semiotic-border, #64748b)",c=n>0?`${i}/${n}${o?" shipped":r?" almost":""}`:"feature "+(t+1),l=zl(Math.max(54,Ll(e.label)+18,Ll(c)+16),54,104),d=Hl(e.label,l-12,"auto"),u=Hl(c,l-12,"auto");return(0,Wl.jsxs)("g",{"data-group":e.id,children:[(0,Wl.jsx)("rect",{x:e.x-l/2,y:e.y-22,width:l,height:44,rx:10,fill:s,stroke:a,strokeWidth:1.5}),(0,Wl.jsxs)("text",{x:e.x,y:e.y-4,textAnchor:"middle",fill:"var(--semiotic-process-text, var(--semiotic-text, #f8fafc))",fontSize:10,fontWeight:800,textLength:d.textLength,lengthAdjust:d.textLength?"spacingAndGlyphs":void 0,children:[(0,Wl.jsx)("title",{children:e.label}),d.text]}),(0,Wl.jsxs)("text",{x:e.x,y:e.y+12,textAnchor:"middle",fill:a,fontSize:9,fontWeight:700,textLength:u.textLength,lengthAdjust:u.textLength?"spacingAndGlyphs":void 0,children:[(0,Wl.jsx)("title",{children:c}),u.text]})]},e.id)}):null]})}var Gl=require("react/jsx-runtime"),Xl=(0,Ol.forwardRef)(function(e,t){const{ballRadius:n=6,chromeOptions:i,colorBy:o,data:r,emptyContent:s,frameProps:a={},groupAnchorAlong:c,groupBy:l,groupCompletion:d,groupLabelAccessor:u,gravityX:h,gravityY:p,idAccessor:m,initialSpawnPacing:f,liveCapacity:y=!0,onCapacityChange:g,selection:b,bodyLimit:x,bodyMark:v,loading:w,loadingContent:k,paused:M,radiusAccessor:I,responsiveHeight:S,responsiveWidth:j,route:A="horizontal",seed:C=1,settle:R,springDamping:$,springStiffness:P,stageAccessor:D="stage",stages:B,workAccessor:T}=e,E=Ga(e,[900,420]),{chartSize:N,showProjection:O,showChrome:W,className:q,title:F,chartMode:z,margin:L,enableHover:Y,description:H,summary:_,accessibleTable:G}=E,X=(0,Ol.useRef)(null),V=(0,Ol.useMemo)(()=>cc(r??[]),[r]),U=(0,Ol.useMemo)(()=>({data:V,stages:B,size:N,idAccessor:m,stageAccessor:D,groupBy:l,groupLabelAccessor:u,workAccessor:T,radiusAccessor:I,ballRadius:n,seed:C,route:A,groupCompletion:d,groupAnchorAlong:c,springStiffness:P,springDamping:$,gravityX:h,gravityY:p,settle:R}),[n,N,h,p,c,l,d,u,m,I,A,V,C,R,$,P,D,B,T]),K=(0,Ol.useMemo)(()=>aa(U),[U]),Q=K.metadata;ha(t,{frameRef:X,spawnDatum:(0,Ol.useCallback)((e,t)=>{const i=aa({...U,data:[e],seed:C+t+1,settle:!0}).initialSpawns[0]??{id:(e.id??"process-flow-push-"+t)+"",x:hs(N).plot.x,y:hs(N).plot.y,mass:1,shape:{type:"circle",radius:n},datum:e};return{datumId:(e.id??i.id)+"",spawns:[i]}},[n,U,N,C]),seedRows:V,seedSpawns:K.initialSpawns});const Z=(0,Ol.useMemo)(()=>ms(o),[o]),J=(0,Ol.useMemo)(()=>{if(!y)return a.controllers;const e=[...B.filter(e=>e.capacity&&e.capacity.unitsPerSecond>0).map(e=>{const t=e.capacity.unitsPerSecond;return qo({id:"process-capacity-"+e.id,regionId:"process-stage-"+e.id,unitsPerSecond:t,unitAccessor:e.capacity.unitAccessor??(T?"string"==typeof T?T:e=>{const t=e.datum;if(!t)return 1;try{return Number(T(t,0))||1}catch{return 1}}:"work"),releaseImpulse:{x:70+Math.min(40,2*t),y:0},queueLayout:"lane",continuous:!0})}),...a.controllers??[]];return e.length?e:void 0},[a.controllers,y,B,T]),[ee,te]=(0,Ol.useState)({}),ne=(0,Ol.useRef)(J);ne.current=J;const ie=(0,Ol.useRef)(a.onTick);ie.current=a.onTick;const oe=!1!==W||null!=g;(0,Ol.useEffect)(()=>{if(!g)return;const e=Object.values(ee);e.length&&g(e)},[ee,g]);const re=(0,Ol.useCallback)((e,t)=>{if(ie.current?.(e,t),!oe)return;const n=ne.current;if(!n?.length)return;const i={};for(const e of n){const t=e.getSnapshot?.();t&&"string"==typeof t.regionId&&(i[t.regionId]=t)}te(e=>function(e,t){const n=Object.keys(e),i=Object.keys(t);if(n.length!==i.length)return!1;for(const i of n){const n=e[i],o=t[i];if(!o)return!1;if(n.queueDepth!==o.queueDepth||n.blockedDepth!==o.blockedDepth||n.processedCount!==o.processedCount||n.unitsPerSecond!==o.unitsPerSecond||n.regionId!==o.regionId||n.metricRevision!==o.metricRevision)return!1}return!0}(e,i)?e:i)},[oe]),se=(0,Ol.useMemo)(()=>{const e=Z,t=a.bodyStyle;return v||t?(n,i)=>{const o="function"==typeof t?t(n,i):t;return{..."function"==typeof e?e(n):e,...o,mark:o?.mark??n.datum?.__physicsMark??n.datum?.mark??v}}:e},[v,Z,a.bodyStyle]),ae=Xa({data:r,emptyContent:s,loading:w,loadingContent:k,size:N});if(ae)return ae;if(!B?.length)return Va("ProcessFlowChart",N,(0,Gl.jsx)("div",{role:"status",style:{width:N[0],height:N[1],display:"grid",placeItems:"center",color:"var(--semiotic-text-secondary, #64748b)"},children:"ProcessFlowChart requires a non-empty stages array."}));const ce=function(e,t,n={},i){if(!1===t||!e)return;const{volume:o,stages:r,groups:s,groupCompletion:a}=e,c=new Map(o.stages.map(e=>[e.id,e])),l=new Map(a.map(e=>[e.id,e]));return({size:e})=>{const t=Number(e[0])||o.width,a=Number(e[1])||o.height,d=r.map(e=>{const t=c.get(e.id),i=n["process-stage-"+e.id];return{id:e.id,label:e.label,x0:t?.x0??e.x-e.width/2,x1:(t?.x0??e.x-e.width/2)+(t?.width??e.width),x:e.x,width:t?.width??e.width,count:e.count,capacity:e.capacity,absorb:e.absorb,portalTarget:e.portalTarget,queueDepth:i?.queueDepth,processed:i?.processedCount}}),u=s.map(e=>{const t=l.get(e.id);return{id:e.id,label:e.label??e.id,x:e.anchor?.x??e.x??0,y:e.anchor?.y??e.y??0,absorbed:t?.absorbed,total:t?.total,complete:t?.complete}});return _l({width:t,height:a,left:o.left,right:o.right,topY:o.topY,bottomY:o.bottomY,midY:o.midY,stages:d,groups:u},{showCapacityBadges:!0,showGroupSockets:!0,...i})}}(Q,W,ee,i),le=function(e,t,n){if(!1===n||!t||0===e.length)return;const i=new Map(t.volume.stages.map(e=>[e.id,e]));return({size:n})=>{const o=[Number(n[0])||t.volume.width,Number(n[1])||t.volume.height],r=hs(o),s=Math.max(1,...e.map(e=>e.value)),a=Math.min(48,.18*r.plot.height),c=r.plot.y+6;return(0,Gl.jsx)("svg",{"aria-hidden":"true","data-testid":"process-flow-projection-overlay",width:o[0],height:o[1],viewBox:`0 0 ${o[0]} ${o[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:t.stages.map((t,n)=>{const o=e[n];if(!o)return null;const r=i.get(t.id);if(!r)return null;const l=Math.max(2,o.value/s*a),d=Math.max(8,.35*r.width);return(0,Gl.jsx)("rect",{x:r.x-d/2,y:c,width:d,height:l,rx:2,fill:"var(--semiotic-primary, #4e79a7)",fillOpacity:.18,stroke:"var(--semiotic-primary, #4e79a7)",strokeOpacity:.45,strokeWidth:1},t.id)})})}}(K.projectionRows,Q,O),de=[...ys(K.projectionRows,N,"stage"),...Bc(Q?.groups??[])],ue=Ka(e.tooltip,a),he=Qa(e,a,de,{chartMode:z,className:q,title:F,description:H,summary:_,accessibleTable:G,enableHover:Y,margin:L}),pe=[...Q?.regionEffects??[],...a.regionEffects??[]];return Va("ProcessFlowChart",N,(0,Gl.jsx)(rs,{...a,...ue,...he,ref:X,controllers:J,regionEffects:pe,selection:b??a.selection,backgroundGraphics:Ua(ce,a.backgroundGraphics),foregroundGraphics:Ua(le,a.foregroundGraphics),initialSpawns:K.initialSpawns,initialSpawnPacing:f??K.initialSpawnPacing,onTick:re,paused:M,responsiveHeight:S,responsiveWidth:j,size:N,bodyStyle:se,config:{...K.config,...null!=x?{bodyLimit:x,eviction:"oldest"}:{},...a.config}}))});Xl.displayName="ProcessFlowChart";var Vl=[.1,.5,.9],Ul=1e6,Kl=12;function Ql(e){const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:null}function Zl(e,t,n,i,o){return"function"==typeof i?i(e,t,n):function(e,t){let n=e;for(const e of t.split(".")){if(null==n||"object"!=typeof n)return;n=n[e]}return n}(e,i??o)}function Jl(e){const t=Number(e.toFixed(Kl));return Object.is(t,-0)?0:t}function ed(e,t,n,i){const o=e.flatMap((e,o)=>{const r=Ql(Zl(e,o,t,n,"time")),s=Ql(Zl(e,o,t,i,"value"));return null==r||null==s?[]:[{time:Jl(r),value:s,index:o}]});o.sort((e,t)=>e.time-t.time||e.index-t.index);const r=[];for(const e of o){const t=r[r.length-1];t?.time===e.time?t.value=e.value:r.push({time:e.time,value:e.value})}return r}function td(e,t,n,i){if(!e.length)return null;const o=e[0],r=e[e.length-1];if(o.time>t)return"clamp"===i?o.value:null;if(t>r.time)return"clamp"===i?r.value:null;const s=function(e,t){let n=0,i=e.length;for(;i>n;){const o=n+i>>>1;t>e[o].time?n=o+1:i=o}return n}(e,t),a=e[s];if(a?.time===t)return a.value;const c=e[Math.max(0,s-1)];return"step"!==n&&a&&a.time!==c.time?c.value+(t-c.time)/(a.time-c.time)*(a.value-c.value):c.value}function nd(e,t){if(1===e.length)return e[0];const n=(e.length-1)*t,i=Math.floor(n),o=Math.ceil(n);return i===o?e[i]:e[i]+(e[o]-e[i])*(n-i)}function id(e){const t=e.interpolation??"step",n=e.outsideDomain??"omit",i=function(e){const t=(e??Vl).map(e=>{const t=Ql(e);if(null==t||0>t||t>1)throw new RangeError("physicsReferenceEnvelope quantiles must be finite values from 0 to 1; received "+e);return Jl(t)});return Array.from(new Set(t)).sort((e,t)=>e-t)}(e.quantiles),o=function(e){if(Array.isArray(e)){if(e.length>Ul)throw new RangeError(`physicsReferenceEnvelope sampleAt exceeds ${Ul} points`);return Array.from(new Set(e.map(Ql).filter(e=>null!=e).map(Jl))).sort((e,t)=>e-t)}const t=e,n=Ql(t.start),i=Ql(t.end),o=Ql(t.step);if(null==n||null==i||null==o||0>=o||n>i)throw new RangeError("physicsReferenceEnvelope sampleAt requires finite start/end values with end >= start and step > 0");const r=Math.floor((i-n)/o)+1;if(r>Ul)throw new RangeError(`physicsReferenceEnvelope sampleAt exceeds ${Ul} points`);const s=[],a=1e-10*Math.max(1,Math.abs(i),Math.abs(n));for(let e=0;r>e;e+=1){const t=n+e*o;if(t>i+a)break;s.push(Jl(Math.min(t,i)))}if(s.length&&a>=Math.abs(s[s.length-1]-i)||s.push(Jl(i)),s.length>Ul)throw new RangeError(`physicsReferenceEnvelope sampleAt exceeds ${Ul} points`);return Array.from(new Set(s)).sort((e,t)=>e-t)}(e.sampleAt),r=e.runs.map(t=>ed(t.samples,t.id,e.timeAccessor,e.valueAccessor));return{points:o.map(e=>{const o=r.map(i=>td(i,e,t,n)).filter(e=>null!=e).sort((e,t)=>e-t),s={};for(const e of i)s[e]=o.length?nd(o,e):null;return{time:e,count:o.length,min:o.length?o[0]:null,max:o.length?o[o.length-1]:null,median:o.length?nd(o,.5):null,quantiles:s}}),quantiles:i,interpolation:t,outsideDomain:n,runCount:e.runs.length}}function od(e,t){return e.quantiles.length?"lower"===t?e.quantiles[0]:e.quantiles[e.quantiles.length-1]:"lower"===t?"min":"max"}function rd(e,t){if("min"===t||"median"===t||"max"===t)return e[t];const n=Ql(t);if(null==n||0>n||n>1)throw new RangeError("comparePhysicsTrace quantile selectors must be from 0 to 1; received "+t);const i=Jl(n);if(!Object.prototype.hasOwnProperty.call(e.quantiles,i))throw Error(`comparePhysicsTrace could not find quantile ${i} in the reference envelope`);return e.quantiles[i]??null}function sd(e,t,n){return t>e?"below":e>n?"above":"inside"}function ad(e,t){const n=Math.max(0,t.time-e.time);if(0>=n||null==e.value||null==e.lower||null==e.upper||null==t.value||null==t.lower||null==t.upper)return{below:0,inside:0,above:0,observed:0};const i=e.value-e.lower,o=t.value-t.lower,r=e.value-e.upper,s=t.value-t.upper,a=[0,1];for(const[e,t]of[[i,o],[r,s]])(0>e&&t>0||e>0&&0>t)&&a.push(-e/(t-e));a.sort((e,t)=>e-t);let c=0,l=0,d=0;for(let i=0;a.length-1>i;i+=1){const o=a[i],r=a[i+1];if(o>=r)continue;const s=(o+r)/2,u=(r-o)*n,h=sd(e.value+(t.value-e.value)*s,e.lower+(t.lower-e.lower)*s,e.upper+(t.upper-e.upper)*s);"below"===h?c+=u:"above"===h?d+=u:l+=u}return{below:c,inside:l,above:d,observed:n}}function cd(e,t,n={}){const i=n.interpolation??t.interpolation,o=n.outsideDomain??t.outsideDomain,r=ed(e,n.traceId??"trace",n.timeAccessor,n.valueAccessor),s=n.lower??od(t,"lower"),a=n.upper??od(t,"upper"),c=t.points.map(e=>{const t=td(r,e.time,i,o),n=rd(e,s),c=rd(e,a);if(null!=n&&null!=c&&n>c)throw new RangeError("comparePhysicsTrace lower band exceeds upper band at time "+e.time);return{time:e.time,value:t,lower:n,upper:c,status:null==t||null==n||null==c?"unobserved":sd(t,n,c)}});let l=0,d=0,u=0,h=0,p=null,m=0,f=null;for(const e of c){if("below"===e.status?l+=1:"inside"===e.status?d+=1:"above"===e.status&&(u+=1),null==e.value||null==e.lower||null==e.upper)continue;const t=Math.max(0,e.value-e.upper),n=Math.max(0,e.lower-e.value);t>h&&(h=t,p=e.time),n>m&&(m=n,f=e.time)}let y=0,g=0,b=0,x=0;for(let e=0;c.length-1>e;e+=1){const t=c[e],n=c[e+1],o=Math.max(0,n.time-t.time);if(o>0){if("linear"===i){const e=ad(t,n);y+=e.below,g+=e.inside,b+=e.above,x+=e.observed;continue}"unobserved"!==t.status&&(x+=o,"below"===t.status?y+=o:"above"===t.status?b+=o:g+=o)}}const v=c[0]?.time,w=c[c.length-1]?.time,k=null==v||null==w?0:Math.max(0,w-v);return{points:c,sampleCount:c.length,observedSamples:l+d+u,belowSamples:l,insideSamples:d,aboveSamples:u,totalDuration:k,observedDuration:x,unobservedDuration:Math.max(0,k-x),belowDuration:y,insideDuration:g,aboveDuration:b,peakExcess:h,peakExcessAt:p,peakDeficit:m,peakDeficitAt:f}}function ld(e){return{id:e,furthestStageIndex:-1,visitedStageIds:[],visitsByStage:{},firstEnteredAt:{},lastEnteredAt:{},regressionCount:0}}function dd(e){const t=Array.from(new Set(e.bodyIds??[]));return{stages:e.stages.map(e=>({...e})),bodyIds:t,entities:Object.fromEntries(t.map(e=>[e,ld(e)]))}}function ud(e,t,n={}){if("region-enter"!==t.type)return e;const i=function(e,t){const n=t.stageId?.(e);if(n)return n;const i=e.region.metadata;if(i&&"object"==typeof i){const e=i.stageId;if("string"==typeof e)return e}return e.region.id}(t,n),o=e.stages.findIndex(e=>e.id===i);if(0>o)return e;const r=n.entityId?.(t)??t.bodyId;if(!r)return e;const s=e.entities[r]??ld(r),a=s.currentStageId?e.stages.findIndex(e=>e.id===s.currentStageId):-1,c=!s.visitedStageIds.includes(i),l=Number(t.observation.timestamp),d=Number.isFinite(l)?l:0,u={...s,currentStageId:i,furthestStageId:o>s.furthestStageIndex?i:s.furthestStageId,furthestStageIndex:Math.max(s.furthestStageIndex,o),visitedStageIds:c?[...s.visitedStageIds,i]:s.visitedStageIds,visitsByStage:{...s.visitsByStage,[i]:(s.visitsByStage[i]??0)+1},firstEnteredAt:c?{...s.firstEnteredAt,[i]:d}:s.firstEnteredAt,lastEnteredAt:{...s.lastEnteredAt,[i]:d},regressionCount:a>=0&&a>o?s.regressionCount+1:s.regressionCount};return{...e,bodyIds:e.bodyIds.includes(r)?e.bodyIds:[...e.bodyIds,r],entities:{...e.entities,[r]:u}}}function hd(e){const t=e.bodyIds.map(t=>e.entities[t]??ld(t)),n=t.length;let i=n;return e.stages.map((e,o)=>{const r=t.filter(e=>e.furthestStageIndex>=o).length,s=t.filter(t=>t.visitedStageIds.includes(e.id)).length,a=t.reduce((t,n)=>t+(n.visitsByStage[e.id]??0),0),c={id:e.id,label:e.label??e.id,reached:r,entered:s,total:n,conversion:n>0?r/n:0,fromPrevious:i>0?r/i:0,dropoff:Math.max(0,i-r),visits:a,repeatVisits:Math.max(0,a-s)};return i=r,c})}function pd(e){const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:null}function md(e,t,n,i){const o="function"==typeof e?e(t,n):e;return Number.isFinite(o)?Number(o):i}function fd(e,t,n){return pd(e[t])??n}function yd(e,t){return"number"==typeof e?e:e?.[t]??0}function gd(e){const{band:t,idPrefix:n,plot:i,projection:o}=e,{includeBoundaryWalls:r=!0,includeInteriorWalls:s=!0,wallThickness:a=4}=t,c=function(e){const t=e.bandwidth??e.scale.bandwidth?.()??0,n=new Set;for(const i of e.values){const o=e.scale(i);Number.isFinite(o)&&(n.add(Number(o)),n.add(Number(o)+t))}return Array.from(n).sort((e,t)=>e-t)}(t);if(2>c.length)return[];const l=r?c.length-1:c.length-2,d=[];for(let e=r?0:1;l>=e;e+=1){if(!s&&e>0&&c.length-1>e)continue;const t=c[e];d.push({id:`${n}-wall-${e}`,shape:"x"===o?{type:"aabb",x:t,y:i.y+i.height/2,width:a,height:i.height}:{type:"aabb",x:i.x+i.width/2,y:t,width:i.width,height:a}})}return d}function bd(e){const{plot:t,idPrefix:n="physics-scale",bounds:i={},xBins:o,xBands:r,yBands:s}=e,a=[];if(!1!==i&&a.push(...Ji(t,{idPrefix:n,...i})),o){const{idPrefix:e,yTop:i,yBottom:r,...s}=o;a.push(...eo({...s,idPrefix:e??n+"-xbin",yTop:i??t.y,yBottom:r??t.y+t.height}))}return r&&a.push(...gd({band:r,idPrefix:r.idPrefix??n+"-xband",plot:t,projection:"x"})),s&&a.push(...gd({band:s,idPrefix:s.idPrefix??n+"-yband",plot:t,projection:"y"})),a}function xd(e){const{plot:t,rows:n,columns:i=n+1,pegRadius:o=3,idPrefix:r="galton-peg",yStart:s=t.y+.18*t.height,yEnd:a=t.y+.58*t.height,stagger:c=!0,restitution:l=.2,friction:d=.04}=e,u=Math.max(0,Math.floor(n)),h=Math.max(1,Math.floor(i));if(0===u)return[];const p=u>1?(a-s)/(u-1):0,m=t.width/h,f=[];for(let e=0;u>e;e+=1){const n=c&&e%2==1?m/2:0;for(let i=0;h>i;i+=1){const a=t.x+m*(i+.5)+n;t.x+o>a||a>t.x+t.width-o||f.push({id:`${r}-${e}-${i}`,shape:{type:"aabb",x:a,y:s+e*p,width:2*o,height:2*o},restitution:l,friction:d})}}return f}function vd(e,t={}){const{idPrefix:n="physics-token",radius:i=5,shape:o,mass:r,vx:s,vy:a,spawnAt:c,seed:l=1,jitter:d,datum:u}=t,h=ni(l),p=yd(d,"x"),m=yd(d,"y");return e.map((e,l)=>{const d=md(t.x,e,l,fd(e,"x",0)),f=md(t.y,e,l,fd(e,"y",0)),y=md(i,e,l,5),g="function"==typeof o?o(e,l):o??{type:"circle",radius:y};return{id:`${n}-${e.index??l}`,x:d+(h()-.5)*p,y:f+(h()-.5)*m,vx:md(s,e,l,0),vy:md(a,e,l,0),mass:md(r,e,l,1),spawnAt:md(c,e,l,void 0),shape:g,datum:u?u(e,l):e.datum??e}}).map(e=>{if(Number.isFinite(e.spawnAt))return e;const{spawnAt:t,...n}=e;return n})}function wd(e,t={}){const{idPrefix:n="sediment",collider:i=!0,colliderThickness:o=1,restitution:r=.05,friction:s=.2,...a}=t,c=Oi(e,a),l=i?c.filter(e=>e.height>0).map(e=>({id:`${n}-${e.binId}`,shape:{type:"aabb",x:e.x+e.width/2,y:e.y+o/2,width:e.width,height:o},restitution:r,friction:s})):[];return{columns:c,colliders:l}}function kd(e,t={}){const{timeAccessor:n="arrivalTime",timeScale:i=1,startAt:o=0,rebase:r=!0,sort:s=!0}=t,a=e.map((e,t)=>({spawn:e,time:function(e,t,n){return pd("function"==typeof n?n(e,t):e[n]??e.datum?.[n])}(e,t,n)??e.spawnAt??t})),c=a.length?Math.min(...a.map(e=>e.time)):0;return{initialSpawns:a.map(({spawn:e,time:t})=>({...e,spawnAt:o+(r?t-c:t)})).sort((e,t)=>s?(e.spawnAt??0)-(t.spawnAt??0):0),initialSpawnPacing:{pacing:"arrival",startAt:o,timeAccessor:"spawnAt",timeScale:i}}}var Md=require("react"),Id=1e-9;function Sd(e,t){return t>e?-1:e>t?1:0}function jd(e){return{...e}}function Ad(e){return e.map(e=>({...e,sourceIds:e.sourceIds?[...e.sourceIds]:void 0,productIds:e.productIds?[...e.productIds]:void 0,relationIds:e.relationIds?[...e.relationIds]:void 0,outletIds:e.outletIds?[...e.outletIds]:void 0}))}function Cd(e){const t=Object.fromEntries(Object.entries(e.components).map(([e,t])=>[e,{...t,initialMetrics:jd(t.initialMetrics),metrics:jd(t.metrics),productIds:[...t.productIds],history:Ad(t.history)}])),n=Object.fromEntries(Object.entries(e.products).map(([e,t])=>[e,{...t,metrics:jd(t.metrics),sourceIds:[...t.sourceIds],history:Ad(t.history)}])),i=Object.fromEntries(Object.entries(e.relations).map(([e,t])=>[e,{...t,sourceIds:[...t.sourceIds],metrics:t.metrics?jd(t.metrics):void 0}]));return{...e,eventsApplied:[...e.eventsApplied],components:t,products:n,relations:i,input:{amount:e.input.amount,metrics:jd(e.input.metrics)},metrics:jd(e.metrics),loss:{amount:e.loss.amount,metrics:jd(e.loss.metrics)},history:Ad(e.history)}}function Rd(e,t,n,i,o){return{severity:e,code:t,message:n,path:i,ids:o?[...o]:void 0}}function $d(e){const t=new Set,n=new Set;for(const i of e)t.has(i)&&n.add(i),t.add(i);return[...n].sort(Sd)}function Pd(e,t){return e?Object.entries(e).flatMap(([e,n])=>Number.isFinite(n)?[]:[Rd("error","invalid-metric",`Metric "${e}" must be a finite number.`,`${t}.${e}`)]):[]}function Dd(e,t){for(const[n,i]of Object.entries(t))e[n]=Number(e[n]??0)+i}function Bd(e,t,n="selector"){const i=[],o=Object.values(e.components),r=new Set(o.map(e=>e.id)),s=(t.ids??[]).filter(e=>!r.has(e));if(s.length&&i.push(Rd("error","unknown-component",`Selector references unknown component id${1===s.length?"":"s"}: ${s.join(", ")}.`,n+".ids",s)),void 0===t.count||Number.isInteger(t.count)&&t.count>=0||i.push(Rd("error","invalid-selector-count","Selector count must be a non-negative integer.",n+".count")),i.some(e=>"error"===e.severity))return{ids:[],diagnostics:i};const a=t.ids?new Set(t.ids):null,c=t.categories?new Set(t.categories):null,l=t.statuses?new Set(t.statuses):null,d=t.outletIds?new Set(t.outletIds):null;let u=o.filter(e=>!a||a.has(e.id)).filter(e=>!c||c.has(e.category)).filter(e=>!l||l.has(e.status)).filter(e=>!d||void 0!==e.outletId&&d.has(e.outletId)).map(e=>e.id).sort(Sd);return void 0!==t.count&&(u=u.slice(0,t.count)),u.length||i.push(Rd("warning","empty-selector","Selector matched no source components.",n)),{ids:u,diagnostics:i}}function Td(e,t,n={}){return{eventId:e.event.id,effectType:t.type,phaseId:e.context.phaseId,authoredAt:e.context.authoredAt,appliedAt:e.context.appliedAt,label:e.event.label,summary:e.event.summary,...n}}function Ed(e,t){const n={...t,eventId:e.event.id};e.materializations.push(n),e.observations.push({...n,phaseId:e.context.phaseId,authoredAt:e.context.authoredAt,appliedAt:e.context.appliedAt})}function Nd(e,t,n){return!(void 0!==t&&!e.outletIds.has(t)&&(e.diagnostics.push(Rd("error","unknown-outlet",`Unknown outlet "${t}".`,n,[t])),1))}function Od(e,t,n){const i=$d(t);t.length||e.diagnostics.push(Rd("error","empty-source-list","A product requires at least one source component.",n)),i.length&&e.diagnostics.push(Rd("error","duplicate-source",`Source ids may appear only once: ${i.join(", ")}.`,n,i));const o=t.filter(t=>!e.state.components[t]);o.length&&e.diagnostics.push(Rd("error","unknown-component",`Unknown source component id${1===o.length?"":"s"}: ${o.join(", ")}.`,n,o));const r=t.filter(t=>(e.state.components[t]?.productIds.length??0)>0);r.length&&e.diagnostics.push(Rd("error","source-already-assigned",`Source component${1===r.length?" is":"s are"} already assigned: ${r.join(", ")}.`,n,r));const s=t.filter(t=>"consumed"===e.state.components[t]?.status&&!r.includes(t));return s.length&&e.diagnostics.push(Rd("error","source-unavailable",`Consumed source component${1===s.length?" is":"s are"} unavailable: ${s.join(", ")}.`,n,s)),e.diagnostics.some(e=>"error"===e.severity)?null:t.map(t=>e.state.components[t])}function Wd(e,t,n,i,o){const r=i?.amount??0;(!Number.isFinite(r)||0>r||r>t+Id)&&e.diagnostics.push(Rd("error","invalid-loss","Loss amount must be finite, non-negative, and no greater than its sources.",o+".amount")),e.diagnostics.push(...Pd(i?.metrics,o+".metrics"));for(const[t,r]of Object.entries(i?.metrics??{}))(0>r||r>Number(n[t]??0)+Id)&&e.diagnostics.push(Rd("error","invalid-metric-loss",`Metric loss "${t}" must be non-negative and no greater than its sources.`,`${o}.metrics.${t}`));return!e.diagnostics.some(e=>"error"===e.severity)}function qd(e,t,n,i,o,r,s){return{id:e.id,label:e.label??e.id,description:e.description,category:e.category??"product",color:e.color,order:e.order,declaredAmount:e.amount,amount:r&&void 0!==e.amount?e.amount:n,metrics:r&&e.metrics?{...i,...e.metrics}:i,status:r?"complete":"forming",sourceIds:[...t],outletId:r?e.outletId??(o.outletIds.has("product")?"product":void 0):void 0,createdByEventId:o.event.id,createdAt:o.context.appliedAt,completedByEventId:r?o.event.id:void 0,completedAt:r?o.context.appliedAt:void 0,history:[s]}}function Fd(e,t,n,i){void 0!==t.amount&&Math.abs(t.amount-n)>Id&&e.diagnostics.push(Rd("warning","declared-product-amount-mismatch",`Product "${t.id}" declares ${t.amount}, while its sources yield ${n}.`,i,[t.id]))}function zd(e,t,n){const i=`events.${e.event.id}.effects.${n}`,o=e.state;if("set-state"===t.type){["queued","active","transformed","retained","ejected","failed","recovered"].includes(t.state)||e.diagnostics.push(Rd("error","invalid-component-state",`set-state cannot assign "${t.state+""}".`,i+".state")),e.diagnostics.push(...Pd(t.metricsDelta,i+".metricsDelta")),Nd(e,t.outletId,i+".outletId");const n=Bd(o,t.select,i+".select");e.diagnostics.push(...n.diagnostics);const r=n.ids.filter(e=>o.components[e].productIds.length);if(r.length&&e.diagnostics.push(Rd("error","source-already-assigned",`Assigned source components cannot be retargeted: ${r.join(", ")}.`,i+".select",r)),e.diagnostics.some(e=>"error"===e.severity))return;const s=Td(e,t,{sourceIds:n.ids,outletIds:t.outletId?[t.outletId]:void 0});for(const e of n.ids){const n=o.components[e];n.status=t.state,n.outletId=t.outletId,n.reason=t.reason,t.metricsDelta&&Dd(n.metrics,t.metricsDelta),n.history.push(s)}return o.history.push(s),void(n.ids.length&&Ed(e,{type:"retarget-component",sourceIds:n.ids,outletIds:t.outletId?[t.outletId]:void 0}))}if("set-relation"===t.type){const{relation:n}=t;n.id&&!o.relations[n.id]||e.diagnostics.push(Rd("error","duplicate-relation",`Relation id "${n.id}" is missing or already active.`,i+".relation.id",[n.id]));const r=function(e,t,n){const i=$d(t),o=t.filter(t=>!e.state.components[t]);return 2>t.length&&e.diagnostics.push(Rd("error","insufficient-relation-sources","A relation requires at least two source components.",n)),i.length&&e.diagnostics.push(Rd("error","duplicate-source",`Relation source ids must be unique: ${i.join(", ")}.`,n,i)),o.length&&e.diagnostics.push(Rd("error","unknown-component",`Relation references unknown source component${1===o.length?"":"s"}: ${o.join(", ")}.`,n,o)),e.diagnostics.some(e=>"error"===e.severity)?null:t.map(t=>e.state.components[t])}(e,n.sourceIds,i+".relation.sourceIds");if(e.diagnostics.push(...Pd(n.metrics,i+".relation.metrics")),!r||e.diagnostics.some(e=>"error"===e.severity))return;o.relations[n.id]={...n,sourceIds:[...n.sourceIds],metrics:n.metrics?{...n.metrics}:void 0,status:"active",createdByEventId:e.event.id,createdAt:e.context.appliedAt};const s=Td(e,t,{sourceIds:[...n.sourceIds],relationIds:[n.id]});return o.history.push(s),void Ed(e,{type:"activate-relation",sourceIds:[...n.sourceIds],relationIds:[n.id]})}if("resolve-relation"===t.type){const n=$d(t.relationIds),r=t.relationIds.filter(e=>!o.relations[e]),s=t.relationIds.filter(e=>"resolved"===o.relations[e]?.status);if(n.length&&e.diagnostics.push(Rd("error","duplicate-relation","Relation ids must be unique.",i+".relationIds",n)),r.length&&e.diagnostics.push(Rd("error","unknown-relation",`Unknown relation: ${r.join(", ")}.`,i+".relationIds",r)),s.length&&e.diagnostics.push(Rd("error","resolved-relation",`Relation is already resolved: ${s.join(", ")}.`,i+".relationIds",s)),e.diagnostics.some(e=>"error"===e.severity))return;for(const n of t.relationIds){const i=o.relations[n];i.status="resolved",i.resolution=t.resolution,i.resolvedByEventId=e.event.id,i.resolvedAt=e.context.appliedAt,i.reason=t.reason}const a=Td(e,t,{relationIds:[...t.relationIds]});return o.history.push(a),void Ed(e,{type:"resolve-relation",relationIds:[...t.relationIds]})}if("combine"===t.type||"contribute"===t.type){const n=e.productDefinitions.get(t.productId);n||e.diagnostics.push(Rd("error","unknown-product",`Product "${t.productId}" has no declared mold.`,i+".productId",[t.productId]));const r=o.products[t.productId];"combine"===t.type&&r&&e.diagnostics.push(Rd("error","duplicate-product",`Product "${t.productId}" has already been formed.`,i+".productId",[t.productId])),"contribute"!==t.type||r&&"forming"===r.status||e.diagnostics.push(Rd("error","product-not-forming",`Contributions require an existing forming product "${t.productId}".`,i+".productId",[t.productId]));const s=Od(e,t.sourceIds,i+".sourceIds"),a="contribute"===t.type&&r?[...r.sourceIds,...t.sourceIds]:t.sourceIds,c=function(e,t,n,i){if(!t?.length)return[];const o=$d(t),r=t.filter(t=>!e.state.relations[t]),s=t.filter(t=>"resolved"===e.state.relations[t]?.status),a=new Set(n),c=t.filter(t=>(e.state.relations[t]?.sourceIds??[]).some(e=>!a.has(e)));return o.length&&e.diagnostics.push(Rd("error","duplicate-relation","Basis relations must be unique.",i,o)),r.length&&e.diagnostics.push(Rd("error","unknown-relation",`Unknown basis relation: ${r.join(", ")}.`,i,r)),s.length&&e.diagnostics.push(Rd("error","resolved-relation",`Basis relation is already resolved: ${s.join(", ")}.`,i,s)),c.length&&e.diagnostics.push(Rd("error","relation-source-mismatch",`Basis relation includes a source outside this product: ${c.join(", ")}.`,i,c)),e.diagnostics.some(e=>"error"===e.severity)?null:t.map(t=>e.state.relations[t])}(e,t.basisRelationIds,a,i+".basisRelationIds");if(!s||!c||!n||e.diagnostics.some(e=>"error"===e.severity))return;const l=s.reduce((e,t)=>e+t.amount,0),d=function(e){const t={};for(const n of e)Dd(t,n.metrics);return t}(s);if(!Wd(e,l,d,t.loss,i+".loss"))return;const u=l-(t.loss?.amount??0);!function(e,t,n){e.state.loss.amount+=n?.amount??0;for(const[i,o]of Object.entries(n?.metrics??{}))t[i]=Number(t[i]??0)-o,e.state.loss.metrics[i]=Number(e.state.loss.metrics[i]??0)+o}(e,d,t.loss);const h="combine"===t.type&&!1!==t.complete,p=Td(e,t,{sourceIds:[...t.sourceIds],productIds:[t.productId],relationIds:t.basisRelationIds?[...t.basisRelationIds]:void 0});let m;if("combine"===t.type){if(h&&Fd(e,n,u,i+".productId"),m=qd(n,t.sourceIds,u,d,e,h,p),h&&!Nd(e,m.outletId,i+".productId"))return;o.products[t.productId]=m}else m=r,m.sourceIds.push(...t.sourceIds),m.amount+=u,Dd(m.metrics,d),m.history.push(p);for(const e of s)e.productIds=[t.productId],e.status="consumed",e.outletId=void 0,e.history.push(p);return o.history.push(p),function(e,t){if(t.length){for(const n of t)n.status="resolved",n.resolution="combined",n.resolvedByEventId=e.event.id,n.resolvedAt=e.context.appliedAt;Ed(e,{type:"resolve-relation",relationIds:t.map(e=>e.id)})}}(e,c),Ed(e,{type:"combine"===t.type?"form-product":"update-product",sourceIds:[...t.sourceIds],productIds:[t.productId],relationIds:t.basisRelationIds?[...t.basisRelationIds]:void 0,outletIds:m.outletId?[m.outletId]:void 0}),void(h&&Ed(e,{type:"complete-product",sourceIds:[...m.sourceIds],productIds:[m.id],outletIds:m.outletId?[m.outletId]:void 0}))}if("complete-product"===t.type){const n=o.products[t.productId];return n?void function(e,t,n,i,o,r){const s=e.productDefinitions.get(t.id),a=n??s?.outletId??(e.outletIds.has("product")?"product":void 0);if(!Nd(e,a,r+".outletId"))return;if("complete"===t.status)return void e.diagnostics.push(Rd("error","product-already-complete",`Product "${t.id}" is already complete.`,r,[t.id]));s&&(Fd(e,s,t.amount,r+".productId"),void 0!==s.amount&&(t.amount=s.amount),s.metrics&&(t.metrics={...t.metrics,...s.metrics})),t.status="complete",t.outletId=a,t.reason=i,t.completedByEventId=e.event.id,t.completedAt=e.context.appliedAt;const c=Td(e,o,{sourceIds:[...t.sourceIds],productIds:[t.id],outletIds:a?[a]:void 0});t.history.push(c),e.state.history.push(c),Ed(e,{type:"complete-product",sourceIds:[...t.sourceIds],productIds:[t.id],outletIds:a?[a]:void 0})}(e,n,t.outletId,t.reason,t,i):void e.diagnostics.push(Rd("error","unknown-product-state",`Product "${t.productId}" has not been formed.`,i+".productId",[t.productId]))}if("split"===t.type){const n=Od(e,[t.sourceId],i+".sourceId");t.products.length||e.diagnostics.push(Rd("error","empty-split","A split requires at least one product allocation.",i+".products"));const r=t.products.map(e=>e.productId),s=$d(r);s.length&&e.diagnostics.push(Rd("error","duplicate-product","Split product ids must be unique.",i+".products",s));const a=r.map(t=>e.productDefinitions.get(t)),c=r.filter((e,t)=>!a[t]),l=r.filter(e=>o.products[e]);c.length&&e.diagnostics.push(Rd("error","unknown-product",`Split references undeclared product molds: ${c.join(", ")}.`,i+".products",c)),l.length&&e.diagnostics.push(Rd("error","duplicate-product",`Split products already exist: ${l.join(", ")}.`,i+".products",l));for(const[n,o]of t.products.entries())void 0===o.amount||Number.isFinite(o.amount)&&o.amount>=0||e.diagnostics.push(Rd("error","invalid-product-amount","Split allocation amounts must be finite and non-negative.",`${i}.products.${n}.amount`)),e.diagnostics.push(...Pd(o.metrics,`${i}.products.${n}.metrics`));if(!n?.length||e.diagnostics.some(e=>"error"===e.severity))return;const d=n[0];if(!Wd(e,d.amount,d.metrics,t.loss,i+".loss"))return;const u=d.amount-(t.loss?.amount??0),h=t.products.map((e,t)=>e.amount??a[t]?.amount),p=h.filter(e=>void 0!==e).length;if(0!==p&&p!==h.length)return void e.diagnostics.push(Rd("error","partial-split-allocation","Either every split product must declare an amount or none may do so.",i+".products"));const m=p?h:t.products.map(()=>u/t.products.length),f=m.reduce((e,t)=>e+t,0);if(Math.abs(f-u)>Id)return void e.diagnostics.push(Rd("error","split-amount-mismatch",`Split allocations total ${f}, but ${u} remains after loss.`,i+".products"));const y={...d.metrics};for(const[e,n]of Object.entries(t.loss?.metrics??{}))y[e]=Number(y[e]??0)-n;const g=Td(e,t,{sourceIds:[d.id],productIds:r});if(t.products.forEach((n,r)=>{const s=a[r],c=u>Id?m[r]/u:1/t.products.length,l=Object.fromEntries(Object.entries(y).map(([e,t])=>[e,t*c])),h=n.metrics??s.metrics??l,p=qd({...s,amount:m[r],metrics:h},[d.id],m[r],{...h},e,!0,g);Nd(e,p.outletId,`${i}.products.${r}.productId`)&&(o.products[p.id]=p)}),e.diagnostics.some(e=>"error"===e.severity))return;d.productIds=r,d.status="consumed",d.outletId=void 0,d.history.push(g),o.loss.amount+=t.loss?.amount??0;for(const[e,n]of Object.entries(t.loss?.metrics??{}))o.loss.metrics[e]=Number(o.loss.metrics[e]??0)+n;o.history.push(g),Ed(e,{type:"split-source",sourceIds:[d.id],productIds:r});for(const t of r)Ed(e,{type:"complete-product",sourceIds:[d.id],productIds:[t],outletIds:o.products[t].outletId?[o.products[t].outletId]:void 0});return}if("eject"===t.type){Nd(e,t.outletId,i+".outletId");const n=Bd(o,t.select,i+".select");e.diagnostics.push(...n.diagnostics);const r=n.ids.filter(e=>o.components[e].productIds.length);if(r.length&&e.diagnostics.push(Rd("error","source-already-assigned",`Assigned source components cannot be ejected: ${r.join(", ")}.`,i+".select",r)),e.diagnostics.some(e=>"error"===e.severity))return;const s=Td(e,t,{sourceIds:n.ids,outletIds:[t.outletId]});for(const e of n.ids){const n=o.components[e];n.status=t.state??"ejected",n.outletId=t.outletId,n.reason=t.reason,n.history.push(s)}return o.history.push(s),void(n.ids.length&&Ed(e,{type:"retarget-component",sourceIds:n.ids,outletIds:[t.outletId]}))}if("set-metric"===t.type){if(e.diagnostics.push(...Pd(t.metricsDelta,i+".metricsDelta")),e.diagnostics.some(e=>"error"===e.severity))return;let n,r;if("run"===t.target)Dd(o.metrics,t.metricsDelta);else if("components"in t.target){const r=Bd(o,t.target.components,i+".target.components");if(e.diagnostics.push(...r.diagnostics),e.diagnostics.some(e=>"error"===e.severity))return;n=r.ids;for(const e of r.ids)Dd(o.components[e].metrics,t.metricsDelta)}else{r=[...t.target.productIds];const n=$d(r),s=r.filter(e=>!o.products[e]);if(n.length&&e.diagnostics.push(Rd("error","duplicate-product","Metric target product ids must be unique.",i+".target.productIds",n)),s.length&&e.diagnostics.push(Rd("error","unknown-product-state",`Metric target product has not formed: ${s.join(", ")}.`,i+".target.productIds",s)),e.diagnostics.some(e=>"error"===e.severity))return;for(const e of r)Dd(o.products[e].metrics,t.metricsDelta)}return void o.history.push(Td(e,t,{sourceIds:n,productIds:r}))}t.outcome.trim()?(o.outcome=t.outcome,o.summary=t.summary,o.history.push(Td(e,t)),e.observations.push({type:"crucible-outcome",eventId:e.event.id,phaseId:e.context.phaseId,authoredAt:e.context.authoredAt,appliedAt:e.context.appliedAt,outcome:t.outcome})):e.diagnostics.push(Rd("error","invalid-outcome","Outcome must be a non-empty string.",i+".outcome"))}function Ld(e,t,n){if(e.eventsApplied.includes(t.id))return{applied:!1,state:e,materializations:[],observations:[],diagnostics:[Rd("warning","duplicate-event-application",`Event "${t.id}" has already been applied.`,"events."+t.id,[t.id])]};const i=Cd(e),o={state:i,event:t,context:n,productDefinitions:new Map(n.products.map(e=>[e.id,e])),outletIds:new Set(n.outlets.map(e=>e.id)),diagnostics:[],materializations:[],observations:[]};for(const[n,i]of t.effects.entries())if(zd(o,i,n),o.diagnostics.some(e=>"error"===e.severity))return{applied:!1,state:e,materializations:[],observations:[],diagnostics:o.diagnostics};return i.elapsed=Math.max(i.elapsed,n.appliedAt),i.phaseId=n.phaseId,i.eventsApplied.push(t.id),o.observations.unshift({type:"crucible-event",eventId:t.id,phaseId:n.phaseId,authoredAt:n.authoredAt,appliedAt:n.appliedAt}),{applied:!0,state:i,materializations:o.materializations,observations:o.observations,diagnostics:o.diagnostics}}function Yd(e,t={}){const n=t.groupBy??"outlet",i=new Map,o=e=>{const t=function(e,t){return"product"===t?"product"===e.kind?e.id:"unassigned":"outlet"===t?e.outletId??"unassigned":"category"===t?e.category:e.status}({...e,status:e.status??"active"},n),o=i.get(t);if(o)return o.count+=1,o.amount+=e.amount,void Dd(o.metrics,e.metrics);i.set(t,{key:t,label:"product"===n&&"product"===e.kind?e.label:t,count:1,amount:e.amount,metrics:{...e.metrics},status:"status"===n?e.status:void 0,outletId:"outlet"===n?e.outletId:void 0,category:"category"===n?e.category:void 0,productId:"product"===n&&"product"===e.kind?e.id:void 0})};for(const t of Object.values(e.components))t.productIds.length||"consumed"===t.status||o({kind:"component",id:t.id,label:t.label,status:t.status,outletId:t.outletId,category:t.category,amount:t.amount,metrics:t.metrics});for(const t of Object.values(e.products))o({kind:"product",id:t.id,label:t.label,status:t.status,outletId:t.outletId,category:t.category,amount:t.amount,metrics:t.metrics});const r=new Map((t.order??[]).map((e,t)=>[e,t]));return[...i.values()].sort((e,t)=>(r.get(e.key)??Number.MAX_SAFE_INTEGER)-(r.get(t.key)??Number.MAX_SAFE_INTEGER)||Sd(e.key,t.key))}var Hd=Yd;function _d(e,t={}){const n=t.field??"amount",i=e=>"amount"===n?e.amount:Number(e.metrics[n]??0),o="amount"===n?e.input.amount:Number(e.input.metrics[n]??0),r=Object.values(e.products).reduce((e,t)=>e+i(t),0),s=Object.values(e.components).filter(e=>!e.productIds.length&&"consumed"!==e.status).reduce((e,t)=>e+i(t),0),a="amount"===n?e.loss.amount:Number(e.loss.metrics[n]??0),c=r+s+a,l=c-o;return{field:n,input:o,products:r,unassigned:s,loss:a,output:c,delta:l,conserved:Math.max(0,t.tolerance??1e-6)>=Math.abs(l)}}function Gd(e,t={}){return{history:Ad(e.history),projection:Yd(e,t.projection),conservation:_d(e,t.conservation)}}var Xd=900,Vd=520,Ud=[Xd,Vd],Kd=[{id:"product",label:"Products",side:"bottom",order:0},{id:"retained",label:"Retained",side:"bottom",order:1},{id:"residue",label:"Residue",side:"left",order:2},{id:"failed",label:"Failed",side:"right",order:3},{id:"recovered",label:"Recovered",side:"right",order:4}],Qd=new Set(["queued","active","transformed","consumed","retained","ejected","failed","recovered"]),Zd=1e-9;function Jd(e,t){return t>e?-1:e>t?1:0}function eu(e,t,n,i,o){return{severity:e,code:t,message:n,path:i,ids:o?[...o]:void 0}}function tu(e){const t=new Set,n=new Set;for(const i of e)t.has(i)&&n.add(i),t.add(i);return[...n].sort(Jd)}function nu(e){const t="number"==typeof e?e:Number(e);return Number.isFinite(t)?t:null}function iu(e,t,n,i,o,r){if(!n)return i;try{return("function"==typeof n?n(e,t):e[n])??i}catch(e){return o.push(eu("error","accessor-error",`Accessor threw: ${e instanceof Error?e.message:e+""}.`,r)),i}}function ou(e,t,n){if(!e||"object"!=typeof e||Array.isArray(e))return null!=e&&t.push(eu("error","invalid-metrics","Metrics must be a numeric object.",n)),{};const i={};for(const[o,r]of Object.entries(e)){const e=nu(r);null!=e?i[o]=e:t.push(eu("error","invalid-metric",`Metric "${o}" must be finite.`,`${n}.${o}`))}return i}function ru(e){const t=[],n={},i=[];let o=0;const r={};e.data.forEach((s,a)=>{const c=(s.id??"component-"+a)+"",l=((iu(s,a,e.idAccessor,c,t,`data.${a}.id`)??c)+"").trim();if(!l)return void t.push(eu("error","invalid-component-id","Component ids may not be empty.",`data.${a}.id`));i.push(l);const d=nu(iu(s,a,e.amountAccessor,1,t,`data.${a}.amount`)),u=null==d||0>d?0:d;(null==d||0>d)&&t.push(eu("error","invalid-component-amount","Component amount must be finite and non-negative.",`data.${a}.amount`,[l]));const h=ou(iu(s,a,e.metricsAccessor,{},t,`data.${a}.metrics`),t,`data.${a}.metrics`),p=iu(s,a,e.initialStateAccessor,"active",t,`data.${a}.status`),m=Qd.has(p)?p:"active";Qd.has(p)||t.push(eu("error","invalid-component-status",`Unknown component status "${p+""}".`,`data.${a}.status`,[l]));const f=iu(s,a,e.labelAccessor,(s.label??s.name??l)+"",t,`data.${a}.label`)+"",y=iu(s,a,e.categoryAccessor,"component",t,`data.${a}.category`)+"";n[l]||(n[l]={id:l,label:f,category:y,datum:s,status:m,initialAmount:u,amount:u,initialMetrics:{...h},metrics:{...h},productIds:[],history:[]},o+=u,function(e,t){for(const[n,i]of Object.entries(t))e[n]=Number(e[n]??0)+i}(r,h))});const s=tu(i);s.length&&t.push(eu("error","duplicate-component-id",`Component ids must be unique: ${s.join(", ")}.`,"data",s));const a=ou(e.metrics??{},t,"metrics");return{state:{elapsed:0,phaseElapsed:0,phaseId:e.phases[0]?.id??"",phaseIndex:e.phases.length?0:-1,playing:!1,complete:0===e.phases.length,outcome:"in_process",eventsApplied:[],components:n,products:{},relations:{},input:{amount:o,metrics:r},metrics:a,loss:{amount:0,metrics:{}},history:[]},diagnostics:t}}function su(e){return e.map((e,t)=>({outlet:e,index:t})).sort((e,t)=>(e.outlet.order??e.index)-(t.outlet.order??t.index)||e.index-t.index).map(({outlet:e})=>({...e}))}function au(e=Ud,t=Kd){const n=Math.max(1,nu(e[0])??Xd),i=Math.max(1,nu(e[1])??Vd),o=360>n||260>i,r=o?Math.max(4,.035*Math.min(n,i)):20,s=o?Math.max(10,.075*i):34,a={x:r,y:r,width:Math.max(1,n-2*r),height:s},c=o?Math.max(16,.14*i):Math.min(78,.16*i),l={x:r,y:i-r-c,width:Math.max(1,n-2*r),height:c},d=o?Math.max(12,.08*n):Math.min(150,.17*n),u=a.y+a.height+(o?12:38),h=l.y-(o?10:34),p={x:d,y:u,width:Math.max(24,n-2*d),height:Math.max(24,h-u)},m=Math.max(18,Math.min(.32*p.width,o?84:180)),f={x:p.x+(p.width-m)/2,y:p.y-(o?10:24),width:m,height:o?12:28},y=su(t),g={left:y.filter(e=>"left"===(e.side??"bottom")),right:y.filter(e=>"right"===e.side),bottom:y.filter(e=>"bottom"===(e.side??"bottom"))},b=[],x=(e,t)=>{const i=Math.max(8,d-1.5*r),s=p.height/Math.max(1,t.length);t.forEach((t,a)=>{b.push({...t,side:e,x:"left"===e?r:n-r-i,y:p.y+a*s,width:i,height:Math.max(8,s-(o?2:8))})})};x("left",g.left),x("right",g.right);const v=p.width/Math.max(1,g.bottom.length);return g.bottom.forEach((e,t)=>{b.push({...e,side:"bottom",x:p.x+t*v,y:p.y+p.height+(o?2:7),width:Math.max(8,v-(o?2:8)),height:Math.max(8,l.y-p.y-p.height-(o?4:12))})}),b.sort((e,t)=>y.findIndex(t=>t.id===e.id)-y.findIndex(e=>e.id===t.id)),{width:n,height:i,phaseRail:a,chamber:p,mouth:f,projection:l,outlets:b}}function cu(e){const{id:t,orientation:n,fixed:i,start:o,end:r,openings:s,thickness:a,friction:c,restitution:l}=e,d=function(e,t,n){const i=n.map(([n,i])=>[Math.max(e,Math.min(n,i)),Math.min(t,Math.max(n,i))]).filter(([e,t])=>t>e+Zd).sort((e,t)=>e[0]-t[0]||e[1]-t[1]),o=[];let r=e;for(const[e,t]of i)e>r+Zd&&o.push([r,e]),r=Math.max(r,t);return t>r+Zd&&o.push([r,t]),o}(o,r,s);return d.map(([e,o],r)=>({id:1===d.length?t:`${t}:${r}`,friction:c,restitution:l,shape:"horizontal"===n?{type:"segment",x1:e,y1:i,x2:o,y2:i,thickness:a}:{type:"segment",x1:i,y1:e,x2:i,y2:o,thickness:a}}))}function lu(e){const{chamber:t,mouth:n}=e,i=Math.max(2,Math.min(10,.018*Math.min(e.width,e.height))),o=Math.max(t.x,n.x),r=Math.min(t.x+t.width,n.x+n.width),s={left:e.outlets.filter(e=>"left"===e.side),right:e.outlets.filter(e=>"right"===e.side),bottom:e.outlets.filter(e=>"bottom"===e.side)},a=[{id:"crucible:wall:top-left",friction:.42,restitution:.1,shape:{type:"segment",x1:t.x,y1:t.y,x2:o,y2:t.y,thickness:i}},{id:"crucible:wall:top-right",friction:.42,restitution:.1,shape:{type:"segment",x1:r,y1:t.y,x2:t.x+t.width,y2:t.y,thickness:i}}];a.push(...cu({id:"crucible:wall:left",orientation:"vertical",fixed:t.x,start:t.y,end:t.y+t.height,openings:s.left.map(e=>[e.y,e.y+e.height]),thickness:i,friction:.46,restitution:.12}),...cu({id:"crucible:wall:right",orientation:"vertical",fixed:t.x+t.width,start:t.y,end:t.y+t.height,openings:s.right.map(e=>[e.y,e.y+e.height]),thickness:i,friction:.46,restitution:.12}),...cu({id:"crucible:wall:bottom",orientation:"horizontal",fixed:t.y+t.height,start:t.x,end:t.x+t.width,openings:s.bottom.map(e=>[e.x,e.x+e.width]),thickness:i,friction:.5,restitution:.08}));for(const t of e.outlets)a.push({id:"crucible:outlet:"+encodeURIComponent(t.id),sensor:!0,shape:{type:"aabb",x:t.x+t.width/2,y:t.y+t.height/2,width:t.width,height:t.height}});return a}function du(e){let t=2166136261;for(let n=0;e.length>n;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return t>>>0}function uu(e){return"number"==typeof e&&Number.isFinite(e)?e>>>0:"string"==typeof e?du(e):1}function hu(e,t){return{fixedDt:1/120,maxSubsteps:8,settleStepLimit:7200,colliders:t.map(e=>({...e,shape:{...e.shape}})),observation:{chartType:"crucible"},kernel:{seed:uu(e),gravity:{x:0,y:0},cellSize:42,collisionIterations:6,velocityDamping:.992,restitution:.12,friction:.42,sleepSpeed:4,sleepAfter:.5,maxVelocity:620}}}function pu(e){return"crucible:component:"+encodeURIComponent(e)}function mu(e){return"crucible:product:"+encodeURIComponent(e)}function fu(e,t){return`crucible:bond:${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function yu(e,t,n,i){if(void 0!==n&&Number.isFinite(n)&&n>0)return n;const o=Math.min(...t,e),r=Math.max(...t,e);return r-o>Zd?i[0]+(i[1]-i[0])*Math.sqrt(Math.max(0,e-o)/(r-o)):(i[0]+i[1])/2}function gu(e,t){const n=Math.max(.25,Math.min(1,t.width/900,t.height/520)),i=e?.[0]??7*n,o=e?.[1]??18*n,r=Math.max(1,Math.min(i,o));return[r,Math.max(r,Math.max(i,o))]}function bu(e,t,n={}){const i=Object.values(e.components).sort((e,t)=>Jd(e.id,t.id)),o=i.map(e=>e.amount),r=gu(n.radiusRange,t),s=function(e){let t=e>>>0;return()=>{t+=1831565813;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(uu(n.seed)),a=t.mouth.x+t.mouth.width/2,c=t.chamber.y+Math.max(18,.18*t.chamber.height),l=Math.max(4,.28*t.chamber.width),d=Math.max(4,.12*t.chamber.height);return i.map((e,t)=>{const u=t/Math.max(1,i.length)*Math.PI*2+.18*(s()-.5),h=yu(e.amount,o,n.bodyRadius,r),p={__crucible:!0,kind:"component",semanticId:e.id,sourceDatum:e.datum};return{id:pu(e.id),x:a+Math.cos(u)*l*(.45+.45*s()),y:c+Math.sin(u)*d*(.45+.45*s()),vx:24*(s()-.5),vy:18*(s()-.5),mass:Math.max(.25,h*h*.015),restitution:.12,friction:.4,shape:{type:"circle",radius:h},datum:p}})}function xu(e,t){if(!e)return[];const n=Math.min(e,Math.max(1,Math.ceil(Math.sqrt(e*Math.max(.5,t.width/Math.max(1,t.height)))))),i=Math.max(1,Math.ceil(e/n));return Array.from({length:e},(e,o)=>({x:t.x+t.width/n*(o%n+.5),y:t.y+(Math.floor(o/n)+.5)*(t.height/i)}))}function vu(e){return e.outletId?e.outletId:"failed"===e.status?"failed":"recovered"===e.status?"recovered":"retained"===e.status?"retained":"ejected"===e.status?"residue":void 0}function wu(e,t){return e.outlets.find(e=>e.id===t)||{x:e.chamber.x+.18*e.chamber.width,y:e.chamber.y+.2*e.chamber.height,width:.64*e.chamber.width,height:.6*e.chamber.height}}function ku(e,t,n={}){const i=Object.values(e.products).sort((e,t)=>Jd(e.id,t.id)),o=Object.values(e.components).sort((e,t)=>Jd(e.id,t.id)),r=[...o.map(e=>e.amount),...i.map(e=>e.amount)],s=gu(n.radiusRange,t),a=function(e,t){const n=new Map;for(const t of e){const e=t.outletId??"__chamber__",i=n.get(e)??[];i.push(t),n.set(e,i)}const i=new Map;for(const[e,o]of n){o.sort((e,t)=>(e.order??Number.MAX_SAFE_INTEGER)-(t.order??Number.MAX_SAFE_INTEGER)||Jd(e.id,t.id));const n=xu(o.length,wu(t,"__chamber__"===e?void 0:e));o.forEach((e,t)=>i.set(e.id,n[t]))}return i}(i,t),c=i.map(e=>{const i=a.get(e.id)??{x:t.chamber.x+t.chamber.width/2,y:t.chamber.y+t.chamber.height/2},o=1.28*yu(e.amount,r,n.bodyRadius,s),c={__crucible:!0,kind:"product",semanticId:e.id,product:e};return{id:mu(e.id),x:i.x,y:i.y,mass:Math.max(.25,o*o*.018),bodyCollisions:!1,shape:{type:"circle",radius:o},datum:c}}),l=new Map;for(const e of o.filter(e=>!e.productIds.length)){const t=vu(e)??"__chamber__",n=l.get(t)??[];n.push(e),l.set(t,n)}const d=new Map;for(const[e,n]of l){const i=xu(n.length,wu(t,"__chamber__"===e?void 0:e));n.forEach((e,t)=>d.set(e.id,i[t]))}return[...o.map(e=>{let i=d.get(e.id);if(e.productIds.length){const n=e.productIds.map(e=>a.get(e)).filter(e=>!!e);if(n.length){i={x:n.reduce((e,t)=>e+t.x,0)/n.length,y:n.reduce((e,t)=>e+t.y,0)/n.length};const o=du(e.id)/4294967295*Math.PI*2,r=Math.min(20,Math.max(4,.012*t.width));i={x:i.x+Math.cos(o)*r,y:i.y+Math.sin(o)*r}}}i??(i={x:t.chamber.x+t.chamber.width/2,y:t.chamber.y+t.chamber.height/2});const o=yu(e.amount,r,n.bodyRadius,s),c={__crucible:!0,kind:"component",semanticId:e.id,sourceDatum:e.datum};return{id:pu(e.id),x:i.x,y:i.y,mass:Math.max(.25,o*o*.015),shape:{type:"circle",radius:o},datum:c}}),...c]}var Mu=ku;function Iu(e){return Array.isArray(e)?e.map(Iu):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e&&"function"!=typeof e).sort(([e],[t])=>Jd(e,t)).map(([e,t])=>[e,Iu(t)])):e}function Su(e){return JSON.stringify(Iu(e))}function ju(e,t){const n=nu(t)??0,i=Math.max(0,Math.min(e.duration,n));if(!e.phases.length)return{elapsed:i,phaseId:"",phaseIndex:-1,phaseElapsed:0,complete:!0};const o=i>=e.duration-Zd,r=o?e.phases[e.phases.length-1]:e.phases.find(e=>i>=e.start&&e.end>i)??e.phases[0];return{elapsed:i,phaseId:r.id,phaseIndex:r.index,phaseElapsed:o?r.duration:Math.max(0,i-r.start),complete:o}}function Au(e,t){if(void 0===t)return e.duration;if("number"==typeof t)return Math.max(0,Math.min(e.duration,nu(t)??0));const n=e.phases.find(e=>e.id===t.phaseId);if(!n)return e.duration;const i=Math.max(0,Math.min(1,nu(t.progress??0)??0));return n.start+n.duration*i}function Cu(e,t=e.duration){const n=ju(e,t);let i=Cd(e.initialState);const o=[],r=[],s=[];for(const t of e.events){if(t.authoredAt>n.elapsed+Zd)break;const a=Ld(i,t,{phaseId:t.phaseId,authoredAt:t.authoredAt,appliedAt:t.authoredAt,products:e.products,outlets:e.outlets});o.push(...a.diagnostics),r.push(...a.materializations),s.push(...a.observations),a.applied&&(i=a.state)}return i.elapsed=n.elapsed,i.phaseId=n.phaseId,i.phaseIndex=n.phaseIndex,i.phaseElapsed=n.phaseElapsed,i.complete=n.complete,n.complete&&"in_process"===i.outcome&&(i.outcome="complete"),i.playing=!1,{state:i,diagnostics:o,materializations:r,observations:s}}function Ru(e){const t=function(e){const t=[];e.length||t.push(eu("error","empty-phase-program","CrucibleChart requires at least one phase.","phases"));const n=tu(e.map(e=>e.id));n.length&&t.push(eu("error","duplicate-phase-id",`Phase ids must be unique: ${n.join(", ")}.`,"phases",n));let i=0;return{phases:e.map((e,n)=>{const o=nu(e.duration),r=null!=o&&o>0?o:0;e.id.trim()||t.push(eu("error","invalid-phase-id","Phase ids may not be empty.",`phases.${n}.id`)),null!=o&&o>0||t.push(eu("error","invalid-phase-duration","Phase duration must be finite and greater than zero.",`phases.${n}.duration`,[e.id])),void 0===e.intensity||Number.isFinite(e.intensity)||t.push(eu("error","invalid-phase-intensity","Phase intensity must be finite.",`phases.${n}.intensity`,[e.id]));const s={...e,duration:r,intensity:void 0===e.intensity?.5:Number.isFinite(e.intensity)?Math.max(0,Math.min(1,e.intensity)):.5,motion:e.motion??"hold",index:n,start:i,end:i+r};return i=s.end,s}),diagnostics:t}}(e.phases),n=t.phases.at(-1)?.end??0,i=su(e.outlets??Kd),o=(e.products??[]).map(e=>({...e,metrics:e.metrics?{...e.metrics}:void 0})),r=function(e,t,n){const i=[],o=tu(e.map(e=>e.id));o.length&&i.push(eu("error","duplicate-event-id",`Event ids must be unique: ${o.join(", ")}.`,"events",o));const r=[];return e.forEach((e,o)=>{let s,a,c;if(e.id.trim()||i.push(eu("error","invalid-event-id","Event ids may not be empty.",`events.${o}.id`)),"time"in e.at&&void 0!==e.at.time){const r=nu(e.at.time);if(null==r||0>r||r>n+Zd)return void i.push(eu("error","event-time-out-of-range",`Event time must fall between 0 and ${n}.`,`events.${o}.at.time`,[e.id]));s=Math.max(0,Math.min(n,r));const l=function(e,t,n){const i=e.find(e=>Zd>=Math.abs(e.start-n));if(i)return{phase:i,boundaryRank:1};const o=e.find(e=>n>=e.start&&e.end>n);return o?{phase:o,boundaryRank:0}:Zd>=Math.abs(n-t)&&e.length?{phase:e[e.length-1],boundaryRank:0}:{phase:void 0,boundaryRank:1}}(t,n,s);a=l.phase,c=l.boundaryRank}else{if(a=t.find(t=>t.id===e.at.phaseId),!a)return void i.push(eu("error","unknown-event-phase",`Event references unknown phase "${e.at.phaseId}".`,`events.${o}.at.phaseId`,[e.id,e.at.phaseId]));const n=e.at.progress??0;if(!Number.isFinite(n)||0>n||n>1)return void i.push(eu("error","event-progress-out-of-range","Event phase progress must be between 0 and 1.",`events.${o}.at.progress`,[e.id]));s=a.start+a.duration*n,c=0===n?1:0}a?r.push({...e,index:o,authoredAt:s,phaseId:a.id,phaseIndex:a.index,boundaryRank:c}):i.push(eu("error","event-without-phase","Event could not be assigned to a phase.",`events.${o}.at`,[e.id]))}),r.sort((e,t)=>e.authoredAt-t.authoredAt||e.boundaryRank-t.boundaryRank||e.index-t.index),{events:r,diagnostics:i}}(e.events??[],t.phases,n),s=ru(e),a=au(e.size??Ud,i),c=lu(a),l=function(e,t){const n=[],i=new Set(t.map(e=>e.id)),o=tu(t.map(e=>e.id)),r=tu(e.map(e=>e.id));return o.length&&n.push(eu("error","duplicate-outlet-id",`Outlet ids must be unique: ${o.join(", ")}.`,"outlets",o)),r.length&&n.push(eu("error","duplicate-product-id",`Product ids must be unique: ${r.join(", ")}.`,"products",r)),t.forEach((e,t)=>{e.id.trim()||n.push(eu("error","invalid-outlet-id","Outlet ids may not be empty.",`outlets.${t}.id`)),void 0===e.order||Number.isFinite(e.order)||n.push(eu("error","invalid-outlet-order","Outlet order must be finite.",`outlets.${t}.order`,[e.id]))}),e.forEach((e,t)=>{e.id.trim()||n.push(eu("error","invalid-product-id","Product ids may not be empty.",`products.${t}.id`)),void 0===e.amount||Number.isFinite(e.amount)&&e.amount>=0||n.push(eu("error","invalid-product-amount","Declared product amount must be finite and non-negative.",`products.${t}.amount`,[e.id])),void 0===e.outletId||i.has(e.outletId)||n.push(eu("error","unknown-outlet",`Product "${e.id}" references unknown outlet "${e.outletId}".`,`products.${t}.outletId`,[e.outletId])),ou(e.metrics??{},n,`products.${t}.metrics`)}),n}(o,i),d=Su({seed:e.seed??1,components:Object.values(s.state.components).sort((e,t)=>Jd(e.id,t.id)).map(e=>({id:e.id,label:e.label,category:e.category,amount:e.amount,metrics:e.metrics,status:e.status})),phases:t.phases.map(({id:e,duration:t,label:n,description:i,intensity:o,motion:r,color:s,metrics:a})=>({id:e,duration:t,label:n,description:i,intensity:o,motion:r,color:s,metrics:a})),products:o,outlets:i,events:r.events.map(({id:e,label:t,description:n,summary:i,authoredAt:o,phaseId:r,boundaryRank:s,effects:a})=>({id:e,label:t,description:n,summary:i,authoredAt:o,phaseId:r,boundaryRank:s,effects:a}))}),u=bu(s.state,a,{seed:e.seed,bodyRadius:e.bodyRadius,radiusRange:e.radiusRange}),h=[...t.diagnostics,...r.diagnostics,...s.diagnostics,...l],p={phases:t.phases,events:r.events,products:o,outlets:i,duration:n,initialState:s.state,terminalState:s.state,layout:a,colliders:c,config:hu(e.seed,c),initialSpawns:u,terminalSpawns:[],semanticKey:d,diagnostics:h},m=Cu(p),f=Object.values(m.state.products).filter(e=>"forming"===e.status).map(e=>e.id),y=f.length?[eu("warning","forming-product-at-end",`Products remain forming at the end of the tape: ${f.join(", ")}.`,"events",f)]:[];return p.terminalState=m.state,p.terminalSpawns=Mu(m.state,a,{seed:e.seed,bodyRadius:e.bodyRadius,radiusRange:e.radiusRange}),p.diagnostics=[...h,...m.diagnostics,...y],p}function $u(e,t){return e.playing=t&&!e.complete,e}function Pu(e,t,n=!1){const i=Cu(e,t);return{...i,state:$u(i.state,n)}}function Du(e,t,n,i=t.playing){const o=Pu(e,n,i),r=new Set(t.eventsApplied);return{...o,observations:o.observations.filter(e=>!r.has(e.eventId)),materializations:o.materializations.filter(e=>!r.has(e.eventId))}}function Bu(e,t,n={}){return ku(t,e.layout,n)}function Tu(e,t){return function(e){let t=2166136261;for(let n=0;e.length>n;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return t>>>0}(`${t}:${e}`)/4294967295}function Eu(e,t){return e.phases[t.phaseIndex]??e.phases.find(e=>e.id===t.phaseId)}function Nu(e,t,n={}){return new Map(Bu(e,t,n).flatMap(e=>{const t=e.datum;return t?.__crucible?[[`${t.kind}:${t.semanticId}`,{x:e.x,y:e.y}]]:[]}))}function Ou(e,t){const n=Object.values(e.terminalState.products).map(e=>e.id).sort(),i=Math.max(0,n.indexOf(t))/Math.max(1,n.length)*Math.PI*2-Math.PI/2,o=Math.min(58,.19*e.layout.chamber.width),r=Math.min(38,.16*e.layout.chamber.height);return{x:e.layout.chamber.x+e.layout.chamber.width/2+Math.cos(i)*o,y:e.layout.chamber.y+.52*e.layout.chamber.height+Math.sin(i)*r}}function Wu(e,t,n){if("string"!=typeof t)return n;if("function"!=typeof getComputedStyle||!e.canvas)return t||n;const i=t.startsWith("var(")?t.match(/var\((--[^,\s)]+)/)?.[1]:t.startsWith("--")?t:null;return i?getComputedStyle(e.canvas).getPropertyValue(i).trim()||n:t||n}function qu(e){return Number.isFinite(e)?1e3>Math.abs(e)?Number.isInteger(e)?e+"":e.toFixed(2).replace(/\.00$/,"").replace(/(\.\d)0$/,"$1"):e.toLocaleString():"0"}function Fu(e){const t=e.productIds.length?` Contributes to ${e.productIds.join(", ")}.`:e.outletId?` Routed to ${e.outletId}.`:"",n=e.reason?` ${e.reason}.`:"";return`${qu(e.amount)} amount; ${e.status}.${t}${n}`}function zu(e){const t=e.outletId?` Routed to ${e.outletId}.`:"";return`${e.status} product with ${e.sourceIds.length} source${1===e.sourceIds.length?"":"s"} and ${qu(e.amount)} amount.${t}`}function Lu(e,t,n){const i=t.datum;if(!i?.__crucible)return;const o="circle"===t.shape.type?t.shape.radius:8,r=Wu(e,n.fill,"product"===i.kind?"#b8792d":"#356b63"),s=Wu(e,n.stroke,"#26323a");if(e.save(),e.translate(t.x,t.y),e.globalAlpha="number"==typeof n.opacity?n.opacity:.96,e.fillStyle=r,e.strokeStyle=s,e.lineWidth="number"==typeof n.strokeWidth?n.strokeWidth:1.25,"product"===i.kind){e.shadowColor=r,e.shadowBlur=10,e.beginPath();for(let t=0;6>t;t+=1){const n=-Math.PI/2+t/6*Math.PI*2,i=Math.cos(n)*o,r=Math.sin(n)*o;0===t?e.moveTo(i,r):e.lineTo(i,r)}e.closePath(),e.fill(),e.shadowBlur=0,e.stroke(),e.beginPath(),e.arc(0,0,Math.max(2,.36*o),0,2*Math.PI),e.strokeStyle=Wu(e,"var(--semiotic-background, #fffaf0)","#fffaf0"),e.globalAlpha*=.72,e.stroke()}else e.beginPath(),e.arc(0,0,o,0,2*Math.PI),e.fill(),e.stroke(),e.beginPath(),e.arc(.25*-o,.28*-o,Math.max(1,.18*o),0,2*Math.PI),e.fillStyle="rgba(255,255,255,0.34)",e.fill();e.restore()}c(require("react")),require("react/jsx-runtime");var Yu=require("react/jsx-runtime"),Hu="var(--semiotic-text, #26323a)",_u="var(--semiotic-text-secondary, #6c7377)",Gu="var(--semiotic-accent, #b8792d)",Xu="var(--semiotic-negative, #9f3d35)",Vu="var(--semiotic-positive, #356b63)";function Uu(e){const{x:t,y:n,width:i,height:o}=e.chamber,r=Math.min(.14*i,48),s=n+o;return[`M ${t} ${n}`,`L ${t+r} ${s-.16*o}`,`Q ${t+i/2} ${s+.1*o} ${t+i-r} ${s-.16*o}`,`L ${t+i} ${n}`].join(" ")}function Ku({layout:e,phases:t,state:n,compact:i=!1}){const o=Math.max(1,t.reduce((e,t)=>e+Math.max(0,t.duration),0));return(0,Yu.jsxs)("svg",{"aria-hidden":"true","data-testid":"crucible-chrome",viewBox:`0 0 ${e.width} ${e.height}`,style:{inset:0,pointerEvents:"none",position:"absolute"},children:[(0,Yu.jsxs)("defs",{children:[(0,Yu.jsxs)("linearGradient",{id:"semiotic-crucible-heat",x1:"0",x2:"0",y1:"0",y2:"1",children:[(0,Yu.jsx)("stop",{offset:"0",stopColor:Gu,stopOpacity:"0.03"}),(0,Yu.jsx)("stop",{offset:"0.66",stopColor:Gu,stopOpacity:"0.1"}),(0,Yu.jsx)("stop",{offset:"1",stopColor:Xu,stopOpacity:"0.18"})]}),(0,Yu.jsx)("pattern",{id:"semiotic-crucible-hatch",width:"7",height:"7",patternUnits:"userSpaceOnUse",patternTransform:"rotate(20)",children:(0,Yu.jsx)("line",{x1:"0",x2:"0",y1:"0",y2:"7",stroke:Hu,strokeOpacity:"0.08",strokeWidth:"1"})})]}),(0,Yu.jsx)("rect",{x:e.chamber.x,y:e.chamber.y,width:e.chamber.width,height:e.chamber.height,rx:2,fill:"url(#semiotic-crucible-heat)",stroke:Hu,strokeOpacity:"0.52",strokeWidth:i?1:2.2}),(0,Yu.jsx)("path",{d:Uu(e),fill:"url(#semiotic-crucible-hatch)",stroke:"none"}),(0,Yu.jsx)("line",{x1:e.mouth.x,x2:e.mouth.x+e.mouth.width,y1:e.mouth.y,y2:e.mouth.y,stroke:Hu,strokeLinecap:"round",strokeOpacity:"0.72",strokeWidth:i?2:5}),i?null:(0,Yu.jsx)("g",{"data-testid":"crucible-phase-rail",children:t.map((i,r)=>{const s=t.slice(0,r).reduce((e,t)=>e+Math.max(0,t.duration),0),a=e.phaseRail.x+s/o*e.phaseRail.width,c=Math.max(0,i.duration)/o*e.phaseRail.width,l=i.id===n.phaseId,d=n.phaseIndex>r||n.complete;return(0,Yu.jsxs)("g",{children:[(0,Yu.jsx)("rect",{x:a,y:e.phaseRail.y,width:Math.max(1,c-2),height:e.phaseRail.height,rx:2,fill:l?i.color??Gu:d?Vu:Hu,fillOpacity:l?.68:d?.28:.09}),46>c?null:(0,Yu.jsx)("text",{x:a+c/2,y:e.phaseRail.y+e.phaseRail.height+13,fill:l?Hu:_u,fontFamily:"system-ui, sans-serif",fontSize:8.5,fontWeight:l?800:650,letterSpacing:"0.04em",textAnchor:"middle",children:(i.label??i.id).toUpperCase()})]},i.id)})}),e.outlets.map(e=>(0,Yu.jsxs)("g",{children:[(0,Yu.jsx)("rect",{x:e.x,y:e.y,width:e.width,height:e.height,rx:3,fill:e.color??("left"===e.side?Xu:Vu),fillOpacity:"0.1",stroke:e.color??("left"===e.side?Xu:Vu),strokeDasharray:"3 3",strokeOpacity:"0.62"}),i?null:(0,Yu.jsx)("text",{x:e.x+e.width/2,y:e.y+Math.min(13,e.height/2+3),fill:_u,fontFamily:"system-ui, sans-serif",fontSize:8,fontWeight:750,letterSpacing:"0.05em",textAnchor:"middle",children:(e.label??e.id).toUpperCase()})]},e.id))]})}function Qu(e,t){return"count"===t?e.count:"amount"===t?e.amount:Number(e.metrics[t]??0)}function Zu({rows:e,layout:t,projection:n,amountLabel:i}){if(!e.length)return null;const o=n.measure??"count",r=e.map(e=>Math.max(0,Qu(e,o))),s=Math.max(1,...r),a=t.projection.width/Math.max(1,e.length),c=t.projection.height>48?21:4,l=Math.max(5,t.projection.height-c-5);return(0,Yu.jsx)("svg",{"aria-hidden":"true","data-testid":"crucible-projection-overlay",viewBox:`0 0 ${t.width} ${t.height}`,style:{inset:0,pointerEvents:"none",position:"absolute"},children:e.map((e,n)=>{const d=r[n],u=Math.max(d>0?2:0,d/s*l),h=t.projection.x+n*a+.18*a;return(0,Yu.jsxs)("g",{children:[(0,Yu.jsx)("rect",{x:h,y:t.projection.y+l-u,width:Math.max(3,.64*a),height:u,rx:2,fill:"failed"===e.status||"ejected"===e.status?Xu:"complete"===e.status?Gu:Vu,fillOpacity:"0.68"}),c>4&&a>=34?(0,Yu.jsxs)(Yu.Fragment,{children:[(0,Yu.jsx)("text",{x:h+.32*a,y:t.projection.y+l+10,fill:_u,fontFamily:"system-ui, sans-serif",fontSize:7.5,fontWeight:700,textAnchor:"middle",children:e.label.length>13?e.label.slice(0,12)+"…":e.label}),(0,Yu.jsxs)("text",{x:h+.32*a,y:t.projection.y+l+19,fill:Hu,fontFamily:"system-ui, sans-serif",fontSize:8,fontWeight:850,textAnchor:"middle",children:[qu(d),"amount"===o&&i?" "+i:""]})]}):null]},e.key)})})}function Ju({controls:e,duration:t,elapsed:n,phaseLabel:i,playing:o,complete:r,playbackRate:s,disabled:a,onPlayPause:c,onReset:l,onStepPhase:d,onPlaybackRateChange:u}){const h=t>0?Math.min(1,Math.max(0,n/t)):1;return(0,Yu.jsxs)("div",{"aria-label":"Crucible replay controls",className:"semiotic-crucible-controls",style:{alignItems:"center",color:Hu,display:"flex",flexWrap:"wrap",fontFamily:"system-ui, sans-serif",fontSize:11,gap:6,marginBottom:7},children:[e.playPause?(0,Yu.jsx)("button",{type:"button",disabled:a,onClick:c,"aria-pressed":o,children:o?"Pause":r?"Replay":"Play"}):null,e.stepPhase?(0,Yu.jsx)("button",{type:"button",disabled:a,onClick:d,children:"Next phase"}):null,e.reset?(0,Yu.jsx)("button",{type:"button",disabled:a,onClick:l,children:"Reset"}):null,e.timeline?(0,Yu.jsxs)("div",{style:{alignItems:"center",display:"flex",flex:"1 1 150px",gap:7,minWidth:130},children:[(0,Yu.jsx)("span",{style:{fontWeight:750,whiteSpace:"nowrap"},children:i}),(0,Yu.jsx)("span",{"aria-hidden":"true",style:{background:"rgba(38,50,58,0.14)",borderRadius:2,flex:1,height:4,overflow:"hidden"},children:(0,Yu.jsx)("span",{style:{background:Gu,display:"block",height:"100%",transform:`scaleX(${h})`,transformOrigin:"left center"}})}),(0,Yu.jsxs)("span",{style:{color:_u,fontVariantNumeric:"tabular-nums"},children:[n.toFixed(1),"s"]})]}):null,e.speed?(0,Yu.jsxs)("label",{style:{alignItems:"center",display:"flex",gap:4},children:["Speed",(0,Yu.jsxs)("select",{disabled:a,value:s,onChange:e=>u(Number(e.currentTarget.value)),children:[(0,Yu.jsx)("option",{value:.25,children:"¼×"}),(0,Yu.jsx)("option",{value:.5,children:"½×"}),(0,Yu.jsx)("option",{value:1,children:"1×"}),(0,Yu.jsx)("option",{value:2,children:"2×"})]})]}):null]})}function eh(e,t,n,i){const o="function"==typeof i?i(t,n):i,r=t.datum;return{fill:e,stroke:"product"===r?.kind?"var(--semiotic-background, #fffaf0)":Hu,strokeWidth:"product"===r?.kind?1.8:1.1,opacity:.96,...o}}function th(e,t,n){return{id:e.id??t,at:{...e.at},effects:n,...void 0===e.label?null:{label:e.label},...void 0===e.description?null:{description:e.description},...void 0===e.summary?null:{summary:e.summary}}}function nh(e){if(e)return{...e,...e.metrics?{metrics:{...e.metrics}}:null}}function ih(e){const{productId:t,form:n,contributions:i=[],complete:o}=e,r=e.idPrefix??t,s=nh(n.loss),a=[th(n,r+"-form",[{type:"combine",sourceIds:[...n.sourceIds],productId:t,...n.basisRelationIds?{basisRelationIds:[...n.basisRelationIds]}:null,...s?{loss:s}:null,complete:!1}])];return i.forEach((e,n)=>{const i=nh(e.loss);a.push(th(e,`${r}-contribute-${n+1}`,[{type:"contribute",sourceIds:[...e.sourceIds],productId:t,...e.basisRelationIds?{basisRelationIds:[...e.basisRelationIds]}:null,...i?{loss:i}:null}]))}),a.push(th(o,r+"-complete",[{type:"complete-product",productId:t,...void 0===o.outletId?null:{outletId:o.outletId},...void 0===o.reason?null:{reason:o.reason}}])),a}var oh=require("react/jsx-runtime"),rh=require("react"),sh=["#356b63","#a34b43","#c08b38","#3e5f83","#785b7c","#6e7740","#8f5c3a","#41717b"];function ah(e){let t=2166136261;for(let n=0;e.length>n;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return t>>>0}function ch(e){return"number"==typeof e&&Number.isFinite(e)?e:ah((e??"crucible")+"")}function lh(e){const t=Number(e);return Number.isFinite(t)&&t>0?Math.max(.05,Math.min(8,t)):1}function dh(e,t,n){return"category"===t?e.category:"status"===t?e.status:"outlet"===t?e.outletId??"in chamber":"product"===t?e.productIds[0]??"unalloyed":function(e,t,n){return(("function"==typeof e?e(t,n):t[e])??"unassigned")+""}(t,e.datum,n)}function uh(e){return sh[ah(e)%sh.length]}function hh(e,t){const n=Object.keys(e.components).length,i=Object.keys(e.products).length,o=Object.values(e.products).reduce((e,t)=>e+t.amount,0),r=t?" "+t:" amount",s=e.outcome?` Outcome: ${e.outcome}.`:"";return`${n} source component${1===n?"":"s"}; ${i} product${1===i?"":"s"}; ${o.toLocaleString()}${r} in products.${s}`}var ph=(0,Md.forwardRef)(function(e,t){const{amountAccessor:n,amountLabel:i,bodyRadius:o,categoryAccessor:r,colorBy:s="category",conservation:a,controls:c,data:l,emptyContent:d,events:u,frameProps:h={},idAccessor:p,initialStateAccessor:m,initialSpawnPacing:f,labelAccessor:y,loading:g,loadingContent:b,metrics:x,metricsAccessor:v,onClick:w,onConservation:k,onCrucibleObservation:M,onDiagnostic:I,onStateChange:S,outlets:j,paused:A,phases:R,playback:P="replay",playbackRate:D=1,products:B,projection:T,radiusRange:E,rerunMS:N,responsiveHeight:O,responsiveWidth:W,seed:q,showBonds:F=!0,snapshotAt:z}=e,L=(0,Md.useRef)(null),Y=(0,Md.useRef)(A);Y.current=A;const H=C(),_=V(),G=Ga(e,Ud),{chartMode:X,chartSize:U,showChrome:K,showProjection:Q,className:Z,title:J,description:ee,summary:te,accessibleTable:ne,enableHover:ie,margin:oe}=G,[re,se]=$(U,W,!1),ae=W?Math.max(1,se[0]):U[0],ce=U[1],le=(0,Md.useMemo)(()=>[ae,ce],[ce,ae]),de=(0,Md.useMemo)(()=>cc(l??[]),[l]),ue=(0,Md.useMemo)(()=>Ru({data:de,phases:R,products:B,outlets:j,events:u,idAccessor:p,labelAccessor:y,categoryAccessor:r,amountAccessor:n,metricsAccessor:v,initialStateAccessor:m,metrics:x,size:le,seed:q,bodyRadius:o,radiusRange:E}),[n,o,r,u,p,m,y,x,v,j,R,B,E,le,de,q]),he=Object.values(ue.initialState.components).map((e,t)=>dh(e,s,t)).join("\0"),pe=`${ue.semanticKey}:${le[0]}x${le[1]}:${(o??"auto")+""}:${E?.join(",")??"auto"}:${he}`,me=(0,Md.useRef)(ue),fe=(0,Md.useRef)(pe);fe.current!==pe&&(fe.current=pe,me.current=ue);const ye=me.current,ge="snapshot"===P||H||_,be=ge?function(e,t){return Au(e,t)}(ye,z):0,xe=!ge,ve=(0,Md.useMemo)(()=>Pu(ye,be,xe&&!A),[fe.current,be,xe]),[we,ke]=(0,Md.useState)(ve),Me=(0,Md.useRef)(we),[Ie,Se]=(0,Md.useState)(xe),je=(0,Md.useRef)(Ie),[Ae,Ce]=(0,Md.useState)(0),[Re,$e]=(0,Md.useState)(()=>lh(D)),Pe=(0,Md.useRef)(Nu(ye,ve.state,{seed:q,bodyRadius:o,radiusRange:E})),De=(0,Md.useRef)(""),Be=(0,Md.useRef)(S),Te=(0,Md.useRef)(M),Ee=(0,Md.useRef)(I),Ne=(0,Md.useRef)(k);Be.current=S,Te.current=M,Ee.current=I,Ne.current=k;const Oe=(0,Md.useRef)({seed:q,bodyRadius:o,radiusRange:E});Oe.current={seed:q,bodyRadius:o,radiusRange:E};const We=(0,Md.useCallback)((e,t=!1)=>{if(Me.current=e,Pe.current=Nu(me.current,e.state,Oe.current),ke(e),t)for(const t of e.observations)Te.current?.(t)},[]);(0,Md.useEffect)(()=>{$e(lh(D))},[D]),(0,Md.useEffect)(()=>{const e=!ge,t=Pu(ye,ge?be:0,e&&!Y.current);je.current=e,Se(e),We(t)},[We,ye,be,ge,pe]),(0,Md.useEffect)(()=>{const e=Me.current,t=je.current&&!A&&!e.state.complete;if(e.state.playing===t)return;const n={...e,state:Cd(e.state)};n.state.playing=t,We(n)},[We,A]),(0,Md.useEffect)(()=>{for(const e of ye.diagnostics)Ee.current?.(e)},[pe,ye.diagnostics]),(0,Md.useEffect)(()=>{if(Be.current?.(we.state),a){const e=!0===a?{}:a;Ne.current?.(_d(we.state,e))}},[a,we.state]);const qe=(0,Md.useCallback)(()=>{De.current="";const e=!ge,t=Pu(me.current,0,e&&!A);je.current=e,Se(e),We(t)},[We,A,ge]),Fe=(0,Md.useMemo)(()=>({...ye.config,...h.config,fixedDt:h.config?.fixedDt??ye.config.fixedDt,maxSubsteps:h.config?.maxSubsteps??ye.config.maxSubsteps,settleStepLimit:h.config?.settleStepLimit??ye.config.settleStepLimit,timeScale:Re,colliders:[...ye.config.colliders??[],...h.config?.colliders??[]],kernel:{...ye.config.kernel,...h.config?.kernel,gravity:h.config?.kernel?.gravity??ye.config.kernel?.gravity??{x:0,y:0}},observation:{...ye.config.observation,...h.config?.observation,chartType:"CrucibleChart"}}),[h.config,Re,ye.config]),ze=ge||!!A||!Ie&&!we.state.complete,Le=_a(Fe,N,ze,qe),Ye=(0,Md.useCallback)(()=>{if("number"!=typeof N||!Number.isFinite(N)||0>N)return;const e=`${pe}:${Ae}:${Le.rerunKey}`;De.current!==e&&(De.current=e,Le.config?.observation?.onSimulationStateChange?.("settled","running"))},[Le.config,Le.rerunKey,N,Ae,pe]),He=(0,Md.useCallback)(()=>{const e=Pu(me.current,0,!1);je.current=!1,Se(!1),We(e),Ce(e=>e+1)},[We]),_e=(0,Md.useCallback)(()=>{const e=me.current,t=Du(e,Me.current.state,e.duration,!1);je.current=!1,Se(!1),We(t,!0);const n=Bu(e,t.state,Oe.current),i=L.current;i&&(i.clear(),i.pushMany(n),i.step(0),i.settle()),Ye()},[We,Ye]),Ge=(0,Md.useCallback)(()=>{je.current=!1,Se(!1);const e={...Me.current,state:Cd(Me.current.state)};e.state.playing=!1,We(e)},[We]),Xe=(0,Md.useCallback)(()=>{if(De.current="",ge){const e=Pu(me.current,be,!1);return je.current=!1,Se(!1),We(e),void Ce(e=>e+1)}const e=Pu(me.current,0,!A);je.current=!0,Se(!0),We(e),Ce(e=>e+1)},[We,A,be,ge]),Ve=(0,Md.useCallback)(()=>{if(ge)return void Xe();if(Me.current.state.complete)return void Xe();je.current=!0,Se(!0);const e={...Me.current,state:Cd(Me.current.state)};e.state.playing=!A,We(e)},[We,A,Xe,ge]),Ue=(0,Md.useCallback)(()=>{const e=me.current,t=function(e,t){const n=e.phases.find(e=>e.end>t+1e-7);return n?.end??e.duration}(e,Me.current.state.elapsed),n=Du(e,Me.current.state,t,!1);je.current=!1,Se(!1),We(n,!0);const i=L.current;i&&(i.clear(),i.pushMany(Bu(e,n.state,Oe.current)),i.step(0))},[We]);(0,Md.useImperativeHandle)(t,()=>({play:Ve,pause:Ge,reset:He,replay:Xe,stepPhase:Ue,settle:_e,getCrucibleState:()=>Cd(Me.current.state)}),[Ge,Ve,Xe,He,_e,Ue]);const Ke=(0,Md.useCallback)((e,t)=>{if(h.onTick?.(e,t),ge||A||!je.current)return;const n=Me.current.state,i=Math.min(me.current.duration,e.elapsedSeconds);if(n.elapsed+.045>=i&&me.current.duration>i)return;const o=Du(me.current,n,i,me.current.duration>i),r=o.state.eventsApplied.length!==n.eventsApplied.length;if(r&&function(e,t){const n=new Set(e.readBodies().map(e=>e.id)),i=t.filter(e=>!n.has(e.id));i.length&&e.pushMany([...i]),i.map(e=>e.id)}(t,Bu(me.current,o.state,Oe.current)),o.state.complete){je.current=!1,Se(!1);const e=Bu(me.current,o.state,Oe.current);t.clear(),t.pushMany(e),t.step(0),t.settle()}We(o,r),o.state.complete&&Ye()},[We,h,A,Ye,ge]),Qe=(0,Md.useCallback)(({body:e})=>function(e){const t=function(e){const{body:t,plan:n,state:i,targets:o}=e,r=t.datum;if(!r?.__crucible)return null;let s=o.get(`${r.kind}:${r.semanticId}`);if(!s)return null;const a=Eu(n,i),c=Math.max(0,Math.min(2,Number(a?.intensity??.5))),l=a?.motion??"hold",d=i.elapsed;if("product"===r.kind){const e=i.products[r.semanticId];"forming"===e?.status&&(s=Ou(n,e.id))}else{const e=i.components[r.semanticId],t=e?.productIds.map(e=>i.products[e]).find(e=>"forming"===e?.status);if(t){const i=Ou(n,t.id),o=Tu(e.id,17)*Math.PI*2,r=Math.max(5,Math.min(18,.026*n.layout.width));s={x:i.x+Math.cos(o)*r,y:i.y+Math.sin(o)*r}}}const u=r.semanticId,h=Tu(u,23)*Math.PI*2;if(!i.complete&&!(n.layout.chamber.x>s.x||s.x>n.layout.chamber.x+n.layout.chamber.width||n.layout.chamber.y>s.y||s.y>n.layout.chamber.y+n.layout.chamber.height))if("mix"===l){const e=Math.min(34,.1*n.layout.chamber.width)*c,t=Math.min(24,.09*n.layout.chamber.height)*c;s={x:s.x+Math.cos(d*(1.4+Tu(u,29))+h)*e,y:s.y+Math.sin(d*(1.8+Tu(u,31))+h)*t}}else if("press"===l){const e=n.layout.chamber.x+n.layout.chamber.width/2,t=n.layout.chamber.y+.56*n.layout.chamber.height;s={x:e+(s.x-e)*Math.max(.3,1-.32*c),y:t+(s.y-t)*Math.max(.35,1-.26*c)}}else if("separate"===l){const e=.5>Tu(u,41)?-1:1;s={x:s.x+e*Math.min(28,.075*n.layout.chamber.width)*c,y:s.y}}else if("bind"===l){const e=n.layout.chamber.x+n.layout.chamber.width/2,t=n.layout.chamber.y+.5*n.layout.chamber.height;s={x:e+.72*(s.x-e),y:t+.72*(s.y-t)}}else"charge"===l?s={x:s.x,y:s.y+4*Math.sin(2*d+h)*c}:"quench"===l&&(s={x:s.x+2*Math.sin(h)*c,y:s.y});return s}(e);if(!t)return null;const{body:n,state:i}=e,o=t.x-n.x,r=t.y-n.y,s=Math.hypot(o,r),a=Math.hypot(n.vx,n.vy);if(i.complete&&.7>s&&.45>a)return null;const c=!i.complete&&"pour"===Eu(e.plan,i)?.motion,l=i.complete?.68:c?.72:.5,d=i.complete?.22:c?.18:.14,u=i.complete?42:c?72:56;return{x:Math.max(-u,Math.min(u,o*l-n.vx*d)),y:Math.max(-u,Math.min(u,r*l-n.vy*d))}}({body:e,plan:me.current,state:Me.current.state,targets:Pe.current}),[]),Ze=(0,Md.useMemo)(()=>new Map(Object.keys(ye.initialState.components).map((e,t)=>[e,t])),[ye.initialState.components]),Je=(0,Md.useCallback)(t=>{if(e.color)return e.color;const n=t.datum;if(!n?.__crucible)return"var(--semiotic-accent, #b8792d)";if("product"===n.kind){const e=Me.current.state.products[n.semanticId];return e?.color??uh(e?.id??n.semanticId)}const i=Me.current.state.components[n.semanticId];return i?uh(dh(i,s,Ze.get(i.id)??0)):"var(--semiotic-accent, #356b63)"},[s,Ze,e.color]),et=(0,Md.useCallback)((t,n)=>({...eh(Je(t),t,n,h.bodyStyle),...void 0!==e.stroke?{stroke:e.stroke}:null,...void 0!==e.strokeWidth?{strokeWidth:e.strokeWidth}:null,...void 0!==e.opacity?{opacity:e.opacity}:null}),[Je,h.bodyStyle,e.opacity,e.stroke,e.strokeWidth]),tt=(0,Md.useCallback)((e,t)=>("function"==typeof h.bodySemanticItems?h.bodySemanticItems(e,t):void 0)??function(e,t){const n=e.datum;if(!n?.__crucible)return!1;if("component"===n.kind){const e=t.components[n.semanticId];return!!e&&{id:"crucible-component-"+e.id,label:e.label,description:Fu(e),group:"source component · "+e.status,datum:e}}const i=t.products[n.semanticId];return!!i&&{id:"crucible-product-"+i.id,label:i.label,description:zu(i),group:"derived product · "+i.status,datum:i}}(e,Me.current.state),[h]),nt=(0,Md.useCallback)(e=>{if(!w||!e||"object"!=typeof e)return;if(!e.__crucible)return;const t=Me.current.state,n="component"===e.kind?t.components[e.semanticId]:t.products[e.semanticId];n&&w(n)},[w]),it=(0,Md.useCallback)((e,t)=>{h.beforePaint?.(e,t),F&&function(e,t,n){const i=new Map;for(const e of t){const t=e.datum;t?.__crucible&&i.set(`${t.kind}:${t.semanticId}`,e)}e.save(),e.lineCap="round";for(const t of Object.values(n.relations)){if("active"!==t.status)continue;const n=t.sourceIds.map(e=>i.get("component:"+e)).filter(e=>!!e);2>n.length||(e.strokeStyle="rejected"===t.category?"#9f3d35":"#b8792d",e.globalAlpha=.4,e.lineWidth=Math.max(.8,1.3*Number(t.strength??1)),e.setLineDash([3,4]),e.beginPath(),n.forEach((t,n)=>{0===n?e.moveTo(t.x,t.y):e.lineTo(t.x,t.y)}),e.stroke())}e.setLineDash([]);for(const t of Object.values(n.products)){const n=i.get("product:"+t.id);if(n)for(const o of t.sourceIds){const r=i.get("component:"+o);r&&(e.strokeStyle=t.color??"#b8792d",e.globalAlpha="complete"===t.status?.5:.28,e.lineWidth="complete"===t.status?1.6:1,e.beginPath(),e.moveTo(r.x,r.y),e.lineTo(n.x,n.y),e.stroke())}}e.restore()}(e,t,Me.current.state)},[h,F]),ot=(0,Md.useMemo)(()=>T??{groupBy:"outlet",measure:"count"},[T]),rt=(0,Md.useMemo)(()=>Yd(we.state,ot),[ot,we.state]),st=(0,Md.useMemo)(()=>Q?function(e,t,n,i){if(!e.length)return[];const o=n.measure??"count",r=t.projection.width/Math.max(1,e.length);return e.map((e,n)=>{const s=Qu(e,o),a="amount"===o&&i?`${qu(s)} ${i}`:`${qu(s)} ${o}`;return{id:"crucible-projection-"+e.key,label:`${e.label}: ${a}`,description:`${e.count} source component${1===e.count?"":"s"}; ${qu(e.amount)} amount.`,datum:e,group:"settled composition",x:t.projection.x+(n+.5)*r,y:t.projection.y+t.projection.height/2,shape:"rect",width:Math.max(12,.62*r),height:Math.max(8,t.projection.height-8)}})}(rt,ye.layout,ot,i):[],[i,ye.layout,ot,rt,Q]),at=Ka(e.tooltip,h),ct=Qa({...e,onClick:void 0},h,st,{chartMode:X,className:Z,title:J??"Crucible",description:ee??"A bounded inventory is transformed by an authored phase and event tape; physics explains the motion but does not determine the outcome.",summary:te??hh(we.state,i),accessibleTable:ne,enableHover:ie,margin:oe}),lt=Ua(K?(0,oh.jsx)(Ku,{layout:ye.layout,phases:ye.phases,state:we.state,compact:G.compactMode||360>le[0]||260>le[1]}):void 0,h.backgroundGraphics),dt=Ua(Q?(0,oh.jsx)(Zu,{rows:rt,layout:ye.layout,projection:ot,amountLabel:i}):void 0,h.foregroundGraphics),ut=(0,Md.useCallback)(e=>function(e,t){const n=e.data;if(!n?.__crucible)return null;const i="component"===n.kind?t.components[n.semanticId]:t.products[n.semanticId];if(!i)return null;const o="product"===n.kind;return(0,Yu.jsxs)("div",{className:"semiotic-tooltip semiotic-crucible-tooltip",style:{background:"var(--semiotic-tooltip-bg, rgba(38, 50, 58, 0.96))",border:"1px solid rgba(255,255,255,0.2)",borderRadius:3,boxShadow:"0 8px 24px rgba(0,0,0,0.28)",color:"var(--semiotic-tooltip-text, #fffaf0)",maxWidth:290,padding:"9px 12px"},children:[(0,Yu.jsx)("strong",{children:i.label}),(0,Yu.jsx)("div",{style:{opacity:.78,fontSize:11,letterSpacing:"0.06em",textTransform:"uppercase"},children:o?"Product · "+i.status:"Source · "+i.status}),(0,Yu.jsx)("div",{style:{marginTop:4},children:o?zu(i):Fu(i)})]})}(e,Me.current.state),[]),ht=ge?Bu(ye,we.state,Oe.current):ye.initialSpawns,pt=function(e){return e?!0===e?{playPause:!0,reset:!0,stepPhase:!0,timeline:!0,speed:!0}:{playPause:e.playPause??!0,reset:e.reset??!0,stepPhase:e.stepPhase??!0,timeline:e.timeline??!0,speed:e.speed??!1}:{playPause:!1,reset:!1,stepPhase:!1,timeline:!1,speed:!1}}(c),mt=Object.values(pt).some(Boolean),ft=ye.phases[we.state.phaseIndex],yt=Xa({data:l,emptyContent:d,loading:g,loadingContent:b,size:le});if(yt)return yt;const gt=ye.diagnostics.filter(e=>"error"===e.severity);return gt.length?(0,oh.jsxs)("div",{className:Z,role:"alert",style:{maxWidth:"100%",width:le[0]},children:[(0,oh.jsx)("strong",{children:"CrucibleChart could not compile this treatment tape."}),(0,oh.jsx)("ul",{children:gt.map((e,t)=>(0,oh.jsx)("li",{children:e.message},`${e.code}-${t}`))})]}):Va("CrucibleChart",le,(0,oh.jsxs)("div",{ref:re,className:"semiotic-crucible-chart",style:{maxWidth:"100%",overflow:"hidden",position:"relative",width:W?"100%":le[0]},children:[mt?(0,oh.jsx)(Ju,{controls:pt,duration:ye.duration,elapsed:we.state.elapsed,phaseLabel:ft?.label??ft?.id??"Complete",playing:Ie&&!A,complete:we.state.complete,playbackRate:Re,disabled:ge,onPlayPause:Ie?Ge:Ve,onReset:He,onStepPhase:Ue,onPlaybackRateChange:$e}):null,(0,rh.createElement)(rs,{...h,...at,...ct,key:`${pe}:${Ae}:${Le.rerunKey}:${ge?be:"replay"}`,ref:L,accessibleTable:e.accessibleTable??h.accessibleTable,backgroundGraphics:lt,bodyForces:Qe,bodySemanticItems:tt,bodyStyle:et,beforePaint:it,config:Le.config,continuous:!ge&&Ie&&!A&&!we.state.complete,enableHover:at.enableHover??ie,foregroundGraphics:dt,hoverRadius:e.hoverRadius??h.hoverRadius??18,initialSpawns:ht,initialSpawnPacing:f,onClick:w?nt:ct.onClick,onTick:Ke,paused:ze,renderBody:h.renderBody??Lu,responsiveHeight:O,responsiveWidth:!1,seed:ch(q),size:le,tooltipContent:at.tooltipContent??ut})]}))});ph.displayName="CrucibleChart";var mh=require("react");function fh(e,t,n={}){const i=new Set,o=[...e.get(t)??[]];let r=0;for(;o.length>r;){const t=o[r];if(r+=1,!i.has(t)){i.add(t);for(const n of e.get(t)??[])o.push(n)}}return n.includeStart&&i.add(t),i}function yh(e,t,n){return wc(n,e,t)}function gh(e,t){return t>e?-1:e>t?1:0}function bh(e,t){return`dependency:${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function xh(e,t){return`socket:${encodeURIComponent(e)}:${t}`}function vh(e){const t=Number(e);return Number.isFinite(t)?Math.max(0,Math.min(1,t)):0}function wh(e){const t=[],n=new Map,i=[],o=new Set;e.data.forEach((r,s)=>{const a=(yh(r,s,e.taskIDAccessor)??"")+"";if(!a)return void t.push({code:"duplicate-task-id",message:`Task row ${s} has an empty id.`,taskIDs:[]});if(n.has(a))return void t.push({code:"duplicate-task-id",message:`Task id "${a}" occurs more than once.`,taskIDs:[a]});const c=(yh(r,s,e.laneAccessor)??"Unassigned")+"";o.has(c)||(o.add(c),i.push(c));const l=yh(r,s,e.dependencyAccessor)??[],d=Array.from(new Set(Array.from(l,e=>e+""))).sort(gh),u=yh(r,s,e.blockerAccessor),h=yh(r,s,e.statusAccessor)??(u?"blocked":"waiting");n.set(a,{id:a,label:(yh(r,s,e.labelAccessor)??a)+"",lane:c,laneIndex:0,level:0,index:s,datum:r,dependencyIDs:d,incomingEdgeIDs:[],outgoingEdgeIDs:[],socketIDs:[],start:yh(r,s,e.startAccessor),end:yh(r,s,e.endAccessor),progress:vh(yh(r,s,e.progressAccessor)),status:h,completionTime:yh(r,s,e.completionTimeAccessor),blockerReason:u||void 0,milestone:!!yh(r,s,e.milestoneAccessor)})});const r=e.laneOrder?[...e.laneOrder,...i.filter(t=>!e.laneOrder?.includes(t))]:i,s=new Map(r.map((e,t)=>[e,t]));for(const e of n.values())e.laneIndex=s.get(e.lane)??0;const a=new Map,c=new Map;for(const e of n.keys())a.set(e,[]),c.set(e,[]);const l=[],d=[...n.values()].sort((e,t)=>e.index-t.index);for(const e of d)e.dependencyIDs.forEach((i,o)=>{const r=n.get(i);if(!r)return void t.push({code:"missing-dependency",message:`Task "${e.id}" depends on missing task "${i}".`,taskIDs:[e.id,i]});const s={id:bh(i,e.id),sourceID:i,targetID:e.id,sourceIndex:r.index,targetIndex:e.index,socketID:xh(e.id,o),socketIndex:o};l.push(s),a.get(e.id)?.push(s),c.get(i)?.push(s),e.incomingEdgeIDs.push(s.id),e.socketIDs.push(s.socketID),r.outgoingEdgeIDs.push(s.id)});for(const e of a.values())e.sort((e,t)=>gh(e.sourceID,t.sourceID)),e.forEach((e,t)=>{e.socketIndex=t,e.socketID=xh(e.targetID,t)});for(const e of c.values())e.sort((e,t)=>gh(e.targetID,t.targetID));for(const e of n.values()){const t=a.get(e.id)??[];e.incomingEdgeIDs=t.map(e=>e.id),e.socketIDs=t.map(e=>e.socketID),e.outgoingEdgeIDs=(c.get(e.id)??[]).map(e=>e.id)}const u=new Map,h=new Map;for(const e of n.keys())u.set(e,a.get(e)?.length??0),h.set(e,0);const p=[...n.keys()].filter(e=>0===u.get(e)).sort(gh);let m=0;for(;p.length;){const e=p.shift();m+=1;for(const t of c.get(e)??[]){const n=Math.max(h.get(t.targetID)??0,(h.get(e)??0)+1);h.set(t.targetID,n);const i=(u.get(t.targetID)??0)-1;if(u.set(t.targetID,i),0===i){const e=p.findIndex(e=>e>t.targetID);0>e?p.push(t.targetID):p.splice(e,0,t.targetID)}}}if(m!==n.size){const e=[...n.keys()].filter(e=>(u.get(e)??0)>0).sort(gh);t.push({code:"cycle",message:`Dependency graph contains a cycle involving: ${e.join(", ")}.`,taskIDs:e})}let f=0;const y=[...n.values()].sort((e,t)=>e.index-t.index);for(const e of y)e.level=h.get(e.id)??0,f=Math.max(f,e.level);return{nodes:y,edges:l,byID:n,incoming:a,outgoing:c,lanes:r,maxLevel:f,diagnostics:t,valid:0===t.length}}function kh(e,t,n={}){const i=Math.max(240,t.width),o=Math.max(220,t.height),r=t.paddingX??48,s=t.paddingTop??48,a=t.paddingBottom??44,c=Math.max(70,(i-2*r)/Math.max(1,e.lanes.length)),l=Math.max(76,(o-s-a)/Math.max(1,e.maxLevel+1)),d=Math.min(n.taskWidth??112,Math.max(58,.78*c)),u=Math.min(n.taskHeight??58,.64*l),h=n.socketRadius??5,p=Math.max(1,Math.round(n.gutterCount??3)),m=new Map;for(const t of e.nodes){const e=`${t.laneIndex}:${t.level}`,n=m.get(e)??[];n.push(t),m.set(e,n)}for(const e of m.values())e.sort((e,t)=>gh(e.id,t.id));const f=e.nodes.map(e=>{const t=m.get(`${e.laneIndex}:${e.level}`)??[e],n=Math.max(0,t.findIndex(t=>t.id===e.id));return{taskID:e.id,lane:e.lane,laneIndex:e.laneIndex,level:e.level,x:r+c*(e.laneIndex+.5),y:s+l*(e.level+.5)+(n-(t.length-1)/2)*Math.min(18,.3*u),width:d,height:u}}),y=new Map(f.map(e=>[e.taskID,e])),g=[],b=[];e.edges.forEach((t,n)=>{const i=y.get(t.sourceID),o=y.get(t.targetID);if(!i||!o)return;const r=e.incoming.get(t.targetID)??[],s=Math.min(.72*o.width,14*Math.max(1,r.length-1)),a=r.length>1?o.x-s/2+s*t.socketIndex/(r.length-1):o.x,c=o.y-o.height/2-h-2;g.push({id:t.socketID,edgeID:t.id,taskID:o.taskID,index:t.socketIndex,x:a,y:c,radius:h});const l={x:i.x,y:i.y+i.height/2+3},d=Math.min(c-10,l.y+.48*Math.max(18,c-l.y)+7*(n%p-(p-1)/2));var u;b.push({edgeID:t.id,sourceID:t.sourceID,targetID:t.targetID,socketID:t.socketID,points:(u=[l,{x:l.x,y:d},{x:a,y:d},{x:a,y:c}],u.filter((e,t)=>{const n=u[t-1];return!n||n.x!==e.x||n.y!==e.y}))})});const x=new Map(g.map(e=>[e.id,e])),v=new Map(b.map(e=>[e.edgeID,e]));return{tasks:f,sockets:g,routes:b,taskByID:y,socketByID:x,routeByEdgeID:v}}function Mh(e,t,n="all"){const i=Array.from(new Set(t)).sort(gh),o=new Set,r=()=>i.every(e=>o.has(e));return{taskID:e,mode:n,incomingEdgeIDs:i,deliver:e=>i.includes(e)?(o.add(e),r()):r(),reset:(e=[])=>{o.clear();for(const t of e)i.includes(t)&&o.add(t)},isSatisfied:r,getSnapshot:()=>({taskID:e,mode:n,incomingEdgeIDs:[...i],deliveredEdgeIDs:[...o].sort(gh),satisfied:r()})}}function Ih(e){return e instanceof Date?e.getTime():Number(e)}function Sh(e,t){const n=Ih("object"!=typeof t||t instanceof Date?t:t.currentTime),i=e.map((e,t)=>({event:e,index:t,time:Ih(e.at)})).filter(e=>Number.isFinite(e.time)&&n>=e.time).sort((e,t)=>e.time-t.time||e.index-t.index),o=new Set,r=new Map,s=new Set,a=new Set;for(const{event:e}of i)"task-completed"===e.type?(o.add(e.taskID),r.delete(e.taskID)):"task-blocked"===e.type?r.set(e.taskID,e.reason):"task-unblocked"===e.type?r.delete(e.taskID):"dependency-delivered"===e.type?s.add(e.edgeID):"task-armed"===e.type&&a.add(e.taskID);return{currentTime:n,appliedEvents:i.map(e=>e.event),completedTaskIDs:o,blockedByTaskID:r,deliveredEdgeIDs:s,armedTaskIDs:a}}function jh(e,t,n={}){const i=new Set(n.completedTaskIDs??[]),o=[...fh(function(e,t){const n=new Map;for(const t of e)n.set(t.id,new Set);for(const e of t)n.has(e.source)||n.set(e.source,new Set),n.has(e.target)||n.set(e.target,new Set),n.get(e.source).add(e.target);return n}(e.nodes,e.edges.map(e=>({source:e.sourceID,target:e.targetID}))),t)].map(t=>e.byID.get(t)).filter(e=>null!=e).filter(e=>!(n.isComplete?n.isComplete(e):i.has(e.id)||"done"===e.status)).sort((e,t)=>e.index-t.index),r=Array.from(new Set(o.map(e=>e.lane)));return{blockerID:t,downstreamTaskCount:o.length,affectedLaneCount:r.length,downstreamTaskIDs:o.map(e=>e.id),affectedLanes:r}}var Ah=[];function Ch(e,t=0){if(e instanceof Date)return e.getTime();const n=Number(e);return Number.isFinite(n)?n:t}function Rh(e){if(null==e.completionTime)return null;const t=Ch(e.completionTime,NaN);return Number.isFinite(t)?t:null}function $h(e,t,n,i){const o=new Set;for(const r of e.nodes){const s=e.incoming.get(r.id)??[];(i.has(r.id)||!n.has(r.id)&&s.every(e=>t.has(e.id)))&&o.add(r.id)}return o}function Ph(e,t,n,i){const o=e.nodes.map(Rh).filter(e=>null!=e),r=o.length?Math.min(...o)-1:0,s="replay"!==t||i?n:r,a=new Set,c=new Map;for(const n of e.nodes){const e=Rh(n);(null!=e&&s>=e||"done"===n.status&&"replay"!==t)&&a.add(n.id),n.blockerReason&&!a.has(n.id)&&c.set(n.id,n.blockerReason)}const l=new Set;if("replay"!==t||i)for(const t of e.edges)a.has(t.sourceID)&&l.add(t.id);return{currentTime:s,playing:!1,completed:a,delivered:l,inFlight:new Set,armed:$h(e,l,c,a),blockers:c,previewTaskID:null}}function Dh(e){return{...e,completed:new Set(e.completed),delivered:new Set(e.delivered),inFlight:new Set(e.inFlight),armed:new Set(e.armed),blockers:new Map(e.blockers)}}function Bh(e){const t=e.datum;return"dependency-ball"===t?.kind&&Array.isArray(t.route)?t:null}function Th(e){const t=Bh(e.body);if(!t||2>t.route.length)return null;const n=function(e){let t=0;for(let n=1;e.length>n;n+=1)t+=Math.hypot(e[n].x-e[n-1].x,e[n].y-e[n-1].y);return t}(t.route),i=function(e,t){let n=1/0,i=0,o=0;for(let r=1;t.length>r;r+=1){const s=t[r-1],a=t[r],c=a.x-s.x,l=a.y-s.y,d=c*c+l*l,u=Math.sqrt(d);if(0>=u)continue;const h=Math.max(0,Math.min(1,((e.x-s.x)*c+(e.y-s.y)*l)/d)),p=Math.hypot(e.x-(s.x+c*h),e.y-(s.y+l*h));n>p&&(n=p,i=o+h*u),o+=u}return i}(e.body,t.route),o=function(e,t){if(2>e.length)return{point:e[0]??{x:0,y:0},tangent:{x:0,y:1}};let n=0;for(let i=1;e.length>i;i+=1){const o=e[i-1],r=e[i],s=r.x-o.x,a=r.y-o.y,c=Math.hypot(s,a);if(c>0){if(n+c>=t){const e=Math.max(0,Math.min(1,(t-n)/c));return{point:{x:o.x+s*e,y:o.y+a*e},tangent:{x:s/c,y:a/c}}}n+=c}}const i=e[e.length-2],o=e[e.length-1],r=o.x-i.x,s=o.y-i.y,a=Math.hypot(r,s)||1;return{point:o,tangent:{x:r/a,y:s/a}}}(t.route,Math.min(n,i+22));return{x:2.5*(78*o.tangent.x-e.body.vx)+8*(o.point.x-e.body.x),y:2.5*(78*o.tangent.y-e.body.vy)+8*(o.point.y-e.body.y)}}function Eh(e,t){const n=t.points[0]??{x:0,y:0},i=t.points[1]??n,o=i.x-n.x,r=i.y-n.y,s=Math.hypot(o,r)||1;return{id:"dependency-ball:"+e.id,x:n.x,y:n.y,vx:o/s*42,vy:r/s*42,mass:.7,restitution:.02,friction:.12,bodyCollisions:!1,shape:{type:"circle",radius:5},datum:{kind:"dependency-ball",edgeID:e.id,sourceID:e.sourceID,targetID:e.targetID,route:t.points}}}var Nh=require("react/jsx-runtime");function Oh({machine:e,layout:t,runtime:n,downstreamSet:i,selectedSet:o,width:r,height:s,seed:a,reduced:c,onSelectTask:l}){return(0,Nh.jsxs)("svg",{"aria-hidden":"true",width:r,height:s,viewBox:`0 0 ${r} ${s}`,style:{position:"absolute",inset:0,overflow:"visible",pointerEvents:"none"},children:[(0,Nh.jsx)("defs",{children:(0,Nh.jsx)("filter",{id:"chain-shadow-"+a,x:"-20%",y:"-20%",width:"140%",height:"150%",children:(0,Nh.jsx)("feDropShadow",{dx:"0",dy:"2",stdDeviation:"2",floodOpacity:"0.2"})})}),e.lanes.map((e,n)=>{const i=t.tasks.filter(e=>e.laneIndex===n),o=i[0]?.x??0;return(0,Nh.jsxs)("g",{children:[(0,Nh.jsx)("line",{x1:o,x2:o,y1:32,y2:s-24,stroke:"var(--semiotic-grid, #d7dde0)",strokeWidth:1,strokeDasharray:"3 7"}),(0,Nh.jsx)("text",{x:o,y:23,textAnchor:"middle",fontSize:12,fontWeight:700,fill:"var(--semiotic-text, #243039)",children:e})]},e)}),t.routes.map(e=>{const t=n.delivered.has(e.edgeID),o=n.inFlight.has(e.edgeID),r=i.has(e.targetID)||i.has(e.sourceID),s=e.points.map(e=>`${e.x},${e.y}`).join(" ");return(0,Nh.jsx)("polyline",{points:s,fill:"none",stroke:r?"var(--semiotic-highlight, #e08a1e)":t?"var(--semiotic-success, #2b8a66)":"var(--semiotic-grid, #aeb8bd)",strokeWidth:r?4:o?3:2,strokeOpacity:t||o||r?.95:.48,strokeLinecap:"round",strokeLinejoin:"round"},e.edgeID)}),t.sockets.map(e=>{const t=n.delivered.has(e.edgeID);return(0,Nh.jsxs)("g",{children:[(0,Nh.jsx)("circle",{cx:e.x,cy:e.y,r:e.radius+2,fill:"var(--semiotic-background, #fff)",stroke:"var(--semiotic-text, #243039)",strokeWidth:1.5}),t&&(0,Nh.jsx)("circle",{cx:e.x,cy:e.y,r:e.radius-.5,fill:"var(--semiotic-success, #2b8a66)"})]},e.id)}),e.nodes.map(e=>{const r=t.taskByID.get(e.id);if(!r)return null;const s=n.completed.has(e.id),d=n.blockers.has(e.id),u=n.previewTaskID===e.id,h=o.has(e.id)||u,p=i.has(e.id),m=function(e,t){return t.completed.has(e.id)?"var(--semiotic-success, #2b8a66)":t.blockers.has(e.id)?"var(--semiotic-error, #c64035)":"in-progress"===e.status?"var(--semiotic-warning, #d18a22)":t.armed.has(e.id)?"var(--semiotic-primary, #2474a6)":"var(--semiotic-muted, #75818a)"}(e,n),f=r.x-r.width/2,y=r.y-r.height/2,g=Math.max(2,r.height*e.progress);return(0,Nh.jsxs)("g",{children:[(0,Nh.jsxs)("g",{style:{transform:`rotate(${s?76:0}deg)`,transformBox:"fill-box",transformOrigin:"50% 100%",transition:c?"none":"transform 520ms cubic-bezier(.2,.8,.25,1)",filter:"url(#chain-shadow-"+a+")"},children:[(0,Nh.jsx)("rect",{x:f,y:y,width:r.width,height:r.height,rx:e.milestone?12:4,fill:"var(--semiotic-background, #fff)",stroke:h||p?"var(--semiotic-highlight, #e08a1e)":m,strokeWidth:h?4:p?3:2}),(0,Nh.jsx)("rect",{x:f+3,y:y+r.height-g+1,width:r.width-6,height:Math.max(0,g-4),rx:2,fill:m,opacity:s?.86:.46})]}),d&&(0,Nh.jsxs)("g",{opacity:u?.28:1,children:[(0,Nh.jsx)("line",{x1:f-8,x2:f+14,y1:r.y+9,y2:r.y-9,stroke:"var(--semiotic-error, #c64035)",strokeWidth:7,strokeLinecap:"round"}),(0,Nh.jsx)("circle",{cx:f-8,cy:r.y+9,r:3,fill:"var(--semiotic-error, #c64035)"})]}),(0,Nh.jsxs)("g",{onPointerDown:()=>l(e.id),style:{cursor:"pointer",pointerEvents:"auto"},children:[(0,Nh.jsx)("rect",{x:f,y:y,width:r.width,height:r.height,fill:"transparent"}),(0,Nh.jsx)("text",{x:r.x,y:r.y-4,textAnchor:"middle",fontSize:10.5,fontWeight:700,fill:"var(--semiotic-text, #243039)",children:e.label.length>24?e.label.slice(0,22)+"…":e.label}),(0,Nh.jsxs)("text",{x:r.x,y:r.y+12,textAnchor:"middle",fontSize:9.5,fill:"var(--semiotic-text-muted, #5f6b72)",children:[Math.round(100*e.progress),"% · ",s?"done":d?"blocked":n.armed.has(e.id)?"ready":"waiting"]})]})]},e.id)})]})}var Wh=require("react/jsx-runtime"),qh={border:0,clip:"rect(0 0 0 0)",clipPath:"inset(50%)",height:1,margin:-1,overflow:"hidden",padding:0,position:"absolute",whiteSpace:"nowrap",width:1},Fh=(0,mh.forwardRef)(function(e,t){const{data:n,taskIDAccessor:i,labelAccessor:o,laneAccessor:r,dependencyAccessor:s,startAccessor:a,endAccessor:c,progressAccessor:l,statusAccessor:d,completionTimeAccessor:u,blockerAccessor:h,milestoneAccessor:p,mode:m="snapshot",insight:f="blocker-amplification",currentTime:y,controls:g=!1,selectedTaskIDs:b,onSelectionChange:x,onObservation:v,reducedMotion:w,seed:k=31,width:M=920,height:I=620,responsiveWidth:S,responsiveHeight:j,title:A="Dependency chain reaction",description:C,className:R,accessibleTable:$=!0,enableHover:P=!0}=e,D=(0,mh.useRef)(null),[B,T]=(0,mh.useState)([]),E=b?Array.from(b):B,N=(0,mh.useMemo)(()=>new Set(E),[E]),O=Ch(y,1/0),W="settle"===w,q=(0,mh.useMemo)(()=>wh({data:n,taskIDAccessor:i,labelAccessor:o,laneAccessor:r,dependencyAccessor:s,startAccessor:a,endAccessor:c,progressAccessor:l,statusAccessor:d,completionTimeAccessor:u,blockerAccessor:h,milestoneAccessor:p}),[n,i,o,r,s,a,c,l,d,u,h,p]),F=(0,mh.useMemo)(()=>kh(q,{width:M,height:I}),[q,M,I]),[z,L]=(0,mh.useState)(()=>Ph(q,m,O,W)),Y=(0,mh.useRef)(z),H=(0,mh.useCallback)(e=>{Y.current=e,L(e)},[]),_=(0,mh.useCallback)(e=>v?.(e),[v]);(0,mh.useEffect)(()=>{const e=Ph(q,m,O,W);D.current?.clear(),Y.current=e,L(e)},[q,m,O,W]);const G=(0,mh.useCallback)(e=>{const t=N.has(e)?E.filter(t=>t!==e):[e];b||T(t),x?.(t)},[b,x,N,E]),X=(0,mh.useCallback)(e=>{if(W)return;const t=Dh(Y.current),n=[];for(const i of q.outgoing.get(e)??[]){if(t.delivered.has(i.id)||t.inFlight.has(i.id))continue;const e=F.routeByEdgeID.get(i.id);e&&(t.inFlight.add(i.id),n.push(Eh(i,e)))}n.length&&(H(t),D.current?.pushMany(n,{pacing:{ratePerSec:8}}))},[H,F,q,W]),V=(0,mh.useCallback)((e,t)=>{const n=q.byID.get(e),i=Y.current;if(!n||i.completed.has(e))return;const o=Dh(i);o.completed.add(e),o.blockers.delete(e),o.armed.add(e),null!=t&&(o.currentTime=t),H(o),_({type:"task-completed",taskID:e,datum:n.datum}),X(e)},[H,_,q,X]),U=(0,mh.useCallback)(e=>{const t=Dh(Y.current),n=[],i=[];for(const i of e){if(t.delivered.has(i))continue;const e=q.edges.find(e=>e.id===i);e&&(t.delivered.add(i),t.inFlight.delete(i),n.push(e))}for(const e of n){const n=q.byID.get(e.targetID);!n||t.blockers.has(n.id)||t.armed.has(n.id)||(q.incoming.get(n.id)??[]).every(e=>t.delivered.has(e.id))&&(t.armed.add(n.id),i.push(n.id))}if(n.length){H(t);for(const e of n)_({type:"dependency-delivered",sourceID:e.sourceID,targetID:e.targetID});for(const e of i)_({type:"task-armed",taskID:e})}},[H,_,q]),K=(0,mh.useCallback)((e,t)=>{const n=[],i=[];for(const e of t.readBodies()){const t=Bh(e);if(!t||Y.current.delivered.has(t.edgeID))continue;const o=t.route[t.route.length-1];o&&9>=Math.hypot(e.x-o.x,e.y-o.y)&&(n.push(t.edgeID),i.push(e.id))}i.length&&t.remove(i),n.length&&U(n)},[U]),Q=(0,mh.useCallback)(()=>{const e=Dh(Y.current);for(const t of q.edges)e.completed.has(t.sourceID)&&e.delivered.add(t.id);e.inFlight.clear(),e.armed=$h(q,e.delivered,e.blockers,e.completed),e.playing=!1,D.current?.settle(),H(e),_({type:"machine-settled"})},[H,_,q]),Z=(0,mh.useCallback)(()=>{const e=Dh(Y.current);e.playing=!1,H(e)},[H]),J=(0,mh.useCallback)(()=>{const e=Y.current,t=q.nodes.map(e=>({node:e,time:Rh(e)})).filter(t=>null!=t.time&&t.time>e.currentTime&&!e.completed.has(t.node.id)).sort((e,t)=>e.time-t.time||e.node.index-t.node.index)[0];if(t)return void V(t.node.id,t.time);Z();const n=[...e.blockers.keys()].map(t=>jh(q,t,{completedTaskIDs:e.completed})).sort((e,t)=>t.affectedLaneCount-e.affectedLaneCount||t.downstreamTaskCount-e.downstreamTaskCount);n[0]&&_({type:"machine-stalled",blockerID:n[0].blockerID,downstreamTaskCount:n[0].downstreamTaskCount,affectedLaneCount:n[0].affectedLaneCount})},[_,q,Z,V]),ee=(0,mh.useCallback)(()=>{if(W)return void Q();const e=Dh(Y.current);e.playing=!0,H(e)},[H,W,Q]);(0,mh.useEffect)(()=>{if(!z.playing||"replay"!==m||W)return;const e=window.setInterval(J,760);return()=>window.clearInterval(e)},[m,W,z.playing,J]);const te=(0,mh.useCallback)(()=>{D.current?.clear(),H(Ph(q,m,O,W))},[H,q,m,O,W]),ne=(0,mh.useCallback)(e=>{if(!q.byID.has(e))return;const t=Dh(Y.current);t.previewTaskID=e,H(t);const n=jh(q,e,{completedTaskIDs:t.completed});_({type:"blocker-previewed",blockerID:e,downstreamTaskIDs:n.downstreamTaskIDs})},[H,_,q]),ie=(0,mh.useCallback)(()=>{const e=Dh(Y.current);e.previewTaskID=null,H(e)},[H]),oe=(0,mh.useCallback)((e,t)=>{if(!q.byID.has(e))return;const n=Dh(Y.current);n.blockers.set(e,t),n.armed.delete(e),H(n)},[H,q]),re=(0,mh.useCallback)(e=>{if(!q.byID.has(e))return;const t=Dh(Y.current);t.blockers.delete(e),(q.incoming.get(e)??[]).every(e=>t.delivered.has(e.id))&&t.armed.add(e),H(t)},[H,q]),se=(0,mh.useCallback)(e=>jh(q,e,{completedTaskIDs:Y.current.completed}),[q]),ae=(0,mh.useCallback)(()=>{const e=Y.current;return{currentTime:e.currentTime,playing:e.playing,previewTaskID:e.previewTaskID,selectedTaskIDs:[...E],tasks:q.nodes.map(t=>({taskID:t.id,completed:e.completed.has(t.id),armed:e.armed.has(t.id),blocked:e.blockers.has(t.id),blockerReason:e.blockers.get(t.id)})),dependencies:q.edges.map(t=>({edgeID:t.id,sourceID:t.sourceID,targetID:t.targetID,state:e.delivered.has(t.id)?"delivered":e.inFlight.has(t.id)?"in-flight":"waiting"}))}},[q,E]);(0,mh.useImperativeHandle)(t,()=>({play:ee,pause:Z,step:J,reset:te,settle:Q,previewResolve:ne,clearPreview:ie,completeTask:V,blockTask:oe,unblockTask:re,getAmplification:se,getMachineState:ae}),[oe,ie,se,ae,Z,V,ee,ne,te,Q,J,re]);const ce=z.previewTaskID??E[0]??null,le=ce?jh(q,ce,{completedTaskIDs:z.completed}):null,de=(0,mh.useMemo)(()=>new Set(le?.downstreamTaskIDs??[]),[le?.downstreamTaskIDs]),ue=(0,mh.useMemo)(()=>function(e,t,n){return e.nodes.flatMap(i=>{const o=t.taskByID.get(i.id);if(!o)return[];const r=e.incoming.get(i.id)??[],s=r.filter(e=>n.delivered.has(e.id)).length,a=n.blockers.get(i.id),c=n.completed.has(i.id)?"completed":a?"blocked: "+a:n.armed.has(i.id)?"armed":"waiting";return[{id:i.id,label:`${i.label}, ${i.lane}, ${Math.round(100*i.progress)}%, ${c}`,description:`${s} of ${r.length} prerequisites delivered.`,datum:i.datum,x:o.x,y:o.y,width:o.width,height:o.height,shape:"rect",group:i.lane}]})}(q,F,z),[F,q,z]),he=(0,mh.useMemo)(()=>(0,Wh.jsx)(Oh,{machine:q,layout:F,runtime:z,downstreamSet:de,selectedSet:N,width:M,height:I,seed:k,reduced:W,onSelectTask:G}),[de,I,F,q,W,z,k,G,N,M]),pe=(0,mh.useMemo)(()=>{const e=[...z.blockers.keys()].map(e=>jh(q,e,{completedTaskIDs:z.completed})).sort((e,t)=>t.affectedLaneCount-e.affectedLaneCount||t.downstreamTaskCount-e.downstreamTaskCount);return e.length?e.map(e=>`${q.byID.get(e.blockerID)?.label??e.blockerID} affects ${e.downstreamTaskCount} unfinished tasks across ${e.affectedLaneCount} lanes.`).join(" "):"No explicit blockers are active."},[q,z.blockers,z.completed]),me=(0,mh.useMemo)(()=>[{id:"chain-left",shape:{type:"segment",x1:2,y1:0,x2:2,y2:I,thickness:4}},{id:"chain-right",shape:{type:"segment",x1:M-2,y1:0,x2:M-2,y2:I,thickness:4}},{id:"chain-top",shape:{type:"segment",x1:0,y1:2,x2:M,y2:2,thickness:4}},{id:"chain-bottom",shape:{type:"segment",x1:0,y1:I-2,x2:M,y2:I-2,thickness:4}}],[I,M]),fe=!0===g?["play","pause","step","reset","settle"]:g||[];return(0,Wh.jsxs)("div",q.valid?{className:R,style:{width:M,maxWidth:"100%",position:"relative"},children:[fe.length>0&&(0,Wh.jsx)("div",{"aria-label":"Chain reaction replay controls",style:{display:"flex",flexWrap:"wrap",gap:6,marginBottom:8},children:fe.map(e=>(0,Wh.jsx)("button",{type:"button",onClick:"play"===e?ee:"pause"===e?Z:"step"===e?J:"reset"===e?te:Q,"aria-pressed":"play"===e?z.playing:void 0,children:e[0].toUpperCase()+e.slice(1)},e))}),(0,Wh.jsx)(rs,{ref:D,size:[M,I],responsiveWidth:S,responsiveHeight:j,title:A,description:C??"Tasks are arranged by workstream and dependency depth. Balls represent satisfied prerequisites; task completion remains an explicit data event.",summary:`${pe}${le&&"blocker-amplification"===f?` Selected task reaches ${le.downstreamTaskCount} unfinished tasks across ${le.affectedLaneCount} lanes.`:""}`,accessibleTable:!1,enableHover:P,initialSpawns:Ah,bodyForces:Th,bodyStyle:{fill:"var(--semiotic-accent, #f0a329)",stroke:"var(--semiotic-text, #243039)",strokeWidth:1.25},bodySemanticItems:!1,semanticItems:ue,onSemanticItemActivate:e=>e.id&&G(e.id),foregroundGraphics:()=>he,paused:W,continuous:z.inFlight.size>0,onTick:K,config:{bodyLimit:Math.max(16,q.edges.length+4),colliders:me,settleStepLimit:2200,kernel:{seed:k,gravity:{x:0,y:7},fixedDt:1/60,cellSize:28,collisionIterations:2,velocityDamping:.992,restitution:.02,friction:.12,maxVelocity:150,sleepSpeed:1.1,sleepAfter:.8},observation:{chartType:"ChainReactionChart"}}}),$&&(0,Wh.jsxs)("table",{style:qh,children:[(0,Wh.jsx)("caption",{children:pe}),(0,Wh.jsx)("thead",{children:(0,Wh.jsxs)("tr",{children:[(0,Wh.jsx)("th",{children:"Task"}),(0,Wh.jsx)("th",{children:"Lane"}),(0,Wh.jsx)("th",{children:"Progress"}),(0,Wh.jsx)("th",{children:"State"}),(0,Wh.jsx)("th",{children:"Waiting on"}),(0,Wh.jsx)("th",{children:"Downstream reach"})]})}),(0,Wh.jsx)("tbody",{children:q.nodes.map(e=>{const t=jh(q,e.id,{completedTaskIDs:z.completed});return(0,Wh.jsxs)("tr",{children:[(0,Wh.jsx)("th",{scope:"row",children:e.label}),(0,Wh.jsx)("td",{children:e.lane}),(0,Wh.jsxs)("td",{children:[Math.round(100*e.progress),"%"]}),(0,Wh.jsx)("td",{children:z.completed.has(e.id)?"Completed":z.blockers.has(e.id)?"Blocked":z.armed.has(e.id)?"Armed":"Waiting"}),(0,Wh.jsx)("td",{children:z.blockers.get(e.id)??(e.dependencyIDs.filter(e=>!z.completed.has(e)).join(", ")||"None")}),(0,Wh.jsxs)("td",{children:[t.downstreamTaskCount," tasks / ",t.affectedLaneCount," lanes"]})]},e.id)})})]})]}:{className:R,role:"alert",style:{width:M,maxWidth:"100%"},children:[(0,Wh.jsx)("strong",{children:"ChainReactionChart could not compile this dependency graph."}),(0,Wh.jsx)("ul",{children:q.diagnostics.map((e,t)=>(0,Wh.jsx)("li",{children:e.message},`${e.code}-${t}`))})]})});Fh.displayName="ChainReactionChart";var zh=rs;