semiotic 3.12.0 → 3.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +50 -46
- package/ai/artifact-surface-inventory.json +1 -1
- package/ai/behaviorContracts.cjs +1 -1
- package/ai/dist/diagnose-operation.js +3 -3
- package/ai/dist/mcp-server.js +1 -1
- package/ai/reference.md +15 -3
- package/ai/schema.json +908 -96
- package/ai/surface-manifest.json +1 -1
- package/ai/task-packets/compare-category-totals.json +5 -5
- package/ai/task-packets/compare-category-totals.md +2 -2
- package/ai/task-packets/correct-published-chart.json +5 -5
- package/ai/task-packets/correct-published-chart.md +2 -2
- package/ai/task-packets/index.json +6 -6
- package/ai/task-packets/update-live-chart.json +5 -5
- package/ai/task-packets/update-live-chart.md +2 -2
- package/dist/c-27DCB5T6.min.js +7 -7
- package/dist/c-2CKIGFD2.min.js +1 -1
- package/dist/c-3FATLOH4.min.js +1 -0
- package/dist/{c-STVM6CBI.min.js → c-4SCJKAWZ.min.js} +200 -200
- package/dist/c-5FUOKMH6.min.js +7 -0
- package/dist/c-AAIPWVQ5.min.js +6 -6
- package/dist/{c-2RG4WOVX.min.js → c-ALLF3Y77.min.js} +1 -1
- package/dist/{c-QMKQVCCZ.min.js → c-C5GXUHUO.min.js} +6 -6
- package/dist/c-C67QDKTU.min.js +34 -0
- package/dist/c-F76M77YC.min.js +1 -0
- package/dist/c-FEVXPKQH.min.js +1 -1
- package/dist/c-G42WVQO2.min.js +1 -0
- package/dist/c-G5A3YWTN.min.js +66 -0
- package/dist/c-H4HVKBU3.min.js +1 -0
- package/dist/c-HU3ASFKT.min.js +1 -0
- package/dist/c-I4FYCVJB.min.js +391 -0
- package/dist/{c-5L7JGWQW.min.js → c-IATPZOL7.min.js} +28 -28
- package/dist/c-IE5EBBP6.min.js +110 -0
- package/dist/c-IGONIKZL.min.js +1 -0
- package/dist/c-IKPM53JH.min.js +1 -0
- package/dist/c-IU4QZ7Y5.min.js +1 -1
- package/dist/{c-2ACLVPKF.min.js → c-K5VE57OI.min.js} +1 -1
- package/dist/c-KWJIBJ4R.min.js +1 -0
- package/dist/c-LIMFU6RD.min.js +1 -0
- package/dist/c-M4T43G76.min.js +1 -0
- package/dist/c-M7QUZZCE.min.js +1 -1
- package/dist/c-NVSINXE5.min.js +1 -0
- package/dist/{c-FAF6EV4E.min.js → c-NWRYV6ZF.min.js} +1 -1
- package/dist/c-O5GU2R5W.min.js +1 -0
- package/dist/c-OC7GNXGZ.min.js +1 -0
- package/dist/c-OV5F3DQP.min.js +1 -0
- package/dist/{c-5TAXHW7I.min.js → c-PJ5CAYAW.min.js} +1 -1
- package/dist/c-Q5LZRQGD.min.js +1 -0
- package/dist/c-QP3PXK3N.min.js +1 -0
- package/dist/c-SGZ7ZD2I.min.js +51 -0
- package/dist/c-SSKV5JPW.min.js +1 -1
- package/dist/c-THWTHWXU.min.js +37 -0
- package/dist/c-TRMNDRC4.min.js +41 -0
- package/dist/c-UP656CST.min.js +1 -1
- package/dist/c-USYOK5OX.min.js +1 -0
- package/dist/c-VI753KBO.min.js +1 -0
- package/dist/{c-TT4CTEBR.min.js → c-VLAAAFST.min.js} +1 -1
- package/dist/c-VSOQPII4.min.js +5 -5
- package/dist/c-WGDM4ZRP.min.js +26 -0
- package/dist/c-XCV7VUU3.min.js +87 -0
- package/dist/c-XGDZPYBI.min.js +1 -0
- package/dist/c-XI6CLZII.min.js +1 -0
- package/dist/{c-L4Q2YMXO.min.js → c-XLC7PKM7.min.js} +1 -1
- package/dist/{c-3YAGKCPU.min.js → c-YEB6Z35F.min.js} +1 -1
- package/dist/c-YWZBFG63.min.js +1 -0
- package/dist/c-ZMYO3NZU.min.js +2 -0
- package/dist/c-ZO36H5VH.min.js +48 -0
- package/dist/components/LinkedCharts.d.ts +6 -1
- package/dist/components/Tooltip/Tooltip.d.ts +11 -1
- package/dist/components/Tooltip/tooltipChrome.d.ts +8 -2
- package/dist/components/bundling/semioticVite.d.ts +24 -0
- package/dist/components/charts/physics/cruciblePhysics.d.ts +2 -2
- package/dist/components/charts/physics/gauntletPhysics.d.ts +2 -6
- package/dist/components/charts/physics/physicsHocUtils.d.ts +8 -1
- package/dist/components/charts/realtime/RealtimeHistogram.d.ts +2 -0
- package/dist/components/charts/shared/chartSize.d.ts +58 -0
- package/dist/components/charts/shared/chartSizeDefaults.d.ts +189 -0
- package/dist/components/charts/shared/chartSizeDefaultsAtlas.d.ts +9 -0
- package/dist/components/charts/shared/chartSizeDefaultsNetwork.d.ts +29 -0
- package/dist/components/charts/shared/chartSizeDefaultsOrdinal.d.ts +13 -0
- package/dist/components/charts/shared/chartSizeDefaultsPhysics.d.ts +41 -0
- package/dist/components/charts/shared/chartSizeDefaultsValue.d.ts +19 -0
- package/dist/components/charts/shared/chartSizeDefaultsXY.d.ts +10 -0
- package/dist/components/charts/shared/networkPerspectiveWireSchema.d.ts +3 -0
- package/dist/components/charts/shared/useChartSetup.d.ts +3 -0
- package/dist/components/charts/shared/useCustomChartSetup.d.ts +4 -0
- package/dist/components/charts/shared/useNetworkChartSetup.d.ts +2 -0
- package/dist/components/charts/shared/withChartWrapper.d.ts +6 -2
- package/dist/components/charts/value/BigNumber.d.ts +0 -8
- package/dist/components/charts/xy/minimapLayout.d.ts +10 -0
- package/dist/components/realtime/BinAccumulator.d.ts +5 -2
- package/dist/components/recipes/atlas/dependencyForestChartProps.d.ts +4 -4
- package/dist/components/recipes/atlas/flowCircuitChartProps.d.ts +177 -1
- package/dist/components/recipes/atlas/flowCircuitLayout.d.ts +3 -0
- package/dist/components/recipes/atlas/motifBraidChartProps.d.ts +2 -0
- package/dist/components/recipes/atlas/resolution/BoundaryLoomChart.d.ts +3 -0
- package/dist/components/recipes/atlas/resolution/ComponentCutaway.d.ts +16 -0
- package/dist/components/recipes/atlas/resolution/ResolutionAtlasChart.d.ts +3 -0
- package/dist/components/recipes/atlas/resolution/ResolutionGlyphs.d.ts +15 -0
- package/dist/components/recipes/atlas/resolution/ResolutionReader.d.ts +5 -0
- package/dist/components/recipes/atlas/resolution/appearance.d.ts +58 -0
- package/dist/components/recipes/atlas/resolution/boundaryLoomLayout.d.ts +4 -0
- package/dist/components/recipes/atlas/resolution/chartProps.d.ts +75 -0
- package/dist/components/recipes/atlas/resolution/componentCutawayLayout.d.ts +12 -0
- package/dist/components/recipes/atlas/resolution/cutawayContext.d.ts +23 -0
- package/dist/components/recipes/atlas/resolution/cutawayGraph.d.ts +4 -0
- package/dist/components/recipes/atlas/resolution/cycles.d.ts +7 -0
- package/dist/components/recipes/atlas/resolution/evidence.d.ts +43 -0
- package/dist/components/recipes/atlas/resolution/glyphs.d.ts +40 -0
- package/dist/components/recipes/atlas/resolution/identity.d.ts +4 -0
- package/dist/components/recipes/atlas/resolution/indexGraph.d.ts +32 -0
- package/dist/components/recipes/atlas/resolution/ownership.d.ts +25 -0
- package/dist/components/recipes/atlas/resolution/plan.d.ts +12 -0
- package/dist/components/recipes/atlas/resolution/ports.d.ts +44 -0
- package/dist/components/recipes/atlas/resolution/prepare.d.ts +4 -0
- package/dist/components/recipes/atlas/resolution/project.d.ts +70 -0
- package/dist/components/recipes/atlas/resolution/queries.d.ts +23 -0
- package/dist/components/recipes/atlas/resolution/resolutionAtlasLayout.d.ts +9 -0
- package/dist/components/recipes/atlas/resolution/rules.d.ts +14 -0
- package/dist/components/recipes/atlas/resolution/scene.d.ts +52 -0
- package/dist/components/recipes/atlas/resolution/selection.d.ts +3 -0
- package/dist/components/recipes/atlas/resolution/sets.d.ts +10 -0
- package/dist/components/recipes/atlas/resolution/types.d.ts +401 -0
- package/dist/components/recipes/atlas/resolution/validate.d.ts +4 -0
- package/dist/components/recipes/atlas/resolution/witnesses.d.ts +18 -0
- package/dist/components/recipes/atlas/resolution/worker.d.ts +34 -0
- package/dist/components/recipes/lineageDag.d.ts +4 -0
- package/dist/components/recipes/recipeUtils.d.ts +2 -0
- package/dist/components/recipes/transitDiagram.d.ts +2 -61
- package/dist/components/recipes/transitDiagramTypes.d.ts +65 -0
- package/dist/components/semiotic-ai.d.ts +2 -0
- package/dist/components/semiotic-experimental-network-resolution-react.d.ts +12 -0
- package/dist/components/semiotic-experimental-network-resolution.d.ts +13 -0
- package/dist/components/semiotic-geo.d.ts +1 -1
- package/dist/components/semiotic-network-perspective-core.d.ts +6 -0
- package/dist/components/semiotic-network.d.ts +1 -1
- package/dist/components/semiotic-ordinal.d.ts +1 -1
- package/dist/components/semiotic-physics.d.ts +1 -1
- package/dist/components/semiotic-realtime-core.d.ts +1 -1
- package/dist/components/semiotic-realtime-react.d.ts +2 -0
- package/dist/components/semiotic-utils-core.d.ts +3 -1
- package/dist/components/semiotic-vite.d.ts +2 -0
- package/dist/components/semiotic-xy.d.ts +3 -1
- package/dist/components/semiotic.d.ts +3 -1
- package/dist/components/server/renderToStaticSVG.d.ts +2 -1
- package/dist/components/server/serverChartConfigShared.d.ts +2 -0
- package/dist/components/store/LinkedCrosshairStore.d.ts +43 -11
- package/dist/components/store/themeCore.d.ts +2 -0
- package/dist/components/stream/frameKeyboardNavigation.d.ts +3 -1
- package/dist/components/stream/hoverUtils.d.ts +5 -0
- package/dist/components/stream/networkCustomLayout.d.ts +3 -0
- package/dist/components/stream/networkPerspective.d.ts +2 -0
- package/dist/components/stream/networkPerspectiveFit.d.ts +12 -1
- package/dist/components/stream/networkPerspectiveSolid.d.ts +1 -1
- package/dist/components/stream/networkSceneTypes.d.ts +4 -0
- package/dist/components/stream/networkTypes.d.ts +2 -0
- package/dist/components/stream/pipelineConfig.d.ts +2 -0
- package/dist/components/stream/pipelineDomainResolution.d.ts +4 -1
- package/dist/components/stream/types.d.ts +2 -0
- package/dist/components/stream/useFrame.d.ts +2 -0
- package/dist/components/stream/xySceneBuilders/types.d.ts +2 -0
- package/dist/controls.module.min.js +31 -31
- package/dist/geo.min.js +150 -150
- package/dist/geo.module.min.js +31 -31
- package/dist/network.module.min.js +1 -1
- package/dist/ordinal.module.min.js +1 -1
- package/dist/physics.module.min.js +1 -1
- package/dist/rough.module.min.js +1 -1
- package/dist/semiotic-ai-core.min.js +1 -1
- package/dist/semiotic-ai-core.module.min.js +1 -1
- package/dist/semiotic-ai.d.ts +2 -0
- package/dist/semiotic-ai.module.min.js +13 -13
- package/dist/semiotic-artifact-react.module.min.js +4 -4
- package/dist/semiotic-artifact.min.js +1 -1
- package/dist/semiotic-artifact.module.min.js +1 -1
- package/dist/semiotic-atlas-selection.module.min.js +1 -1
- package/dist/semiotic-atlas.module.min.js +10 -12
- package/dist/semiotic-client-cjs-shared.min.js +1078 -925
- package/dist/semiotic-client-glyph.module.min.js +2 -2
- package/dist/semiotic-client-shared.module.min.js +1 -1
- package/dist/semiotic-experimental-auxiliary.module.min.js +8 -9
- package/dist/semiotic-experimental-network-resolution-react.d.ts +12 -0
- package/dist/semiotic-experimental-network-resolution-react.min.js +2 -0
- package/dist/semiotic-experimental-network-resolution-react.module.min.js +89 -0
- package/dist/semiotic-experimental-network-resolution.d.ts +13 -0
- package/dist/semiotic-experimental-network-resolution.min.js +2 -0
- package/dist/semiotic-experimental-network-resolution.module.min.js +2 -0
- package/dist/semiotic-experimental-node-auxiliary.module.min.js +9 -10
- package/dist/semiotic-geo.d.ts +1 -1
- package/dist/semiotic-line.module.min.js +1 -1
- package/dist/semiotic-network-perspective-core.d.ts +6 -0
- package/dist/semiotic-network-perspective-core.min.js +1 -0
- package/dist/semiotic-network-perspective-core.module.min.js +1 -0
- package/dist/semiotic-network-perspective.module.min.js +1 -1
- package/dist/semiotic-network-placement.min.js +4 -0
- package/dist/semiotic-network-placement.module.min.js +4 -0
- package/dist/semiotic-network-zoom.module.min.js +1 -1
- package/dist/semiotic-network.d.ts +1 -1
- package/dist/semiotic-ordinal.d.ts +1 -1
- package/dist/semiotic-physics.d.ts +1 -1
- package/dist/semiotic-realtime-core.d.ts +1 -1
- package/dist/semiotic-realtime-core.module.min.js +1 -1
- package/dist/semiotic-realtime-react.d.ts +2 -0
- package/dist/semiotic-realtime-react.module.min.js +1 -1
- package/dist/semiotic-recipes-core-cjs-base.min.js +101 -106
- package/dist/semiotic-recipes-core.module.min.js +75 -76
- package/dist/semiotic-server-edge-node.module.min.js +391 -392
- package/dist/semiotic-server-edge.min.js +387 -388
- package/dist/semiotic-server-edge.module.min.js +371 -371
- package/dist/semiotic-server-node.min.js +387 -388
- package/dist/semiotic-server-node.module.min.js +1 -1
- package/dist/semiotic-utils-core.d.ts +3 -1
- package/dist/semiotic-utils-core.min.js +12 -11
- package/dist/semiotic-utils-core.module.min.js +12 -11
- package/dist/semiotic-value.module.min.js +4 -4
- package/dist/semiotic-vite.d.ts +2 -0
- package/dist/semiotic-vite.min.js +1 -0
- package/dist/semiotic-vite.module.min.js +1 -0
- package/dist/semiotic-xy.d.ts +3 -1
- package/dist/semiotic.d.ts +3 -1
- package/dist/semiotic.module.min.js +12 -12
- package/dist/server.min.js +387 -388
- package/dist/server.module.min.js +1 -1
- package/dist/xy.module.min.js +1 -1
- package/package.json +42 -13
- package/dist/c-2AB65V3L.min.js +0 -1
- package/dist/c-2U5JMOPN.min.js +0 -88
- package/dist/c-3DCTIRW4.min.js +0 -1
- package/dist/c-3OKFRTYM.min.js +0 -1
- package/dist/c-3VZHOPFW.min.js +0 -1
- package/dist/c-4ZSQIBC7.min.js +0 -1
- package/dist/c-5M4RUS7V.min.js +0 -34
- package/dist/c-6O5WWP7F.min.js +0 -1
- package/dist/c-73TOIYIW.min.js +0 -48
- package/dist/c-AE4M7BWH.min.js +0 -1
- package/dist/c-AEIK2NFW.min.js +0 -30
- package/dist/c-AFQSEIZ4.min.js +0 -4
- package/dist/c-BBX7DVVB.min.js +0 -51
- package/dist/c-CNYFCSG4.min.js +0 -5
- package/dist/c-E6QH2WYE.min.js +0 -1
- package/dist/c-GOMQWQJR.min.js +0 -1
- package/dist/c-GTYG4PDT.min.js +0 -1
- package/dist/c-H23GIKTK.min.js +0 -1
- package/dist/c-HQLUUSRJ.min.js +0 -1
- package/dist/c-HXUOFDSD.min.js +0 -64
- package/dist/c-L3LKYOLK.min.js +0 -1
- package/dist/c-MIKDFGKH.min.js +0 -1
- package/dist/c-OYSPTIAG.min.js +0 -1
- package/dist/c-PWPJNYQP.min.js +0 -1
- package/dist/c-QZ5SWKHC.min.js +0 -392
- package/dist/c-RXJH4IRX.min.js +0 -41
- package/dist/c-SN2D6QMH.min.js +0 -1
- package/dist/c-U5YGK6HL.min.js +0 -1
- package/dist/c-VIN5ASK2.min.js +0 -37
- package/dist/c-XZ3GASUJ.min.js +0 -1
- package/dist/c-ZLZZTH4I.min.js +0 -118
|
@@ -1,206 +1,206 @@
|
|
|
1
|
-
import{a as e}from"./c-LVHJJUOF.min.js";import{a as t}from"./c-GU2FIJ7F.min.js";import{a as i,b as r,c as n,d as o,e as s,f as a,g as l,h as d,i as c,j as u,k as h,l as p,m,n as y,o as f,p as g}from"./c-
|
|
2
|
-
return
|
|
3
|
-
/* @__PURE__ */
|
|
4
|
-
/* @__PURE__ */
|
|
5
|
-
/* @__PURE__ */ze(Y,{title:s,totalWidth:r,marginTop:Math.max(o.top,28)}),a?I({legend:a,totalWidth:r,totalHeight:n,margin:o,legendPosition:h,legendLayout:p,title:s,legendHoverBehavior:l,legendClickBehavior:d,legendHighlightedCategory:c,legendIsolatedCategories:u}):null]})]})}function Ye(e){let t=e.fixedPosition;Number.isFinite(t?.x)&&(e.x=e.prevX=t.x,e.vx=0),Number.isFinite(t?.y)&&(e.y=e.prevY=t.y,e.vy=0)}function _e(e){if(!e)return;let t=Number.isFinite(e.x)?e.x:void 0,i=Number.isFinite(e.y)?e.y:void 0;return null==t&&null==i?void 0:{x:t,y:i}}function Xe(e,t,i){let r,n="x"===i?"y":"x",o=Math.abs(t[i]-e[i]),s=t[n]-e[n],a=(e,t)=>"circle"===e.shape.type?e.shape.radius:("x"===t?e.shape.width:e.shape.height)/2;if("circle"===e.shape.type&&"circle"===t.shape.type){let i=e.shape.radius+t.shape.radius;r=Math.sqrt(Math.max(0,i*i-o*o))}else if("aabb"===e.shape.type&&"aabb"===t.shape.type)r=a(e,n)+a(t,n);else{let s="circle"===e.shape.type?e:t,l="aabb"===e.shape.type?e:t,d=a(s,i),c=Math.max(0,o-a(l,i));r=a(l,n)+Math.sqrt(Math.max(0,d*d-c*c))}let l=s<0?-1:1;return{nx:"x"===n?l:0,ny:"y"===n?l:0,penetration:Math.max(0,r-Math.abs(s))}}function Ge(e){return"circle"===e.type?{type:"circle",radius:e.radius}:{type:"aabb",width:e.width,height:e.height}}function Ve(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 Ue(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,...e.fixedPosition?{fixedPosition:_e(e.fixedPosition)}:{},shape:Ge(e.shape),sleeping:e.sleeping,datum:e.datum,index:e.index,sleepTime:e.sleepTime,restitution:e.restitution,friction:e.friction}}function Ke(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 Qe(e){return{id:e.id,shape:Ve(e.shape),sensor:e.sensor,restitution:e.restitution,friction:e.friction,bodyFilter:Ke(e.bodyFilter),index:e.index}}function Je(e,t,i){if("aabb"!==t.type)return null;let r=e.x-e.prevX,n=e.y-e.prevY;if(0===r&&0===n)return null;let o="circle"===e.shape.type?e.shape.radius:e.shape.width/2,s="circle"===e.shape.type?e.shape.radius:e.shape.height/2,a=t.x-t.width/2,l=t.x+t.width/2,d=t.y-t.height/2,c=t.y+t.height/2;if(Math.max(e.x,e.prevX)+o<a||Math.min(e.x,e.prevX)-o>l||Math.max(e.y,e.prevY)+s<d||Math.min(e.y,e.prevY)-s>c)return null;let u="circle"===e.shape.type?0:o,h="circle"===e.shape.type?0:s,p=1/0,m=null,y=(e,t,r,n,o,s,a,l,d,c,u)=>{let h,y,f;if(r>0&&t+n<=o+i&&e+n>o)h=Math.max(0,(o-n-t)/r),y=e+n-o,f=-1;else{if(!(r<0&&t-n>=s-i&&e-n<s))return;h=Math.max(0,(s+n-t)/r),y=s-(e-n),f=1}let g=a+l*h;h<p&&g>=d&&g<=c&&(p=h,m={nx:u?f:0,ny:u?0:f,penetration:y})};return y(e.x,e.prevX,r,o,a,l,e.prevY,n,d-h,c+h,!0),y(e.y,e.prevY,n,s,d,c,e.prevX,r,a-u,l+u,!1),m}function Ze(e,t){return Math.abs(e.x-t.x)<=t.padding&&Math.abs(e.y-t.y)<=t.padding}function et(e,t){let i=tt(e),r=[];for(let e=0;e<t.length;e++)nt(i,t[e].bounds)&&r.push(e);return{bounds:i,indexes:r}}function tt(e,t=!0){let i="circle"===e.shape.type?e.shape.radius:e.shape.width/2,r="circle"===e.shape.type?e.shape.radius:e.shape.height/2,n=t?Math.max(.005,Math.min(i,r)):0;return{x:e.x,y:e.y,padding:n,minX:Math.min(e.x,e.prevX)-i-n,minY:Math.min(e.y,e.prevY)-r-n,maxX:Math.max(e.x,e.prevX)+i+n,maxY:Math.max(e.y,e.prevY)+r+n}}function it(e){let t="circle"===e.shape.type?e.shape.radius:e.shape.width/2,i="circle"===e.shape.type?e.shape.radius:e.shape.height/2;return{minX:e.x-t,minY:e.y-i,maxX:e.x+t,maxY:e.y+i}}function rt(e){let t=e.shape;if("aabb"===t.type)return it({x:t.x,y:t.y,shape:t});let i=(t.thickness??0)/2;return{minX:Math.min(t.x1,t.x2)-i,minY:Math.min(t.y1,t.y2)-i,maxX:Math.max(t.x1,t.x2)+i,maxY:Math.max(t.y1,t.y2)+i}}function nt(e,t){return e.minX<=t.maxX&&e.maxX>=t.minX&&e.minY<=t.maxY&&e.maxY>=t.minY}function ot(e,t,i={x:0,y:0}){let r=1,n=e.map(e=>{let t=tt(e,!(e.sleeping&&e.x===e.prevX&&e.y===e.prevY));return!1!==e.bodyCollisions&&(r=Math.max(r,t.maxX-t.minX,t.maxY-t.minY)),t}),o=Math.max(1,Math.min(t,r)),s=/* @__PURE__ */new Map;for(let t=0;t<e.length;t+=1){if(!1===e[t].bodyCollisions)continue;let i=n[t];i.cellX=Math.floor(i.minX/o),i.cellY=Math.floor(i.minY/o);for(let e=i.cellX;e<=Math.floor(i.maxX/o);e+=1){let r=s.get(e);r||s.set(e,r=/* @__PURE__ */new Map);for(let e=i.cellY;e<=Math.floor(i.maxY/o);e+=1){let i=r.get(e);i?i.push(t):r.set(e,[t])}}}let a=[];for(let[e,t]of s)for(let[i,r]of t)for(let t=0;t<r.length;t+=1)for(let o=t+1;o<r.length;o+=1){let s=r[t],l=r[o],d=n[s],c=n[l];e!==Math.max(d.cellX,c.cellX)||i!==Math.max(d.cellY,c.cellY)||nt(d,c)&&a.push([s,l])}let l=e.map(e=>e.x*i.x+e.y*i.y);return a.sort(([e,t],[i,r])=>Math.max(l[i],l[r])-Math.max(l[e],l[t])||(e===i?t-r:e-i)),{pairs:a,coversPositions:()=>e.every((e,t)=>!1===e.bodyCollisions||Ze(e,n[t]))}}function st(e,t){if("circle"!==e.shape.type||"circle"!==t.shape.type)return null;let i=e.shape.radius+t.shape.radius;if(i<=0)return null;let r=t.prevX-e.prevX,n=t.prevY-e.prevY,o=t.x-e.x-r,s=t.y-e.y-n,a=o*o+s*s,l=2*(r*o+n*s),d=r*r+n*n-i*i;if(d<-1e-5||a<=1e-12||l>=0)return null;let c=l*l-4*a*d;if(c<0)return null;let u=(-l-Math.sqrt(c))/(2*a);if(u<0||u>1)return null;let h=(r+u*o)/i,p=(n+u*s)/i,m=i-((t.x-e.x)*h+(t.y-e.y)*p);return m>0?{nx:h,ny:p,penetration:m}:null}var at={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},lt=1e-9,dt=.005;function ct(e,t,i){return Math.max(t,Math.min(i,e))}function ut(e,t,i){return Math.min(e??i,t??i)}function ht(e,t,i){return ct(Math.max(e??i,t??i),0,1)}function pt(e){return e<0?-1:1}function mt(e){return e.sleeping&&e.x===e.prevX&&e.y===e.prevY}function yt(e,t,i,r,n,o){let s=r-e,a=n-t,l=i+o,d=s*s+a*a;if(d>=l*l)return null;if(d<=lt)return{nx:1,ny:0,penetration:l};let c=Math.sqrt(d);return{nx:s/c,ny:a/c,penetration:l-c}}function ft(e,t,i,r,n,o,s,a){let l=n-e,d=(i+s)/2-Math.abs(l);if(d<=0)return null;let c=o-t,u=(r+a)/2-Math.abs(c);return u<=0?null:d<u?{nx:pt(l),ny:0,penetration:d}:{nx:0,ny:pt(c),penetration:u}}function gt(e,t,i,r,n,o,s){let a=o/2,l=s/2,d=e-ct(e,r-a,r+a),c=t-ct(t,n-l,n+l),u=d*d+c*c;if(u>i*i)return null;if(u<=lt){let o=Math.abs(e-(r-a)),s=Math.abs(e-(r+a)),d=Math.abs(t-(n-l)),c=Math.abs(t-(n+l)),u=Math.min(o,s,d,c);return u===o?{nx:-1,ny:0,penetration:i+o}:u===s?{nx:1,ny:0,penetration:i+s}:u===d?{nx:0,ny:-1,penetration:i+d}:{nx:0,ny:1,penetration:i+c}}let h=Math.sqrt(u);return{nx:d/h,ny:c/h,penetration:i-h}}function bt(e,t,i,r,n,o,s,a=0){let l=o-r,d=s-n,c=l*l+d*d,u=c<=lt?0:ct(((e-r)*l+(t-n)*d)/c,0,1),h=i+a/2,p=e-(r+l*u),m=t-(n+d*u),y=p*p+m*m;if(y>=h*h)return null;if(y<=lt){let e=Math.sqrt(c);return e<=lt?{nx:1,ny:0,penetration:h}:{nx:-d/e,ny:l/e,penetration:h}}let f=Math.sqrt(y);return{nx:p/f,ny:m/f,penetration:h-f}}function vt(e,t){if("circle"===e.shape.type&&"circle"===t.shape.type)return yt(e.x,e.y,e.shape.radius,t.x,t.y,t.shape.radius);if("aabb"===e.shape.type&&"aabb"===t.shape.type)return ft(e.x,e.y,e.shape.width,e.shape.height,t.x,t.y,t.shape.width,t.shape.height);let i="circle"===e.shape.type?e:t,r=i===e?t:e;if("circle"!==i.shape.type||"aabb"!==r.shape.type)return null;let n=gt(i.x,i.y,i.shape.radius,r.x,r.y,r.shape.width,r.shape.height);return n&&i===e&&(n.nx=-n.nx,n.ny=-n.ny),n}function xt(e,t){let i=t.shape;if("aabb"===i.type)return"circle"===e.shape.type?gt(e.x,e.y,e.shape.radius,i.x,i.y,i.width,i.height):ft(i.x,i.y,i.width,i.height,e.x,e.y,e.shape.width,e.shape.height);let r="circle"===e.shape.type?e.shape.radius:Math.sqrt(e.shape.width*e.shape.width+e.shape.height*e.shape.height)/2;return bt(e.x,e.y,r,i.x1,i.y1,i.x2,i.y2,i.thickness??0)}function wt(e,t){return`${e}\0${t}`}function It(e){let t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}function kt(e,t){if(!t)return;let i=e;for(let e of t.split(".")){if(null==i||"object"!=typeof i||!Object.prototype.hasOwnProperty.call(i,e))return;i=i[e]}return i}function St(e,t){return!!t?.some(t=>Object.is(e,t))}function Mt(e,t){if(!t)return!0;if("function"==typeof t)return t(e);let i=kt(e,t.property);return!("equals"in t&&!Object.is(i,t.equals)||"notEquals"in t&&Object.is(i,t.notEquals)||t.oneOf&&!St(i,t.oneOf)||t.notOneOf&&St(i,t.notOneOf))}function At(e,t){return Mt(t,e.bodyFilter)}var $t=class{constructor(e={}){this.capabilities={determinism:"strict",sensors:!0,joints:!1,ccd:!1,maxBodiesHint:5e3,worker:!1},this.bodies=/* @__PURE__ */new Map,this.colliders=/* @__PURE__ */new Map,this.springs=/* @__PURE__ */new Map,this.activeSensors=/* @__PURE__ */new Set,this.supportedThisStep=/* @__PURE__ */new Set,this.supportDependents=/* @__PURE__ */new Map,this.supportContactsThisStep=/* @__PURE__ */new Set,this.reboundingThisStep=/* @__PURE__ */new Set,this.interpenetratingThisStep=/* @__PURE__ */new Set,this.lastEvents=[],this.nextBodyIndex=0,this.nextColliderIndex=0,this.nextSpringIndex=0,this.options={...at,...e},this.random=b(this.options.seed)}init(e={}){this.options={...at,...e},this.random=b(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){let 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(lt,e.mass??1),bodyCollisions:e.bodyCollisions??!0,...e.fixedPosition?{fixedPosition:_e(e.fixedPosition)}:{},shape:Ge(e.shape),sleeping:!1,datum:e.datum,restitution:e.restitution,friction:e.friction,index:this.nextBodyIndex,sleepTime:0};Ye(t),this.nextBodyIndex+=1,this.bodies.set(e.id,t)}remove(e){for(let t of e){this.bodies.delete(t);for(let e of Array.from(this.activeSensors))It(e).bodyId===t&&this.activeSensors.delete(e)}}setColliders(e){this.colliders.clear(),this.activeSensors.clear(),this.nextColliderIndex=0;for(let t of e)this.colliders.set(t.id,{...t,shape:Ve(t.shape),bodyFilter:Ke(t.bodyFilter),index:this.nextColliderIndex}),this.nextColliderIndex+=1}setConstraint(e){let 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,i){let r=this.bodies.get(e);r&&(r.vx+=t/r.mass,r.vy+=i/r.mass,Ye(r),this.wake(r))}step(e=this.options.fixedDt){let t=Math.max(0,e);if(this.lastEvents=[],0===t)return;this.reboundingThisStep.clear();let i=this.sortedBodies();for(let e of i)e.prevX=e.x,e.prevY=e.y;this.applySprings(t);let r=this.options.maxVelocity;for(let e of i)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,Ye(e),r>0){let t=Math.sqrt(e.vx*e.vx+e.vy*e.vy);if(t>r){let i=r/t;e.vx*=i,e.vy*=i}}e.x+=e.vx*t,e.y+=e.vy*t}this.supportedThisStep.clear(),this.supportDependents.clear(),this.supportContactsThisStep.clear(),this.interpenetratingThisStep.clear();let n=this.sortedColliders().filter(e=>!e.sensor).map(e=>({collider:e,bounds:rt(e)})),o=n.some(({collider:e})=>e.bodyFilter)?void 0:new Array(i.length);this.resolveColliders(i,n,!1,o);let s=o&&i.map(mt),a=ot(i,this.options.cellSize,this.options.gravity);for(let e=0;e<this.options.collisionIterations;e+=1){e>0&&!a.coversPositions()&&(a=ot(i,this.options.cellSize,this.options.gravity));let t=this.resolveBodyPairs(i,a.pairs,0===e,s),r=this.resolveColliders(i,n,0===e,o);if(o&&!t&&!r)break}a.coversPositions()||(a=ot(i,this.options.cellSize,this.options.gravity));for(let[e,t]of a.pairs){let r=vt(i[e],i[t]);r&&r.penetration>.02&&(this.interpenetratingThisStep.add(i[e].id),this.interpenetratingThisStep.add(i[t].id))}let l=Array.from(this.supportedThisStep);for(let e=0;e<l.length;e+=1)for(let t of this.supportDependents.get(l[e])??[])this.supportedThisStep.has(t)||(this.supportedThisStep.add(t),l.push(t));this.reconcileSupportedVelocity(i,t),this.updateSensors(i),this.updateSleeping(i,t)}settle(e=1200,t=this.options.fixedDt){let i=0;for(;i<e&&!this.allSleeping();)this.step(t),i+=1;return i}readState(e=[]){e.length=0;for(let 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,...t.fixedPosition?{fixedPosition:_e(t.fixedPosition)}:{},shape:Ge(t.shape),sleeping:t.sleeping,datum:t.datum});return e}events(){return this.lastEvents.slice()}activeSensorPairs(){return Array.from(this.activeSensors).sort().map(It)}allSleeping(){for(let 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(Ue),colliders:this.sortedColliders().map(Qe),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=b(this.options.seed),this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors=new Set(e.activeSensors),this.lastEvents=[],this.nextBodyIndex=0;for(let t of e.bodies){let e=Ue(t);Ye(e),this.bodies.set(e.id,e),this.nextBodyIndex=Math.max(this.nextBodyIndex,e.index+1)}this.nextColliderIndex=0;for(let t of e.colliders){let e=Qe(t);this.colliders.set(e.id,e),this.nextColliderIndex=Math.max(this.nextColliderIndex,e.index+1)}this.nextSpringIndex=0;for(let t of e.springs){this.springs.set(t.id,{...t,target:{...t.target}});let 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(let t of Array.from(this.springs.values()).sort((e,t)=>e.id.localeCompare(t.id))){let i=this.bodies.get(t.bodyId);if(!i||i.sleeping)continue;let r="point"===t.target.type?t.target:this.bodies.get(t.target.bodyId);if(!r)continue;let n=r.x-i.x,o=r.y-i.y,s=n*n+o*o,a=Math.sqrt(s);if(a<=lt)continue;let l=n/a,d=o/a,c="vx"in r?r.vx:0,u="vy"in r?r.vy:0,h=(c-i.vx)*l+(u-i.vy)*d,p=(a-t.restLength)*t.stiffness+h*t.damping;i.vx+=p*l*e/i.mass,i.vy+=p*d*e/i.mass}}resolveBodyPairs(e,t,i,r){let n=!1;for(let[o,s]of t){let t=e[o],a=e[s];if(!t||!a)continue;if(!i&&r?.[o]&&r[s]&&mt(t)&&mt(a)){n=!0;continue}let l=st(t,a)??vt(t,a);l&&(n=!0,this.resolveDynamicCollision(t,a,l),i&&this.lastEvents.push({type:"contact",bodyId:t.id,otherId:a.id,sensor:!1}))}return n}resolveDynamicCollision(e,t,i){(e.fixedPosition||t.fixedPosition)&&(!e.sleeping&&null==e.fixedPosition?.x||!t.sleeping&&null==t.fixedPosition?.x?(e.sleeping||null!=e.fixedPosition?.y)&&(t.sleeping||null!=t.fixedPosition?.y)&&(i=Xe(e,t,"y")):i=Xe(e,t,"x"));let r=this.options.gravity,n=Math.hypot(r.x,r.y),o=this.contactOpposesGravity(i.nx,i.ny,n),s=this.contactOpposesGravity(-i.nx,-i.ny,n);o&&(e.sleeping&&this.supportedThisStep.add(t.id),this.addSupportContact(e.id,t.id)),s&&(t.sleeping&&this.supportedThisStep.add(e.id),this.addSupportContact(t.id,e.id));let a=e.sleeping?0:1/e.mass,l=t.sleeping?0:1/t.mass,d=null==e.fixedPosition?.x?a:0,c=null==e.fixedPosition?.y?a:0,u=null==t.fixedPosition?.x?l:0,h=null==t.fixedPosition?.y?l:0,p=e.fixedPosition||t.fixedPosition?i.nx**2*(d+u)+i.ny**2*(c+h):a+l;if(p<=lt)return;let m=this.supportedThisStep.has(e.id)&&o&&!t.sleeping&&!t.fixedPosition,y=this.supportedThisStep.has(t.id)&&s&&!e.sleeping&&!e.fixedPosition,f=n>1,g=f&&m?0:d,b=f&&m?0:c,v=f&&!m&&y?0:u,x=f&&!m&&y?0:h,w=i.nx**2*(g+v)+i.ny**2*(b+x),I=Math.max(0,i.penetration-dt)/Math.max(lt,w);e.x-=i.nx*I*g,e.y-=i.ny*I*b,t.x+=i.nx*I*v,t.y+=i.ny*I*x,f&&m&&this.supportedThisStep.add(t.id),f&&y&&this.supportedThisStep.add(e.id);let k=t.vx-e.vx,S=t.vy-e.vy,M=k*i.nx+S*i.ny;if(M>0)return;let A=Math.abs(M),$=ut(e.restitution,t.restitution,this.options.restitution),C=e.vx*r.x+e.vy*r.y,P=t.vx*r.x+t.vy*r.y,R=-(1+$)*M/p,D=R*i.nx,B=R*i.ny;e.vx-=D*d,e.vy-=B*c,t.vx+=D*u,t.vy+=B*h,this.applyFriction(e,t,i,R,d,c,u,h),$>0&&(C>=0&&e.vx*r.x+e.vy*r.y<0&&this.reboundingThisStep.add(e.id),P>=0&&t.vx*r.x+t.vy*r.y<0&&this.reboundingThisStep.add(t.id)),A>this.options.contactWakeSpeed&&(this.wake(e),this.wake(t))}applyFriction(e,t,i,r,n,o,s,a){let l=-i.ny,d=i.nx,c=(t.vx-e.vx)*l+(t.vy-e.vy)*d,u=e.fixedPosition||t.fixedPosition?l**2*(n+s)+d**2*(o+a):n+s;if(Math.abs(c)<=lt||u<=lt)return;let h=ht(e.friction,t.friction,this.options.friction),p=ct(-c/u,-r*h,r*h),m=p*l,y=p*d;e.vx-=m*n,e.vy-=y*o,t.vx+=m*s,t.vy+=y*a}resolveColliders(e,t,i,r){if(0===t.length)return!1;let n=!1;for(let o=0;o<e.length;o++){let s=e[o],a=r?.[o];r&&(!a||!Ze(s,a.bounds))&&(r[o]=a=et(s,t));let l=0;for(;l<(a?a.indexes.length:t.length);){let e=a?a.indexes[l++]:l++,{collider:d,bounds:c}=t[e];if(!At(d,s))continue;let u=Je(s,d.shape,dt+lt);if(!u&&!nt(it(s),c))continue;let h=u??xt(s,d);if(h&&(n=!0,this.resolveStaticCollision(s,d,h),this.contactOpposesGravity(h.nx,h.ny)&&this.supportedThisStep.add(s.id),i&&this.lastEvents.push({type:"contact",bodyId:s.id,otherId:d.id,sensor:!1}),a&&r&&!Ze(s,a.bounds)))for(r[o]=a=et(s,t),l=0;l<a.indexes.length&&a.indexes[l]<=e;)l++}}return n}resolveStaticCollision(e,t,i){e.x+=i.nx*Math.max(0,i.penetration-dt),e.y+=i.ny*Math.max(0,i.penetration-dt);let r=e.vx*i.nx+e.vy*i.ny;if(r<0){let n=ut(e.restitution,t.restitution,this.options.restitution),o=this.options.gravity,s=e.vx*o.x+e.vy*o.y;e.vx-=(1+n)*r*i.nx,e.vy-=(1+n)*r*i.ny;let a=-i.ny,l=i.nx,d=e.vx*a+e.vy*l,c=ht(e.friction,t.friction,this.options.friction);e.vx-=d*a*c,e.vy-=d*l*c,n>0&&s>=0&&e.vx*o.x+e.vy*o.y<0&&this.reboundingThisStep.add(e.id)}Ye(e)}updateSensors(e){let t=this.sortedColliders().filter(e=>e.sensor);if(0===t.length&&0===this.activeSensors.size)return;let i=/* @__PURE__ */new Set;for(let r of e){let e=it(r);for(let n of t){if(!At(n,r)||!nt(e,rt(n))||!xt(r,n))continue;let t=wt(n.id,r.id);i.add(t),this.activeSensors.has(t)||this.lastEvents.push({type:"sensor-enter",bodyId:r.id,sensorId:n.id})}}for(let e of Array.from(this.activeSensors).sort()){if(i.has(e))continue;let{sensorId:t,bodyId:r}=It(e);this.lastEvents.push({type:"sensor-exit",bodyId:r,sensorId:t})}this.activeSensors=i}updateSleeping(e,t){let i=Math.hypot(this.options.gravity.x,this.options.gravity.y)>1;for(let r of e){let e=Math.sqrt(r.vx*r.vx+r.vy*r.vy),n=Math.sqrt((r.x-r.prevX)*(r.x-r.prevX)+(r.y-r.prevY)*(r.y-r.prevY));e<this.options.sleepSpeed&&n<this.options.sleepSpeed*t&&!this.interpenetratingThisStep.has(r.id)&&(!i||this.supportedThisStep.has(r.id))?(r.sleepTime+=t,!r.sleeping&&r.sleepTime>=this.options.sleepAfter&&(r.sleeping=!0,r.vx=0,r.vy=0,this.lastEvents.push({type:"sleep",bodyId:r.id}))):r.sleeping?this.wake(r):r.sleepTime=0}}addSupportContact(e,t){let i=this.supportDependents.get(e);i?.has(t)||(this.supportContactsThisStep.add(e),this.supportContactsThisStep.add(t),i||(i=/* @__PURE__ */new Set,this.supportDependents.set(e,i)),i.add(t))}reconcileSupportedVelocity(e,t){let i=this.options.gravity;if(!(Math.hypot(i.x,i.y)<=1))for(let r of e)r.sleeping||!this.supportedThisStep.has(r.id)||!this.supportContactsThisStep.has(r.id)||this.reboundingThisStep.has(r.id)&&r.vx*i.x+r.vy*i.y<0||(r.vx=(r.x-r.prevX)/t,r.vy=(r.y-r.prevY)/t,Ye(r))}contactOpposesGravity(e,t,i){let{x:r,y:n}=this.options.gravity;return i??(i=Math.hypot(r,n)),i<=1e-9||(e*r+t*n)/i<-.2}wake(e){e.sleeping&&this.lastEvents.push({type:"wake",bodyId:e.id}),e.sleeping=!1,e.sleepTime=0}nextRandom(){return this.random()}},Ct=class{constructor(e={}){this.id="builtin",this.capabilities={...(new $t).capabilities,engine:"builtin"},this.world=new $t(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,i){this.world.applyImpulse(e,t,i)}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 Pt(e={}){return new Ct(e)}function Rt(e,t={}){return e?"function"==typeof e?e(t):(e.init(t),e):Pt(t)}var Dt=["binId","targetBin","category","windowIndex","lane","group"];function Bt(){return{count:0,total:0,mean:0,m2:0,min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY}}function Tt(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);let i=t-e.mean;e.mean+=i/e.count;let r=t-e.mean;e.m2+=i*r}function jt(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 Ot(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:Number.POSITIVE_INFINITY,max:e.count>0?e.max:Number.NEGATIVE_INFINITY}}function Et(e,t){let i=e;if(null!=i[t])return i[t];let r=e.datum;return r&&"object"==typeof r?r[t]:void 0}function Nt(e,t,i){return"function"==typeof e?e(t,i):"string"==typeof e?Et(t,e):void 0}function Ft(e,t,i){if("number"==typeof e)return e;let r="function"==typeof e?e(t,i):"string"==typeof e?Et(t,e):1,n="number"==typeof r?r:Number(r);return Number.isFinite(n)?n:1}function Wt(e){if(null==e)return;let t=String(e);return t.trim()?t:void 0}function qt(e){for(let t of Dt){let i=Wt(Et(e,t));if(i)return i}return"sediment"}function zt(e){let t=jt(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:jt(e.x),y:jt(e.y),value:t}}var Ht=class{constructor(e=!1){this.bins=/* @__PURE__ */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;let t=this.nextIndex;this.nextIndex+=1;let i=Wt(Nt(this.config.binAccessor,e,t))??qt(e),r=Wt(Nt(this.config.labelAccessor,e,t))??i,n=Ft(this.config.valueAccessor,e,t),o=Math.max(0,Math.floor(this.config.retainBodyIds??12)),s=this.bins.get(i);return s||(s={id:i,label:r,bodyIds:[],x:Bt(),y:Bt(),value:Bt()},this.bins.set(i,s)),s.label=r,s.lastBodyId=e.id,s.lastDatum=e.datum,Tt(s.x,e.x),Tt(s.y,e.y),Tt(s.value,n),o>0&&(s.bodyIds.push(e.id),s.bodyIds.length>o&&(s.bodyIds=s.bodyIds.slice(s.bodyIds.length-o))),zt(s)}clear(){this.bins.clear(),this.nextIndex=0}snapshot(){return Array.from(this.bins.values()).map(zt)}restore(e=[]){this.bins.clear();for(let 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:Ot(t.x),y:Ot(t.y),value:Ot(t.value)});this.nextIndex=e.reduce((e,t)=>e+t.count,0)}totals(){let 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 Lt(e,t={}){let{baselineY:i=0,binWidth:r=24,gap:n=2,maxHeight:o=80,value:s="count",x:a}=t,l=e.reduce((e,t)=>Math.max(e,t[s]),1);return e.map((e,t)=>{let d=Math.max(0,e[s]/l*o),c=a?.(e,t)??t*(r+n);return{binId:e.id,label:e.label,index:t,count:e.count,total:e.total,x:c,y:i-d,width:r,height:d,meanX:e.x.mean,meanY:e.y.mean}})}function Yt(e){let t=Number(e);if(Number.isFinite(t)&&!(t<=0))return Math.floor(t)}function _t(e,t,i){if(!1===i)return;let r=Yt(i?.warnAt);return null!=r?r:null!=e?Math.max(1,Math.floor(.8*e)):null!=t?Math.max(1,Math.floor(.8*t)):void 0}function Xt(e){let t=Math.max(0,Math.floor(e.liveBodies)),i=Math.max(0,Math.floor(e.queuedBodies??0)),r=t+i,n=Yt(e.bodyLimit),o=Yt(e.engineMaxBodiesHint),s=_t(n,o,e.options),a=null==n?0:Math.max(0,t-n),l=a>0?"overflow":null!=s&&r>=s?"warning":"ok";return{action:"overflow"!==l?"continue":e.sedimentEnabled?"sediment":e.evictionEnabled?"evict":"retain",bodyLimit:n,engineMaxBodiesHint:o,liveBodies:t,overflow:a,projectedBodies:r,queuedBodies:i,state:l,warnAt:s}}var Gt={bodyLimit:Number.POSITIVE_INFINITY,eviction:"oldest",fixedDt:1/120,maxDeltaSeconds:.1,maxSubsteps:8,settleStepLimit:1200,timeScale:1},Vt={chartId:"physics",chartType:"physics",sensors:{},onObservation:void 0,onSimulationStateChange:void 0};function Ut(e={},t=Vt){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 Kt(e){return{...e,shape:{...e.shape},...e.fixedPosition?{fixedPosition:{...e.fixedPosition}}:{},datum:e.datum,springs:e.springs?.map(e=>({...e,target:{...e.target}}))}}function Qt(e){if(e instanceof Date){let t=e.getTime();return Number.isFinite(t)?t:void 0}let t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:void 0}function Jt(e,t){let i=e;if(null!=i[t])return i[t];let r=e.datum;return r&&"object"==typeof r?r[t]:void 0}function Zt(e,t,i){return"function"==typeof i?Qt(i(e,t)):"string"==typeof i?Qt(Jt(e,i)):Qt(e.spawnAt)??Qt(Jt(e,"arrivalTime"))??Qt(Jt(e,"timestamp"))??Qt(Jt(e,"time"))??Qt(Jt(e,"eventTime"))}function ei(e,t={}){let i=Qt(t.startAt)??0,r=t.pacing??"immediate";if("arrival"===r){let r=1/0,n=e.map((e,i)=>{let n=Zt(e,i,t.timeAccessor);return null!=n&&(r=Math.min(r,n)),n}),o=Qt(t.timeScale)??1,s=o>0?o:1;return e.map((e,t)=>{let o=n[t],a=null==o?0:Math.max(0,o-r);return{...Kt(e),spawnAt:i+a/s}})}if("object"==typeof r){let t=Qt(r.ratePerSec);if(t&&t>0)return e.map((e,r)=>({...Kt(e),spawnAt:i+r/t}))}return e.map(e=>({...Kt(e),spawnAt:i}))}function ti(e){return{...Kt(e),sequence:e.sequence,spawnAt:e.spawnAt}}function ii(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 ri(e){return!1!==e&&{...e}}function ni(e,t){return e.spawnAt===t.spawnAt?e.sequence-t.sequence:e.spawnAt-t.spawnAt}function oi(e){return{...e,gravity:{...e.gravity}}}function si(e){return"circle"===e.shape.type?e.shape.radius:Math.hypot(e.shape.width,e.shape.height)/2}function ai(e,t,i,r){if("circle"===e.shape.type){let n=e.x-t,o=e.y-i,s=e.shape.radius+r,a=n*n+o*o;return a<=s*s?a:null}let n=Math.max(Math.abs(t-e.x)-e.shape.width/2,0),o=Math.max(Math.abs(i-e.y)-e.shape.height/2,0),s=n*n+o*o;return s<=r*r?s:null}function li(e,t){return`${e}\0${t}`}function di(e){let t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}function ci(e,t={}){let{idPrefix:i="plot",includeFloor:r=!0,includeCeiling:n=!1,includeLeftWall:o=!0,includeRightWall:s=!0,wallThickness:a=20,floorThickness:l=a}=t,d=[],c=e.x+e.width/2,u=e.y+e.height/2,h=(e,t,r,n,o)=>{d.push({id:`${i}-${e}`,shape:{type:"aabb",x:t,y:r,width:n,height:o}})};return r&&h("floor",c,e.y+e.height+l/2,e.width+2*a,l),n&&h("ceiling",c,e.y-l/2,e.width+2*a,l),o&&h("left-wall",e.x-a/2,u,a,e.height+2*l),s&&h("right-wall",e.x+e.width+a/2,u,a,e.height+2*l),d}function ui(e){let{idPrefix:t="bin",count:i,domainStart:r,domainStep:n,xScale:o,yTop:s,yBottom:a,wallThickness:l=4,includeBoundaryWalls:d=!0,includeInteriorWalls:c=!0,closedBefore:u,lidY:h=s,lidThickness:p=Math.max(2,l)}=e,m=[],y=s+(a-s)/2,f=Math.abs(a-s),g=d?i:i-1;if(c||d)for(let e=d?0:1;e<=g;e+=1){if(!c&&e>0&&e<i)continue;let s=o(r+e*n);m.push({id:`${t}-wall-${e}`,shape:{type:"aabb",x:s,y:y,width:l,height:f}})}if(null!=u)for(let e=0;e<i;e+=1){let i=r+e*n,s=i+n;if(s>=u)continue;let a=o(i),d=o(s);m.push({id:`${t}-lid-${e}`,shape:{type:"segment",x1:Math.min(a,d)+l/2,y1:h,x2:Math.max(a,d)-l/2,y2:h,thickness:p}})}return m}import{quadtree as hi}from"d3-quadtree";var pi=class{constructor(){this.maxSearchRadius=0,this.revision=-1,this.tree=null}hitTest(e,t,i,r,n,o=0,s){let a=this.ensure(e,t);if(!a)return null;let l=null,d=Number.POSITIVE_INFINITY,c=Math.max(0,s?.searchRadius??Math.max(0,o)+this.maxSearchRadius),u=r-c,h=r+c,p=n-c,m=n+c;return a.visit((e,t,a,c,y)=>{if(c<u||t>h||y<p||a>m)return!0;if(e.length)return!1;let f=e;for(;f;){let e=f.data;if(e&&(!s?.include||s.include(e))){let t=s?.distanceSquared?s.distanceSquared(e,r,n):ai(e,r,n,Math.max(0,o));null!=t&&(t<d||t===d&&i.indexOf(e.id)>i.indexOf(l?.id??""))&&(l=e,d=t)}f=f.next}return!1}),l}ensure(e,t){if(this.tree&&this.revision===t)return this.tree;let i=e.readState();return 0===i.length?(this.tree=null,this.maxSearchRadius=0,this.revision=t,null):(this.maxSearchRadius=i.reduce((e,t)=>Math.max(e,si(t)),0),this.tree=hi().x(e=>e.x).y(e=>e.y).addAll(i),this.revision=t,this.tree)}},mi=["data","scene-geometry","data-paint","accessibility","evidence"],yi=["scene-geometry","data-paint","accessibility","evidence"],fi=["overlay","accessibility","evidence"],gi=(e,t)=>({retainedData:e,invalidations:t}),bi=["layout","scene-geometry","data-paint","overlay","accessibility","evidence"],vi=["scene-geometry","data-paint","accessibility","evidence"],xi=[],wi={engine:/* @__PURE__ */gi("rebuild",["scene-geometry","data-paint","accessibility","evidence"]),kernel:/* @__PURE__ */gi("preserve",vi),colliders:/* @__PURE__ */gi("preserve",vi),sediment:/* @__PURE__ */gi("preserve",vi),bodyBudget:/* @__PURE__ */gi("preserve",bi),bodyLimit:/* @__PURE__ */gi("preserve",bi),eviction:/* @__PURE__ */gi("preserve",bi),fixedDt:/* @__PURE__ */gi("preserve",xi),maxDeltaSeconds:/* @__PURE__ */gi("preserve",xi),maxSubsteps:/* @__PURE__ */gi("preserve",xi),settleStepLimit:/* @__PURE__ */gi("preserve",xi),timeScale:/* @__PURE__ */gi("preserve",xi),observation:/* @__PURE__ */gi("preserve",xi)},Ii=/* @__PURE__ */gi("preserve",bi);function ki(e){let t="preserve",i=/* @__PURE__ */new Set;for(let r of e){let e=wi[r]??Ii;"rebuild"===e.retainedData&&(t="rebuild");for(let t of e.invalidations)i.add(t)}return{retainedData:t,invalidations:i}}var Si=["seed","fixedDt","cellSize","collisionIterations","velocityDamping","sleepSpeed","sleepAfter","restitution","friction","maxVelocity","contactWakeSpeed"];function Mi(e,t){return e===t||!(!e||!t||e.gravity?.x!==t.gravity?.x||e.gravity?.y!==t.gravity?.y)&&Si.every(i=>e[i]===t[i])}function Ai(e,t){return Object.keys(e).filter(i=>"kernel"===i?!Mi(e.kernel,t.kernel):e[i]!==t[i])}function $i(e,t,i){if(!t.some(e=>"sleep"===e.type))return;let r=new Map(e.readState().map(e=>[e.id,e]));for(let e of t){if("sleep"!==e.type)continue;let t=r.get(e.bodyId);i.emit({type:"physics-settle",timestamp:i.elapsedSeconds,chartType:i.observation.chartType,chartId:i.observation.chartId,bodyId:e.bodyId,datum:t?.datum,x:t?.x,y:t?.y})}}function Ci(e,t,i){let r=new Set(e.activeSensorPairs().map(e=>li(e.sensorId,e.bodyId))),n=r.size!==t.size;if(!n)for(let e of r)if(!t.has(e)){n=!0;break}if(!n)return r;let o=new Map(e.readState().map(e=>[e.id,e])),s=(e,t)=>{let{sensorId:r,bodyId:n}=di(t),s=i.observation.sensors[r],a=o.get(n);i.emit({type:"enter"===e?s?.enterType??"physics-bin-enter":s?.exitType??"physics-bin-exit",timestamp:i.elapsedSeconds,chartType:i.observation.chartType,chartId:i.observation.chartId,bodyId:n,datum:a?.datum,x:a?.x,y:a?.y,sensorId:r,binId:s?.binId??r})};for(let e of Array.from(r).sort())t.has(e)||s("enter",e);for(let e of Array.from(t).sort())r.has(e)||s("exit",e);return r}function Pi(e,t){for(let i of e)t.has(di(i).bodyId)&&e.delete(i)}function Ri(e,t,i,r){return e||!t?"paused":i||!r?"running":"settled"}function Di(e,t,i){i.observation.onSimulationStateChange?.(t,e),("running"===t||"settled"===t)&&i.emit({type:"running"===t?"sim-active":"sim-idle",timestamp:i.elapsedSeconds,chartType:i.observation.chartType,chartId:i.observation.chartId,simulationState:t,previousSimulationState:e})}function Bi(e,t){t.emit({type:"overflow"===e.state?"physics-budget-overflow":"physics-budget-warning",timestamp:t.elapsedSeconds,chartType:t.observation.chartType,chartId:t.observation.chartId,budgetAction:e.action,bodyLimit:e.bodyLimit,engineMaxBodiesHint:e.engineMaxBodiesHint,liveBodies:e.liveBodies,overflow:e.overflow,projectedBodies:e.projectedBodies,queuedBodies:e.queuedBodies,warnAt:e.warnAt})}function Ti(e,t,i){if("sleeping-first"!==t)return i.slice();let r=new Map(e.readState().map(e=>[e.id,e.sleeping])),n=[],o=[];for(let e of i)r.get(e)?n.push(e):o.push(e);return[...n,...o]}function ji(e,t,i,r){let n=new Map(e.readState().map(e=>[e.id,e])),o=[];for(let e of i){let i=n.get(e);if(!i)continue;let s=t.add(i);s&&(o.push(e),r.emit({type:"physics-sediment",timestamp:r.elapsedSeconds,chartType:r.observation.chartType,chartId:r.observation.chartId,bodyId:e,datum:i.datum,x:i.x,y:i.y,binId:s.id,count:s.count,total:s.total}))}return o}function Oi(e,t,i,r,n,o){let s={evicted:[],sedimented:[],liveBodyOrder:n};if(!1===i)return s;let a=Math.max(0,Math.floor(r));if(!Number.isFinite(a))return s;let l=n.length-a;if(l<=0)return s;let d=Ti(e,i,n).slice(0,l);if(0===d.length)return s;let c=ji(e,t,d,o);e.remove(d);let u=new Set(d);return{evicted:d,sedimented:c,liveBodyOrder:n.filter(e=>!u.has(e))}}function Ei(e){let t=e?.sleepSpeed;return"number"==typeof t&&Number.isFinite(t)&&t>0?t:8}var Ni=class{constructor(){this.seconds=0,this.speed=8,this.scratch=[]}setKernelOptions(e){this.speed=Ei(e)}reset(){this.seconds=0}isAtRest(){return this.seconds>=.6}refresh(e,t,i){if(i>0)return void(this.seconds=0);if(e.allSleeping())return void(this.seconds+=Math.max(0,t));let r=e.readState(this.scratch),n=this.speed*this.speed,o=!0;for(let e of r){if(e.sleeping)continue;let i=e.x-e.prevX,r=e.y-e.prevY;if(e.vx*e.vx+e.vy*e.vy>=n||t>0&&i*i+r*r>=n*t*t){o=!1;break}}this.seconds=o?this.seconds+Math.max(0,t):0}};function Fi(e,t,i=!1){if(!e)return;let r=["spawned","evicted","sedimented","events","observations"],n={spawned:0,evicted:0,sedimented:0,events:0,observations:0},o=o=>{let s=t(o),a={...s};r.forEach(e=>{a[e]=s[e].slice(n[e]),n[e]=s[e].length}),(0!==o||i||!r.every(e=>0===a[e].length))&&e.onStep(a)};return o(0),()=>o(1)}function Wi(e,t,i,r={}){let n,o=0,s=0,a=t+(r.drainArrivals?Math.max(0,Math.ceil(((e.lastArrival()??e.elapsed())-e.elapsed())/e.fixedDt)):0);for(;o+s<a&&!r.shouldStop?.()&&(!1===r.stopAtRest||e.queueSize()>0||!e.atRest()||r.continueWhile?.());){let t=e.nextArrival(),l=r.skipIdle&&null!=t&&e.atRest()?Math.min(Math.max(0,Math.floor((t-e.elapsed())/e.fixedDt)-1),Math.max(0,a-o-s-1)):0;l>0&&(e.advanceTime(l*e.fixedDt),s+=l),e.step(e.fixedDt),e.advanceTime(e.fixedDt);let d=e.drainEvents();i.events&&(i.events.push(...d),e.observeKernelEvents(d,i.observations),e.observeSensorTransitions(i.observations));let c=[];if(e.spawnDue(c,i.observations),c.length>0){i.spawned.push(...c),n=e.observeBodyBudget(i.observations);let t=e.evictOverflow(i.observations);i.evicted?.push(...t.evicted),i.sedimented?.push(...t.sedimented)}o+=1,e.refreshQuiescence(e.fixedDt,c.length),r.afterStep?.()}return{steps:o,budget:n}}var qi=class{constructor(e={}){this.activeSensorPairs=/* @__PURE__ */new Set,this.accumulator=0,this.bodyBudgetObservationKey="ok",this.bodySpatialIndex=new pi,this.elapsedSeconds=0,this.liveBodyOrder=[],this.nextSequence=0,this.paused=!1,this.queue=[],this.revision=0,this.observedInitialBoundary=!1,this.updateResults=new oe,this.simulationState="settled",this.visible=!0,this.quiescence=new Ni;let{bodyBudget:t,colliders:i,engine:r,kernel:n,observation:o,sediment:s,...a}=e;this.config={...Gt,...a},this.configInput={...e},this.bodyBudget=t??{},this.engineInput=r,this.observation=Ut(o),this.sediment=new Ht(s??!1),this.world=Rt(r,{fixedDt:this.config.fixedDt,...n}),this.quiescence.setKernelOptions(n),i&&this.world.setColliders(ii(i))}updateConfig(e){let t=Ai(e,this.configInput),{colliders:i,bodyBudget:r,engine:n,kernel:o,observation:s,sediment:a,...l}=e;if(this.config={...this.config,...l},void 0!==r&&(this.bodyBudget=r,!1===r&&(this.bodyBudgetObservationKey="ok")),n&&n!==this.engineInput){let e=this.world.snapshot();this.world.dispose(),this.engineInput=n,this.world=Rt(n,e.options),this.world.restore(e),this.revision+=1}if(o&&!Mi(o,this.configInput.kernel)){let 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=Ut(s,this.observation)),this.sediment.updateConfig(a),i&&(this.world.setColliders(ii(i)),this.revision+=1),this.configInput={...this.configInput,...e};let d=ki(t);this.updateResults.record({kind:"config",keys:t},d.invalidations)}updateConfigWithResult(e){return this.updateConfig(e),this.updateResults.last}setColliders(e){this.world.setColliders(ii(e)),this.revision+=1,this.updateResults.record({kind:"config",keys:["colliders"]},ki(["colliders"]).invalidations)}enqueue(e,t){let i=Array.isArray(e)?e:[e],r=t?ei(i,{...t,startAt:t.startAt??this.elapsedSeconds}):i;for(let e of r)this.queue.push({...Kt(e),sequence:this.nextSequence,spawnAt:e.spawnAt??this.elapsedSeconds}),this.nextSequence+=1;this.queue.sort(ni),r.length>0&&(this.revision+=1),this.updateResults.record({kind:"enqueue",count:r.length},r.length?mi:[])}enqueueWithResult(e,t){return this.enqueue(e,t),this.updateResults.last}spawnNow(e){this.spawnOne(Kt(e)),this.nextSequence+=1,this.observeBodyBudget(),this.evictOverflow(),this.revision+=1,this.updateResults.record({kind:"enqueue",count:1},mi)}materializeDueSpawns(){let e=this.revision,t=[],i=[];return this.spawnDue(t,i),0===t.length||(this.observeBodyBudget(i),this.evictOverflow(i),this.syncSimulationState(i),this.revision+=1,this.updateResults.record({kind:"enqueue",count:t.length},this.revision!==e?mi:[])),t}clear(){this.observedInitialBoundary=!1;let 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"},mi)}tick(e,t){let i=this.revision,r=[],n=[],o=[],s=[],a=[];if(this.paused||!this.visible){let e=this.result(0,r,n,o,s,a,!1);return this.updateResults.record({kind:"tick",count:0},[]),e}let l=Math.max(0,Math.min(Number.isFinite(e)?e:0,this.config.maxDeltaSeconds))*this.config.timeScale;this.spawnDue(r,a);let d=this.observeBodyBudget(a),c=this.evictOverflow(a);n.push(...c.evicted),o.push(...c.sedimented),this.syncSimulationState(a),r.length>0&&this.quiescence.reset(),this.accumulator+=l;let u=this.stepObserver(t,{spawned:r,evicted:n,sedimented:o,events:s,observations:a}),h=l>0?Math.floor((this.accumulator+1e-9*this.config.fixedDt)/this.config.fixedDt):0,{steps:p,budget:m}=Wi(this.settleHost(),Math.min(h,this.config.maxSubsteps),{spawned:r,evicted:n,sedimented:o,events:s,observations:a},{stopAtRest:!1,shouldStop:()=>this.paused||!this.visible,afterStep:u});this.accumulator=Math.max(0,this.accumulator-p*this.config.fixedDt),p===this.config.maxSubsteps&&(this.accumulator=Math.min(this.accumulator,this.config.fixedDt)),(p>0||r.length>0||n.length>0||o.length>0||s.length>0)&&(this.revision+=1);let y=this.result(p,r,n,o,s,a,void 0,m??d);return this.updateResults.record({kind:"tick",count:p},this.revision!==i?r.length||n.length||o.length?mi:yi:[]),y}settle(e){return this.runSettle(e,!1).steps}settleWithObservations(e,t){return this.runSettle(e,!0,t)}stepObserver(e,t){let i=!this.observedInitialBoundary;return e&&(this.observedInitialBoundary=!0),Fi(e,e=>(e&&(this.revision+=1),this.result(e,t.spawned,t.evicted,t.sedimented,t.events,t.observations)),i)}settleHost(){return{fixedDt:this.config.fixedDt,queueSize:()=>this.queue.length,atRest:()=>this.atRest(),elapsed:()=>this.elapsedSeconds,nextArrival:()=>this.queue[0]?.spawnAt,lastArrival:()=>this.queue.at(-1)?.spawnAt,advanceTime:e=>{this.elapsedSeconds+=e},spawnDue:(e,t)=>this.spawnDue(e,t),observeBodyBudget:e=>this.observeBodyBudget(e),evictOverflow:e=>this.evictOverflow(e),step:e=>this.world.step(e),drainEvents:()=>this.world.events(),observeKernelEvents:(e,t)=>this.observeKernelEvents(e,t),observeSensorTransitions:e=>this.observeSensorTransitions(e),refreshQuiescence:(e,t)=>this.quiescence.refresh(this.world,e,t)}}runSettle(e,t,i){let r=this.revision,n=[],o=[],s=[],a=[],l=t?[]:void 0;if(t&&(this.paused||!this.visible)){let e=this.result(0,n,o,s,a,l??[],!1);return this.updateResults.record({kind:"settle",count:0},[]),e}this.spawnDue(n,l);let d=this.observeBodyBudget(l),c=this.evictOverflow(l);o.push(...c.evicted),s.push(...c.sedimented),this.syncSimulationState(l),n.length>0&&this.quiescence.reset();let u=t?{spawned:n,evicted:o,sedimented:s,events:a,observations:l}:{spawned:n},h=this.stepObserver(i,{spawned:n,evicted:o,sedimented:s,events:a,observations:l??[]}),{steps:p,budget:m}=Wi(this.settleHost(),e??this.config.settleStepLimit,u,{afterStep:h,continueWhile:i?.continueWhile,shouldStop:t?()=>this.paused||!this.visible:void 0,drainArrivals:void 0===e,skipIdle:void 0===e&&!i}),y=n.length+o.length+s.length>0;(p>0||y||a.length>0)&&(this.revision+=1);let f=this.result(p,n,o,s,a,l??[],void 0,m??d);return this.updateResults.record({kind:"settle",count:p},this.revision===r?[]:y?mi:yi),f}readBodies(e=[]){return this.world.readState(e)}readSediment(){return this.sediment.snapshot()}bodyBudgetStatus(){return this.evaluateBodyBudget()}sedimentTotals(){return this.sediment.totals()}sedimentHeightfield(e={}){return Lt(this.readSediment(),e)}hitTest(e,t,i=0,r){return this.bodySpatialIndex.hitTest(this.world,this.revision,this.liveBodyOrder,e,t,i,r)}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){let{timestamp:t,chartType:i,chartId:r,...n}=e,o={...n,timestamp:t??this.elapsedSeconds,chartType:i??this.observation.chartType,chartId:r??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){let t=this.paused!==e;this.paused=e,this.syncSimulationState(),this.updateResults.record({kind:"pause"},t?fi:[])}setVisible(e){let t=this.visible!==e;this.visible=e,this.syncSimulationState(),this.updateResults.record({kind:"visibility"},t?fi:[])}remove(e){let t=new Set(e),i=new Set(this.liveBodyOrder),r=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);let n=e.filter(e=>i.has(e)||r.has(e));return n.length>0&&(this.revision+=1,this.syncSimulationState()),this.updateResults.record({kind:"remove",keys:n,count:n.length},n.length?mi:[]),n}setConstraint(e){let t=this.world.setConstraint(e);return this.revision+=1,this.updateResults.record({kind:"constraint",keys:[t]},yi),t}removeConstraint(e){this.world.removeConstraint(e),this.revision+=1,this.updateResults.record({kind:"constraint",keys:[e]},yi)}applyImpulse(e,t,i){this.world.applyImpulse(e,t,i),this.revision+=1,this.updateResults.record({kind:"impulse",keys:[e]},yi)}nextRandom(){return this.world.nextRandom()}controls(){return e=this,{applyImpulse:(t,i,r)=>e.applyImpulse(t,i,r),clear:()=>e.clear(),hitTest:(t,i,r)=>e.hitTest(t,i,r),pause:()=>e.setPaused(!0),push:(t,i)=>e.enqueue(t,i),pushMany:(t,i)=>e.enqueue(t,i),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(){let e=this.world.snapshot();return{accumulator:this.accumulator,activeSensorPairs:Array.from(this.activeSensorPairs).sort(),bodyBudget:ri(this.bodyBudget),config:{...this.config,kernel:oi(e.options)},elapsedSeconds:this.elapsedSeconds,paused:this.paused,queue:this.queue.map(ti),revision:this.revision,sediment:this.readSediment(),simulationState:this.simulationState,liveBodyOrder:this.liveBodyOrder.slice(),visible:this.visible,world:e}}restore(e){this.observedInitialBoundary=!1;let t=this.simulationState;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:ri(e.bodyBudget??{}),kernel:oi(e.world.options)},this.bodyBudget=ri(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(ti).sort(ni),this.revision=e.revision,this.sediment.restore(e.sediment??[]),this.simulationState=e.simulationState??Ri(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"},mi),this.simulationState!==t&&this.observation.onSimulationStateChange?.(this.simulationState,t)}spawnDue(e,t){for(;this.queue.length>0&&this.queue[0].spawnAt<=this.elapsedSeconds+1e-9*this.config.fixedDt;){let i=this.queue.shift();if(!i)return;this.spawnOne(i,t),e.push(i.id)}}spawnOne(e,t){this.liveBodyOrder=this.liveBodyOrder.filter(t=>t!==e.id),this.removeActiveSensorPairsForBodies(/* @__PURE__ */new Set([e.id])),this.world.spawn(e),this.liveBodyOrder.push(e.id);for(let t of e.springs??[])this.world.setConstraint({...t,bodyId:e.id});if(!t&&!this.observation.onObservation)return;let i=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:i?.datum??e.datum,x:i?.x??e.x,y:i?.y??e.y},t)}result(e,t,i,r,n,o,s,a=this.evaluateBodyBudget()){this.syncSimulationState(o);let l=this.world.allSleeping();return{budget:a,elapsedSeconds:this.elapsedSeconds,evicted:i,events:n,observations:o,queueSize:this.queue.length,revision:this.revision,shouldContinue:s??(!this.paused&&this.visible&&(this.queue.length>0||!this.atRest())),sleeping:l,sedimented:r,spawned:t,steps:e}}observeKernelEvents(e,t){$i(this.world,e,this.observationContext(t))}observeSensorTransitions(e){this.activeSensorPairs=Ci(this.world,this.activeSensorPairs,this.observationContext(e))}removeActiveSensorPairsForBodies(e){Pi(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 Xt({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){let t=this.evaluateBodyBudget();if("ok"===t.state||!1===this.bodyBudget)return this.bodyBudgetObservationKey="ok",t;let i=`${t.state}:${t.action}`;return i===this.bodyBudgetObservationKey||(this.bodyBudgetObservationKey=i,Bi(t,this.observationContext(e))),t}syncSimulationState(e){let t=Ri(this.paused,this.visible,this.queue.length>0,this.atRest());if(t===this.simulationState)return;let i=this.simulationState;this.simulationState=t,Di(i,t,this.observationContext(e))}evictOverflow(e){let{evicted:t,sedimented:i,liveBodyOrder:r}=Oi(this.world,this.sediment,this.config.eviction,this.config.bodyLimit,this.liveBodyOrder,this.observationContext(e));return t.length>0&&(this.liveBodyOrder=r,this.removeActiveSensorPairsForBodies(new Set(t))),{evicted:t,sedimented:i}}};function zi(e,t){if("function"==typeof t){let i=t(e);return Number.isFinite(i)&&i>0?Number(i):1}let i=e.datum;if(t&&i&&"object"==typeof i){let e=Number(i[t]);if(Number.isFinite(e)&&e>0)return e}let r=Number(i?.work??i?.reviewWork??i?.value);return Number.isFinite(r)&&r>0?r:1}function Hi(e,t){if("function"==typeof t){let i=t(e);if(null!=i&&String(i).length>0)return String(i)}else if(t){let i=kt(e.datum,t),r=kt(e,t),n=i??r;if(null!=n&&String(n).length>0)return String(n)}return e.id}function Li(e,t){if(0===e.length)return 0;if(1===e.length)return e[0];let i=Math.max(0,Math.min(1,t))*(e.length-1),r=Math.floor(i),n=Math.ceil(i),o=i-r;return e[r]+(e[n]-e[r])*o}function Yi(e){let t=e.regionId,i=Math.max(0,e.unitsPerSecond),r=e.queueLayout??"lane",n=e.queueSlotSpacing??14,o=e.queueStiffness??.35,s=Number.isFinite(e.maxQueue)?Math.max(0,Math.floor(Number(e.maxQueue))):Number.POSITIVE_INFINITY,a=Math.max(.25,e.metricWindowSeconds??30),l=Math.max(1/60,e.snapshotIntervalSeconds??.25),d=e.releaseImpulse??{x:90,y:0},c=/* @__PURE__ */new Map,u=/* @__PURE__ */new Map,h=/* @__PURE__ */new Map,p=/* @__PURE__ */new Map,m=/* @__PURE__ */new Map,y=/* @__PURE__ */new Map,f=/* @__PURE__ */new Map,g=[],b=0,v=/* @__PURE__ */new Map,x=/* @__PURE__ */new Map,w=0,I=0,k=0,S=null,M=0,A=0,$=0,C=0,P=0,R=0,D=0,B=0,T=0,j=0,O=0,E=0,N=-1,F=!1;function W(e,i){let r=i(e);return!!r&&r.activeRegionIds.includes(t)}function q(){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 H(i,r,n){let o=z(r);e.onQueued?.(i,o),n.controls.recordObservation({type:"physics-capacity-queued",bodyId:i.id,datum:i.datum,x:i.x,y:i.y,regionId:t,work:r.total,jobId:r.jobId,visitId:r.visitId,visit:r.visit,queuedAt:r.queuedAt,queueDepth:c.size})}function L(e,t,i,r){let n={bodyId:e.id,jobId:t.jobId,visitId:t.visitId,visit:t.visit,remaining:t.work,total:t.work,queuedAt:t.queuedAt,sequence:r};return c.set(t.jobId,n),f.delete(e.id),y.set(e.id,t.jobId),A+=1,$+=t.work,q(),H(e,n,i),n}function Y(e){if(c.size>=s||0===u.size)return;let t=Array.from(u.values()).sort((e,t)=>e.sequence-t.sequence);for(let i of t){if(c.size>=s)break;let t=m.get(i.jobId);t&&h.has(i.jobId)?(u.delete(i.jobId),f.delete(i.bodyId),L(t,i,e,i.sequence)):u.delete(i.jobId)}}function _(){let e=0;for(let t of c.values())e+=t.remaining;return e}function X(){let e=0;for(let t of u.values())e+=t.work;return e}function G(){T=Math.max(T,c.size),j=Math.max(j,_())}function V(){let e=Array.from(c.values()).sort((e,t)=>e.sequence-t.sequence);v=new Map(e.map((e,t)=>[e.bodyId,t]));let t=Array.from(u.values()).sort((e,t)=>e.sequence-t.sequence);x=new Map(t.map((e,t)=>[e.bodyId,t])),w=e.length}function U(e){(e.end>e.start||e.arrivals>0||e.completions>0||e.processedWork>0)&&g.push(e);let t=k-a;for(;g.length>0&&g[0].end<t;)g.shift()}function K(){let e=k-a,t=Math.max(0,Math.min(a,k-(S??k))),r=0,n=0,o=0,s=0,l=0;for(let t of g){if(t.end<e)continue;r+=t.arrivals,n+=t.arrivalWork,o+=t.completions,s+=t.completedWork;let i=t.end-t.start;if(i<=0||t.start>=e)l+=t.processedWork;else{let r=Math.max(0,t.end-e);l+=t.processedWork*Math.min(1,r/i)}}let d=t>0?n/t:0;return{seconds:t,arrivals:r,arrivalWork:n,completions:o,completedWork:s,processedWork:l,arrivalsPerSecond:t>0?r/t:0,throughputPerSecond:t>0?o/t:0,utilization:t>0&&i>0?Math.max(0,Math.min(1,l/(i*t))):0,pressure:i>0?d/i:0}}return{id:e.id??`capacity-queue:${t}`,continuous:!1!==e.continuous,tick:r=>{let n=r.controls.readBodies(),o=/* @__PURE__ */new Map,a=/* @__PURE__ */new Map;for(let t of n){if(o.set(t.id,t),!W(t.id,r.getRegionState)||!Mt(t,e.bodyFilter))continue;let i=Hi(t,e.jobKey),n=a.get(i)??[];n.push(t),a.set(i,n)}let g=Number.isFinite(r.dt)?Math.max(0,r.dt):0;if(!F){let e=Number.isFinite(r.elapsed)?Math.max(0,r.elapsed):g;k=Math.max(0,e-g),F=!0}let v=k,x=v+g;k=x,S=null==S?v:Math.min(S,v);let w={start:v,end:x,arrivals:0,arrivalWork:0,completions:0,completedWork:0,processedWork:0},A=/* @__PURE__ */new Map;for(let[e,t]of a){let i=h.get(e)?.bodyId,r=t.find(e=>e.id===i)??t[0];A.set(e,r),m.set(e,r)}for(let[i,n]of h){if(A.has(i))continue;let s=c.get(i),a=o.get(n.bodyId)??m.get(i);if(s){c.delete(i),y.delete(s.bodyId),D+=1,B+=s.remaining,q();let o={...z(s),abandonedAt:k,remainingWork:s.remaining,queueSeconds:Math.max(0,k-s.queuedAt)};a&&e.onAbandoned?.(a,o),r.controls.recordObservation({type:"physics-capacity-abandoned",bodyId:n.bodyId,datum:a?.datum,x:a?.x,y:a?.y,regionId:t,work:s.total,remainingWork:s.remaining,jobId:i,visitId:s.visitId,visit:s.visit,queuedAt:s.queuedAt,abandonedAt:k,queueSeconds:o.queueSeconds,queueDepth:c.size})}u.delete(i),f.delete(n.bodyId),h.delete(i),m.delete(i)}for(let[i,n]of A){if(h.has(i))continue;let o=(p.get(i)??0)+1;p.set(i,o);let a=zi(n,e.unitAccessor),l={bodyId:n.id,jobId:i,visitId:`${t}:${i}:${o}`,visit:o,regionId:t,work:a,queuedAt:k};h.set(i,l),M+=1,w.arrivals+=1,w.arrivalWork+=a;let d=b++;if(c.size<s)L(n,l,r,d);else{let s={...l,blockedAt:k,sequence:d};u.set(i,s),f.set(n.id,i),R+=1,q(),e.onBlocked?.(n,s),r.controls.recordObservation({type:"physics-capacity-blocked",bodyId:n.id,datum:n.datum,x:n.x,y:n.y,regionId:t,work:a,jobId:i,visitId:l.visitId,visit:o,queuedAt:k,blockedAt:k,queueDepth:c.size,blockedDepth:u.size})}}Y(r),G();let $=Array.from(c.values()).sort((e,t)=>e.sequence-t.sequence),T=i*g;for(let i of $){if(!(T>0))break;let n=Math.min(i.remaining,T);if(i.remaining-=n,T-=n,C+=n,w.processedWork+=n,i.remaining>1e-6)continue;c.delete(i.jobId),y.delete(i.bodyId),I+=1,P+=i.total,w.completions+=1,w.completedWork+=i.total;let s=Math.max(0,k-i.queuedAt);O+=s,q();let a=o.get(i.bodyId);if(!a)continue;r.controls.applyImpulse(i.bodyId,d.x??0,d.y??0);let l={...z(i),completedAt:k,queueSeconds:s};e.onProcessed?.(a,l),r.controls.recordObservation({type:"physics-capacity-processed",bodyId:i.bodyId,datum:a.datum,x:a.x,y:a.y,regionId:t,work:i.total,jobId:i.jobId,visitId:i.visitId,visit:i.visit,queuedAt:i.queuedAt,completedAt:k,queueSeconds:s,queueDepth:c.size})}Y(r),G(),V(),U(w);let j=Math.floor(k/l);j!==N&&(N=j,q())},getSnapshot:()=>{let e=_(),r=X(),n=c.size,o=Array.from(c.values()).map(e=>Math.max(0,k-e.queuedAt)).sort((e,t)=>e-t),s=o.reduce((e,t)=>e+t,0);return{regionId:t,queueDepth:n,processedCount:I,unitsPerSecond:i,remainingWork:e,meanRemainingWork:n>0?e/n:0,waitingWork:e+r,blockedDepth:u.size,blockedWork:r,arrivalCount:M,admittedCount:A,admittedWork:$,processedWork:C,completedWork:P,blockedCount:R,abandonedCount:D,abandonedWork:B,peakQueueDepth:T,peakRemainingWork:j,queueAge:{count:o.length,meanSeconds:o.length>0?s/o.length:0,p50Seconds:Li(o,.5),p95Seconds:Li(o,.95),oldestSeconds:o.at(-1)??0},meanCompletedQueueSeconds:I>0?O/I:0,window:K(),simulatedAt:k,metricRevision:E}},bodyForce:e=>{if("none"===r)return null;let i=y.get(e.body.id),s=f.get(e.body.id),a=i?c.get(i):void 0,l=s?u.get(s):void 0;if(!a&&!l)return null;let d=a?v.get(e.body.id):x.get(e.body.id);if(null==d)return null;let h,p=e.regions;if(p)for(let e=0;e<p.length;e+=1)if(p[e].id===t){let t=p[e].shape;t&&"aabb"===t.type&&(h=t);break}if(!h)return{x:8*-Math.sign(e.body.vx||1),y:0};let m=l?h.x-.44*h.width:h.x-.22*h.width-d*(.15*n),g=h.y-(d-((l?u.size:w)-1)/2)*n/Math.max(1,Math.sqrt(l?u.size:w)),b=m-e.body.x,I=g-e.body.y;return{x:b*o,y:I*o*.85}}}}function _i(e,t){return e||t?{x:(e?.x??0)+(t?.x??0),y:(e?.y??0)+(t?.y??0)}:null}function Xi(e){if(!e?.length)return null;let t=e.slice(),i=t.some(e=>!1!==e.continuous);return{controllers:t,continuous:i,onTick:(e,i,r)=>{let n={result:e,controls:i,dt:r.dt,elapsed:r.elapsed,getRegionState:r.getRegionState};for(let e of t)e.tick(n)},bodyForce:e=>{let i=null;for(let r of t)r.bodyForce&&(i=_i(i,r.bodyForce(e)));return i}}}function Gi(e){let t=/* @__PURE__ */new Set,i=e.impulse??{x:-60,y:0};return{id:e.id??`portal:${e.fromRegionId}`,continuous:!0===e.continuous,tick:r=>{let n=r.controls.readBodies();for(let o of n)r.getRegionState(o.id)?.activeRegionIds.includes(e.fromRegionId)?t.has(o.id)||(t.add(o.id),r.controls.applyImpulse(o.id,i.x??0,i.y??0),e.onPortal?.(o)):t.delete(o.id)}}}import*as Vi from"react";import{forwardRef as Ui,memo as Ki,useCallback as Qi,useEffect as Ji,useImperativeHandle as Zi,useId as er,useRef as tr}from"react";var ir={annotationBackground:"rgba(248, 250, 252, 0.94)",annotationStroke:"#334155",annotationText:"#0f172a",background:"#f8fafc",border:"#334155",closedWindowFill:"rgba(220, 38, 38, 0.08)",closedWindowStroke:"rgba(220, 38, 38, 0.55)",danger:"#dc2626",focus:"#f97316",grid:"#cbd5e1",gutterFill:"rgba(71, 85, 105, 0.14)",lateFill:"#f97316",openWindowFill:"rgba(14, 165, 233, 0.07)",openWindowStroke:"rgba(14, 165, 233, 0.3)",primary:"#0ea5e9",selectedFill:"#f97316",selectedStroke:"#7c2d12",success:"#22c55e",text:"#0f172a",textSecondary:"#475569",warning:"#f97316"},rr={background:{names:["--semiotic-bg","--surface-1","--surface-0"],fallback:ir.background},border:{names:["--semiotic-border","--surface-3"],fallback:ir.border},danger:{names:["--semiotic-danger","--viz-4"],fallback:ir.danger},focus:{names:["--semiotic-focus","--accent","--viz-9"],fallback:ir.focus},grid:{names:["--semiotic-grid","--surface-3"],fallback:ir.grid},primary:{names:["--semiotic-primary","--accent","--viz-5"],fallback:ir.primary},success:{names:["--semiotic-success","--viz-2"],fallback:ir.success},text:{names:["--semiotic-text","--text-primary"],fallback:ir.text},textSecondary:{names:["--semiotic-text-secondary","--text-secondary"],fallback:ir.textSecondary},warning:{names:["--semiotic-warning","--viz-9","--viz-3"],fallback:ir.warning}};function nr(e){let t=rr[e];return t.names.reduceRight((e,t)=>`var(${t}, ${e})`,t.fallback)}function or(e,t,i){if(!t)return i.fallback;for(let r of i.names){let i=t.getPropertyValue(r).trim();if(i)return ve(e,i)??i}return i.fallback}function sr(e,t){let i=Math.max(0,Math.min(1,t)),r=e.trim(),n=r.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);if(n){let[,e,t,r]=n;return sr(`#${e}${e}${t}${t}${r}${r}`,i)}let o=r.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(o){let[,e,t,r]=o;return`rgba(${parseInt(e,16)}, ${parseInt(t,16)}, ${parseInt(r,16)}, ${i})`}let s=r.match(/^rgb\s*\(\s*([^)]+?)\s*\)$/i);if(s)return`rgba(${s[1]}, ${i})`;let a=r.match(/^rgba\s*\(\s*([^,]+,\s*[^,]+,\s*[^,]+),\s*[^)]+\)$/i);return a?`rgba(${a[1]}, ${i})`:r}function ar(e){let t=e.canvas,i="function"==typeof getComputedStyle&&t?getComputedStyle(t):null,r=or(e,i,rr.primary),n=or(e,i,rr.danger),o=or(e,i,rr.warning),s=or(e,i,rr.success),a=or(e,i,rr.border),l=or(e,i,rr.background),d=or(e,i,rr.text),c=or(e,i,rr.textSecondary),u=or(e,i,rr.focus),h=or(e,i,rr.grid);return{annotationBackground:sr(l,.94),annotationStroke:a,annotationText:d,background:l,border:a,closedWindowFill:sr(n,.08),closedWindowStroke:sr(n,.55),danger:n,focus:u,grid:h,gutterFill:sr(c,.14),lateFill:o,openWindowFill:sr(r,.07),openWindowStroke:sr(r,.3),primary:r,selectedFill:o,selectedStroke:u,success:s,text:d,textSecondary:c,warning:o}}function lr(){let e=null,t=-1,i=ir;return{resolve(r){let n=r.canvas??null,o=xe();return n===e&&o===t||(e=n,t=o,i=ar(r)),i},invalidate(){t=-1}}}function dr(e){return"function"==typeof e}function cr(e){return void 0===e||!1===e||!dr(e.binAccessor)&&!dr(e.labelAccessor)&&!dr(e.valueAccessor)}function ur(e){return!dr(e?.timeAccessor)}function hr(e){if(void 0!==e){if(!1===e)return!1;if(!cr(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 pr(e){if(e)return{chartId:e.chartId,chartType:e.chartType,sensors:e.sensors}}function mr(e){return!e||e.every(e=>{let t=e.bodyFilter;return!t||"function"!=typeof t})}function yr(e){return ur(e)}function fr(e={}){if(e.engine)throw new TypeError("Physics workers use the built-in kernel adapter");let{engine:t,observation:i,sediment:r,...n}=e;return{...n,observation:pr(i),sediment:hr(r)}}function gr(e,t,i=0,r=2500){return"sync"!==e&&("worker"===e||t+i>=r)}function br(){return"string"==typeof import.meta.url&&import.meta.url?new Worker(new URL("./physicsWorker.js",import.meta.url),{type:"module",name:"semiotic-physics"}):new Worker(e("physicsWorker.js"),{type:"module",name:"semiotic-physics"})}function vr(){if(typeof DOMException<"u")return new DOMException("Physics worker request aborted","AbortError");let e=new Error("Physics worker request aborted");return e.name="AbortError",e}function xr(e){let t=new Error(e.error.message);return t.name=e.error.name??"Error",e.error.stack&&(t.stack=e.error.stack),t}var wr=class{constructor(e=br()){this.nextRequestId=1,this.pending=/* @__PURE__ */new Map,this.worker=e,this.worker.onmessage=e=>{let t=e.data,i=this.pending.get(t.requestId);i&&(this.pending.delete(t.requestId),i.cleanup(),t.ok?i.resolve(t.payload):i.reject(xr(t)))},this.worker.onerror=e=>{this.rejectAll(new Error(e.message||"Physics worker failed")),this.worker.terminate()}}request(e,t){if(t?.aborted)return Promise.reject(vr());let i=this.nextRequestId;this.nextRequestId+=1;let r={command:e,requestId:i};return new Promise((e,n)=>{let o=()=>{this.pending.delete(i),t?.removeEventListener("abort",o),n(vr())},s=()=>t?.removeEventListener("abort",o);this.pending.set(i,{cleanup:s,reject:n,resolve:e}),t?.addEventListener("abort",o,{once:!0});try{this.worker.postMessage(r)}catch(e){this.pending.delete(i),s(),n(e)}})}async init(e,t,i,r){if(!yr(i))throw new TypeError("Physics worker spawn pacing only supports string time accessors");let n=await this.request({type:"init",config:fr(e),initialSpawns:t,initialSpawnPacing:i},r);if("frame"!==n.type)throw new Error("Physics worker returned a non-frame init response");return n.frame}async restore(e,t){let i=await this.request({type:"restore",snapshot:e},t);if("frame"!==i.type)throw new Error("Physics worker returned a non-frame restore response");return i.frame}async initFromSnapshot(e,t,i){let r=await this.request({type:"init",config:fr(e),snapshot:t},i);if("frame"!==r.type)throw new Error("Physics worker returned a non-frame init response");return r.frame}async enqueue(e,t,i){if(!yr(t))throw new TypeError("Physics worker spawn pacing only supports string time accessors");let r=await this.request({type:"enqueue",spawns:e,pacing:t},i);if("frame"!==r.type)throw new Error("Physics worker returned a non-frame enqueue response");return r.frame}async tick(e,t){let i=await this.request({type:"tick",deltaSeconds:e},t);if("frame"!==i.type)throw new Error("Physics worker returned a non-frame tick response");return i.frame}async settle(e,t){let i=await this.request({type:"settle",maxSteps:e},t);if("frame"!==i.type)throw new Error("Physics worker returned a non-frame settle response");return i.frame}async snapshot(e){let t=await this.request({type:"snapshot"},e);if("snapshot"!==t.type)throw new Error("Physics worker returned a non-snapshot response");return t.snapshot}async remove(e,t){let i=await this.request({type:"remove",ids:e},t);if("removed"!==i.type)throw new Error("Physics worker returned a non-remove response");return{frame:i.frame,removed:i.removed}}terminate(){this.rejectAll(new Error("Physics worker terminated")),this.worker.terminate()}rejectAll(e){for(let[t,i]of this.pending)this.pending.delete(t),i.cleanup(),i.reject(e)}};function Ir(e,t,i){let r=new qi(e);return t?.length&&(r.enqueue(t,i),r.materializeDueSpawns()),r}function kr(){return typeof performance<"u"?performance.now():Date.now()}function Sr(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}))}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}:{}}))}function Ar(e,t,i,r){let n=e-(t+i+r);return{charge:e,live:t,queued:i,sedimented:r,unaccounted:n,balanced:0===n}}function $r(e,t={}){let i=t.bodies??Sr(e),r=i.filter(e=>e.sleeping).length,n=e.queue.length,o=e.sediment.reduce((e,t)=>e+t.count,0),s="settled"===e.simulationState&&0===n&&r===i.length,a=[];s||a.push("PHYSICS_NOT_SETTLED"),n>0&&a.push("PHYSICS_QUEUE_UNDRAINED");let l=null!=t.charge&&Number.isFinite(t.charge)?Ar(t.charge,i.length,n,o):void 0;return l&&!l.balanced&&a.push("PHYSICS_LEDGER_MISMATCH"),{bodyCount:i.length,sleepingCount:r,settled:s,stepsRun:Math.max(0,Math.floor(t.stepsRun??0)),seed:e.world.options.seed,binCounts:Mr(t.projectionRows),queuedCount:n,sedimentedCount:o,...l?{ledger:l}:{},warnings:a}}var Cr={fill:"#4e79a7",stroke:"#172033",strokeWidth:1,opacity:.85};function Pr(e){return e.datum&&"object"==typeof e.datum?e.datum:null}function Rr(e){let t=e.datum;if(t&&"object"==typeof t){let e=t,i=e.label??e.name??e.id;if(null!=i&&""!==i)return String(i)}return e.id}function Dr(e,t,i){let r="function"==typeof t?t(e,i):t;return{...Cr,...r??{}}}function Br(e,t={},i={index:0,simulationState:"settled"}){let r=Pr(e),n={label:t.getBodyLabel?.(e)??Rr(e)},o={style:Dr(e,t.bodyStyle,i),datum:r,accessibleDatum:r,accessibility:n,_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}}function Tr(e,t={},i="settled"){return e.map((e,r)=>Br(e,t,{index:r,simulationState:i}))}function jr(e,t={}){let i=e.settle(t.maxSteps),r=e.readBodies(),n=e.snapshot();return{snapshot:n,bodies:r,sceneNodes:Tr(r,t,n.simulationState),evidence:$r(n,{bodies:r,projectionRows:t.projectionRows,stepsRun:i,charge:t.charge}),stepsRun:i}}import{jsx as Or,jsxs as Er}from"react/jsx-runtime";function Nr(e){let t=e.replace(/[^A-Za-z0-9_-]/g,"_");return!t||/^\d/.test(t)?`physics-${t}`:t}var Fr={top:0,right:0,bottom:0,left:0};function Wr(e,t,i){return"function"==typeof e?e({size:t,margin:i}):e}function qr(e,t={}){let{width:i=640,height:r=360,title:n,description:o,background:s,backgroundGraphics:a,backgroundGraphicsBackdrop:l,className:d,foregroundGraphics:c,idPrefix:u="physics",margin:h,style:p,renderBodySVG:m,renderChrome:y,...f}=t,g=jr(e,f),b={...Fr,...h},v=[i,r],x=Wr(a,v,b),w=Wr(c,v,b),I=Nr(u),k=n?`${I}-title`:void 0,S=o?`${I}-desc`:void 0,M=[k,S].filter(Boolean).join(" ")||void 0,A=b.left||b.top?`translate(${b.left},${b.top})`:void 0,$=Math.max(1,i-b.left-b.right),C=Math.max(1,r-b.top-b.bottom),P=`${I}-plot-clip`,R=A&&null!=x?/* @__PURE__ */Or("g",{transform:A,children:x}):x;return{element:/* @__PURE__ */Er("svg",{xmlns:"http://www.w3.org/2000/svg",className:d??"stream-physics-frame",width:i,height:r,viewBox:`0 0 ${i} ${r}`,role:"img","aria-labelledby":M,style:p,children:[n&&/* @__PURE__ */Or("title",{id:k,children:n}),o&&/* @__PURE__ */Or("desc",{id:S,children:o}),
|
|
1
|
+
import{a as e}from"./c-LVHJJUOF.min.js";import{a as t}from"./c-GU2FIJ7F.min.js";import{a as i,b as r,c as n,d as o,e as s,f as a,g as l,h as d,i as c,j as u,k as h,l as p,m,n as y,o as f,p as g}from"./c-XLC7PKM7.min.js";import{a as b}from"./c-RHDOOQ4X.min.js";import{a as v,b as x}from"./c-RDM36RTX.min.js";import{$a as w,A as I,Aa as k,Ba as S,Ca as M,E as A,Ea as $,Fa as C,Fb as P,Ga as R,Ha as D,Hb as B,I as T,J as j,K as O,Na as E,O as N,Oa as F,Q as W,Sa as q,U as H,Ua as z,Xa as L,_a as Y,ab as _,b as X,ba as G,e as V,ea as U,ha as K,ia as Q,ja as J,k as Z,ka as ee,l as te,m as ie,ma as re,o as ne,oa as oe,ra as se,sa as ae,xa as le,ya as de,za as ce}from"./c-XCV7VUU3.min.js";import{a as ue}from"./c-2P6E22WZ.min.js";import{a as he}from"./c-ZOE7TAR3.min.js";import{a as pe,c as me,e as ye,g as fe,q as ge,r as be}from"./c-SSKV5JPW.min.js";import{m as ve,n as xe,o as we,p as Ie}from"./c-K2Z4F22S.min.js";import{b as ke,e as Se,h as Me,j as Ae,k as $e,l as Ce,o as Pe,p as Re,q as De,s as Be}from"./c-5FUOKMH6.min.js";import{a as Te}from"./c-3PFVJFBK.min.js";import{scaleLinear as je}from"d3-scale";function Oe(e){return"circle"===e.shape.type?e.shape.radius:Math.max(e.shape.width,e.shape.height)/2}function Ee(e){return e.map(e=>({pointId:e.id,x:e.x,y:e.y,r:Math.max(1,Oe(e))}))}function Ne(e){let{width:t,height:i,pointNodes:r=[],data:n}=e;return{scales:{x:je().domain([0,Math.max(1,t)]).range([0,Math.max(1,t)]),y:je().domain([0,Math.max(1,i)]).range([0,Math.max(1,i)])},width:t,height:i,frameType:"network",pointNodes:r,data:n,xAccessor:"x",yAccessor:"y"}}function Fe(e){return e?.length?e.map(e=>null!=e.pointId||null==e.bodyId?e:{...e,pointId:String(e.bodyId)}):e}import*as We from"react";import{Fragment as qe,jsx as He,jsxs as ze}from"react/jsx-runtime";function Le(e){let{width:t,height:i,totalWidth:r,totalHeight:n,margin:o,title:s,legend:a,legendHoverBehavior:l,legendClickBehavior:d,legendHighlightedCategory:c,legendIsolatedCategories:u,legendPosition:h="right",legendLayout:p,pointNodes:m=[],annotations:y,onAnnotationActivate:f,onObservation:g,chartId:b,chartType:v,autoPlaceAnnotations:x,svgAnnotationRules:w,children:k}=e,S=A({onAnnotationActivate:f,onObservation:g,chartId:b,chartType:v}),M=We.useMemo(()=>Fe(y),[y]),$=We.useMemo(()=>Ne({width:t,height:i,pointNodes:m}),[i,m,t]),C=We.useMemo(()=>M&&x?W({annotations:M,context:$,..."object"==typeof x?x:{}}):M,[$,x,M]),P=We.useMemo(()=>O("network",S),[S]),R=C?j(C,P,w,$):null,D=!0===C?.some(e=>"widget"===e.type&&!0===e._annotationDeferred);/* */
|
|
2
|
+
return ze(qe,{children:[D?/* @__PURE__ */He("style",{children:T},"physics-annotation-disclosure-style"):null,
|
|
3
|
+
/* @__PURE__ */ze("svg",{className:"stream-physics-frame__overlay","data-testid":"stream-physics-overlay",role:"presentation",width:r,height:n,style:{position:"absolute",top:0,left:0,pointerEvents:"none",overflow:"visible"},children:[
|
|
4
|
+
/* @__PURE__ */ze("g",{transform:`translate(${o.left},${o.top})`,children:[R,k]}),
|
|
5
|
+
/* @__PURE__ */He(H,{title:s,totalWidth:r,marginTop:Math.max(o.top,28)}),a?I({legend:a,totalWidth:r,totalHeight:n,margin:o,legendPosition:h,legendLayout:p,title:s,legendHoverBehavior:l,legendClickBehavior:d,legendHighlightedCategory:c,legendIsolatedCategories:u}):null]})]})}function Ye(e){let t=e.fixedPosition;Number.isFinite(t?.x)&&(e.x=e.prevX=t.x,e.vx=0),Number.isFinite(t?.y)&&(e.y=e.prevY=t.y,e.vy=0)}function _e(e){if(!e)return;let t=Number.isFinite(e.x)?e.x:void 0,i=Number.isFinite(e.y)?e.y:void 0;return null==t&&null==i?void 0:{x:t,y:i}}function Xe(e,t,i){let r,n="x"===i?"y":"x",o=Math.abs(t[i]-e[i]),s=t[n]-e[n],a=(e,t)=>"circle"===e.shape.type?e.shape.radius:("x"===t?e.shape.width:e.shape.height)/2;if("circle"===e.shape.type&&"circle"===t.shape.type){let i=e.shape.radius+t.shape.radius;r=Math.sqrt(Math.max(0,i*i-o*o))}else if("aabb"===e.shape.type&&"aabb"===t.shape.type)r=a(e,n)+a(t,n);else{let s="circle"===e.shape.type?e:t,l="aabb"===e.shape.type?e:t,d=a(s,i),c=Math.max(0,o-a(l,i));r=a(l,n)+Math.sqrt(Math.max(0,d*d-c*c))}let l=s<0?-1:1;return{nx:"x"===n?l:0,ny:"y"===n?l:0,penetration:Math.max(0,r-Math.abs(s))}}function Ge(e){return"circle"===e.type?{type:"circle",radius:e.radius}:{type:"aabb",width:e.width,height:e.height}}function Ve(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 Ue(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,...e.fixedPosition?{fixedPosition:_e(e.fixedPosition)}:{},shape:Ge(e.shape),sleeping:e.sleeping,datum:e.datum,index:e.index,sleepTime:e.sleepTime,restitution:e.restitution,friction:e.friction}}function Ke(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 Qe(e){return{id:e.id,shape:Ve(e.shape),sensor:e.sensor,restitution:e.restitution,friction:e.friction,bodyFilter:Ke(e.bodyFilter),index:e.index}}function Je(e,t,i){if("aabb"!==t.type)return null;let r=e.x-e.prevX,n=e.y-e.prevY;if(0===r&&0===n)return null;let o="circle"===e.shape.type?e.shape.radius:e.shape.width/2,s="circle"===e.shape.type?e.shape.radius:e.shape.height/2,a=t.x-t.width/2,l=t.x+t.width/2,d=t.y-t.height/2,c=t.y+t.height/2;if(Math.max(e.x,e.prevX)+o<a||Math.min(e.x,e.prevX)-o>l||Math.max(e.y,e.prevY)+s<d||Math.min(e.y,e.prevY)-s>c)return null;let u="circle"===e.shape.type?0:o,h="circle"===e.shape.type?0:s,p=1/0,m=null,y=(e,t,r,n,o,s,a,l,d,c,u)=>{let h,y,f;if(r>0&&t+n<=o+i&&e+n>o)h=Math.max(0,(o-n-t)/r),y=e+n-o,f=-1;else{if(!(r<0&&t-n>=s-i&&e-n<s))return;h=Math.max(0,(s+n-t)/r),y=s-(e-n),f=1}let g=a+l*h;h<p&&g>=d&&g<=c&&(p=h,m={nx:u?f:0,ny:u?0:f,penetration:y})};return y(e.x,e.prevX,r,o,a,l,e.prevY,n,d-h,c+h,!0),y(e.y,e.prevY,n,s,d,c,e.prevX,r,a-u,l+u,!1),m}function Ze(e,t){return Math.abs(e.x-t.x)<=t.padding&&Math.abs(e.y-t.y)<=t.padding}function et(e,t){let i=tt(e),r=[];for(let e=0;e<t.length;e++)nt(i,t[e].bounds)&&r.push(e);return{bounds:i,indexes:r}}function tt(e,t=!0){let i="circle"===e.shape.type?e.shape.radius:e.shape.width/2,r="circle"===e.shape.type?e.shape.radius:e.shape.height/2,n=t?Math.max(.005,Math.min(i,r)):0;return{x:e.x,y:e.y,padding:n,minX:Math.min(e.x,e.prevX)-i-n,minY:Math.min(e.y,e.prevY)-r-n,maxX:Math.max(e.x,e.prevX)+i+n,maxY:Math.max(e.y,e.prevY)+r+n}}function it(e){let t="circle"===e.shape.type?e.shape.radius:e.shape.width/2,i="circle"===e.shape.type?e.shape.radius:e.shape.height/2;return{minX:e.x-t,minY:e.y-i,maxX:e.x+t,maxY:e.y+i}}function rt(e){let t=e.shape;if("aabb"===t.type)return it({x:t.x,y:t.y,shape:t});let i=(t.thickness??0)/2;return{minX:Math.min(t.x1,t.x2)-i,minY:Math.min(t.y1,t.y2)-i,maxX:Math.max(t.x1,t.x2)+i,maxY:Math.max(t.y1,t.y2)+i}}function nt(e,t){return e.minX<=t.maxX&&e.maxX>=t.minX&&e.minY<=t.maxY&&e.maxY>=t.minY}function ot(e,t,i={x:0,y:0}){let r=1,n=e.map(e=>{let t=tt(e,!(e.sleeping&&e.x===e.prevX&&e.y===e.prevY));return!1!==e.bodyCollisions&&(r=Math.max(r,t.maxX-t.minX,t.maxY-t.minY)),t}),o=Math.max(1,Math.min(t,r)),s=/* @__PURE__ */new Map;for(let t=0;t<e.length;t+=1){if(!1===e[t].bodyCollisions)continue;let i=n[t];i.cellX=Math.floor(i.minX/o),i.cellY=Math.floor(i.minY/o);for(let e=i.cellX;e<=Math.floor(i.maxX/o);e+=1){let r=s.get(e);r||s.set(e,r=/* @__PURE__ */new Map);for(let e=i.cellY;e<=Math.floor(i.maxY/o);e+=1){let i=r.get(e);i?i.push(t):r.set(e,[t])}}}let a=[];for(let[e,t]of s)for(let[i,r]of t)for(let t=0;t<r.length;t+=1)for(let o=t+1;o<r.length;o+=1){let s=r[t],l=r[o],d=n[s],c=n[l];e!==Math.max(d.cellX,c.cellX)||i!==Math.max(d.cellY,c.cellY)||nt(d,c)&&a.push([s,l])}let l=e.map(e=>e.x*i.x+e.y*i.y);return a.sort(([e,t],[i,r])=>Math.max(l[i],l[r])-Math.max(l[e],l[t])||(e===i?t-r:e-i)),{pairs:a,coversPositions:()=>e.every((e,t)=>!1===e.bodyCollisions||Ze(e,n[t]))}}function st(e,t){if("circle"!==e.shape.type||"circle"!==t.shape.type)return null;let i=e.shape.radius+t.shape.radius;if(i<=0)return null;let r=t.prevX-e.prevX,n=t.prevY-e.prevY,o=t.x-e.x-r,s=t.y-e.y-n,a=o*o+s*s,l=2*(r*o+n*s),d=r*r+n*n-i*i;if(d<-1e-5||a<=1e-12||l>=0)return null;let c=l*l-4*a*d;if(c<0)return null;let u=(-l-Math.sqrt(c))/(2*a);if(u<0||u>1)return null;let h=(r+u*o)/i,p=(n+u*s)/i,m=i-((t.x-e.x)*h+(t.y-e.y)*p);return m>0?{nx:h,ny:p,penetration:m}:null}var at={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},lt=1e-9,dt=.005;function ct(e,t,i){return Math.max(t,Math.min(i,e))}function ut(e,t,i){return Math.min(e??i,t??i)}function ht(e,t,i){return ct(Math.max(e??i,t??i),0,1)}function pt(e){return e<0?-1:1}function mt(e){return e.sleeping&&e.x===e.prevX&&e.y===e.prevY}function yt(e,t,i,r,n,o){let s=r-e,a=n-t,l=i+o,d=s*s+a*a;if(d>=l*l)return null;if(d<=lt)return{nx:1,ny:0,penetration:l};let c=Math.sqrt(d);return{nx:s/c,ny:a/c,penetration:l-c}}function ft(e,t,i,r,n,o,s,a){let l=n-e,d=(i+s)/2-Math.abs(l);if(d<=0)return null;let c=o-t,u=(r+a)/2-Math.abs(c);return u<=0?null:d<u?{nx:pt(l),ny:0,penetration:d}:{nx:0,ny:pt(c),penetration:u}}function gt(e,t,i,r,n,o,s){let a=o/2,l=s/2,d=e-ct(e,r-a,r+a),c=t-ct(t,n-l,n+l),u=d*d+c*c;if(u>i*i)return null;if(u<=lt){let o=Math.abs(e-(r-a)),s=Math.abs(e-(r+a)),d=Math.abs(t-(n-l)),c=Math.abs(t-(n+l)),u=Math.min(o,s,d,c);return u===o?{nx:-1,ny:0,penetration:i+o}:u===s?{nx:1,ny:0,penetration:i+s}:u===d?{nx:0,ny:-1,penetration:i+d}:{nx:0,ny:1,penetration:i+c}}let h=Math.sqrt(u);return{nx:d/h,ny:c/h,penetration:i-h}}function bt(e,t,i,r,n,o,s,a=0){let l=o-r,d=s-n,c=l*l+d*d,u=c<=lt?0:ct(((e-r)*l+(t-n)*d)/c,0,1),h=i+a/2,p=e-(r+l*u),m=t-(n+d*u),y=p*p+m*m;if(y>=h*h)return null;if(y<=lt){let e=Math.sqrt(c);return e<=lt?{nx:1,ny:0,penetration:h}:{nx:-d/e,ny:l/e,penetration:h}}let f=Math.sqrt(y);return{nx:p/f,ny:m/f,penetration:h-f}}function vt(e,t){if("circle"===e.shape.type&&"circle"===t.shape.type)return yt(e.x,e.y,e.shape.radius,t.x,t.y,t.shape.radius);if("aabb"===e.shape.type&&"aabb"===t.shape.type)return ft(e.x,e.y,e.shape.width,e.shape.height,t.x,t.y,t.shape.width,t.shape.height);let i="circle"===e.shape.type?e:t,r=i===e?t:e;if("circle"!==i.shape.type||"aabb"!==r.shape.type)return null;let n=gt(i.x,i.y,i.shape.radius,r.x,r.y,r.shape.width,r.shape.height);return n&&i===e&&(n.nx=-n.nx,n.ny=-n.ny),n}function xt(e,t){let i=t.shape;if("aabb"===i.type)return"circle"===e.shape.type?gt(e.x,e.y,e.shape.radius,i.x,i.y,i.width,i.height):ft(i.x,i.y,i.width,i.height,e.x,e.y,e.shape.width,e.shape.height);let r="circle"===e.shape.type?e.shape.radius:Math.sqrt(e.shape.width*e.shape.width+e.shape.height*e.shape.height)/2;return bt(e.x,e.y,r,i.x1,i.y1,i.x2,i.y2,i.thickness??0)}function wt(e,t){return`${e}\0${t}`}function It(e){let t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}function kt(e,t){if(!t)return;let i=e;for(let e of t.split(".")){if(null==i||"object"!=typeof i||!Object.prototype.hasOwnProperty.call(i,e))return;i=i[e]}return i}function St(e,t){return!!t?.some(t=>Object.is(e,t))}function Mt(e,t){if(!t)return!0;if("function"==typeof t)return t(e);let i=kt(e,t.property);return!("equals"in t&&!Object.is(i,t.equals)||"notEquals"in t&&Object.is(i,t.notEquals)||t.oneOf&&!St(i,t.oneOf)||t.notOneOf&&St(i,t.notOneOf))}function At(e,t){return Mt(t,e.bodyFilter)}var $t=class{constructor(e={}){this.capabilities={determinism:"strict",sensors:!0,joints:!1,ccd:!1,maxBodiesHint:5e3,worker:!1},this.bodies=/* @__PURE__ */new Map,this.colliders=/* @__PURE__ */new Map,this.springs=/* @__PURE__ */new Map,this.activeSensors=/* @__PURE__ */new Set,this.supportedThisStep=/* @__PURE__ */new Set,this.supportDependents=/* @__PURE__ */new Map,this.supportContactsThisStep=/* @__PURE__ */new Set,this.reboundingThisStep=/* @__PURE__ */new Set,this.interpenetratingThisStep=/* @__PURE__ */new Set,this.lastEvents=[],this.nextBodyIndex=0,this.nextColliderIndex=0,this.nextSpringIndex=0,this.options={...at,...e},this.random=b(this.options.seed)}init(e={}){this.options={...at,...e},this.random=b(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){let 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(lt,e.mass??1),bodyCollisions:e.bodyCollisions??!0,...e.fixedPosition?{fixedPosition:_e(e.fixedPosition)}:{},shape:Ge(e.shape),sleeping:!1,datum:e.datum,restitution:e.restitution,friction:e.friction,index:this.nextBodyIndex,sleepTime:0};Ye(t),this.nextBodyIndex+=1,this.bodies.set(e.id,t)}remove(e){for(let t of e){this.bodies.delete(t);for(let e of Array.from(this.activeSensors))It(e).bodyId===t&&this.activeSensors.delete(e)}}setColliders(e){this.colliders.clear(),this.activeSensors.clear(),this.nextColliderIndex=0;for(let t of e)this.colliders.set(t.id,{...t,shape:Ve(t.shape),bodyFilter:Ke(t.bodyFilter),index:this.nextColliderIndex}),this.nextColliderIndex+=1}setConstraint(e){let 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,i){let r=this.bodies.get(e);r&&(r.vx+=t/r.mass,r.vy+=i/r.mass,Ye(r),this.wake(r))}step(e=this.options.fixedDt){let t=Math.max(0,e);if(this.lastEvents=[],0===t)return;this.reboundingThisStep.clear();let i=this.sortedBodies();for(let e of i)e.prevX=e.x,e.prevY=e.y;this.applySprings(t);let r=this.options.maxVelocity;for(let e of i)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,Ye(e),r>0){let t=Math.sqrt(e.vx*e.vx+e.vy*e.vy);if(t>r){let i=r/t;e.vx*=i,e.vy*=i}}e.x+=e.vx*t,e.y+=e.vy*t}this.supportedThisStep.clear(),this.supportDependents.clear(),this.supportContactsThisStep.clear(),this.interpenetratingThisStep.clear();let n=this.sortedColliders().filter(e=>!e.sensor).map(e=>({collider:e,bounds:rt(e)})),o=n.some(({collider:e})=>e.bodyFilter)?void 0:new Array(i.length);this.resolveColliders(i,n,!1,o);let s=o&&i.map(mt),a=ot(i,this.options.cellSize,this.options.gravity);for(let e=0;e<this.options.collisionIterations;e+=1){e>0&&!a.coversPositions()&&(a=ot(i,this.options.cellSize,this.options.gravity));let t=this.resolveBodyPairs(i,a.pairs,0===e,s),r=this.resolveColliders(i,n,0===e,o);if(o&&!t&&!r)break}a.coversPositions()||(a=ot(i,this.options.cellSize,this.options.gravity));for(let[e,t]of a.pairs){let r=vt(i[e],i[t]);r&&r.penetration>.02&&(this.interpenetratingThisStep.add(i[e].id),this.interpenetratingThisStep.add(i[t].id))}let l=Array.from(this.supportedThisStep);for(let e=0;e<l.length;e+=1)for(let t of this.supportDependents.get(l[e])??[])this.supportedThisStep.has(t)||(this.supportedThisStep.add(t),l.push(t));this.reconcileSupportedVelocity(i,t),this.updateSensors(i),this.updateSleeping(i,t)}settle(e=1200,t=this.options.fixedDt){let i=0;for(;i<e&&!this.allSleeping();)this.step(t),i+=1;return i}readState(e=[]){e.length=0;for(let 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,...t.fixedPosition?{fixedPosition:_e(t.fixedPosition)}:{},shape:Ge(t.shape),sleeping:t.sleeping,datum:t.datum});return e}events(){return this.lastEvents.slice()}activeSensorPairs(){return Array.from(this.activeSensors).sort().map(It)}allSleeping(){for(let 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(Ue),colliders:this.sortedColliders().map(Qe),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=b(this.options.seed),this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors=new Set(e.activeSensors),this.lastEvents=[],this.nextBodyIndex=0;for(let t of e.bodies){let e=Ue(t);Ye(e),this.bodies.set(e.id,e),this.nextBodyIndex=Math.max(this.nextBodyIndex,e.index+1)}this.nextColliderIndex=0;for(let t of e.colliders){let e=Qe(t);this.colliders.set(e.id,e),this.nextColliderIndex=Math.max(this.nextColliderIndex,e.index+1)}this.nextSpringIndex=0;for(let t of e.springs){this.springs.set(t.id,{...t,target:{...t.target}});let 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(let t of Array.from(this.springs.values()).sort((e,t)=>e.id.localeCompare(t.id))){let i=this.bodies.get(t.bodyId);if(!i||i.sleeping)continue;let r="point"===t.target.type?t.target:this.bodies.get(t.target.bodyId);if(!r)continue;let n=r.x-i.x,o=r.y-i.y,s=n*n+o*o,a=Math.sqrt(s);if(a<=lt)continue;let l=n/a,d=o/a,c="vx"in r?r.vx:0,u="vy"in r?r.vy:0,h=(c-i.vx)*l+(u-i.vy)*d,p=(a-t.restLength)*t.stiffness+h*t.damping;i.vx+=p*l*e/i.mass,i.vy+=p*d*e/i.mass}}resolveBodyPairs(e,t,i,r){let n=!1;for(let[o,s]of t){let t=e[o],a=e[s];if(!t||!a)continue;if(!i&&r?.[o]&&r[s]&&mt(t)&&mt(a)){n=!0;continue}let l=st(t,a)??vt(t,a);l&&(n=!0,this.resolveDynamicCollision(t,a,l),i&&this.lastEvents.push({type:"contact",bodyId:t.id,otherId:a.id,sensor:!1}))}return n}resolveDynamicCollision(e,t,i){(e.fixedPosition||t.fixedPosition)&&(!e.sleeping&&null==e.fixedPosition?.x||!t.sleeping&&null==t.fixedPosition?.x?(e.sleeping||null!=e.fixedPosition?.y)&&(t.sleeping||null!=t.fixedPosition?.y)&&(i=Xe(e,t,"y")):i=Xe(e,t,"x"));let r=this.options.gravity,n=Math.hypot(r.x,r.y),o=this.contactOpposesGravity(i.nx,i.ny,n),s=this.contactOpposesGravity(-i.nx,-i.ny,n);o&&(e.sleeping&&this.supportedThisStep.add(t.id),this.addSupportContact(e.id,t.id)),s&&(t.sleeping&&this.supportedThisStep.add(e.id),this.addSupportContact(t.id,e.id));let a=e.sleeping?0:1/e.mass,l=t.sleeping?0:1/t.mass,d=null==e.fixedPosition?.x?a:0,c=null==e.fixedPosition?.y?a:0,u=null==t.fixedPosition?.x?l:0,h=null==t.fixedPosition?.y?l:0,p=e.fixedPosition||t.fixedPosition?i.nx**2*(d+u)+i.ny**2*(c+h):a+l;if(p<=lt)return;let m=this.supportedThisStep.has(e.id)&&o&&!t.sleeping&&!t.fixedPosition,y=this.supportedThisStep.has(t.id)&&s&&!e.sleeping&&!e.fixedPosition,f=n>1,g=f&&m?0:d,b=f&&m?0:c,v=f&&!m&&y?0:u,x=f&&!m&&y?0:h,w=i.nx**2*(g+v)+i.ny**2*(b+x),I=Math.max(0,i.penetration-dt)/Math.max(lt,w);e.x-=i.nx*I*g,e.y-=i.ny*I*b,t.x+=i.nx*I*v,t.y+=i.ny*I*x,f&&m&&this.supportedThisStep.add(t.id),f&&y&&this.supportedThisStep.add(e.id);let k=t.vx-e.vx,S=t.vy-e.vy,M=k*i.nx+S*i.ny;if(M>0)return;let A=Math.abs(M),$=ut(e.restitution,t.restitution,this.options.restitution),C=e.vx*r.x+e.vy*r.y,P=t.vx*r.x+t.vy*r.y,R=-(1+$)*M/p,D=R*i.nx,B=R*i.ny;e.vx-=D*d,e.vy-=B*c,t.vx+=D*u,t.vy+=B*h,this.applyFriction(e,t,i,R,d,c,u,h),$>0&&(C>=0&&e.vx*r.x+e.vy*r.y<0&&this.reboundingThisStep.add(e.id),P>=0&&t.vx*r.x+t.vy*r.y<0&&this.reboundingThisStep.add(t.id)),A>this.options.contactWakeSpeed&&(this.wake(e),this.wake(t))}applyFriction(e,t,i,r,n,o,s,a){let l=-i.ny,d=i.nx,c=(t.vx-e.vx)*l+(t.vy-e.vy)*d,u=e.fixedPosition||t.fixedPosition?l**2*(n+s)+d**2*(o+a):n+s;if(Math.abs(c)<=lt||u<=lt)return;let h=ht(e.friction,t.friction,this.options.friction),p=ct(-c/u,-r*h,r*h),m=p*l,y=p*d;e.vx-=m*n,e.vy-=y*o,t.vx+=m*s,t.vy+=y*a}resolveColliders(e,t,i,r){if(0===t.length)return!1;let n=!1;for(let o=0;o<e.length;o++){let s=e[o],a=r?.[o];r&&(!a||!Ze(s,a.bounds))&&(r[o]=a=et(s,t));let l=0;for(;l<(a?a.indexes.length:t.length);){let e=a?a.indexes[l++]:l++,{collider:d,bounds:c}=t[e];if(!At(d,s))continue;let u=Je(s,d.shape,dt+lt);if(!u&&!nt(it(s),c))continue;let h=u??xt(s,d);if(h&&(n=!0,this.resolveStaticCollision(s,d,h),this.contactOpposesGravity(h.nx,h.ny)&&this.supportedThisStep.add(s.id),i&&this.lastEvents.push({type:"contact",bodyId:s.id,otherId:d.id,sensor:!1}),a&&r&&!Ze(s,a.bounds)))for(r[o]=a=et(s,t),l=0;l<a.indexes.length&&a.indexes[l]<=e;)l++}}return n}resolveStaticCollision(e,t,i){e.x+=i.nx*Math.max(0,i.penetration-dt),e.y+=i.ny*Math.max(0,i.penetration-dt);let r=e.vx*i.nx+e.vy*i.ny;if(r<0){let n=ut(e.restitution,t.restitution,this.options.restitution),o=this.options.gravity,s=e.vx*o.x+e.vy*o.y;e.vx-=(1+n)*r*i.nx,e.vy-=(1+n)*r*i.ny;let a=-i.ny,l=i.nx,d=e.vx*a+e.vy*l,c=ht(e.friction,t.friction,this.options.friction);e.vx-=d*a*c,e.vy-=d*l*c,n>0&&s>=0&&e.vx*o.x+e.vy*o.y<0&&this.reboundingThisStep.add(e.id)}Ye(e)}updateSensors(e){let t=this.sortedColliders().filter(e=>e.sensor);if(0===t.length&&0===this.activeSensors.size)return;let i=/* @__PURE__ */new Set;for(let r of e){let e=it(r);for(let n of t){if(!At(n,r)||!nt(e,rt(n))||!xt(r,n))continue;let t=wt(n.id,r.id);i.add(t),this.activeSensors.has(t)||this.lastEvents.push({type:"sensor-enter",bodyId:r.id,sensorId:n.id})}}for(let e of Array.from(this.activeSensors).sort()){if(i.has(e))continue;let{sensorId:t,bodyId:r}=It(e);this.lastEvents.push({type:"sensor-exit",bodyId:r,sensorId:t})}this.activeSensors=i}updateSleeping(e,t){let i=Math.hypot(this.options.gravity.x,this.options.gravity.y)>1;for(let r of e){let e=Math.sqrt(r.vx*r.vx+r.vy*r.vy),n=Math.sqrt((r.x-r.prevX)*(r.x-r.prevX)+(r.y-r.prevY)*(r.y-r.prevY));e<this.options.sleepSpeed&&n<this.options.sleepSpeed*t&&!this.interpenetratingThisStep.has(r.id)&&(!i||this.supportedThisStep.has(r.id))?(r.sleepTime+=t,!r.sleeping&&r.sleepTime>=this.options.sleepAfter&&(r.sleeping=!0,r.vx=0,r.vy=0,this.lastEvents.push({type:"sleep",bodyId:r.id}))):r.sleeping?this.wake(r):r.sleepTime=0}}addSupportContact(e,t){let i=this.supportDependents.get(e);i?.has(t)||(this.supportContactsThisStep.add(e),this.supportContactsThisStep.add(t),i||(i=/* @__PURE__ */new Set,this.supportDependents.set(e,i)),i.add(t))}reconcileSupportedVelocity(e,t){let i=this.options.gravity;if(!(Math.hypot(i.x,i.y)<=1))for(let r of e)r.sleeping||!this.supportedThisStep.has(r.id)||!this.supportContactsThisStep.has(r.id)||this.reboundingThisStep.has(r.id)&&r.vx*i.x+r.vy*i.y<0||(r.vx=(r.x-r.prevX)/t,r.vy=(r.y-r.prevY)/t,Ye(r))}contactOpposesGravity(e,t,i){let{x:r,y:n}=this.options.gravity;return i??(i=Math.hypot(r,n)),i<=1e-9||(e*r+t*n)/i<-.2}wake(e){e.sleeping&&this.lastEvents.push({type:"wake",bodyId:e.id}),e.sleeping=!1,e.sleepTime=0}nextRandom(){return this.random()}},Ct=class{constructor(e={}){this.id="builtin",this.capabilities={...(new $t).capabilities,engine:"builtin"},this.world=new $t(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,i){this.world.applyImpulse(e,t,i)}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 Pt(e={}){return new Ct(e)}function Rt(e,t={}){return e?"function"==typeof e?e(t):(e.init(t),e):Pt(t)}var Dt=["binId","targetBin","category","windowIndex","lane","group"];function Bt(){return{count:0,total:0,mean:0,m2:0,min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY}}function Tt(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);let i=t-e.mean;e.mean+=i/e.count;let r=t-e.mean;e.m2+=i*r}function jt(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 Ot(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:Number.POSITIVE_INFINITY,max:e.count>0?e.max:Number.NEGATIVE_INFINITY}}function Et(e,t){let i=e;if(null!=i[t])return i[t];let r=e.datum;return r&&"object"==typeof r?r[t]:void 0}function Nt(e,t,i){return"function"==typeof e?e(t,i):"string"==typeof e?Et(t,e):void 0}function Ft(e,t,i){if("number"==typeof e)return e;let r="function"==typeof e?e(t,i):"string"==typeof e?Et(t,e):1,n="number"==typeof r?r:Number(r);return Number.isFinite(n)?n:1}function Wt(e){if(null==e)return;let t=String(e);return t.trim()?t:void 0}function qt(e){for(let t of Dt){let i=Wt(Et(e,t));if(i)return i}return"sediment"}function Ht(e){let t=jt(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:jt(e.x),y:jt(e.y),value:t}}var zt=class{constructor(e=!1){this.bins=/* @__PURE__ */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;let t=this.nextIndex;this.nextIndex+=1;let i=Wt(Nt(this.config.binAccessor,e,t))??qt(e),r=Wt(Nt(this.config.labelAccessor,e,t))??i,n=Ft(this.config.valueAccessor,e,t),o=Math.max(0,Math.floor(this.config.retainBodyIds??12)),s=this.bins.get(i);return s||(s={id:i,label:r,bodyIds:[],x:Bt(),y:Bt(),value:Bt()},this.bins.set(i,s)),s.label=r,s.lastBodyId=e.id,s.lastDatum=e.datum,Tt(s.x,e.x),Tt(s.y,e.y),Tt(s.value,n),o>0&&(s.bodyIds.push(e.id),s.bodyIds.length>o&&(s.bodyIds=s.bodyIds.slice(s.bodyIds.length-o))),Ht(s)}clear(){this.bins.clear(),this.nextIndex=0}snapshot(){return Array.from(this.bins.values()).map(Ht)}restore(e=[]){this.bins.clear();for(let 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:Ot(t.x),y:Ot(t.y),value:Ot(t.value)});this.nextIndex=e.reduce((e,t)=>e+t.count,0)}totals(){let 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 Lt(e,t={}){let{baselineY:i=0,binWidth:r=24,gap:n=2,maxHeight:o=80,value:s="count",x:a}=t,l=e.reduce((e,t)=>Math.max(e,t[s]),1);return e.map((e,t)=>{let d=Math.max(0,e[s]/l*o),c=a?.(e,t)??t*(r+n);return{binId:e.id,label:e.label,index:t,count:e.count,total:e.total,x:c,y:i-d,width:r,height:d,meanX:e.x.mean,meanY:e.y.mean}})}function Yt(e){let t=Number(e);if(Number.isFinite(t)&&!(t<=0))return Math.floor(t)}function _t(e,t,i){if(!1===i)return;let r=Yt(i?.warnAt);return null!=r?r:null!=e?Math.max(1,Math.floor(.8*e)):null!=t?Math.max(1,Math.floor(.8*t)):void 0}function Xt(e){let t=Math.max(0,Math.floor(e.liveBodies)),i=Math.max(0,Math.floor(e.queuedBodies??0)),r=t+i,n=Yt(e.bodyLimit),o=Yt(e.engineMaxBodiesHint),s=_t(n,o,e.options),a=null==n?0:Math.max(0,t-n),l=a>0?"overflow":null!=s&&r>=s?"warning":"ok";return{action:"overflow"!==l?"continue":e.sedimentEnabled?"sediment":e.evictionEnabled?"evict":"retain",bodyLimit:n,engineMaxBodiesHint:o,liveBodies:t,overflow:a,projectedBodies:r,queuedBodies:i,state:l,warnAt:s}}var Gt={bodyLimit:Number.POSITIVE_INFINITY,eviction:"oldest",fixedDt:1/120,maxDeltaSeconds:.1,maxSubsteps:8,settleStepLimit:1200,timeScale:1},Vt={chartId:"physics",chartType:"physics",sensors:{},onObservation:void 0,onSimulationStateChange:void 0};function Ut(e={},t=Vt){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 Kt(e){return{...e,shape:{...e.shape},...e.fixedPosition?{fixedPosition:{...e.fixedPosition}}:{},datum:e.datum,springs:e.springs?.map(e=>({...e,target:{...e.target}}))}}function Qt(e){if(e instanceof Date){let t=e.getTime();return Number.isFinite(t)?t:void 0}let t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:void 0}function Jt(e,t){let i=e;if(null!=i[t])return i[t];let r=e.datum;return r&&"object"==typeof r?r[t]:void 0}function Zt(e,t,i){return"function"==typeof i?Qt(i(e,t)):"string"==typeof i?Qt(Jt(e,i)):Qt(e.spawnAt)??Qt(Jt(e,"arrivalTime"))??Qt(Jt(e,"timestamp"))??Qt(Jt(e,"time"))??Qt(Jt(e,"eventTime"))}function ei(e,t={}){let i=Qt(t.startAt)??0,r=t.pacing??"immediate";if("arrival"===r){let r=1/0,n=e.map((e,i)=>{let n=Zt(e,i,t.timeAccessor);return null!=n&&(r=Math.min(r,n)),n}),o=Qt(t.timeScale)??1,s=o>0?o:1;return e.map((e,t)=>{let o=n[t],a=null==o?0:Math.max(0,o-r);return{...Kt(e),spawnAt:i+a/s}})}if("object"==typeof r){let t=Qt(r.ratePerSec);if(t&&t>0)return e.map((e,r)=>({...Kt(e),spawnAt:i+r/t}))}return e.map(e=>({...Kt(e),spawnAt:i}))}function ti(e){return{...Kt(e),sequence:e.sequence,spawnAt:e.spawnAt}}function ii(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 ri(e){return!1!==e&&{...e}}function ni(e,t){return e.spawnAt===t.spawnAt?e.sequence-t.sequence:e.spawnAt-t.spawnAt}function oi(e){return{...e,gravity:{...e.gravity}}}function si(e){return"circle"===e.shape.type?e.shape.radius:Math.hypot(e.shape.width,e.shape.height)/2}function ai(e,t,i,r){if("circle"===e.shape.type){let n=e.x-t,o=e.y-i,s=e.shape.radius+r,a=n*n+o*o;return a<=s*s?a:null}let n=Math.max(Math.abs(t-e.x)-e.shape.width/2,0),o=Math.max(Math.abs(i-e.y)-e.shape.height/2,0),s=n*n+o*o;return s<=r*r?s:null}function li(e,t){return`${e}\0${t}`}function di(e){let t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}function ci(e,t={}){let{idPrefix:i="plot",includeFloor:r=!0,includeCeiling:n=!1,includeLeftWall:o=!0,includeRightWall:s=!0,wallThickness:a=20,floorThickness:l=a}=t,d=[],c=e.x+e.width/2,u=e.y+e.height/2,h=(e,t,r,n,o)=>{d.push({id:`${i}-${e}`,shape:{type:"aabb",x:t,y:r,width:n,height:o}})};return r&&h("floor",c,e.y+e.height+l/2,e.width+2*a,l),n&&h("ceiling",c,e.y-l/2,e.width+2*a,l),o&&h("left-wall",e.x-a/2,u,a,e.height+2*l),s&&h("right-wall",e.x+e.width+a/2,u,a,e.height+2*l),d}function ui(e){let{idPrefix:t="bin",count:i,domainStart:r,domainStep:n,xScale:o,yTop:s,yBottom:a,wallThickness:l=4,includeBoundaryWalls:d=!0,includeInteriorWalls:c=!0,closedBefore:u,lidY:h=s,lidThickness:p=Math.max(2,l)}=e,m=[],y=s+(a-s)/2,f=Math.abs(a-s),g=d?i:i-1;if(c||d)for(let e=d?0:1;e<=g;e+=1){if(!c&&e>0&&e<i)continue;let s=o(r+e*n);m.push({id:`${t}-wall-${e}`,shape:{type:"aabb",x:s,y:y,width:l,height:f}})}if(null!=u)for(let e=0;e<i;e+=1){let i=r+e*n,s=i+n;if(s>=u)continue;let a=o(i),d=o(s);m.push({id:`${t}-lid-${e}`,shape:{type:"segment",x1:Math.min(a,d)+l/2,y1:h,x2:Math.max(a,d)-l/2,y2:h,thickness:p}})}return m}import{quadtree as hi}from"d3-quadtree";var pi=class{constructor(){this.maxSearchRadius=0,this.revision=-1,this.tree=null}hitTest(e,t,i,r,n,o=0,s){let a=this.ensure(e,t);if(!a)return null;let l=null,d=Number.POSITIVE_INFINITY,c=Math.max(0,s?.searchRadius??Math.max(0,o)+this.maxSearchRadius),u=r-c,h=r+c,p=n-c,m=n+c;return a.visit((e,t,a,c,y)=>{if(c<u||t>h||y<p||a>m)return!0;if(e.length)return!1;let f=e;for(;f;){let e=f.data;if(e&&(!s?.include||s.include(e))){let t=s?.distanceSquared?s.distanceSquared(e,r,n):ai(e,r,n,Math.max(0,o));null!=t&&(t<d||t===d&&i.indexOf(e.id)>i.indexOf(l?.id??""))&&(l=e,d=t)}f=f.next}return!1}),l}ensure(e,t){if(this.tree&&this.revision===t)return this.tree;let i=e.readState();return 0===i.length?(this.tree=null,this.maxSearchRadius=0,this.revision=t,null):(this.maxSearchRadius=i.reduce((e,t)=>Math.max(e,si(t)),0),this.tree=hi().x(e=>e.x).y(e=>e.y).addAll(i),this.revision=t,this.tree)}},mi=["data","scene-geometry","data-paint","accessibility","evidence"],yi=["scene-geometry","data-paint","accessibility","evidence"],fi=["overlay","accessibility","evidence"],gi=(e,t)=>({retainedData:e,invalidations:t}),bi=["layout","scene-geometry","data-paint","overlay","accessibility","evidence"],vi=["scene-geometry","data-paint","accessibility","evidence"],xi=[],wi={engine:/* @__PURE__ */gi("rebuild",["scene-geometry","data-paint","accessibility","evidence"]),kernel:/* @__PURE__ */gi("preserve",vi),colliders:/* @__PURE__ */gi("preserve",vi),sediment:/* @__PURE__ */gi("preserve",vi),bodyBudget:/* @__PURE__ */gi("preserve",bi),bodyLimit:/* @__PURE__ */gi("preserve",bi),eviction:/* @__PURE__ */gi("preserve",bi),fixedDt:/* @__PURE__ */gi("preserve",xi),maxDeltaSeconds:/* @__PURE__ */gi("preserve",xi),maxSubsteps:/* @__PURE__ */gi("preserve",xi),settleStepLimit:/* @__PURE__ */gi("preserve",xi),timeScale:/* @__PURE__ */gi("preserve",xi),observation:/* @__PURE__ */gi("preserve",xi)},Ii=/* @__PURE__ */gi("preserve",bi);function ki(e){let t="preserve",i=/* @__PURE__ */new Set;for(let r of e){let e=wi[r]??Ii;"rebuild"===e.retainedData&&(t="rebuild");for(let t of e.invalidations)i.add(t)}return{retainedData:t,invalidations:i}}var Si=["seed","fixedDt","cellSize","collisionIterations","velocityDamping","sleepSpeed","sleepAfter","restitution","friction","maxVelocity","contactWakeSpeed"];function Mi(e,t){return e===t||!(!e||!t||e.gravity?.x!==t.gravity?.x||e.gravity?.y!==t.gravity?.y)&&Si.every(i=>e[i]===t[i])}function Ai(e,t){return Object.keys(e).filter(i=>"kernel"===i?!Mi(e.kernel,t.kernel):e[i]!==t[i])}function $i(e,t,i){if(!t.some(e=>"sleep"===e.type))return;let r=new Map(e.readState().map(e=>[e.id,e]));for(let e of t){if("sleep"!==e.type)continue;let t=r.get(e.bodyId);i.emit({type:"physics-settle",timestamp:i.elapsedSeconds,chartType:i.observation.chartType,chartId:i.observation.chartId,bodyId:e.bodyId,datum:t?.datum,x:t?.x,y:t?.y})}}function Ci(e,t,i){let r=new Set(e.activeSensorPairs().map(e=>li(e.sensorId,e.bodyId))),n=r.size!==t.size;if(!n)for(let e of r)if(!t.has(e)){n=!0;break}if(!n)return r;let o=new Map(e.readState().map(e=>[e.id,e])),s=(e,t)=>{let{sensorId:r,bodyId:n}=di(t),s=i.observation.sensors[r],a=o.get(n);i.emit({type:"enter"===e?s?.enterType??"physics-bin-enter":s?.exitType??"physics-bin-exit",timestamp:i.elapsedSeconds,chartType:i.observation.chartType,chartId:i.observation.chartId,bodyId:n,datum:a?.datum,x:a?.x,y:a?.y,sensorId:r,binId:s?.binId??r})};for(let e of Array.from(r).sort())t.has(e)||s("enter",e);for(let e of Array.from(t).sort())r.has(e)||s("exit",e);return r}function Pi(e,t){for(let i of e)t.has(di(i).bodyId)&&e.delete(i)}function Ri(e,t,i,r){return e||!t?"paused":i||!r?"running":"settled"}function Di(e,t,i){i.observation.onSimulationStateChange?.(t,e),("running"===t||"settled"===t)&&i.emit({type:"running"===t?"sim-active":"sim-idle",timestamp:i.elapsedSeconds,chartType:i.observation.chartType,chartId:i.observation.chartId,simulationState:t,previousSimulationState:e})}function Bi(e,t){t.emit({type:"overflow"===e.state?"physics-budget-overflow":"physics-budget-warning",timestamp:t.elapsedSeconds,chartType:t.observation.chartType,chartId:t.observation.chartId,budgetAction:e.action,bodyLimit:e.bodyLimit,engineMaxBodiesHint:e.engineMaxBodiesHint,liveBodies:e.liveBodies,overflow:e.overflow,projectedBodies:e.projectedBodies,queuedBodies:e.queuedBodies,warnAt:e.warnAt})}function Ti(e,t,i){if("sleeping-first"!==t)return i.slice();let r=new Map(e.readState().map(e=>[e.id,e.sleeping])),n=[],o=[];for(let e of i)r.get(e)?n.push(e):o.push(e);return[...n,...o]}function ji(e,t,i,r){let n=new Map(e.readState().map(e=>[e.id,e])),o=[];for(let e of i){let i=n.get(e);if(!i)continue;let s=t.add(i);s&&(o.push(e),r.emit({type:"physics-sediment",timestamp:r.elapsedSeconds,chartType:r.observation.chartType,chartId:r.observation.chartId,bodyId:e,datum:i.datum,x:i.x,y:i.y,binId:s.id,count:s.count,total:s.total}))}return o}function Oi(e,t,i,r,n,o){let s={evicted:[],sedimented:[],liveBodyOrder:n};if(!1===i)return s;let a=Math.max(0,Math.floor(r));if(!Number.isFinite(a))return s;let l=n.length-a;if(l<=0)return s;let d=Ti(e,i,n).slice(0,l);if(0===d.length)return s;let c=ji(e,t,d,o);e.remove(d);let u=new Set(d);return{evicted:d,sedimented:c,liveBodyOrder:n.filter(e=>!u.has(e))}}function Ei(e){let t=e?.sleepSpeed;return"number"==typeof t&&Number.isFinite(t)&&t>0?t:8}var Ni=class{constructor(){this.seconds=0,this.speed=8,this.scratch=[]}setKernelOptions(e){this.speed=Ei(e)}reset(){this.seconds=0}isAtRest(){return this.seconds>=.6}refresh(e,t,i){if(i>0)return void(this.seconds=0);if(e.allSleeping())return void(this.seconds+=Math.max(0,t));let r=e.readState(this.scratch),n=this.speed*this.speed,o=!0;for(let e of r){if(e.sleeping)continue;let i=e.x-e.prevX,r=e.y-e.prevY;if(e.vx*e.vx+e.vy*e.vy>=n||t>0&&i*i+r*r>=n*t*t){o=!1;break}}this.seconds=o?this.seconds+Math.max(0,t):0}};function Fi(e,t,i=!1){if(!e)return;let r=["spawned","evicted","sedimented","events","observations"],n={spawned:0,evicted:0,sedimented:0,events:0,observations:0},o=o=>{let s=t(o),a={...s};r.forEach(e=>{a[e]=s[e].slice(n[e]),n[e]=s[e].length}),(0!==o||i||!r.every(e=>0===a[e].length))&&e.onStep(a)};return o(0),()=>o(1)}function Wi(e,t,i,r={}){let n,o=0,s=0,a=t+(r.drainArrivals?Math.max(0,Math.ceil(((e.lastArrival()??e.elapsed())-e.elapsed())/e.fixedDt)):0);for(;o+s<a&&!r.shouldStop?.()&&(!1===r.stopAtRest||e.queueSize()>0||!e.atRest()||r.continueWhile?.());){let t=e.nextArrival(),l=r.skipIdle&&null!=t&&e.atRest()?Math.min(Math.max(0,Math.floor((t-e.elapsed())/e.fixedDt)-1),Math.max(0,a-o-s-1)):0;l>0&&(e.advanceTime(l*e.fixedDt),s+=l),e.step(e.fixedDt),e.advanceTime(e.fixedDt);let d=e.drainEvents();i.events&&(i.events.push(...d),e.observeKernelEvents(d,i.observations),e.observeSensorTransitions(i.observations));let c=[];if(e.spawnDue(c,i.observations),c.length>0){i.spawned.push(...c),n=e.observeBodyBudget(i.observations);let t=e.evictOverflow(i.observations);i.evicted?.push(...t.evicted),i.sedimented?.push(...t.sedimented)}o+=1,e.refreshQuiescence(e.fixedDt,c.length),r.afterStep?.()}return{steps:o,budget:n}}var qi=class{constructor(e={}){this.activeSensorPairs=/* @__PURE__ */new Set,this.accumulator=0,this.bodyBudgetObservationKey="ok",this.bodySpatialIndex=new pi,this.elapsedSeconds=0,this.liveBodyOrder=[],this.nextSequence=0,this.paused=!1,this.queue=[],this.revision=0,this.observedInitialBoundary=!1,this.updateResults=new te,this.simulationState="settled",this.visible=!0,this.quiescence=new Ni;let{bodyBudget:t,colliders:i,engine:r,kernel:n,observation:o,sediment:s,...a}=e;this.config={...Gt,...a},this.configInput={...e},this.bodyBudget=t??{},this.engineInput=r,this.observation=Ut(o),this.sediment=new zt(s??!1),this.world=Rt(r,{fixedDt:this.config.fixedDt,...n}),this.quiescence.setKernelOptions(n),i&&this.world.setColliders(ii(i))}updateConfig(e){let t=Ai(e,this.configInput),{colliders:i,bodyBudget:r,engine:n,kernel:o,observation:s,sediment:a,...l}=e;if(this.config={...this.config,...l},void 0!==r&&(this.bodyBudget=r,!1===r&&(this.bodyBudgetObservationKey="ok")),n&&n!==this.engineInput){let e=this.world.snapshot();this.world.dispose(),this.engineInput=n,this.world=Rt(n,e.options),this.world.restore(e),this.revision+=1}if(o&&!Mi(o,this.configInput.kernel)){let 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=Ut(s,this.observation)),this.sediment.updateConfig(a),i&&(this.world.setColliders(ii(i)),this.revision+=1),this.configInput={...this.configInput,...e};let d=ki(t);this.updateResults.record({kind:"config",keys:t},d.invalidations)}updateConfigWithResult(e){return this.updateConfig(e),this.updateResults.last}setColliders(e){this.world.setColliders(ii(e)),this.revision+=1,this.updateResults.record({kind:"config",keys:["colliders"]},ki(["colliders"]).invalidations)}enqueue(e,t){let i=Array.isArray(e)?e:[e],r=t?ei(i,{...t,startAt:t.startAt??this.elapsedSeconds}):i;for(let e of r)this.queue.push({...Kt(e),sequence:this.nextSequence,spawnAt:e.spawnAt??this.elapsedSeconds}),this.nextSequence+=1;this.queue.sort(ni),r.length>0&&(this.revision+=1),this.updateResults.record({kind:"enqueue",count:r.length},r.length?mi:[])}enqueueWithResult(e,t){return this.enqueue(e,t),this.updateResults.last}spawnNow(e){this.spawnOne(Kt(e)),this.nextSequence+=1,this.observeBodyBudget(),this.evictOverflow(),this.revision+=1,this.updateResults.record({kind:"enqueue",count:1},mi)}materializeDueSpawns(){let e=this.revision,t=[],i=[];return this.spawnDue(t,i),0===t.length||(this.observeBodyBudget(i),this.evictOverflow(i),this.syncSimulationState(i),this.revision+=1,this.updateResults.record({kind:"enqueue",count:t.length},this.revision!==e?mi:[])),t}clear(){this.observedInitialBoundary=!1;let 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"},mi)}tick(e,t){let i=this.revision,r=[],n=[],o=[],s=[],a=[];if(this.paused||!this.visible){let e=this.result(0,r,n,o,s,a,!1);return this.updateResults.record({kind:"tick",count:0},[]),e}let l=Math.max(0,Math.min(Number.isFinite(e)?e:0,this.config.maxDeltaSeconds))*this.config.timeScale;this.spawnDue(r,a);let d=this.observeBodyBudget(a),c=this.evictOverflow(a);n.push(...c.evicted),o.push(...c.sedimented),this.syncSimulationState(a),r.length>0&&this.quiescence.reset(),this.accumulator+=l;let u=this.stepObserver(t,{spawned:r,evicted:n,sedimented:o,events:s,observations:a}),h=l>0?Math.floor((this.accumulator+1e-9*this.config.fixedDt)/this.config.fixedDt):0,{steps:p,budget:m}=Wi(this.settleHost(),Math.min(h,this.config.maxSubsteps),{spawned:r,evicted:n,sedimented:o,events:s,observations:a},{stopAtRest:!1,shouldStop:()=>this.paused||!this.visible,afterStep:u});this.accumulator=Math.max(0,this.accumulator-p*this.config.fixedDt),p===this.config.maxSubsteps&&(this.accumulator=Math.min(this.accumulator,this.config.fixedDt)),(p>0||r.length>0||n.length>0||o.length>0||s.length>0)&&(this.revision+=1);let y=this.result(p,r,n,o,s,a,void 0,m??d);return this.updateResults.record({kind:"tick",count:p},this.revision!==i?r.length||n.length||o.length?mi:yi:[]),y}settle(e){return this.runSettle(e,!1).steps}settleWithObservations(e,t){return this.runSettle(e,!0,t)}stepObserver(e,t){let i=!this.observedInitialBoundary;return e&&(this.observedInitialBoundary=!0),Fi(e,e=>(e&&(this.revision+=1),this.result(e,t.spawned,t.evicted,t.sedimented,t.events,t.observations)),i)}settleHost(){return{fixedDt:this.config.fixedDt,queueSize:()=>this.queue.length,atRest:()=>this.atRest(),elapsed:()=>this.elapsedSeconds,nextArrival:()=>this.queue[0]?.spawnAt,lastArrival:()=>this.queue.at(-1)?.spawnAt,advanceTime:e=>{this.elapsedSeconds+=e},spawnDue:(e,t)=>this.spawnDue(e,t),observeBodyBudget:e=>this.observeBodyBudget(e),evictOverflow:e=>this.evictOverflow(e),step:e=>this.world.step(e),drainEvents:()=>this.world.events(),observeKernelEvents:(e,t)=>this.observeKernelEvents(e,t),observeSensorTransitions:e=>this.observeSensorTransitions(e),refreshQuiescence:(e,t)=>this.quiescence.refresh(this.world,e,t)}}runSettle(e,t,i){let r=this.revision,n=[],o=[],s=[],a=[],l=t?[]:void 0;if(t&&(this.paused||!this.visible)){let e=this.result(0,n,o,s,a,l??[],!1);return this.updateResults.record({kind:"settle",count:0},[]),e}this.spawnDue(n,l);let d=this.observeBodyBudget(l),c=this.evictOverflow(l);o.push(...c.evicted),s.push(...c.sedimented),this.syncSimulationState(l),n.length>0&&this.quiescence.reset();let u=t?{spawned:n,evicted:o,sedimented:s,events:a,observations:l}:{spawned:n},h=this.stepObserver(i,{spawned:n,evicted:o,sedimented:s,events:a,observations:l??[]}),{steps:p,budget:m}=Wi(this.settleHost(),e??this.config.settleStepLimit,u,{afterStep:h,continueWhile:i?.continueWhile,shouldStop:t?()=>this.paused||!this.visible:void 0,drainArrivals:void 0===e,skipIdle:void 0===e&&!i}),y=n.length+o.length+s.length>0;(p>0||y||a.length>0)&&(this.revision+=1);let f=this.result(p,n,o,s,a,l??[],void 0,m??d);return this.updateResults.record({kind:"settle",count:p},this.revision===r?[]:y?mi:yi),f}readBodies(e=[]){return this.world.readState(e)}readSediment(){return this.sediment.snapshot()}bodyBudgetStatus(){return this.evaluateBodyBudget()}sedimentTotals(){return this.sediment.totals()}sedimentHeightfield(e={}){return Lt(this.readSediment(),e)}hitTest(e,t,i=0,r){return this.bodySpatialIndex.hitTest(this.world,this.revision,this.liveBodyOrder,e,t,i,r)}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){let{timestamp:t,chartType:i,chartId:r,...n}=e,o={...n,timestamp:t??this.elapsedSeconds,chartType:i??this.observation.chartType,chartId:r??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){let t=this.paused!==e;this.paused=e,this.syncSimulationState(),this.updateResults.record({kind:"pause"},t?fi:[])}setVisible(e){let t=this.visible!==e;this.visible=e,this.syncSimulationState(),this.updateResults.record({kind:"visibility"},t?fi:[])}remove(e){let t=new Set(e),i=new Set(this.liveBodyOrder),r=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);let n=e.filter(e=>i.has(e)||r.has(e));return n.length>0&&(this.revision+=1,this.syncSimulationState()),this.updateResults.record({kind:"remove",keys:n,count:n.length},n.length?mi:[]),n}setConstraint(e){let t=this.world.setConstraint(e);return this.revision+=1,this.updateResults.record({kind:"constraint",keys:[t]},yi),t}removeConstraint(e){this.world.removeConstraint(e),this.revision+=1,this.updateResults.record({kind:"constraint",keys:[e]},yi)}applyImpulse(e,t,i){this.world.applyImpulse(e,t,i),this.revision+=1,this.updateResults.record({kind:"impulse",keys:[e]},yi)}nextRandom(){return this.world.nextRandom()}controls(){return e=this,{applyImpulse:(t,i,r)=>e.applyImpulse(t,i,r),clear:()=>e.clear(),hitTest:(t,i,r)=>e.hitTest(t,i,r),pause:()=>e.setPaused(!0),push:(t,i)=>e.enqueue(t,i),pushMany:(t,i)=>e.enqueue(t,i),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(){let e=this.world.snapshot();return{accumulator:this.accumulator,activeSensorPairs:Array.from(this.activeSensorPairs).sort(),bodyBudget:ri(this.bodyBudget),config:{...this.config,kernel:oi(e.options)},elapsedSeconds:this.elapsedSeconds,paused:this.paused,queue:this.queue.map(ti),revision:this.revision,sediment:this.readSediment(),simulationState:this.simulationState,liveBodyOrder:this.liveBodyOrder.slice(),visible:this.visible,world:e}}restore(e){this.observedInitialBoundary=!1;let t=this.simulationState;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:ri(e.bodyBudget??{}),kernel:oi(e.world.options)},this.bodyBudget=ri(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(ti).sort(ni),this.revision=e.revision,this.sediment.restore(e.sediment??[]),this.simulationState=e.simulationState??Ri(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"},mi),this.simulationState!==t&&this.observation.onSimulationStateChange?.(this.simulationState,t)}spawnDue(e,t){for(;this.queue.length>0&&this.queue[0].spawnAt<=this.elapsedSeconds+1e-9*this.config.fixedDt;){let i=this.queue.shift();if(!i)return;this.spawnOne(i,t),e.push(i.id)}}spawnOne(e,t){this.liveBodyOrder=this.liveBodyOrder.filter(t=>t!==e.id),this.removeActiveSensorPairsForBodies(/* @__PURE__ */new Set([e.id])),this.world.spawn(e),this.liveBodyOrder.push(e.id);for(let t of e.springs??[])this.world.setConstraint({...t,bodyId:e.id});if(!t&&!this.observation.onObservation)return;let i=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:i?.datum??e.datum,x:i?.x??e.x,y:i?.y??e.y},t)}result(e,t,i,r,n,o,s,a=this.evaluateBodyBudget()){this.syncSimulationState(o);let l=this.world.allSleeping();return{budget:a,elapsedSeconds:this.elapsedSeconds,evicted:i,events:n,observations:o,queueSize:this.queue.length,revision:this.revision,shouldContinue:s??(!this.paused&&this.visible&&(this.queue.length>0||!this.atRest())),sleeping:l,sedimented:r,spawned:t,steps:e}}observeKernelEvents(e,t){$i(this.world,e,this.observationContext(t))}observeSensorTransitions(e){this.activeSensorPairs=Ci(this.world,this.activeSensorPairs,this.observationContext(e))}removeActiveSensorPairsForBodies(e){Pi(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 Xt({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){let t=this.evaluateBodyBudget();if("ok"===t.state||!1===this.bodyBudget)return this.bodyBudgetObservationKey="ok",t;let i=`${t.state}:${t.action}`;return i===this.bodyBudgetObservationKey||(this.bodyBudgetObservationKey=i,Bi(t,this.observationContext(e))),t}syncSimulationState(e){let t=Ri(this.paused,this.visible,this.queue.length>0,this.atRest());if(t===this.simulationState)return;let i=this.simulationState;this.simulationState=t,Di(i,t,this.observationContext(e))}evictOverflow(e){let{evicted:t,sedimented:i,liveBodyOrder:r}=Oi(this.world,this.sediment,this.config.eviction,this.config.bodyLimit,this.liveBodyOrder,this.observationContext(e));return t.length>0&&(this.liveBodyOrder=r,this.removeActiveSensorPairsForBodies(new Set(t))),{evicted:t,sedimented:i}}};function Hi(e,t){if("function"==typeof t){let i=t(e);return Number.isFinite(i)&&i>0?Number(i):1}let i=e.datum;if(t&&i&&"object"==typeof i){let e=Number(i[t]);if(Number.isFinite(e)&&e>0)return e}let r=Number(i?.work??i?.reviewWork??i?.value);return Number.isFinite(r)&&r>0?r:1}function zi(e,t){if("function"==typeof t){let i=t(e);if(null!=i&&String(i).length>0)return String(i)}else if(t){let i=kt(e.datum,t),r=kt(e,t),n=i??r;if(null!=n&&String(n).length>0)return String(n)}return e.id}function Li(e,t){if(0===e.length)return 0;if(1===e.length)return e[0];let i=Math.max(0,Math.min(1,t))*(e.length-1),r=Math.floor(i),n=Math.ceil(i),o=i-r;return e[r]+(e[n]-e[r])*o}function Yi(e){let t=e.regionId,i=Math.max(0,e.unitsPerSecond),r=e.queueLayout??"lane",n=e.queueSlotSpacing??14,o=e.queueStiffness??.35,s=Number.isFinite(e.maxQueue)?Math.max(0,Math.floor(Number(e.maxQueue))):Number.POSITIVE_INFINITY,a=Math.max(.25,e.metricWindowSeconds??30),l=Math.max(1/60,e.snapshotIntervalSeconds??.25),d=e.releaseImpulse??{x:90,y:0},c=/* @__PURE__ */new Map,u=/* @__PURE__ */new Map,h=/* @__PURE__ */new Map,p=/* @__PURE__ */new Map,m=/* @__PURE__ */new Map,y=/* @__PURE__ */new Map,f=/* @__PURE__ */new Map,g=[],b=0,v=/* @__PURE__ */new Map,x=/* @__PURE__ */new Map,w=0,I=0,k=0,S=null,M=0,A=0,$=0,C=0,P=0,R=0,D=0,B=0,T=0,j=0,O=0,E=0,N=-1,F=!1;function W(e,i){let r=i(e);return!!r&&r.activeRegionIds.includes(t)}function q(){E+=1}function H(e){return{bodyId:e.bodyId,jobId:e.jobId,visitId:e.visitId,visit:e.visit,regionId:t,work:e.total,queuedAt:e.queuedAt}}function z(i,r,n){let o=H(r);e.onQueued?.(i,o),n.controls.recordObservation({type:"physics-capacity-queued",bodyId:i.id,datum:i.datum,x:i.x,y:i.y,regionId:t,work:r.total,jobId:r.jobId,visitId:r.visitId,visit:r.visit,queuedAt:r.queuedAt,queueDepth:c.size})}function L(e,t,i,r){let n={bodyId:e.id,jobId:t.jobId,visitId:t.visitId,visit:t.visit,remaining:t.work,total:t.work,queuedAt:t.queuedAt,sequence:r};return c.set(t.jobId,n),f.delete(e.id),y.set(e.id,t.jobId),A+=1,$+=t.work,q(),z(e,n,i),n}function Y(e){if(c.size>=s||0===u.size)return;let t=Array.from(u.values()).sort((e,t)=>e.sequence-t.sequence);for(let i of t){if(c.size>=s)break;let t=m.get(i.jobId);t&&h.has(i.jobId)?(u.delete(i.jobId),f.delete(i.bodyId),L(t,i,e,i.sequence)):u.delete(i.jobId)}}function _(){let e=0;for(let t of c.values())e+=t.remaining;return e}function X(){let e=0;for(let t of u.values())e+=t.work;return e}function G(){T=Math.max(T,c.size),j=Math.max(j,_())}function V(){let e=Array.from(c.values()).sort((e,t)=>e.sequence-t.sequence);v=new Map(e.map((e,t)=>[e.bodyId,t]));let t=Array.from(u.values()).sort((e,t)=>e.sequence-t.sequence);x=new Map(t.map((e,t)=>[e.bodyId,t])),w=e.length}function U(e){(e.end>e.start||e.arrivals>0||e.completions>0||e.processedWork>0)&&g.push(e);let t=k-a;for(;g.length>0&&g[0].end<t;)g.shift()}function K(){let e=k-a,t=Math.max(0,Math.min(a,k-(S??k))),r=0,n=0,o=0,s=0,l=0;for(let t of g){if(t.end<e)continue;r+=t.arrivals,n+=t.arrivalWork,o+=t.completions,s+=t.completedWork;let i=t.end-t.start;if(i<=0||t.start>=e)l+=t.processedWork;else{let r=Math.max(0,t.end-e);l+=t.processedWork*Math.min(1,r/i)}}let d=t>0?n/t:0;return{seconds:t,arrivals:r,arrivalWork:n,completions:o,completedWork:s,processedWork:l,arrivalsPerSecond:t>0?r/t:0,throughputPerSecond:t>0?o/t:0,utilization:t>0&&i>0?Math.max(0,Math.min(1,l/(i*t))):0,pressure:i>0?d/i:0}}return{id:e.id??`capacity-queue:${t}`,continuous:!1!==e.continuous,tick:r=>{let n=r.controls.readBodies(),o=/* @__PURE__ */new Map,a=/* @__PURE__ */new Map;for(let t of n){if(o.set(t.id,t),!W(t.id,r.getRegionState)||!Mt(t,e.bodyFilter))continue;let i=zi(t,e.jobKey),n=a.get(i)??[];n.push(t),a.set(i,n)}let g=Number.isFinite(r.dt)?Math.max(0,r.dt):0;if(!F){let e=Number.isFinite(r.elapsed)?Math.max(0,r.elapsed):g;k=Math.max(0,e-g),F=!0}let v=k,x=v+g;k=x,S=null==S?v:Math.min(S,v);let w={start:v,end:x,arrivals:0,arrivalWork:0,completions:0,completedWork:0,processedWork:0},A=/* @__PURE__ */new Map;for(let[e,t]of a){let i=h.get(e)?.bodyId,r=t.find(e=>e.id===i)??t[0];A.set(e,r),m.set(e,r)}for(let[i,n]of h){if(A.has(i))continue;let s=c.get(i),a=o.get(n.bodyId)??m.get(i);if(s){c.delete(i),y.delete(s.bodyId),D+=1,B+=s.remaining,q();let o={...H(s),abandonedAt:k,remainingWork:s.remaining,queueSeconds:Math.max(0,k-s.queuedAt)};a&&e.onAbandoned?.(a,o),r.controls.recordObservation({type:"physics-capacity-abandoned",bodyId:n.bodyId,datum:a?.datum,x:a?.x,y:a?.y,regionId:t,work:s.total,remainingWork:s.remaining,jobId:i,visitId:s.visitId,visit:s.visit,queuedAt:s.queuedAt,abandonedAt:k,queueSeconds:o.queueSeconds,queueDepth:c.size})}u.delete(i),f.delete(n.bodyId),h.delete(i),m.delete(i)}for(let[i,n]of A){if(h.has(i))continue;let o=(p.get(i)??0)+1;p.set(i,o);let a=Hi(n,e.unitAccessor),l={bodyId:n.id,jobId:i,visitId:`${t}:${i}:${o}`,visit:o,regionId:t,work:a,queuedAt:k};h.set(i,l),M+=1,w.arrivals+=1,w.arrivalWork+=a;let d=b++;if(c.size<s)L(n,l,r,d);else{let s={...l,blockedAt:k,sequence:d};u.set(i,s),f.set(n.id,i),R+=1,q(),e.onBlocked?.(n,s),r.controls.recordObservation({type:"physics-capacity-blocked",bodyId:n.id,datum:n.datum,x:n.x,y:n.y,regionId:t,work:a,jobId:i,visitId:l.visitId,visit:o,queuedAt:k,blockedAt:k,queueDepth:c.size,blockedDepth:u.size})}}Y(r),G();let $=Array.from(c.values()).sort((e,t)=>e.sequence-t.sequence),T=i*g;for(let i of $){if(!(T>0))break;let n=Math.min(i.remaining,T);if(i.remaining-=n,T-=n,C+=n,w.processedWork+=n,i.remaining>1e-6)continue;c.delete(i.jobId),y.delete(i.bodyId),I+=1,P+=i.total,w.completions+=1,w.completedWork+=i.total;let s=Math.max(0,k-i.queuedAt);O+=s,q();let a=o.get(i.bodyId);if(!a)continue;r.controls.applyImpulse(i.bodyId,d.x??0,d.y??0);let l={...H(i),completedAt:k,queueSeconds:s};e.onProcessed?.(a,l),r.controls.recordObservation({type:"physics-capacity-processed",bodyId:i.bodyId,datum:a.datum,x:a.x,y:a.y,regionId:t,work:i.total,jobId:i.jobId,visitId:i.visitId,visit:i.visit,queuedAt:i.queuedAt,completedAt:k,queueSeconds:s,queueDepth:c.size})}Y(r),G(),V(),U(w);let j=Math.floor(k/l);j!==N&&(N=j,q())},getSnapshot:()=>{let e=_(),r=X(),n=c.size,o=Array.from(c.values()).map(e=>Math.max(0,k-e.queuedAt)).sort((e,t)=>e-t),s=o.reduce((e,t)=>e+t,0);return{regionId:t,queueDepth:n,processedCount:I,unitsPerSecond:i,remainingWork:e,meanRemainingWork:n>0?e/n:0,waitingWork:e+r,blockedDepth:u.size,blockedWork:r,arrivalCount:M,admittedCount:A,admittedWork:$,processedWork:C,completedWork:P,blockedCount:R,abandonedCount:D,abandonedWork:B,peakQueueDepth:T,peakRemainingWork:j,queueAge:{count:o.length,meanSeconds:o.length>0?s/o.length:0,p50Seconds:Li(o,.5),p95Seconds:Li(o,.95),oldestSeconds:o.at(-1)??0},meanCompletedQueueSeconds:I>0?O/I:0,window:K(),simulatedAt:k,metricRevision:E}},bodyForce:e=>{if("none"===r)return null;let i=y.get(e.body.id),s=f.get(e.body.id),a=i?c.get(i):void 0,l=s?u.get(s):void 0;if(!a&&!l)return null;let d=a?v.get(e.body.id):x.get(e.body.id);if(null==d)return null;let h,p=e.regions;if(p)for(let e=0;e<p.length;e+=1)if(p[e].id===t){let t=p[e].shape;t&&"aabb"===t.type&&(h=t);break}if(!h)return{x:8*-Math.sign(e.body.vx||1),y:0};let m=l?h.x-.44*h.width:h.x-.22*h.width-d*(.15*n),g=h.y-(d-((l?u.size:w)-1)/2)*n/Math.max(1,Math.sqrt(l?u.size:w)),b=m-e.body.x,I=g-e.body.y;return{x:b*o,y:I*o*.85}}}}function _i(e,t){return e||t?{x:(e?.x??0)+(t?.x??0),y:(e?.y??0)+(t?.y??0)}:null}function Xi(e){if(!e?.length)return null;let t=e.slice(),i=t.some(e=>!1!==e.continuous);return{controllers:t,continuous:i,onTick:(e,i,r)=>{let n={result:e,controls:i,dt:r.dt,elapsed:r.elapsed,getRegionState:r.getRegionState};for(let e of t)e.tick(n)},bodyForce:e=>{let i=null;for(let r of t)r.bodyForce&&(i=_i(i,r.bodyForce(e)));return i}}}function Gi(e){let t=/* @__PURE__ */new Set,i=e.impulse??{x:-60,y:0};return{id:e.id??`portal:${e.fromRegionId}`,continuous:!0===e.continuous,tick:r=>{let n=r.controls.readBodies();for(let o of n)r.getRegionState(o.id)?.activeRegionIds.includes(e.fromRegionId)?t.has(o.id)||(t.add(o.id),r.controls.applyImpulse(o.id,i.x??0,i.y??0),e.onPortal?.(o)):t.delete(o.id)}}}import*as Vi from"react";import{forwardRef as Ui,memo as Ki,useCallback as Qi,useEffect as Ji,useImperativeHandle as Zi,useId as er,useRef as tr}from"react";var ir={annotationBackground:"rgba(248, 250, 252, 0.94)",annotationStroke:"#334155",annotationText:"#0f172a",background:"#f8fafc",border:"#334155",closedWindowFill:"rgba(220, 38, 38, 0.08)",closedWindowStroke:"rgba(220, 38, 38, 0.55)",danger:"#dc2626",focus:"#f97316",grid:"#cbd5e1",gutterFill:"rgba(71, 85, 105, 0.14)",lateFill:"#f97316",openWindowFill:"rgba(14, 165, 233, 0.07)",openWindowStroke:"rgba(14, 165, 233, 0.3)",primary:"#0ea5e9",selectedFill:"#f97316",selectedStroke:"#7c2d12",success:"#22c55e",text:"#0f172a",textSecondary:"#475569",warning:"#f97316"},rr={background:{names:["--semiotic-bg","--surface-1","--surface-0"],fallback:ir.background},border:{names:["--semiotic-border","--surface-3"],fallback:ir.border},danger:{names:["--semiotic-danger","--viz-4"],fallback:ir.danger},focus:{names:["--semiotic-focus","--accent","--viz-9"],fallback:ir.focus},grid:{names:["--semiotic-grid","--surface-3"],fallback:ir.grid},primary:{names:["--semiotic-primary","--accent","--viz-5"],fallback:ir.primary},success:{names:["--semiotic-success","--viz-2"],fallback:ir.success},text:{names:["--semiotic-text","--text-primary"],fallback:ir.text},textSecondary:{names:["--semiotic-text-secondary","--text-secondary"],fallback:ir.textSecondary},warning:{names:["--semiotic-warning","--viz-9","--viz-3"],fallback:ir.warning}};function nr(e){let t=rr[e];return t.names.reduceRight((e,t)=>`var(${t}, ${e})`,t.fallback)}function or(e,t,i){if(!t)return i.fallback;for(let r of i.names){let i=t.getPropertyValue(r).trim();if(i)return me(e,i)??i}return i.fallback}function sr(e,t){let i=Math.max(0,Math.min(1,t)),r=e.trim(),n=r.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);if(n){let[,e,t,r]=n;return sr(`#${e}${e}${t}${t}${r}${r}`,i)}let o=r.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(o){let[,e,t,r]=o;return`rgba(${parseInt(e,16)}, ${parseInt(t,16)}, ${parseInt(r,16)}, ${i})`}let s=r.match(/^rgb\s*\(\s*([^)]+?)\s*\)$/i);if(s)return`rgba(${s[1]}, ${i})`;let a=r.match(/^rgba\s*\(\s*([^,]+,\s*[^,]+,\s*[^,]+),\s*[^)]+\)$/i);return a?`rgba(${a[1]}, ${i})`:r}function ar(e){let t=e.canvas,i="function"==typeof getComputedStyle&&t?getComputedStyle(t):null,r=or(e,i,rr.primary),n=or(e,i,rr.danger),o=or(e,i,rr.warning),s=or(e,i,rr.success),a=or(e,i,rr.border),l=or(e,i,rr.background),d=or(e,i,rr.text),c=or(e,i,rr.textSecondary),u=or(e,i,rr.focus),h=or(e,i,rr.grid);return{annotationBackground:sr(l,.94),annotationStroke:a,annotationText:d,background:l,border:a,closedWindowFill:sr(n,.08),closedWindowStroke:sr(n,.55),danger:n,focus:u,grid:h,gutterFill:sr(c,.14),lateFill:o,openWindowFill:sr(r,.07),openWindowStroke:sr(r,.3),primary:r,selectedFill:o,selectedStroke:u,success:s,text:d,textSecondary:c,warning:o}}function lr(){let e=null,t=-1,i=ir;return{resolve(r){let n=r.canvas??null,o=ye();return n===e&&o===t||(e=n,t=o,i=ar(r)),i},invalidate(){t=-1}}}function dr(e){return"function"==typeof e}function cr(e){return void 0===e||!1===e||!dr(e.binAccessor)&&!dr(e.labelAccessor)&&!dr(e.valueAccessor)}function ur(e){return!dr(e?.timeAccessor)}function hr(e){if(void 0!==e){if(!1===e)return!1;if(!cr(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 pr(e){if(e)return{chartId:e.chartId,chartType:e.chartType,sensors:e.sensors}}function mr(e){return!e||e.every(e=>{let t=e.bodyFilter;return!t||"function"!=typeof t})}function yr(e){return ur(e)}function fr(e={}){if(e.engine)throw new TypeError("Physics workers use the built-in kernel adapter");let{engine:t,observation:i,sediment:r,...n}=e;return{...n,observation:pr(i),sediment:hr(r)}}function gr(e,t,i=0,r=2500){return"sync"!==e&&("worker"===e||t+i>=r)}function br(){return"string"==typeof import.meta.url&&import.meta.url?new Worker(new URL("./physicsWorker.js",import.meta.url),{type:"module",name:"semiotic-physics"}):new Worker(e("physicsWorker.js"),{type:"module",name:"semiotic-physics"})}function vr(){if(typeof DOMException<"u")return new DOMException("Physics worker request aborted","AbortError");let e=new Error("Physics worker request aborted");return e.name="AbortError",e}function xr(e){let t=new Error(e.error.message);return t.name=e.error.name??"Error",e.error.stack&&(t.stack=e.error.stack),t}var wr=class{constructor(e=br()){this.nextRequestId=1,this.pending=/* @__PURE__ */new Map,this.worker=e,this.worker.onmessage=e=>{let t=e.data,i=this.pending.get(t.requestId);i&&(this.pending.delete(t.requestId),i.cleanup(),t.ok?i.resolve(t.payload):i.reject(xr(t)))},this.worker.onerror=e=>{this.rejectAll(new Error(e.message||"Physics worker failed")),this.worker.terminate()}}request(e,t){if(t?.aborted)return Promise.reject(vr());let i=this.nextRequestId;this.nextRequestId+=1;let r={command:e,requestId:i};return new Promise((e,n)=>{let o=()=>{this.pending.delete(i),t?.removeEventListener("abort",o),n(vr())},s=()=>t?.removeEventListener("abort",o);this.pending.set(i,{cleanup:s,reject:n,resolve:e}),t?.addEventListener("abort",o,{once:!0});try{this.worker.postMessage(r)}catch(e){this.pending.delete(i),s(),n(e)}})}async init(e,t,i,r){if(!yr(i))throw new TypeError("Physics worker spawn pacing only supports string time accessors");let n=await this.request({type:"init",config:fr(e),initialSpawns:t,initialSpawnPacing:i},r);if("frame"!==n.type)throw new Error("Physics worker returned a non-frame init response");return n.frame}async restore(e,t){let i=await this.request({type:"restore",snapshot:e},t);if("frame"!==i.type)throw new Error("Physics worker returned a non-frame restore response");return i.frame}async initFromSnapshot(e,t,i){let r=await this.request({type:"init",config:fr(e),snapshot:t},i);if("frame"!==r.type)throw new Error("Physics worker returned a non-frame init response");return r.frame}async enqueue(e,t,i){if(!yr(t))throw new TypeError("Physics worker spawn pacing only supports string time accessors");let r=await this.request({type:"enqueue",spawns:e,pacing:t},i);if("frame"!==r.type)throw new Error("Physics worker returned a non-frame enqueue response");return r.frame}async tick(e,t){let i=await this.request({type:"tick",deltaSeconds:e},t);if("frame"!==i.type)throw new Error("Physics worker returned a non-frame tick response");return i.frame}async settle(e,t){let i=await this.request({type:"settle",maxSteps:e},t);if("frame"!==i.type)throw new Error("Physics worker returned a non-frame settle response");return i.frame}async snapshot(e){let t=await this.request({type:"snapshot"},e);if("snapshot"!==t.type)throw new Error("Physics worker returned a non-snapshot response");return t.snapshot}async remove(e,t){let i=await this.request({type:"remove",ids:e},t);if("removed"!==i.type)throw new Error("Physics worker returned a non-remove response");return{frame:i.frame,removed:i.removed}}terminate(){this.rejectAll(new Error("Physics worker terminated")),this.worker.terminate()}rejectAll(e){for(let[t,i]of this.pending)this.pending.delete(t),i.cleanup(),i.reject(e)}};function Ir(e,t,i){let r=new qi(e);return t?.length&&(r.enqueue(t,i),r.materializeDueSpawns()),r}function kr(){return typeof performance<"u"?performance.now():Date.now()}function Sr(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}))}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}:{}}))}function Ar(e,t,i,r){let n=e-(t+i+r);return{charge:e,live:t,queued:i,sedimented:r,unaccounted:n,balanced:0===n}}function $r(e,t={}){let i=t.bodies??Sr(e),r=i.filter(e=>e.sleeping).length,n=e.queue.length,o=e.sediment.reduce((e,t)=>e+t.count,0),s="settled"===e.simulationState&&0===n&&r===i.length,a=[];s||a.push("PHYSICS_NOT_SETTLED"),n>0&&a.push("PHYSICS_QUEUE_UNDRAINED");let l=null!=t.charge&&Number.isFinite(t.charge)?Ar(t.charge,i.length,n,o):void 0;return l&&!l.balanced&&a.push("PHYSICS_LEDGER_MISMATCH"),{bodyCount:i.length,sleepingCount:r,settled:s,stepsRun:Math.max(0,Math.floor(t.stepsRun??0)),seed:e.world.options.seed,binCounts:Mr(t.projectionRows),queuedCount:n,sedimentedCount:o,...l?{ledger:l}:{},warnings:a}}var Cr={fill:"#4e79a7",stroke:"#172033",strokeWidth:1,opacity:.85};function Pr(e){return e.datum&&"object"==typeof e.datum?e.datum:null}function Rr(e){let t=e.datum;if(t&&"object"==typeof t){let e=t,i=e.label??e.name??e.id;if(null!=i&&""!==i)return String(i)}return e.id}function Dr(e,t,i){let r="function"==typeof t?t(e,i):t;return{...Cr,...r??{}}}function Br(e,t={},i={index:0,simulationState:"settled"}){let r=Pr(e),n={label:t.getBodyLabel?.(e)??Rr(e)},o={style:Dr(e,t.bodyStyle,i),datum:r,accessibleDatum:r,accessibility:n,_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}}function Tr(e,t={},i="settled"){return e.map((e,r)=>Br(e,t,{index:r,simulationState:i}))}function jr(e,t={}){let i=e.settle(t.maxSteps),r=e.readBodies(),n=e.snapshot();return{snapshot:n,bodies:r,sceneNodes:Tr(r,t,n.simulationState),evidence:$r(n,{bodies:r,projectionRows:t.projectionRows,stepsRun:i,charge:t.charge}),stepsRun:i}}import{jsx as Or,jsxs as Er}from"react/jsx-runtime";function Nr(e){let t=e.replace(/[^A-Za-z0-9_-]/g,"_");return!t||/^\d/.test(t)?`physics-${t}`:t}var Fr={top:0,right:0,bottom:0,left:0};function Wr(e,t,i){return"function"==typeof e?e({size:t,margin:i}):e}function qr(e,t={}){let{width:i=640,height:r=360,title:n,description:o,background:s,backgroundGraphics:a,backgroundGraphicsBackdrop:l,className:d,foregroundGraphics:c,idPrefix:u="physics",margin:h,style:p,renderBodySVG:m,renderChrome:y,...f}=t,g=jr(e,f),b={...Fr,...h},v=[i,r],x=Wr(a,v,b),w=Wr(c,v,b),I=Nr(u),k=n?`${I}-title`:void 0,S=o?`${I}-desc`:void 0,M=[k,S].filter(Boolean).join(" ")||void 0,A=b.left||b.top?`translate(${b.left},${b.top})`:void 0,$=Math.max(1,i-b.left-b.right),C=Math.max(1,r-b.top-b.bottom),P=`${I}-plot-clip`,R=A&&null!=x?/* @__PURE__ */Or("g",{transform:A,children:x}):x;return{element:/* @__PURE__ */Er("svg",{xmlns:"http://www.w3.org/2000/svg",className:d??"stream-physics-frame",width:i,height:r,viewBox:`0 0 ${i} ${r}`,role:"img","aria-labelledby":M,style:p,children:[n&&/* @__PURE__ */Or("title",{id:k,children:n}),o&&/* @__PURE__ */Or("desc",{id:S,children:o}),
|
|
6
6
|
/* @__PURE__ */Or("defs",{children:/* @__PURE__ */Or("clipPath",{id:P,children:/* @__PURE__ */Or("rect",{width:$,height:C})})}),l&&"transparent"!==l?/* @__PURE__ */Or("rect",{className:"stream-frame-background__backdrop",x:0,y:0,width:i,height:r,fill:l}):null,!a&&s&&"transparent"!==s?/* @__PURE__ */Or("rect",{x:0,y:0,width:i,height:r,fill:s}):null,R,
|
|
7
|
-
/* @__PURE__ */Or("g",{id:`${I}-data-area`,transform:A,clipPath:`url(#${P})`,children:g.sceneNodes.map((e,t)=>{let i=g.bodies[t],r=i&&m?m(i,e.style??{},t,I):void 0;return null!=r?
|
|
8
|
-
return zr(Le,{width:o,height:s,totalWidth:i[0],totalHeight:i[1],margin:r,title:t.title,legend:t.legend,legendPosition:t.legendPosition,legendLayout:t.legendLayout,legendHoverBehavior:t.legendHoverBehavior,legendClickBehavior:t.legendClickBehavior,legendHighlightedCategory:t.legendHighlightedCategory,legendIsolatedCategories:t.legendIsolatedCategories,pointNodes:Ee(e.bodies),annotations:t.annotations,onAnnotationActivate:t.onAnnotationActivate,onObservation:t.onObservation,chartId:t.chartId,chartType:n,autoPlaceAnnotations:t.autoPlaceAnnotations,svgAnnotationRules:t.svgAnnotationRules})}import{useEffect as Lr,useRef as Yr}from"react";function _r(){return typeof document>"u"||!document.hidden}function Xr({cancelRender:e,frameRuntime:t,lastFrameTimeRef:i,paused:r,postWorkerCommand:n,requestRender:o,storeRef:s,suspendWhenHidden:a}){let l=Yr(n);l.current=n;let d=Yr(o);d.current=o,Lr(()=>{let n=s.current;n&&(t.setPaused(r),n.setPaused(r),r&&(i.current=null,e()),l.current({type:"setPaused",paused:r},!1),d.current())},[e,t,r]),Lr(()=>{if(!a){let e=s.current;return t.setVisible(!0),void(e&&!e.snapshot().visible&&(e.setVisible(!0),l.current({type:"setVisible",visible:!0},!1),d.current()))}if(typeof document>"u")return;let r=()=>{let r=s.current;if(!r)return;let n=_r();t.setVisible(n),r.setVisible(n),n||(i.current=null,e()),l.current({type:"setVisible",visible:n},!1),d.current()};return r(),document.addEventListener("visibilitychange",r),()=>document.removeEventListener("visibilitychange",r)},[e,t,a])}function Gr(e,t){let i=t.mark;if(i)return i;let r=e.datum,n=r?.__physicsMark??r?.mark;return"circle"===n||"halo"===n||"faceted"===n||"pill"===n||"diamond"===n||"square"===n?n:"circle"===e.shape.type?"circle":"square"}function Vr(e,t,i){let r=ke(e,i.fill)??"#4e79a7",n=ke(e,i.stroke),o="none"!==n?n:void 0,s=i.strokeWidth??0,a=i.opacity??1,l=i.fillOpacity??1,d=Gr(t,i),c="circle"===t.shape.type?i.r??t.shape.radius:Math.max(t.shape.width,t.shape.height)/2;if(e.save(),e.globalAlpha*=a,e.beginPath(),"pill"===d||"square"===d||"aabb"===t.shape.type){let i="pill"===d?2.4*c:"aabb"===t.shape.type?t.shape.width:1.7*c,r="pill"===d?1.35*c:"aabb"===t.shape.type?t.shape.height:1.7*c,n=t.x-i/2,o=t.y-r/2,s="pill"===d?r/2:Math.min(4,i/4);e.moveTo(n+s,o),e.arcTo(n+i,o,n+i,o+r,s),e.arcTo(n+i,o+r,n,o+r,s),e.arcTo(n,o+r,n,o,s),e.arcTo(n,o,n+i,o,s),e.closePath()}else if("diamond"===d)e.moveTo(t.x,t.y-c),e.lineTo(t.x+c,t.y),e.lineTo(t.x,t.y+c),e.lineTo(t.x-c,t.y),e.closePath();else if("faceted"===d){for(let i=0;i<6;i+=1){let r=2*Math.PI*i/6-Math.PI/2,n=t.x+Math.cos(r)*c,o=t.y+Math.sin(r)*c;0===i?e.moveTo(n,o):e.lineTo(n,o)}e.closePath()}else e.arc(t.x,t.y,c,0,2*Math.PI);r&&(e.save(),e.globalAlpha*=l,e.fillStyle=r,e.fill(),e.restore()),"halo"===d&&(s??1.5)>0&&(e.beginPath(),e.arc(t.x,t.y,1.35*c,0,2*Math.PI),e.strokeStyle=o??r,e.lineWidth=Math.max(1.5,s??1.5),e.globalAlpha*=.55,e.stroke(),e.globalAlpha/=.55),o&&s>0&&(e.strokeStyle=o,e.lineWidth=s,i.strokeDasharray&&e.setLineDash(i.strokeDasharray.split(/[,\s]+/).map(e=>Number(e)).filter(e=>Number.isFinite(e))),e.stroke()),e.restore()}function Ur(e){return"circle"===e.shape.type?e.shape.radius:Math.max(e.shape.width,e.shape.height)/2}function Kr(e,t){return"circle"===e.shape.type?t.r??e.shape.radius:Math.max(e.shape.width,e.shape.height)/2}function Qr(e){return e.stroke&&"none"!==e.stroke&&(e.strokeWidth??0)>0?(e.strokeWidth??0)/2:0}function Jr(e,t,i,r,n,o,s){let a=r/2+s,l=n/2+s,d=Math.abs(t-e.x),c=Math.abs(i-e.y);if(d>a||c>l)return!1;let u=Math.min(o+s,a,l);if(d<=a-u||c<=l-u)return!0;let h=d-(a-u),p=c-(l-u);return h*h+p*p<=u*u}function Zr(e,t,i,r){let n=Math.abs(t-e.x),o=Math.abs(i-e.y);return!(n>Math.sqrt(3)*r/2||o>r)&&o<=r-n/Math.sqrt(3)}function en(e,t){let i=Gr(e,t),r=Kr(e,t),n=Qr(t);if("pill"===i||"square"===i||"aabb"===e.shape.type){let t="pill"===i?2.4*r:"aabb"===e.shape.type?e.shape.width:1.7*r,o="pill"===i?1.35*r:"aabb"===e.shape.type?e.shape.height:1.7*r;return Math.hypot(t/2+n,o/2+n)}return"halo"===i&&(t.strokeWidth??0)>0?1.35*r+Math.max(1.5,t.strokeWidth??1.5)/2:r+n}function tn(e,t,i,r){let n=Gr(e,t),o=Kr(e,t),s=Qr(t),a=i-e.x,l=r-e.y,d=!1;if("pill"===n||"square"===n||"aabb"===e.shape.type){let t="pill"===n?2.4*o:"aabb"===e.shape.type?e.shape.width:1.7*o,a="pill"===n?1.35*o:"aabb"===e.shape.type?e.shape.height:1.7*o;d=Jr(e,i,r,t,a,"pill"===n?a/2:Math.min(4,t/4),s)}else if("diamond"===n)d=Math.abs(a)+Math.abs(l)<=o+s*Math.SQRT2;else if("faceted"===n)d=Zr(e,i,r,o+s);else{let e="halo"===n&&(t.strokeWidth??0)>0?1.35*o+Math.max(1.5,t.strokeWidth??1.5)/2:o+s;d=a*a+l*l<=e*e}return d?a*a+l*l:null}function rn(e,t,i){let r=!1;for(let[n,o]of t){let s=Math.min(1,Math.max(0,(i-o.startedAt)/o.durationMs));if(s>=1){t.delete(n);continue}r=!0;let a=1-Math.pow(1-s,3),{body:l}=o,d=o.scale>0?o.scale:1,c=(o.radius+28*a)*d,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)*d),e.beginPath(),e.arc(l.x,l.y,c,0,2*Math.PI),e.stroke(),e.globalAlpha*=.18,e.beginPath(),e.arc(l.x,l.y,.52*c,0,2*Math.PI),e.fill(),e.restore(),e.save(),e.globalAlpha*=u,e.strokeStyle=o.color,e.lineWidth=Math.max(.5,1.8*d);for(let t=0;t<8;t+=1){let i=t*(Math.PI/4)+1.4*s,r=(o.radius+5+12*a)*d,n=(o.radius+12+34*a)*d;e.beginPath(),e.moveTo(l.x+Math.cos(i)*r,l.y+Math.sin(i)*r),e.lineTo(l.x+Math.cos(i)*n,l.y+Math.sin(i)*n),e.stroke()}e.restore()}return r}function nn(e,t){return!!t?.isActive&&(t.predicate?.(e)??!0)}function on(e){return e.sensorId??`stream-region-${e.id}`}function sn(e){let t=on(e),i={bodyFilter:e.bodyFilter,friction:e.friction,restitution:e.restitution};if("boundary"===e.collider&&"aabb"===e.shape.type){let r=e.colliderThickness??8,n=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[{...i,id:`${t}-top`,shape:{type:"segment",x1:n,y1:s,x2:o,y2:s,thickness:r}},{...i,id:`${t}-right`,shape:{type:"segment",x1:o,y1:s,x2:o,y2:a,thickness:r}},{...i,id:`${t}-bottom`,shape:{type:"segment",x1:o,y1:a,x2:n,y2:a,thickness:r}},{...i,id:`${t}-left`,shape:{type:"segment",x1:n,y1:a,x2:n,y2:s,thickness:r}}]}return e.collider?[{...i,id:`${t}-collider`,shape:e.shape}]:[]}function an(e){if(e)return{activeRegionIds:Array.from(e.activeRegionIds),regionIds:Array.from(e.regionIds),charges:{...e.charges},attributes:{...e.attributes},energy:e.energy}}function ln(e){let t={};return e.forEach((e,i)=>{let r=an(e);r&&Object.defineProperty(t,i,{configurable:!0,enumerable:!0,writable:!0,value:r})}),t}function dn(e,t){let i=e.get(t);return i||(i={activeRegionIds:/* @__PURE__ */new Set,attributes:{},charges:{},energy:0,regionIds:/* @__PURE__ */new Set},e.set(t,i)),i}function cn(e,t){let i="function"==typeof e?e(t):e;if(!i)return null;let r=Number(i.x??0),n=Number(i.y??0);return Number.isFinite(r)||Number.isFinite(n)?{x:Number.isFinite(r)?r:0,y:Number.isFinite(n)?n:0}:null}function un(e,t,i){let r="function"==typeof e.attributes?e.attributes(t):e.attributes;r&&(i.attributes={...i.attributes,...r})}function hn(e,t){return void 0!==e.charge?"function"==typeof e.charge?e.charge(t):e.charge:"charge-gate"===e.kind?1:void 0}function pn(e){if(!1===e.semanticItem)return null;let t=e.shape,i=e.semanticItem??{},r="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{...r,...i,id:i.id??r.id}}function mn(e){return e.some(e=>null!=e.force||null!=e.damping||null!=e.impulseOnEnter||null!=e.impulseOnExit)}function yn(e,t,i,r){let n=Number.isFinite(r)?Math.max(0,r):0;if(!(n>0&&mn(t)))return!1;let o=new Map(t.map(e=>[e.id,e])),s=e.readBodies(),a=!1;for(let t of s){let r=i.get(t.id);if(!r||!r.activeRegionIds.size)continue;let s=an(r);if(s)for(let i of r.activeRegionIds){let r=o.get(i);if(!r)continue;let l={body:t,region:r,regionState:s},d=cn(r.force,l),c=Number(r.damping??0),u=(d?.x??0)*n-(Number.isFinite(c)?t.vx*c*n:0),h=(d?.y??0)*n-(Number.isFinite(c)?t.vy*c*n:0);(u||h)&&(e.applyImpulse(t.id,u,h),a=!0)}}return a}function fn(e,t){let i="function"==typeof e?e(t):e;if(!i)return null;let r=Number(i.x??0),n=Number(i.y??0);return Number.isFinite(r)||Number.isFinite(n)?{x:Number.isFinite(r)?r:0,y:Number.isFinite(n)?n:0}:null}var gn=[];function bn(e,t,i,r,n,o){let s=Number.isFinite(o)?Math.max(0,o):0;if(!(s>0&&t))return!1;let a=new Map(i.map(e=>[e.id,e])),l=e.readBodies(),d=!1;for(let i=0;i<l.length;i+=1){let o=l[i],c=r.get(o.id),u=an(c),h=gn;if(c&&c.activeRegionIds.size>0){let e=[];for(let t of c.activeRegionIds){let i=a.get(t);i&&e.push(i)}h=e}let p=fn(t,{body:o,bodies:l,index:i,regionState:u,regions:h,simulationState:n});if(!p)continue;let m=(p.x??0)*s,y=(p.y??0)*s;(m||y)&&(e.applyImpulse(o.id,m,y),d=!0)}return d}function vn(e,t,i={}){let r=!1,n=!1,o={continueWhile:i.continueWhile,onStep:e=>{let i=t(e);r||(r=i.regionEffectsApplied),n||(n=i.bodyForcesApplied)}},s=void 0===i.deltaSeconds?e.settleWithObservations(i.maxSteps,o):e.tick(i.deltaSeconds,o);return{regionEffectsApplied:r,bodyForcesApplied:n,result:s,snapshot:e.snapshot()}}function xn(e){let t=e.store.controls(),i=e.store.snapshot(),r=i.config.fixedDt||1/60,n=Math.max(0,e.result.steps*r),o=yn(t,e.regionEffects,e.regionState,n),s=bn(t,e.bodyForces,e.regionEffects,e.regionState,i.simulationState,n);return e.composed&&e.composed.onTick(e.result,t,{dt:n,elapsed:e.result.elapsedSeconds,getRegionState:t=>an(e.regionState.get(t))}),e.onTick?.(e.result,t),{regionEffectsApplied:o,bodyForcesApplied:s,snapshot:e.store.snapshot()}}function wn(e,t,i,r,n,o,s,a,l,d){let c=nn(e,n),u={selected:c,simulationState:t,regionState:o,regions:s},h="function"==typeof i?i(e,u):i,p=s.reduce((t,i)=>i.bodyStyle?{...t,..."function"==typeof i.bodyStyle?i.bodyStyle(e,u):i.bodyStyle}:t,{}),m=c?"function"==typeof r?r(e,u):r:void 0;return{fill:d?.color??a,stroke:d?.stroke??l,strokeWidth:d?.strokeWidth??1,opacity:d?.opacity??.9,...h,...p,...m}}import{useCallback as In}from"react";function kn({onObservationRef:e,chartIdRef:t,wallClockRef:i}){let r=De(e=>e.pushObservation);return In((n,o)=>{let s={timestamp:i.current(),chartType:"StreamPhysicsFrame",chartId:t.current};var a;a="hover"===n||"click"===n?{...s,type:n,datum:o?.datum??{},x:o?.x??0,y:o?.y??0}:"focus"===n?{...s,type:n,datum:o?.datum??{},inputType:"touch"===o?.inputType?"pointer":o?.inputType??"keyboard"}:"activate"===n?{...s,type:n,datum:o?.datum??{},inputType:o?.inputType??"keyboard"}:{...s,type:n},e.current?.(a),r(a)},[t,e,i,r])}function Sn(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function Mn(e,t){let i="sensor"===e.physics?t.sensorThickness:t.barrierThickness;return Math.max(0,Sn(e.thickness)??Sn(i)??Sn(t.thickness)??4)}function An(e=[],t={}){let i=t.idPrefix?`${t.idPrefix}-`:"",r=[];for(let n of e){if("barrier"!==n.physics&&"sensor"!==n.physics)continue;let e,o=n.axis??t.defaultAxis??"x",s=Mn(n,t),a=n.colliderId??`${i}${n.id}`;if("x"===o){let i=Sn(n.x),r=Sn(n.y1)??Sn(t.plotBounds?.y)??Sn(n.y),o=Sn(n.y2)??(t.plotBounds?t.plotBounds.y+t.plotBounds.height:void 0)??Sn(n.y);if(null==i||null==r||null==o)continue;e={type:"segment",x1:i,y1:r,x2:i,y2:o,thickness:s}}else{let i=Sn(n.y),r=Sn(n.x1)??Sn(t.plotBounds?.x)??Sn(n.x),o=Sn(n.x2)??(t.plotBounds?t.plotBounds.x+t.plotBounds.width:void 0)??Sn(n.x);if(null==i||null==r||null==o)continue;e={type:"segment",x1:r,y1:i,x2:o,y2:i,thickness:s}}r.push({id:a,shape:e,sensor:"sensor"===n.physics,..."barrier"!==n.physics||null==n.restitution&&null==t.barrierRestitution?{}:{restitution:Sn(n.restitution)??Sn(t.barrierRestitution)},..."barrier"!==n.physics||null==n.friction&&null==t.barrierFriction?{}:{friction:Sn(n.friction)??Sn(t.barrierFriction)}})}return r}function $n({annotations:e,chartId:t,chartType:i,config:r,onRegionObservation:n,regionEffects:o,seed:s,size:a}){let l=An((e??[]).filter(e=>"barrier"===e.physics||"sensor"===e.physics),{idPrefix:t?`${t}-ann`:"physics-ann",plotBounds:{x:0,y:0,width:a[0],height:a[1]}}),d=void 0===s||void 0!==r?.kernel?.seed?r:{...r,kernel:{...r?.kernel,seed:s}},c=o.flatMap(e=>[{id:on(e),sensor:!0,shape:e.shape,bodyFilter:e.bodyFilter,friction:e.friction,restitution:e.restitution},...sn(e)]),u=Object.fromEntries(o.map(e=>[on(e),{binId:e.binId??e.id,enterType:"physics-proximity-enter",exitType:"physics-proximity-exit"}])),h=d?.observation,p=o.length>0,m=c.length>0||l.length>0;return p||m||null!=t||h?{...d,colliders:[...d?.colliders??[],...c,...l],observation:{...h,chartId:t??h?.chartId,chartType:h?.chartType??i,sensors:{...h?.sensors??{},...u},onObservation:e=>{p&&n(e),h?.onObservation?.(e)}}}:d}import*as Cn from"react";import*as Pn from"react";import{Fragment as Rn,jsx as Dn,jsxs as Bn}from"react/jsx-runtime";function Tn(e,t,i,r){/* @__PURE__ */
|
|
9
|
-
return Dn(Rn,{children:/* @__PURE__ */Dn("div",{id:r,"aria-live":"polite","aria-atomic":"true",style:
|
|
10
|
-
return Bn("div",{className:"semiotic-tooltip",style:
|
|
7
|
+
/* @__PURE__ */Or("g",{id:`${I}-data-area`,transform:A,clipPath:`url(#${P})`,children:g.sceneNodes.map((e,t)=>{let i=g.bodies[t],r=i&&m?m(i,e.style??{},t,I):void 0;return null!=r?Q(r,e,t):Q("point"===e.type||"rect"===e.type?G(e,t,I):null,e,`xy-cursor-${t}`)})}),w,y?.(g)]}),scene:g,evidence:g.evidence}}import{jsx as Hr}from"react/jsx-runtime";function zr(e,t,i,r,n="StreamPhysicsFrame"){let o=Math.max(1,i[0]-r.left-r.right),s=Math.max(1,i[1]-r.top-r.bottom);/* */
|
|
8
|
+
return Hr(Le,{width:o,height:s,totalWidth:i[0],totalHeight:i[1],margin:r,title:t.title,legend:t.legend,legendPosition:t.legendPosition,legendLayout:t.legendLayout,legendHoverBehavior:t.legendHoverBehavior,legendClickBehavior:t.legendClickBehavior,legendHighlightedCategory:t.legendHighlightedCategory,legendIsolatedCategories:t.legendIsolatedCategories,pointNodes:Ee(e.bodies),annotations:t.annotations,onAnnotationActivate:t.onAnnotationActivate,onObservation:t.onObservation,chartId:t.chartId,chartType:n,autoPlaceAnnotations:t.autoPlaceAnnotations,svgAnnotationRules:t.svgAnnotationRules})}import{useEffect as Lr,useRef as Yr}from"react";function _r(){return typeof document>"u"||!document.hidden}function Xr({cancelRender:e,frameRuntime:t,lastFrameTimeRef:i,paused:r,postWorkerCommand:n,requestRender:o,storeRef:s,suspendWhenHidden:a}){let l=Yr(n);l.current=n;let d=Yr(o);d.current=o,Lr(()=>{let n=s.current;n&&(t.setPaused(r),n.setPaused(r),r&&(i.current=null,e()),l.current({type:"setPaused",paused:r},!1),d.current())},[e,t,r]),Lr(()=>{if(!a){let e=s.current;return t.setVisible(!0),void(e&&!e.snapshot().visible&&(e.setVisible(!0),l.current({type:"setVisible",visible:!0},!1),d.current()))}if(typeof document>"u")return;let r=()=>{let r=s.current;if(!r)return;let n=_r();t.setVisible(n),r.setVisible(n),n||(i.current=null,e()),l.current({type:"setVisible",visible:n},!1),d.current()};return r(),document.addEventListener("visibilitychange",r),()=>document.removeEventListener("visibilitychange",r)},[e,t,a])}function Gr(e,t){let i=t.mark;if(i)return i;let r=e.datum,n=r?.__physicsMark??r?.mark;return"circle"===n||"halo"===n||"faceted"===n||"pill"===n||"diamond"===n||"square"===n?n:"circle"===e.shape.type?"circle":"square"}function Vr(e,t,i){let r=be(e,i.fill)??"#4e79a7",n=be(e,i.stroke),o="none"!==n?n:void 0,s=i.strokeWidth??0,a=i.opacity??1,l=i.fillOpacity??1,d=Gr(t,i),c="circle"===t.shape.type?i.r??t.shape.radius:Math.max(t.shape.width,t.shape.height)/2;if(e.save(),e.globalAlpha*=a,e.beginPath(),"pill"===d||"square"===d||"aabb"===t.shape.type){let i="pill"===d?2.4*c:"aabb"===t.shape.type?t.shape.width:1.7*c,r="pill"===d?1.35*c:"aabb"===t.shape.type?t.shape.height:1.7*c,n=t.x-i/2,o=t.y-r/2,s="pill"===d?r/2:Math.min(4,i/4);e.moveTo(n+s,o),e.arcTo(n+i,o,n+i,o+r,s),e.arcTo(n+i,o+r,n,o+r,s),e.arcTo(n,o+r,n,o,s),e.arcTo(n,o,n+i,o,s),e.closePath()}else if("diamond"===d)e.moveTo(t.x,t.y-c),e.lineTo(t.x+c,t.y),e.lineTo(t.x,t.y+c),e.lineTo(t.x-c,t.y),e.closePath();else if("faceted"===d){for(let i=0;i<6;i+=1){let r=2*Math.PI*i/6-Math.PI/2,n=t.x+Math.cos(r)*c,o=t.y+Math.sin(r)*c;0===i?e.moveTo(n,o):e.lineTo(n,o)}e.closePath()}else e.arc(t.x,t.y,c,0,2*Math.PI);r&&(e.save(),e.globalAlpha*=l,e.fillStyle=r,e.fill(),e.restore()),"halo"===d&&(s??1.5)>0&&(e.beginPath(),e.arc(t.x,t.y,1.35*c,0,2*Math.PI),e.strokeStyle=o??r,e.lineWidth=Math.max(1.5,s??1.5),e.globalAlpha*=.55,e.stroke(),e.globalAlpha/=.55),o&&s>0&&(e.strokeStyle=o,e.lineWidth=s,i.strokeDasharray&&e.setLineDash(i.strokeDasharray.split(/[,\s]+/).map(e=>Number(e)).filter(e=>Number.isFinite(e))),e.stroke()),e.restore()}function Ur(e){return"circle"===e.shape.type?e.shape.radius:Math.max(e.shape.width,e.shape.height)/2}function Kr(e,t){return"circle"===e.shape.type?t.r??e.shape.radius:Math.max(e.shape.width,e.shape.height)/2}function Qr(e){return e.stroke&&"none"!==e.stroke&&(e.strokeWidth??0)>0?(e.strokeWidth??0)/2:0}function Jr(e,t,i,r,n,o,s){let a=r/2+s,l=n/2+s,d=Math.abs(t-e.x),c=Math.abs(i-e.y);if(d>a||c>l)return!1;let u=Math.min(o+s,a,l);if(d<=a-u||c<=l-u)return!0;let h=d-(a-u),p=c-(l-u);return h*h+p*p<=u*u}function Zr(e,t,i,r){let n=Math.abs(t-e.x),o=Math.abs(i-e.y);return!(n>Math.sqrt(3)*r/2||o>r)&&o<=r-n/Math.sqrt(3)}function en(e,t){let i=Gr(e,t),r=Kr(e,t),n=Qr(t);if("pill"===i||"square"===i||"aabb"===e.shape.type){let t="pill"===i?2.4*r:"aabb"===e.shape.type?e.shape.width:1.7*r,o="pill"===i?1.35*r:"aabb"===e.shape.type?e.shape.height:1.7*r;return Math.hypot(t/2+n,o/2+n)}return"halo"===i&&(t.strokeWidth??0)>0?1.35*r+Math.max(1.5,t.strokeWidth??1.5)/2:r+n}function tn(e,t,i,r){let n=Gr(e,t),o=Kr(e,t),s=Qr(t),a=i-e.x,l=r-e.y,d=!1;if("pill"===n||"square"===n||"aabb"===e.shape.type){let t="pill"===n?2.4*o:"aabb"===e.shape.type?e.shape.width:1.7*o,a="pill"===n?1.35*o:"aabb"===e.shape.type?e.shape.height:1.7*o;d=Jr(e,i,r,t,a,"pill"===n?a/2:Math.min(4,t/4),s)}else if("diamond"===n)d=Math.abs(a)+Math.abs(l)<=o+s*Math.SQRT2;else if("faceted"===n)d=Zr(e,i,r,o+s);else{let e="halo"===n&&(t.strokeWidth??0)>0?1.35*o+Math.max(1.5,t.strokeWidth??1.5)/2:o+s;d=a*a+l*l<=e*e}return d?a*a+l*l:null}function rn(e,t,i){let r=!1;for(let[n,o]of t){let s=Math.min(1,Math.max(0,(i-o.startedAt)/o.durationMs));if(s>=1){t.delete(n);continue}r=!0;let a=1-Math.pow(1-s,3),{body:l}=o,d=o.scale>0?o.scale:1,c=(o.radius+28*a)*d,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)*d),e.beginPath(),e.arc(l.x,l.y,c,0,2*Math.PI),e.stroke(),e.globalAlpha*=.18,e.beginPath(),e.arc(l.x,l.y,.52*c,0,2*Math.PI),e.fill(),e.restore(),e.save(),e.globalAlpha*=u,e.strokeStyle=o.color,e.lineWidth=Math.max(.5,1.8*d);for(let t=0;t<8;t+=1){let i=t*(Math.PI/4)+1.4*s,r=(o.radius+5+12*a)*d,n=(o.radius+12+34*a)*d;e.beginPath(),e.moveTo(l.x+Math.cos(i)*r,l.y+Math.sin(i)*r),e.lineTo(l.x+Math.cos(i)*n,l.y+Math.sin(i)*n),e.stroke()}e.restore()}return r}function nn(e,t){return!!t?.isActive&&(t.predicate?.(e)??!0)}function on(e){return e.sensorId??`stream-region-${e.id}`}function sn(e){let t=on(e),i={bodyFilter:e.bodyFilter,friction:e.friction,restitution:e.restitution};if("boundary"===e.collider&&"aabb"===e.shape.type){let r=e.colliderThickness??8,n=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[{...i,id:`${t}-top`,shape:{type:"segment",x1:n,y1:s,x2:o,y2:s,thickness:r}},{...i,id:`${t}-right`,shape:{type:"segment",x1:o,y1:s,x2:o,y2:a,thickness:r}},{...i,id:`${t}-bottom`,shape:{type:"segment",x1:o,y1:a,x2:n,y2:a,thickness:r}},{...i,id:`${t}-left`,shape:{type:"segment",x1:n,y1:a,x2:n,y2:s,thickness:r}}]}return e.collider?[{...i,id:`${t}-collider`,shape:e.shape}]:[]}function an(e){if(e)return{activeRegionIds:Array.from(e.activeRegionIds),regionIds:Array.from(e.regionIds),charges:{...e.charges},attributes:{...e.attributes},energy:e.energy}}function ln(e){let t={};return e.forEach((e,i)=>{let r=an(e);r&&Object.defineProperty(t,i,{configurable:!0,enumerable:!0,writable:!0,value:r})}),t}function dn(e,t){let i=e.get(t);return i||(i={activeRegionIds:/* @__PURE__ */new Set,attributes:{},charges:{},energy:0,regionIds:/* @__PURE__ */new Set},e.set(t,i)),i}function cn(e,t){let i="function"==typeof e?e(t):e;if(!i)return null;let r=Number(i.x??0),n=Number(i.y??0);return Number.isFinite(r)||Number.isFinite(n)?{x:Number.isFinite(r)?r:0,y:Number.isFinite(n)?n:0}:null}function un(e,t,i){let r="function"==typeof e.attributes?e.attributes(t):e.attributes;r&&(i.attributes={...i.attributes,...r})}function hn(e,t){return void 0!==e.charge?"function"==typeof e.charge?e.charge(t):e.charge:"charge-gate"===e.kind?1:void 0}function pn(e){if(!1===e.semanticItem)return null;let t=e.shape,i=e.semanticItem??{},r="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{...r,...i,id:i.id??r.id}}function mn(e){return e.some(e=>null!=e.force||null!=e.damping||null!=e.impulseOnEnter||null!=e.impulseOnExit)}function yn(e,t,i,r){let n=Number.isFinite(r)?Math.max(0,r):0;if(!(n>0&&mn(t)))return!1;let o=new Map(t.map(e=>[e.id,e])),s=e.readBodies(),a=!1;for(let t of s){let r=i.get(t.id);if(!r||!r.activeRegionIds.size)continue;let s=an(r);if(s)for(let i of r.activeRegionIds){let r=o.get(i);if(!r)continue;let l={body:t,region:r,regionState:s},d=cn(r.force,l),c=Number(r.damping??0),u=(d?.x??0)*n-(Number.isFinite(c)?t.vx*c*n:0),h=(d?.y??0)*n-(Number.isFinite(c)?t.vy*c*n:0);(u||h)&&(e.applyImpulse(t.id,u,h),a=!0)}}return a}function fn(e,t){let i="function"==typeof e?e(t):e;if(!i)return null;let r=Number(i.x??0),n=Number(i.y??0);return Number.isFinite(r)||Number.isFinite(n)?{x:Number.isFinite(r)?r:0,y:Number.isFinite(n)?n:0}:null}var gn=[];function bn(e,t,i,r,n,o){let s=Number.isFinite(o)?Math.max(0,o):0;if(!(s>0&&t))return!1;let a=new Map(i.map(e=>[e.id,e])),l=e.readBodies(),d=!1;for(let i=0;i<l.length;i+=1){let o=l[i],c=r.get(o.id),u=an(c),h=gn;if(c&&c.activeRegionIds.size>0){let e=[];for(let t of c.activeRegionIds){let i=a.get(t);i&&e.push(i)}h=e}let p=fn(t,{body:o,bodies:l,index:i,regionState:u,regions:h,simulationState:n});if(!p)continue;let m=(p.x??0)*s,y=(p.y??0)*s;(m||y)&&(e.applyImpulse(o.id,m,y),d=!0)}return d}function vn(e,t,i={}){let r=!1,n=!1,o={continueWhile:i.continueWhile,onStep:e=>{let i=t(e);r||(r=i.regionEffectsApplied),n||(n=i.bodyForcesApplied)}},s=void 0===i.deltaSeconds?e.settleWithObservations(i.maxSteps,o):e.tick(i.deltaSeconds,o);return{regionEffectsApplied:r,bodyForcesApplied:n,result:s,snapshot:e.snapshot()}}function xn(e){let t=e.store.controls(),i=e.store.snapshot(),r=i.config.fixedDt||1/60,n=Math.max(0,e.result.steps*r),o=yn(t,e.regionEffects,e.regionState,n),s=bn(t,e.bodyForces,e.regionEffects,e.regionState,i.simulationState,n);return e.composed&&e.composed.onTick(e.result,t,{dt:n,elapsed:e.result.elapsedSeconds,getRegionState:t=>an(e.regionState.get(t))}),e.onTick?.(e.result,t),{regionEffectsApplied:o,bodyForcesApplied:s,snapshot:e.store.snapshot()}}function wn(e,t,i,r,n,o,s,a,l,d){let c=nn(e,n),u={selected:c,simulationState:t,regionState:o,regions:s},h="function"==typeof i?i(e,u):i,p=s.reduce((t,i)=>i.bodyStyle?{...t,..."function"==typeof i.bodyStyle?i.bodyStyle(e,u):i.bodyStyle}:t,{}),m=c?"function"==typeof r?r(e,u):r:void 0;return{fill:d?.color??a,stroke:d?.stroke??l,strokeWidth:d?.strokeWidth??1,opacity:d?.opacity??.9,...h,...p,...m}}import{useCallback as In}from"react";function kn({onObservationRef:e,chartIdRef:t,wallClockRef:i}){let r=Ae(e=>e.pushObservation);return In((n,o)=>{let s={timestamp:i.current(),chartType:"StreamPhysicsFrame",chartId:t.current};var a;a="hover"===n||"click"===n?{...s,type:n,datum:o?.datum??{},x:o?.x??0,y:o?.y??0}:"focus"===n?{...s,type:n,datum:o?.datum??{},inputType:"touch"===o?.inputType?"pointer":o?.inputType??"keyboard"}:"activate"===n?{...s,type:n,datum:o?.datum??{},inputType:o?.inputType??"keyboard"}:{...s,type:n},e.current?.(a),r(a)},[t,e,i,r])}function Sn(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function Mn(e,t){let i="sensor"===e.physics?t.sensorThickness:t.barrierThickness;return Math.max(0,Sn(e.thickness)??Sn(i)??Sn(t.thickness)??4)}function An(e=[],t={}){let i=t.idPrefix?`${t.idPrefix}-`:"",r=[];for(let n of e){if("barrier"!==n.physics&&"sensor"!==n.physics)continue;let e,o=n.axis??t.defaultAxis??"x",s=Mn(n,t),a=n.colliderId??`${i}${n.id}`;if("x"===o){let i=Sn(n.x),r=Sn(n.y1)??Sn(t.plotBounds?.y)??Sn(n.y),o=Sn(n.y2)??(t.plotBounds?t.plotBounds.y+t.plotBounds.height:void 0)??Sn(n.y);if(null==i||null==r||null==o)continue;e={type:"segment",x1:i,y1:r,x2:i,y2:o,thickness:s}}else{let i=Sn(n.y),r=Sn(n.x1)??Sn(t.plotBounds?.x)??Sn(n.x),o=Sn(n.x2)??(t.plotBounds?t.plotBounds.x+t.plotBounds.width:void 0)??Sn(n.x);if(null==i||null==r||null==o)continue;e={type:"segment",x1:r,y1:i,x2:o,y2:i,thickness:s}}r.push({id:a,shape:e,sensor:"sensor"===n.physics,..."barrier"!==n.physics||null==n.restitution&&null==t.barrierRestitution?{}:{restitution:Sn(n.restitution)??Sn(t.barrierRestitution)},..."barrier"!==n.physics||null==n.friction&&null==t.barrierFriction?{}:{friction:Sn(n.friction)??Sn(t.barrierFriction)}})}return r}function $n({annotations:e,chartId:t,chartType:i,config:r,onRegionObservation:n,regionEffects:o,seed:s,size:a}){let l=An((e??[]).filter(e=>"barrier"===e.physics||"sensor"===e.physics),{idPrefix:t?`${t}-ann`:"physics-ann",plotBounds:{x:0,y:0,width:a[0],height:a[1]}}),d=void 0===s||void 0!==r?.kernel?.seed?r:{...r,kernel:{...r?.kernel,seed:s}},c=o.flatMap(e=>[{id:on(e),sensor:!0,shape:e.shape,bodyFilter:e.bodyFilter,friction:e.friction,restitution:e.restitution},...sn(e)]),u=Object.fromEntries(o.map(e=>[on(e),{binId:e.binId??e.id,enterType:"physics-proximity-enter",exitType:"physics-proximity-exit"}])),h=d?.observation,p=o.length>0,m=c.length>0||l.length>0;return p||m||null!=t||h?{...d,colliders:[...d?.colliders??[],...c,...l],observation:{...h,chartId:t??h?.chartId,chartType:h?.chartType??i,sensors:{...h?.sensors??{},...u},onObservation:e=>{p&&n(e),h?.onObservation?.(e)}}}:d}import*as Cn from"react";import*as Pn from"react";import{Fragment as Rn,jsx as Dn,jsxs as Bn}from"react/jsx-runtime";function Tn(e,t,i,r){/* */
|
|
9
|
+
return Dn(Rn,{children:/* @__PURE__ */Dn("div",{id:r,"aria-live":"polite","aria-atomic":"true",style:ue,children:t?t.description??t.label:""})})}function jn(e){return null==e?null:"string"==typeof e||"number"==typeof e||"boolean"==typeof e?String(e):null}function On(e){return{__semioticHoverData:!0,body:e,data:e.datum??e,id:e.id,type:"body",x:e.x,y:e.y}}function En(e){if("circle"===e.shape.type){let 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 Nn(e){let t=e.datum;if(t&&"object"==typeof t){let e=t,i=e.label??e.name??e.id;if("string"==typeof i||"number"==typeof i||"boolean"==typeof i)return String(i)}return e.id}function Fn(e){let t=Hn(e.datum??e);return t.length?t.map(([e,t])=>`${e}: ${t}`).join(", "):`Physics body ${e.id}`}function Wn(e,t,i,r){if(!i)return[];let n=Math.max(0,Math.floor(r));if(!n)return[];let o=[];for(let r=0;r<e.length&&o.length<n;r+=1){let n=e[r],s="function"==typeof i?i(n,{index:r,simulationState:t}):void 0;if(!1===s)continue;let a=En(n);o.push({datum:n.datum??n,description:Fn(n),group:"body",label:Nn(n),...a,...s??{},bodyId:s?.bodyId??n.id,id:s?.id??`body:${n.id}`,x:s?.x??n.x,y:s?.y??n.y})}return o}function qn(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=1){let r=e[i],n=t[i];if(r.id!==n.id||r.label!==n.label||r.description!==n.description||r.group!==n.group||r.bodyId!==n.bodyId||Math.round(r.x)!==Math.round(n.x)||Math.round(r.y)!==Math.round(n.y))return!0}return!1}function Hn(e){return e&&"object"==typeof e?Object.entries(e).map(([e,t])=>{if(e.startsWith("_"))return null;let i=jn(t);return null==i?null:[e,i]}).filter(e=>null!=e).slice(0,8):[]}function zn({enableHover:e,hoverData:t,tooltipContent:i,plotWidth:r,plotHeight:n,margin:o}){if(!e||!t)return null;let s=i?i(t):/* @__PURE__ */Dn(Ln,{hover:t});return $e(s)?/* @__PURE__ */Dn(k,{contentOwnsChrome:De(i),x:t.x,y:t.y,containerWidth:r,containerHeight:n,margin:o,className:"stream-physics-tooltip",children:s}):null}var Ln=/* @__PURE__ */Re(function({hover:e}){let t=Hn(e.data);/* */
|
|
10
|
+
return Bn("div",{className:"semiotic-tooltip",style:Ce,children:[
|
|
11
11
|
/* @__PURE__ */Dn("div",{style:{fontWeight:700,marginBottom:t.length?4:0},children:e.id}),t.map(([e,t])=>/* @__PURE__ */Bn("div",{children:[
|
|
12
12
|
/* @__PURE__ */Bn("span",{style:{opacity:.72},children:[e,": "]}),
|
|
13
|
-
/* @__PURE__ */Dn("span",{children:t})]},e))]})});function Yn(e){return e.datum&&"object"==typeof e.datum?Object.entries(e.datum).map(([e,t])=>{let i=jn(t);return null==i?null:`${e}: ${i}`}).filter(e=>null!=e).slice(0,8).join(", "):""}function _n(e){let t=[`${e.length} semantic item${1===e.length?"":"s"}.`],i=/* @__PURE__ */new Map;for(let t of e)t.group&&i.set(t.group,(i.get(t.group)??0)+1);return i.size&&t.push(Array.from(i).map(([e,t])=>`${e}: ${t}`).join(", ")),t.join(" ")}function Xn(e){let{chartTitle:i,items:r,tableId:n}=e,[o,s]=Pn.useState(5),a=
|
|
14
|
-
return Bn(
|
|
15
|
-
/* @__PURE__ */Bn("table",{className:"semiotic-accessible-data-table-table",role:"table","aria-label":`Semantic items for ${i??"physics chart"}`,style:
|
|
16
|
-
/* @__PURE__ */Dn("caption",{className:"semiotic-accessible-data-table-caption",style
|
|
13
|
+
/* @__PURE__ */Dn("span",{children:t})]},e))]})});function Yn(e){return e.datum&&"object"==typeof e.datum?Object.entries(e.datum).map(([e,t])=>{let i=jn(t);return null==i?null:`${e}: ${i}`}).filter(e=>null!=e).slice(0,8).join(", "):""}function _n(e){let t=[`${e.length} semantic item${1===e.length?"":"s"}.`],i=/* @__PURE__ */new Map;for(let t of e)t.group&&i.set(t.group,(i.get(t.group)??0)+1);return i.size&&t.push(Array.from(i).map(([e,t])=>`${e}: ${t}`).join(", ")),t.join(" ")}function Xn(e){let{chartTitle:i,items:r,tableId:n}=e,[o,s]=Pn.useState(5),a=se(),{isExpanded:l,revealRows:d}=a,c=Pn.useMemo(()=>l?_n(r):"",[l,r]),u=i?`Data summary for ${i}`:`Data summary for physics chart ${n}`;if(Pn.useEffect(()=>{l||s(5)},[l]),!r.length/* @__PURE__ */)return Dn("span",{id:n,tabIndex:-1,style:ue});let h={interaction:a,tableId:n,regionLabel:u,countLabel:`${r.length} semantic items`};if(!l)/* */return Dn(oe,{...h});let p=Math.min(o,r.length),m=r.slice(0,p),y=r.length-p;/* */
|
|
14
|
+
return Bn(oe,{...h,summary:c,children:[
|
|
15
|
+
/* @__PURE__ */Bn("table",{className:"semiotic-accessible-data-table-table",role:"table","aria-label":`Semantic items for ${i??"physics chart"}`,style:ve,children:[
|
|
16
|
+
/* @__PURE__ */Dn("caption",{className:"semiotic-accessible-data-table-caption",style:Ie,children:y>0?`First ${p} of ${r.length} semantic items`:`All ${r.length} semantic items`}),
|
|
17
17
|
/* @__PURE__ */Dn("thead",{children:/* @__PURE__ */Bn("tr",{children:[
|
|
18
|
-
/* @__PURE__ */Dn("th",{scope:"col",style:
|
|
19
|
-
/* @__PURE__ */Dn("th",{scope:"col",style:
|
|
20
|
-
/* @__PURE__ */Dn("th",{scope:"col",style:
|
|
21
|
-
/* @__PURE__ */Dn("th",{scope:"col",style:
|
|
22
|
-
/* @__PURE__ */Dn("th",{scope:"col",style:
|
|
18
|
+
/* @__PURE__ */Dn("th",{scope:"col",style:xe,children:"Item"}),
|
|
19
|
+
/* @__PURE__ */Dn("th",{scope:"col",style:xe,children:"Description"}),
|
|
20
|
+
/* @__PURE__ */Dn("th",{scope:"col",style:xe,children:"Group"}),
|
|
21
|
+
/* @__PURE__ */Dn("th",{scope:"col",style:xe,children:"Position"}),
|
|
22
|
+
/* @__PURE__ */Dn("th",{scope:"col",style:xe,children:"Data"})]})}),
|
|
23
23
|
/* @__PURE__ */Dn("tbody",{children:m.map((e,t)=>/* @__PURE__ */Bn("tr",{tabIndex:-1,children:[
|
|
24
|
-
/* @__PURE__ */Dn("th",{scope:"row",style:
|
|
25
|
-
/* @__PURE__ */Dn("td",{style:
|
|
26
|
-
/* @__PURE__ */Dn("td",{style:
|
|
27
|
-
/* @__PURE__ */Bn("td",{style:
|
|
28
|
-
/* @__PURE__ */Dn("td",{style:
|
|
29
|
-
/* @__PURE__ */Dn(t,{remaining:y,onClick:e=>{d(e.currentTarget,p,Math.min(p+25,r.length),r.length),s(e=>e+25)},kind:"row"})]})}function Gn(e,t,i,r={left:0,top:0}){let n=e.getBoundingClientRect(),o=n.width>0&&e.clientWidth>0?e.clientWidth/n.width:1,s=n.height>0&&e.clientHeight>0?e.clientHeight/n.height:1;return{x:(t-n.left)*o-r.left,y:(i-n.top)*s-r.top}}function Vn(e,t,i,r){i.cursor&&((e.targets??(e.targets=/* @__PURE__ */new Map)).set(t.id,i),e.collisionGeometry||(e.collisionGeometry=r),e.maxSearchRadius=Math.max(e.maxSearchRadius,r?si(t):en(t,i)))}function Un({margin:e,clearKeyboardFocus:t,resolveSemanticBody:i,canvasRef:r,clearHover:n,emitObservation:o,enableHover:s,hoverRadius:a,hoverDataRef:l,onBodyHover:d,setHoverData:c,storeRef:u}){let h=Cn.useRef({inside:!1,x:0,y:0,pointerType:void 0}),p=Cn.useRef(null);p.current??(p.current={maxSearchRadius:0}),
|
|
30
|
-
/* @__PURE__ */Ui(function(e,t){let{accessibleTable:i=!0,annotations:r,onAnnotationActivate:n,autoPlaceAnnotations:o,background:s,backgroundGraphics:a,backgroundGraphicsBackdrop:l,maxDevicePixelRatio:d,bodySemanticItemLimit:c=200,bodySemanticItems:u=!1,bodySemanticUpdateMs:h=200,bodyForces:p,bodyStyle:m,chartId:y,className:f,frameScheduler:g,clock:b,random:v,seed:x,color:w,config:I,controllers:k,continuous:S=!1,description:
|
|
31
|
-
/* @__PURE__ */new Map),_t=`${Tt}-physics-live`,Xt=kn({onObservationRef:je,chartIdRef:Oe,wallClockRef:ot}),{clearSemanticFocus:Gt,resolveSemanticBody:Vt,clearHover:Ut,focusedBodyIdRef:Kt,focusedSemanticItem:Qt,handleCanvasPointerDown:Jt,hoverData:Zt,hoverDataRef:ei,onKeyDown:ti,setFocusedSemanticItem:ii,setHoverData:ri,syncBodySemanticItems:ni}=io({margin:ut,allSemanticItems:tt,bodySemanticItemLimit:c,bodySemanticItems:u,bodySemanticUpdateMs:h,emitObservation:Xt,enableHover:C,hoverRadius:D,logicalClockRef:zt,onBodyHover:K,onBodyPointerDown:Q,onClick:X,onSemanticItemActivate:J,onSemanticItemFocus:Z,setBodySemanticItemsSnapshot:et,storeRef:nt}),[oi,si]=Vi.useState([]),ai=tr(0),li=!!r?.length&&r.some(e=>null!=e.pointId||null!=e.bodyId||"latest"===e.anchor),{canvasRef:di,resolutionDirtyRef:ci}=N(ct,{hydrated:Ht,wasHydratingFromSSR:Lt,storeRef:nt,dirtyRef:dt,manageFrameRuntime:!1,skipInitialCanvasPaintInvalidation:!0,maxDevicePixelRatio:d,canvasPaintDependencies:[s,a,xt]}),ui=Un({margin:ut,clearKeyboardFocus:Gt,hoverDataRef:ei,resolveSemanticBody:Vt,canvasRef:di,clearHover:Ut,emitObservation:Xt,enableHover:C,hoverRadius:D,onBodyHover:K,setHoverData:ri,storeRef:nt}),hi=Qi((e=!1)=>{let t=di.current,i=nt.current;if(!t||!i)return;let r=Dt.current.beforeCompute(i.getLastUpdateResult(),!1);ci.current=!1;let n=O(d,wt),o=B(t,wt,ut,n);if(!o)return void Dt.current.afterCompute(r,!1,!1);let l=Rt.current.resolve(o),c={theme:l,resolvePaint:(e,t)=>Ie(o,e,t),withAlpha:sr};o.clearRect(-ut.left,-ut.top,wt[0],wt[1]),!a&&"transparent"!==s&&(o.fillStyle=null==s?l.background:c.resolvePaint(s,l.background),o.fillRect(-ut.left,-ut.top,wt[0],wt[1])),o.save(),o.beginPath(),o.rect(0,0,Mt,At),o.clip();let u=i.snapshot(),h=i.readBodies(),p=ui.begin();if(ni(h,u.simulationState,e||mt.current||"running"!==u.simulationState),li){let e=zt.current();if(e-ai.current>=100){ai.current=e;let t=Ee(h);si(e=>e.length===t.length&&e.every((e,i)=>e.pointId===t[i].pointId&&Math.round(e.x)===Math.round(t[i].x)&&Math.round(e.y)===Math.round(t[i].y))?e:t)}}De&&(o.save(),De(o,h,c),o.restore());for(let e of h){let t=Ne.current.get(e.id),i=t?Array.from(t.activeRegionIds).map(e=>Qe.get(e)).filter(e=>null!=e):[],r=wn(e,u.simulationState,m,ye,fe,an(t),i,l.primary,l.text,Te);ui.collect(p,e,r,!!Re),Re?(o.save(),Re(o,e,r,c),o.restore()):Vr(o,e,r)}ui.syncBodyCursors(t,i,p),Be&&(o.save(),Be(o,h,c),o.restore()),mt.current?Yt.current.clear():rn(o,Yt.current,zt.current()),o.restore(),Dt.current.afterCompute(r,!0,!1),dt.current=!1},[di,ci,Dt,wt,ut,Mt,At,a,s,d,ni,li,De,Be,m,ye,fe,Te,Re,Qe,ui,mt]),pi=Qi((e,t)=>{let i=nt.current,r=`${ve}:${e}:${t??""}`;Bt.current!==r&&(Bt.current=r,U?.({execution:e,liveBodies:i?.liveBodyCount()??0,queuedBodies:i?.queueSize()??0,reason:t,requested:ve}))},[U,ve]),mi=Qi((e,t=!0)=>{Et.current+=1,jt.current=!1,Nt.current=!1,Ft.current=!1,qt.current=!1,Wt.current?.terminate(),Wt.current=null,t&&pi("sync",e)},[pi]),yi=Qi(()=>{return Ht?typeof window<"u"&&typeof Worker<"u"?it?"runtime region effects require sync":rt?"body forces require sync":_e?"physics controllers require sync":ee?"fixed-step onTick requires sync":!(e=$t??{})||!e.engine&&cr(e.sediment)&&mr(e.colliders)?yr(j)?Ot.current?"worker fallback":null:"spawn pacing is not worker-cloneable":"config is not worker-cloneable":"worker unavailable":"hydrating";var e},[$t,_e,rt,it,Ht,ee,j]),fi=Qi(()=>{let e=nt.current,t=yi();if(!e||t)return{reason:t,useWorker:!1};let i=e.liveBodyCount(),r=e.queueSize(),n=gr(ve,i,r,Pe);return{reason:n?"worker"===ve?"forced worker":"body threshold":"below threshold",useWorker:n}},[ve,Pe,yi]),gi=Qi((e,t=!0)=>{let i=nt.current;if(!i||!e.snapshot)return i;if(i.restore(e.snapshot),t)for(let t of e.result.observations)$t?.observation?.onObservation?.(t);return dt.current=!0,i},[$t]),bi=Qi((e,t=!0,i=!0)=>{let r=gi(e,i);if(!r)return;t&&ee?.(e.result,r.controls()),hi();let n=r.snapshot(),o=Yt.current.size>0;(e.result.shouldContinue||o)&&!n.paused&&n.visible&&!mt.current&&xt()},[gi,ee,hi,mt,xt]),vi=Qi(e=>{Ot.current=!0;let t=e instanceof Error?e.message:String(e);mi(`worker failed: ${t||"unknown error"}`)},[mi]),xi=Qi(()=>{let e=nt.current;if(!e)return!1;let t=fi();if(!t.useWorker)return jt.current||qt.current?mi(t.reason??"sync fallback"):pi("sync",t.reason??"sync"),!1;if(jt.current||qt.current)return!0;let i=Wt.current??new wr;Wt.current=i,qt.current=!0;let r=Et.current+1;return Et.current=r,i.initFromSnapshot($t??{},e.snapshot()).then(e=>{if(Et.current!==r)return;qt.current=!1,jt.current=!0,Ot.current=!1,gi(e),pi("worker",t.reason??"worker"),hi();let i=nt.current?.snapshot();e.result.shouldContinue&&i&&!i.paused&&i.visible&&!mt.current&&(Pt.current=null,xt())}).catch(e=>{Et.current===r&&vi(e)}),!0},[gi,$t,vi,hi,mt,pi,xt,mi,fi]),wi=Qi(e=>"frame"===e.type||"removed"===e.type?e.frame:null,[]),Ii=Qi((e,t=!0)=>{let i=Wt.current;if(!i||!jt.current)return;let r=Et.current;i.request(e).then(i=>{if(Et.current!==r)return;let n=wi(i);n&&bi(n,t,"tick"!==e.type&&"settle"!==e.type)}).catch(vi)},[bi,wi,vi]),ki=Qi((e={})=>{let t=nt.current,i=ze.current;ze.current=!0;try{return Xe.current||qe.current||We.current||mn(Fe.current)?vn(t,e=>xn({store:t,result:e,regionEffects:Fe.current,regionState:Ne.current,bodyForces:We.current,composed:Xe.current,onTick:qe.current}),{...e,continueWhile:()=>!!(Ve.current||Xe.current||We.current||mn(Fe.current))}):{result:void 0===e.deltaSeconds?t.settleWithObservations(e.maxSteps):t.tick(e.deltaSeconds),snapshot:t.snapshot(),regionEffectsApplied:!1,bodyForcesApplied:!1}}finally{ze.current=i}},[]),Si=Qi(()=>{let e=nt.current;if(!e||!He.current||ze.current)return;let t=xi(),i=e.snapshot(),r=Ge||rt||it||!!_e;i.paused||!i.visible||!e.hasPendingWork()&&!r||mt.current?yt.current():t&&qt.current||xt()},[_e,Ge,rt,it,mt,yt,xt,xi]),Mi=Qi(()=>{ft(),ht.current=null;let e=nt.current;if(!e||!He.current)return;let t=mt.current;if(t){Pt.current=null;let t=Ye.current,i=e.snapshot();if(t?.store===e&&t.revision===e.version()&&t.bodyForces===We.current&&t.controllers===Xe.current&&t.regionEffects===Fe.current&&t.paused===i.paused&&t.visible===i.visible)return void hi()}if(jt.current&&Wt.current){if(Nt.current)return void(Ft.current=!0);let e=0;if(!t){let t=zt.current();e=null!==Pt.current?(t-Pt.current)/1e3:0,Pt.current=t}let i=Wt.current,r=Et.current;return Nt.current=!0,void(t?i.settle():i.tick(e)).then(e=>{Nt.current=!1;let t=Ft.current;Ft.current=!1,Et.current===r&&(bi(e),t&&Si())}).catch(i=>{Nt.current=!1;let n=Ft.current;Ft.current=!1,Et.current===r&&(vi(i),ki(t?{}:{deltaSeconds:e}),hi(),n&&Si())})}let i,r=Xe.current;if(!t){let e=zt.current(),t=Pt.current;Pt.current=e,i=null===t?0:(e-t)/1e3}let n=ki({deltaSeconds:i});t&&(Ye.current={store:e,revision:e.version(),bodyForces:We.current,controllers:Xe.current,regionEffects:Fe.current,paused:n.snapshot.paused,visible:n.snapshot.visible});let{result:o,regionEffectsApplied:s,bodyForcesApplied:a,snapshot:l}=n;hi();let d=Yt.current.size>0;(Ve.current||o.shouldContinue||s||a||r||d)&&!l.paused&&l.visible&&!mt.current&&xt()},[bi,vi,hi,ft,Si,ki,xt,mt,ht]);yt.current=Mi,Ji(()=>{Ot.current=!1,(jt.current||qt.current)&&mi("config changed",!1);let e=nt.current;e?.updateConfig($t??{}),e&&void 0===$t?.colliders&&Ct.current&&e.setColliders([]),Ct.current=void 0!==$t?.colliders,Si()},[$t,mi]),Ji(()=>{Ot.current=!1,Si()},[Ht,ve,Pe]),Ji(()=>{Si()},[pt,Si,Ue,_e,se]),Xr({cancelRender:ft,frameRuntime:It,lastFrameTimeRef:Pt,paused:oe,postWorkerCommand:Ii,requestRender:Si,storeRef:nt,suspendWhenHidden:Me}),Ji(()=>()=>mi("unmount",!1),[mi]),Ji(()=>{hi()},[hi]),Zi(t,()=>({...nt.current.controls(),applyImpulse:(e,t,i)=>{nt.current.applyImpulse(e,t,i),Ii({type:"applyImpulse",id:e,ix:t,iy:i}),Si()},clear:()=>{nt.current.clear(),Ne.current.clear(),Yt.current.clear(),Ii({type:"clear"}),Si()},clearRegionState:e=>{e?Ne.current.delete(e):Ne.current.clear(),Ye.current=null,Si()},getData:()=>nt.current.readBodies(),getRegionState:e=>e?an(Ne.current.get(e)):ln(Ne.current),getStore:()=>nt.current,pause:()=>{It.setPaused(!0),Pt.current=null,ft(),nt.current.setPaused(!0),Ii({type:"setPaused",paused:!0},!1),Si()},push:(e,t)=>{nt.current.enqueue(e,t),yr(t)?Ii({type:"enqueue",spawns:[e],pacing:t}):(jt.current||qt.current)&&mi("spawn pacing is not worker-cloneable"),Si()},pushMany:(e,t)=>{nt.current.enqueue(e,t),yr(t)?Ii({type:"enqueue",spawns:e,pacing:t}):(jt.current||qt.current)&&mi("spawn pacing is not worker-cloneable"),Si()},popBodies:(e,t={})=>{let i=nt.current,r=new Map(i.readBodies().map(e=>[e.id,e])),n=i.remove(e),o=zt.current();for(let e of n){let i=r.get(e);i&&(Ne.current.delete(e),mt.current||Yt.current.set(e,{body:i,color:t.color??"#f59e0b",durationMs:Math.max(120,t.durationMs??520),radius:t.radius??Ur(i),scale:null!=t.scale&&t.scale>0?t.scale:1,startedAt:o}),Kt.current===e&&(Kt.current=null,ii(null)),ri(t=>t?.id===e?null:t))}return n.length&&(Ii({type:"remove",ids:n}),Si()),n},remove:e=>{let t=nt.current.remove(e);for(let t of e)Ne.current.delete(t);return Ii({type:"remove",ids:e}),Si(),t},restore:e=>{nt.current.restore(e),Ne.current.clear(),Yt.current.clear(),Ii({type:"restore",snapshot:e},!1),Si()},resume:()=>{It.setPaused(!1),Pt.current=null,nt.current.setPaused(!1),Ii({type:"setPaused",paused:!1},!1),Si()},settle:e=>{let t=ki({maxSteps:e}).result.steps;return Ii({type:"settle",maxSteps:e}),hi(!0),t},settleWithObservations:e=>{let{result:t}=ki({maxSteps:e});return Ii({type:"settle",maxSteps:e}),hi(!0),t},step:e=>{let{result:t}=ki({deltaSeconds:e});return Ii({type:"tick",deltaSeconds:e}),hi(!0),t}}),[ft,Kt,It,hi,Ii,mt,Si,ki,ii,ri,mi]),Ji(()=>(He.current=!0,Si(),()=>{He.current=!1}),[Si]);let Ai=ne||!Ht&&Lt,$i=["stream-physics-frame",$?`stream-physics-frame--mode-${$}`:null,A?`stream-physics-frame--emphasis-${A}`:null,f].filter(Boolean).join(" "),Ci=M??("string"==typeof $e?$e:void 0)??"Physics chart",Pi=`${Tt}-physics-table`,Ri=Hn({enableHover:C,hoverData:Zt,tooltipContent:Ce,plotWidth:Mt,plotHeight:At,margin:ut}),Di=i?/* @__PURE__ */no(ue,{accessibleTable:i,children:[
|
|
32
|
-
/* @__PURE__ */ro(
|
|
33
|
-
/* @__PURE__ */ro(Xn,{chartTitle:"string"==typeof $e?$e:
|
|
34
|
-
return no("div",{ref:vt,className
|
|
35
|
-
/* @__PURE__ */ro(
|
|
36
|
-
return no("div",{ref:vt,className
|
|
37
|
-
/* @__PURE__ */ro(
|
|
38
|
-
/* @__PURE__ */no("div",{role:"img","aria-label":
|
|
39
|
-
/* @__PURE__ */ro(
|
|
24
|
+
/* @__PURE__ */Dn("th",{scope:"row",style:we,children:e.label}),
|
|
25
|
+
/* @__PURE__ */Dn("td",{style:we,children:e.description??e.label}),
|
|
26
|
+
/* @__PURE__ */Dn("td",{style:we,children:e.group??""}),
|
|
27
|
+
/* @__PURE__ */Bn("td",{style:we,children:[Math.round(e.x),", ",Math.round(e.y)]}),
|
|
28
|
+
/* @__PURE__ */Dn("td",{style:we,children:Yn(e)})]},e.id??`${e.label}-${t}`))})]}),
|
|
29
|
+
/* @__PURE__ */Dn(t,{remaining:y,onClick:e=>{d(e.currentTarget,p,Math.min(p+25,r.length),r.length),s(e=>e+25)},kind:"row"})]})}function Gn(e,t,i,r={left:0,top:0}){let n=e.getBoundingClientRect(),o=n.width>0&&e.clientWidth>0?e.clientWidth/n.width:1,s=n.height>0&&e.clientHeight>0?e.clientHeight/n.height:1;return{x:(t-n.left)*o-r.left,y:(i-n.top)*s-r.top}}function Vn(e,t,i,r){i.cursor&&((e.targets??(e.targets=/* @__PURE__ */new Map)).set(t.id,i),e.collisionGeometry||(e.collisionGeometry=r),e.maxSearchRadius=Math.max(e.maxSearchRadius,r?si(t):en(t,i)))}function Un({margin:e,clearKeyboardFocus:t,resolveSemanticBody:i,canvasRef:r,clearHover:n,emitObservation:o,enableHover:s,hoverRadius:a,hoverDataRef:l,onBodyHover:d,setHoverData:c,storeRef:u}){let h=Cn.useRef({inside:!1,x:0,y:0,pointerType:void 0}),p=Cn.useRef(null);p.current??(p.current={maxSearchRadius:0}),K(r);let m=Cn.useCallback(()=>{let e=p.current;return e.targets?.clear(),e.maxSearchRadius=0,e.collisionGeometry=!1,e},[]),y=Cn.useCallback((e,t,i,r)=>{let n=p.current,o=n.targets;if(!o?.size)return;let s=t.hitTest(i,r,0,{include:e=>o.has(e.id),searchRadius:n.maxSearchRadius,distanceSquared:(e,t,i)=>{let r=o.get(e.id);return r?n.collisionGeometry?ai(e,t,i,0):tn(e,r,t,i):null}});U(e,s?o.get(s.id)?.cursor:void 0)},[]),f=Cn.useCallback(r=>{if(!s&&!p.current?.targets?.size)return;if(t?.(),!s&&"touch"===r.pointerType)return h.current.inside=!1,void U(r.currentTarget);let m=u.current,{x:f,y:g}=Gn(r.currentTarget,r.clientX,r.clientY,e),b=h.current;if(b.inside=!0,b.x=f,b.y=g,b.pointerType=r.pointerType,!m||("touch"===r.pointerType?U(r.currentTarget):y(r.currentTarget,m,f,g),!s))return;let v=m.hitTest(f,g,a),x=v&&i?i(v):v;if(!x)return void n();let w=On(x),I=l.current;I?.id===w.id&&I.data===w.data&&I.x===w.x&&I.y===w.y||(l.current=w,c(w),d?.(x,w),o("hover",{datum:x.datum,x:x.x,y:x.y}))},[n,t,e,o,s,a,l,d,i,y,c,u]),g=Cn.useCallback(e=>{h.current.inside=!1,U(e.currentTarget),n()},[n]),b=Cn.useCallback((e,t,i)=>{let r=h.current;r.inside&&"touch"!==r.pointerType&&i.targets?.size?y(e,t,r.x,r.y):U(e)},[y]);return Cn.useMemo(()=>({begin:m,collect:Vn,handlePointerLeave:g,handlePointerMove:f,syncBodyCursors:b}),[m,g,f,b])}import{useCallback as Kn,useEffect as Qn,useMemo as Jn,useRef as Zn,useState as eo}from"react";var to=/* @__PURE__ */new Set(["ArrowRight","ArrowLeft","ArrowUp","ArrowDown","Home","End","PageUp","PageDown"]);function io({margin:e,allSemanticItems:t,bodySemanticItemLimit:i,bodySemanticItems:r,bodySemanticUpdateMs:n,emitObservation:o,enableHover:s,hoverRadius:a,logicalClockRef:l,onBodyHover:d,onBodyPointerDown:c,onClick:u,onSemanticItemActivate:h,onSemanticItemFocus:p,setBodySemanticItemsSnapshot:m,storeRef:y}){let f=Zn(-1),[g,b]=eo(null),[v,x]=eo(null),w=Zn(v);w.current=v;let I=Zn(null),k=Zn(0),S=Jn(()=>new Map(t.filter(e=>e.bodyId).map(e=>[e.bodyId,e])),[t]),M=Kn(e=>{let t=S.get(e.id)?.datum;return void 0===t||t===e.datum?e:{...e,datum:t}},[S]),A=Kn((e,t,o=!1)=>{if(!r)return void m(e=>e.length?[]:e);let s=l.current();if(!o&&n>0&&s-k.current<n)return;k.current=s;let a=Wn(e,t,r,i);m(e=>qn(e,a)?a:e)},[i,r,n,l,m]),$=Kn(e=>{if(!t.length)return;let i=Math.max(0,Math.min(e,t.length-1));f.current=i;let r=t[i];if(I.current=r.bodyId??null,b(r),p?.(r),r.bodyId&&y.current){let e=y.current.readBodies().find(e=>e.id===r.bodyId);if(e){let t=M(e),i=On(t);w.current=i,x(i),d?.(t,i)}}else w.current=null,x(null),d?.(null,null)},[t,d,p,y,M]),C=Kn(()=>{f.current<0&&null===I.current||(f.current=-1,I.current=null,b(null),p?.(null))},[p]),P=Kn(()=>{w.current&&(w.current=null,x(null),d?.(null,null),o("hover-end"))},[o,d]),R=Kn(t=>{C();let i=y.current,{x:r,y:n}=Gn(t.currentTarget,t.clientX,t.clientY,e),s=i?i.hitTest(r,n,Math.max(16,a)):null,l=s?M(s):null;c?.(l,t),l?(o("click",{datum:l.datum,x:l.x,y:l.y}),o("activate",{datum:l.datum,inputType:"touch"===t.pointerType?"touch":"pointer"}),u?.(l.datum??null,{x:l.x,y:l.y,body:l})):(o("click-end"),u?.(null,{x:r,y:n,body:null}),P())},[P,C,e,o,a,c,u,M,y]);Qn(()=>{if(!t.length)return void C();let e=f.current;if(e>=t.length)$(t.length-1);else if(e>=0){let i=t[e];if(I.current=i.bodyId??null,b(e=>null!=e&&e.id===i.id&&e.label===i.label&&e.description===i.description&&e.datum===i.datum&&Math.round(e.x)===Math.round(i.x)&&Math.round(e.y)===Math.round(i.y)?e:i),i.bodyId&&y.current){let e=y.current.readBodies().find(e=>e.id===i.bodyId);if(e){let t=On(M(e));x(e=>e?.id===t.id&&e.data===t.data&&Math.round(e.x)===Math.round(t.x)&&Math.round(e.y)===Math.round(t.y)?e:t)}}}},[t,C,$,y,M]),Qn(()=>{s||P()},[P,s]);let D=Kn(e=>{if(z(e)||!t.length)return;if("Escape"===e.key)return e.preventDefault(),w.current?P():f.current>=0&&o("hover-end"),void C();if(("Enter"===e.key||" "===e.key)&&f.current>=0){e.preventDefault();let i=t[f.current];return o("click",{datum:i.datum??{id:i.id,label:i.label},x:i.x,y:i.y}),o("activate",{datum:i.datum??{id:i.id,label:i.label},inputType:"keyboard"}),void h?.(i)}if(!to.has(e.key))return;e.preventDefault();let i=f.current;if(i<0){$(0);let e=t[0];return o("hover",{datum:e.datum??{id:e.id,label:e.label},x:e.x,y:e.y}),void o("focus",{datum:e.datum??{id:e.id,label:e.label},inputType:"keyboard"})}let r=Math.max(1,Math.floor(.1*t.length)),n=i;if("Home"===e.key?n=0:"End"===e.key?n=t.length-1:"PageDown"===e.key?n=Math.min(t.length-1,i+r):"PageUp"===e.key?n=Math.max(0,i-r):"ArrowRight"===e.key||"ArrowDown"===e.key?n=Math.min(t.length-1,i+1):("ArrowLeft"===e.key||"ArrowUp"===e.key)&&(n=Math.max(0,i-1)),$(n),n!==i){let e=t[n];o("hover",{datum:e.datum??{id:e.id,label:e.label},x:e.x,y:e.y}),o("focus",{datum:e.datum??{id:e.id,label:e.label},inputType:"keyboard"})}},[t,P,C,o,$,h]);return{clearSemanticFocus:C,resolveSemanticBody:M,clearHover:P,focusedBodyIdRef:I,focusedSemanticItem:g,handleCanvasPointerDown:R,hoverData:v,hoverDataRef:w,onKeyDown:D,setFocusedSemanticItem:b,setHoverData:x,syncBodySemanticItems:A}}import{jsx as ro,jsxs as no}from"react/jsx-runtime";var oo=[640,360],so=[],ao={top:0,right:0,bottom:0,left:0},lo="StreamPhysicsFrame",co=/* @__PURE__ */nr("background"),uo=/* @__PURE__ */nr("primary"),ho=/* @__PURE__ */nr("text"),po={stroke:ho,strokeWidth:2,opacity:1},mo=/* @__PURE__ */L(/* @__PURE__ */Ki(
|
|
30
|
+
/* @__PURE__ */Ui(function(e,t){let{accessibleTable:i=!0,annotations:r,onAnnotationActivate:n,autoPlaceAnnotations:o,background:s,backgroundGraphics:a,backgroundGraphicsBackdrop:l,maxDevicePixelRatio:d,bodySemanticItemLimit:c=200,bodySemanticItems:u=!1,bodySemanticUpdateMs:h=200,bodyForces:p,bodyStyle:m,chartId:y,className:f,frameScheduler:g,clock:b,random:v,seed:x,color:w,config:I,controllers:k,continuous:S=!1,description:A,emphasis:P,chartMode:B,enableHover:T=!0,foregroundGraphics:j,hoverRadius:O=16,initialSpawns:E,initialSpawnPacing:N,legend:F,legendClickBehavior:W,legendHighlightedCategory:q,legendHoverBehavior:H,legendIsolatedCategories:z,legendLayout:L,legendPosition:Y,margin:_,onClick:X,onObservation:G,onRegionEvent:V,onSimulationExecutionChange:U,onBodyHover:K,onBodyPointerDown:Q,onSemanticItemActivate:te,onSemanticItemFocus:re,onTick:oe,opacity:se,paused:ue=!1,regionEffects:he=so,responsiveHeight:me,responsiveWidth:ye,selectedBodyStyle:fe=po,selection:be,semanticItems:ve=[],simulationExecution:xe="auto",size:we=oo,stroke:Ie,strokeWidth:ke,summary:Se,suspendWhenHidden:Me=!0,svgAnnotationRules:Ae,title:$e,tooltipContent:Ce,workerBodyThreshold:Pe=2500,renderBody:Re,beforePaint:De,afterPaint:Be}=e,Te=Vi.useMemo(()=>({color:w,stroke:Ie,strokeWidth:ke,opacity:se}),[w,se,Ie,ke]),je=tr(G);je.current=G;let Oe=tr(y);Oe.current=y;let Ne=tr(/* @__PURE__ */new Map),Fe=tr(he);Fe.current=he;let We=tr(p),qe=tr(oe);qe.current=oe;let He=tr(!1),ze=tr(!1),Ye=tr(null),_e=Vi.useMemo(()=>Xi(k),[k]),Xe=tr(_e);Xe.current=_e;let Ge=S||!!_e?.continuous,Ve=tr(Ge);Ve.current=Ge;let Ue=Vi.useMemo(()=>{if(!p&&!_e?.bodyForce||!_e?.bodyForce)return p;if(!p)return _e.bodyForce;let e=_e.bodyForce;return t=>{let i="function"==typeof p?p(t):p,r="function"==typeof e?e(t):e;return i||r?{x:(i?.x??0)+(r?.x??0),y:(i?.y??0)+(r?.y??0)}:null}},[p,_e]);We.current=Ue;let Ke=Vi.useMemo(()=>new Map(he.map(e=>[on(e),e])),[he]),Qe=Vi.useMemo(()=>new Map(he.map(e=>[e.id,e])),[he]),Je=Vi.useMemo(()=>he.map(pn).filter(e=>null!=e),[he]),[Ze,et]=Vi.useState([]),tt=Vi.useMemo(()=>Ze.length||Je.length?[...ve,...Ze,...Je]:ve,[Ze,Je,ve]),it=Vi.useMemo(()=>mn(he),[he]),rt=!!Ue,nt=tr(null),ot=tr(b??kr);ot.current=b??kr;let st=Qi((e,t,i)=>{let r=nt.current;if(!r||!i)return!1;let n=r.readBodies().find(t=>t.id===e),o=an(Ne.current.get(e));if(!n||!o)return!1;let s=cn(i,{body:n,region:t,regionState:o});return!(!s||!s.x&&!s.y||(r.applyImpulse(e,s.x??0,s.y??0),0))},[]),at=Qi((e,t,i)=>{if(!i.bodyId)return;let r=an(Ne.current.get(i.bodyId));if(!r)return;let n={bodyId:i.bodyId,datum:i.datum,observation:i,region:t,regionState:r,type:e};"region-enter"===e?t.onEnter?.(n):t.onExit?.(n),V?.(n)},[V]),lt=Qi(e=>{let t=e.sensorId?Ke.get(e.sensorId):void 0;if(!t||!e.bodyId)return;let i=dn(Ne.current,e.bodyId),r=nt.current?.readBodies().find(t=>t.id===e.bodyId),n=an(i),o=r&&n?{body:r,region:t,regionState:n}:null;if("physics-proximity-enter"===e.type){if(i.activeRegionIds.add(t.id),i.regionIds.add(t.id),i.energy+=t.energyDelta??0,o){un(t,o,i);let e=hn(t,o);void 0!==e&&(i.charges[t.id]=e)}st(e.bodyId,t,t.impulseOnEnter),at("region-enter",t,e)}else"physics-proximity-exit"===e.type&&(i.activeRegionIds.delete(t.id),st(e.bodyId,t,t.impulseOnExit),at("region-exit",t,e))},[st,at,Ke]),dt=tr(!0),ct=M({sizeProp:we,responsiveWidth:ye,responsiveHeight:me,userMargin:_,marginDefault:ao,legend:F,legendPosition:Y,legendLayout:L,themeDirtyRef:dt,skipInitialThemeInvalidation:!0,foregroundGraphics:j,backgroundGraphics:a,frameScheduler:g,clock:b,random:v,seed:x,paused:ue,suspendWhenHidden:Me}),{margin:ut,rafRef:ht,reducedMotion:pt,reducedMotionRef:mt,renderFnRef:yt,cancelRender:ft,resolvedBackground:gt,resolvedForeground:bt,responsiveRef:vt,scheduleRender:xt,size:wt,frameRuntime:It}=ct;Ji(()=>pe(()=>{dt.current=!0,xt()}),[xt]);let kt=wt[0],St=wt[1],Mt=Math.max(1,kt-ut.left-ut.right),At=Math.max(1,St-ut.top-ut.bottom),$t=Vi.useMemo(()=>$n({annotations:r,chartId:y,chartType:lo,config:I,onRegionObservation:lt,regionEffects:he,seed:x,size:[Mt,At]}),[r,y,I,lt,he,x,Mt,At]),Ct=tr(void 0!==$t?.colliders);if(!nt.current){let e=Ir($t,E,N);e.setPaused(ue),Me&&e.setVisible(_r()),nt.current=e}let Pt=tr(null),Rt=tr(null);Rt.current||(Rt.current=lr());let Dt=ie("StreamPhysicsFrame"),Bt=tr(""),Tt=er().replace(/:/g,""),jt=tr(!1),Ot=tr(!1),Et=tr(0),Nt=tr(!1),Ft=tr(!1),Wt=tr(null),qt=tr(!1),Ht=tr(It.now);Ht.current=It.now;let zt=J(),Lt=ee(),Yt=tr(
|
|
31
|
+
/* @__PURE__ */new Map),_t=`${Tt}-physics-live`,Xt=kn({onObservationRef:je,chartIdRef:Oe,wallClockRef:ot}),{clearSemanticFocus:Gt,resolveSemanticBody:Vt,clearHover:Ut,focusedBodyIdRef:Kt,focusedSemanticItem:Qt,handleCanvasPointerDown:Jt,hoverData:Zt,hoverDataRef:ei,onKeyDown:ti,setFocusedSemanticItem:ii,setHoverData:ri,syncBodySemanticItems:ni}=io({margin:ut,allSemanticItems:tt,bodySemanticItemLimit:c,bodySemanticItems:u,bodySemanticUpdateMs:h,emitObservation:Xt,enableHover:T,hoverRadius:O,logicalClockRef:Ht,onBodyHover:K,onBodyPointerDown:Q,onClick:X,onSemanticItemActivate:te,onSemanticItemFocus:re,setBodySemanticItemsSnapshot:et,storeRef:nt}),[oi,si]=Vi.useState([]),ai=tr(0),li=!!r?.length&&r.some(e=>null!=e.pointId||null!=e.bodyId||"latest"===e.anchor),{canvasRef:di,resolutionDirtyRef:ci}=R(ct,{hydrated:zt,wasHydratingFromSSR:Lt,storeRef:nt,dirtyRef:dt,manageFrameRuntime:!1,skipInitialCanvasPaintInvalidation:!0,maxDevicePixelRatio:d,canvasPaintDependencies:[s,a,xt]}),ui=Un({margin:ut,clearKeyboardFocus:Gt,hoverDataRef:ei,resolveSemanticBody:Vt,canvasRef:di,clearHover:Ut,emitObservation:Xt,enableHover:T,hoverRadius:O,onBodyHover:K,setHoverData:ri,storeRef:nt}),hi=Qi((e=!1)=>{let t=di.current,i=nt.current;if(!t||!i)return;let r=Dt.current.beforeCompute(i.getLastUpdateResult(),!1);ci.current=!1;let n=C(d,wt),o=$(t,wt,ut,n);if(!o)return void Dt.current.afterCompute(r,!1,!1);let l=Rt.current.resolve(o),c={theme:l,resolvePaint:(e,t)=>ge(o,e,t),withAlpha:sr};o.clearRect(-ut.left,-ut.top,wt[0],wt[1]),!a&&"transparent"!==s&&(o.fillStyle=null==s?l.background:c.resolvePaint(s,l.background),o.fillRect(-ut.left,-ut.top,wt[0],wt[1])),o.save(),o.beginPath(),o.rect(0,0,Mt,At),o.clip();let u=i.snapshot(),h=i.readBodies(),p=ui.begin();if(ni(h,u.simulationState,e||mt.current||"running"!==u.simulationState),li){let e=Ht.current();if(e-ai.current>=100){ai.current=e;let t=Ee(h);si(e=>e.length===t.length&&e.every((e,i)=>e.pointId===t[i].pointId&&Math.round(e.x)===Math.round(t[i].x)&&Math.round(e.y)===Math.round(t[i].y))?e:t)}}De&&(o.save(),De(o,h,c),o.restore());for(let e of h){let t=Ne.current.get(e.id),i=t?Array.from(t.activeRegionIds).map(e=>Qe.get(e)).filter(e=>null!=e):[],r=wn(e,u.simulationState,m,fe,be,an(t),i,l.primary,l.text,Te);ui.collect(p,e,r,!!Re),Re?(o.save(),Re(o,e,r,c),o.restore()):Vr(o,e,r)}ui.syncBodyCursors(t,i,p),Be&&(o.save(),Be(o,h,c),o.restore()),mt.current?Yt.current.clear():rn(o,Yt.current,Ht.current()),o.restore(),Dt.current.afterCompute(r,!0,!1),dt.current=!1},[di,ci,Dt,wt,ut,Mt,At,a,s,d,ni,li,De,Be,m,fe,be,Te,Re,Qe,ui,mt]),pi=tr(U);pi.current=U;let mi=Qi((e,t)=>{let i=nt.current,r=`${xe}:${e}:${t??""}`;Bt.current!==r&&(Bt.current=r,pi.current?.({execution:e,liveBodies:i?.liveBodyCount()??0,queuedBodies:i?.queueSize()??0,reason:t,requested:xe}))},[xe]),yi=Qi((e,t=!0)=>{Et.current+=1,jt.current=!1,Nt.current=!1,Ft.current=!1,qt.current=!1,Wt.current?.terminate(),Wt.current=null,t&&mi("sync",e)},[mi]),fi=Qi(()=>{return zt?typeof window<"u"&&typeof Worker<"u"?it?"runtime region effects require sync":rt?"body forces require sync":_e?"physics controllers require sync":oe?"fixed-step onTick requires sync":!(e=$t??{})||!e.engine&&cr(e.sediment)&&mr(e.colliders)?yr(N)?Ot.current?"worker fallback":null:"spawn pacing is not worker-cloneable":"config is not worker-cloneable":"worker unavailable":"hydrating";var e},[$t,_e,rt,it,zt,oe,N]),gi=Qi(()=>{let e=nt.current,t=fi();if(!e||t)return{reason:t,useWorker:!1};let i=e.liveBodyCount(),r=e.queueSize(),n=gr(xe,i,r,Pe);return{reason:n?"worker"===xe?"forced worker":"body threshold":"below threshold",useWorker:n}},[xe,Pe,fi]),bi=Qi((e,t=!0)=>{let i=nt.current;if(!i||!e.snapshot)return i;if(i.restore(e.snapshot),t)for(let t of e.result.observations)$t?.observation?.onObservation?.(t);return dt.current=!0,i},[$t]),vi=Qi((e,t=!0,i=!0)=>{let r=bi(e,i);if(!r)return;t&&oe?.(e.result,r.controls()),hi();let n=r.snapshot(),o=Yt.current.size>0;(e.result.shouldContinue||o)&&!n.paused&&n.visible&&!mt.current&&xt()},[bi,oe,hi,mt,xt]),xi=Qi(e=>{Ot.current=!0;let t=e instanceof Error?e.message:String(e);yi(`worker failed: ${t||"unknown error"}`)},[yi]),wi=Qi(()=>{let e=nt.current;if(!e)return!1;let t=gi();if(!t.useWorker)return jt.current||qt.current?yi(t.reason??"sync fallback"):mi("sync",t.reason??"sync"),!1;if(jt.current||qt.current)return!0;let i=Wt.current??new wr;Wt.current=i,qt.current=!0;let r=Et.current+1;return Et.current=r,i.initFromSnapshot($t??{},e.snapshot()).then(e=>{if(Et.current!==r)return;qt.current=!1,jt.current=!0,Ot.current=!1,bi(e),mi("worker",t.reason??"worker"),hi();let i=nt.current?.snapshot();e.result.shouldContinue&&i&&!i.paused&&i.visible&&!mt.current&&(Pt.current=null,xt())}).catch(e=>{Et.current===r&&xi(e)}),!0},[bi,$t,xi,hi,mt,mi,xt,yi,gi]),Ii=Qi(e=>"frame"===e.type||"removed"===e.type?e.frame:null,[]),ki=Qi((e,t=!0)=>{let i=Wt.current;if(!i||!jt.current)return;let r=Et.current;i.request(e).then(i=>{if(Et.current!==r)return;let n=Ii(i);n&&vi(n,t,"tick"!==e.type&&"settle"!==e.type)}).catch(xi)},[vi,Ii,xi]),Si=Qi((e={})=>{let t=nt.current,i=He.current;He.current=!0;try{return Xe.current||qe.current||We.current||mn(Fe.current)?vn(t,e=>xn({store:t,result:e,regionEffects:Fe.current,regionState:Ne.current,bodyForces:We.current,composed:Xe.current,onTick:qe.current}),{...e,continueWhile:()=>!!(Ve.current||Xe.current||We.current||mn(Fe.current))}):{result:void 0===e.deltaSeconds?t.settleWithObservations(e.maxSteps):t.tick(e.deltaSeconds),snapshot:t.snapshot(),regionEffectsApplied:!1,bodyForcesApplied:!1}}finally{He.current=i}},[]),Mi=Qi(()=>{let e=nt.current;if(!e||!ze.current||He.current)return;let t=wi(),i=e.snapshot(),r=Ge||rt||it||!!_e;i.paused||!i.visible||!e.hasPendingWork()&&!r||mt.current?yt.current():t&&qt.current||xt()},[_e,Ge,rt,it,mt,yt,xt,wi]),Ai=Qi(()=>{ft(),ht.current=null;let e=nt.current;if(!e||!ze.current)return;let t=mt.current;if(t){Pt.current=null;let t=Ye.current,i=e.snapshot();if(t?.store===e&&t.revision===e.version()&&t.bodyForces===We.current&&t.controllers===Xe.current&&t.regionEffects===Fe.current&&t.paused===i.paused&&t.visible===i.visible)return void hi()}if(jt.current&&Wt.current){if(Nt.current)return void(Ft.current=!0);let e=0;if(!t){let t=Ht.current();e=null!==Pt.current?(t-Pt.current)/1e3:0,Pt.current=t}let i=Wt.current,r=Et.current;return Nt.current=!0,void(t?i.settle():i.tick(e)).then(e=>{Nt.current=!1;let t=Ft.current;Ft.current=!1,Et.current===r&&(vi(e),t&&Mi())}).catch(i=>{Nt.current=!1;let n=Ft.current;Ft.current=!1,Et.current===r&&(xi(i),Si(t?{}:{deltaSeconds:e}),hi(),n&&Mi())})}let i,r=Xe.current;if(!t){let e=Ht.current(),t=Pt.current;Pt.current=e,i=null===t?0:(e-t)/1e3}let n=Si({deltaSeconds:i});t&&(Ye.current={store:e,revision:e.version(),bodyForces:We.current,controllers:Xe.current,regionEffects:Fe.current,paused:n.snapshot.paused,visible:n.snapshot.visible});let{result:o,regionEffectsApplied:s,bodyForcesApplied:a,snapshot:l}=n;hi();let d=Yt.current.size>0;(Ve.current||o.shouldContinue||s||a||r||d)&&!l.paused&&l.visible&&!mt.current&&xt()},[vi,xi,hi,ft,Mi,Si,xt,mt,ht]);yt.current=Ai,Ji(()=>{Ot.current=!1,(jt.current||qt.current)&&yi("config changed",!1);let e=nt.current;e?.updateConfig($t??{}),e&&void 0===$t?.colliders&&Ct.current&&e.setColliders([]),Ct.current=void 0!==$t?.colliders,Mi()},[$t,yi]),Ji(()=>{Ot.current=!1,Mi()},[zt,xe,Pe]),Ji(()=>{Mi()},[pt,Mi,Ue,_e,he]),Xr({cancelRender:ft,frameRuntime:It,lastFrameTimeRef:Pt,paused:ue,postWorkerCommand:ki,requestRender:Mi,storeRef:nt,suspendWhenHidden:Me}),Ji(()=>()=>yi("unmount",!1),[yi]),Ji(()=>{hi()},[hi]),Zi(t,()=>({...nt.current.controls(),applyImpulse:(e,t,i)=>{nt.current.applyImpulse(e,t,i),ki({type:"applyImpulse",id:e,ix:t,iy:i}),Mi()},clear:()=>{nt.current.clear(),Ne.current.clear(),Yt.current.clear(),ki({type:"clear"}),Mi()},clearRegionState:e=>{e?Ne.current.delete(e):Ne.current.clear(),Ye.current=null,Mi()},getData:()=>nt.current.readBodies(),getRegionState:e=>e?an(Ne.current.get(e)):ln(Ne.current),getStore:()=>nt.current,pause:()=>{It.setPaused(!0),Pt.current=null,ft(),nt.current.setPaused(!0),ki({type:"setPaused",paused:!0},!1),Mi()},push:(e,t)=>{nt.current.enqueue(e,t),yr(t)?ki({type:"enqueue",spawns:[e],pacing:t}):(jt.current||qt.current)&&yi("spawn pacing is not worker-cloneable"),Mi()},pushMany:(e,t)=>{nt.current.enqueue(e,t),yr(t)?ki({type:"enqueue",spawns:e,pacing:t}):(jt.current||qt.current)&&yi("spawn pacing is not worker-cloneable"),Mi()},popBodies:(e,t={})=>{let i=nt.current,r=new Map(i.readBodies().map(e=>[e.id,e])),n=i.remove(e),o=Ht.current();for(let e of n){let i=r.get(e);i&&(Ne.current.delete(e),mt.current||Yt.current.set(e,{body:i,color:t.color??"#f59e0b",durationMs:Math.max(120,t.durationMs??520),radius:t.radius??Ur(i),scale:null!=t.scale&&t.scale>0?t.scale:1,startedAt:o}),Kt.current===e&&(Kt.current=null,ii(null)),ri(t=>t?.id===e?null:t))}return n.length&&(ki({type:"remove",ids:n}),Mi()),n},remove:e=>{let t=nt.current.remove(e);for(let t of e)Ne.current.delete(t);return ki({type:"remove",ids:e}),Mi(),t},restore:e=>{nt.current.restore(e),Ne.current.clear(),Yt.current.clear(),ki({type:"restore",snapshot:e},!1),Mi()},resume:()=>{It.setPaused(!1),Pt.current=null,nt.current.setPaused(!1),ki({type:"setPaused",paused:!1},!1),Mi()},settle:e=>{let t=Si({maxSteps:e}).result.steps;return ki({type:"settle",maxSteps:e}),hi(!0),t},settleWithObservations:e=>{let{result:t}=Si({maxSteps:e});return ki({type:"settle",maxSteps:e}),hi(!0),t},step:e=>{let{result:t}=Si({deltaSeconds:e});return ki({type:"tick",deltaSeconds:e}),hi(!0),t}}),[ft,Kt,It,hi,ki,mt,Mi,Si,ii,ri,yi]),Ji(()=>(ze.current=!0,Mi(),()=>{ze.current=!1}),[Mi]);let $i=Z||!zt&&Lt,Ci=["stream-physics-frame",B?`stream-physics-frame--mode-${B}`:null,P?`stream-physics-frame--emphasis-${P}`:null,f].filter(Boolean).join(" "),Pi=A??("string"==typeof $e?$e:void 0)??"Physics chart",Ri=`${Tt}-physics-table`,Di=zn({enableHover:T,hoverData:Zt,tooltipContent:Ce,plotWidth:Mt,plotHeight:At,margin:ut}),Bi=i?/* @__PURE__ */no(ae,{accessibleTable:i,children:[
|
|
32
|
+
/* @__PURE__ */ro(de,{tableId:Ri}),
|
|
33
|
+
/* @__PURE__ */ro(Xn,{chartTitle:"string"==typeof $e?$e:A,items:tt,tableId:Ri})]}):null;if($i){let t=nt.current??Ir($t,E,N),r="string"==typeof $e?$e:void 0,n=(e,t)=>{let i=Ne.current.get(e.id),r=i?Array.from(i.activeRegionIds).map(e=>Qe.get(e)).filter(e=>null!=e):[];return wn(e,t.simulationState,m,fe,be,an(i),r,uo,ho,Te)},{element:o}=qr(t,{width:wt[0],height:wt[1],title:r,description:A,background:a||"transparent"===s?void 0:s??co,backgroundGraphics:gt,backgroundGraphicsBackdrop:l,className:"stream-physics-frame__svg",foregroundGraphics:bt,idPrefix:`physics-${Tt}`,margin:ut,bodyStyle:n,renderChrome:t=>zr(t,e,wt,ut,lo)});/* */
|
|
34
|
+
return no("div",{ref:vt,className:Ci,"data-semiotic-mode":B,role:i?"group":"img","aria-label":Pi,style:{width:ye?"100%":wt[0],height:me?"100%":wt[1]},children:[Bi,
|
|
35
|
+
/* @__PURE__ */ro(le,{summary:Se}),o]})}/* */
|
|
36
|
+
return no("div",{ref:vt,className:Ci,"data-semiotic-mode":B,role:"group","aria-label":Pi,"aria-describedby":Qt?_t:void 0,tabIndex:0,style:{position:"relative",width:ye?"100%":wt[0],height:me?"100%":wt[1]},onKeyDown:ti,children:["production"!==process.env.NODE_ENV&&nt.current&&/* @__PURE__ */ro(ne,{store:nt.current,diagnostics:Dt.current}),Bi,
|
|
37
|
+
/* @__PURE__ */ro(le,{summary:Se}),Tn(0,Qt,0,_t),
|
|
38
|
+
/* @__PURE__ */no("div",{role:"img","aria-label":Pi,style:{position:"relative",width:"100%",height:"100%"},children:[
|
|
39
|
+
/* @__PURE__ */ro(D,{size:wt,margin:ut,backdropFill:l,children:gt}),
|
|
40
40
|
/* @__PURE__ */ro("canvas",{ref:di,width:wt[0],height:wt[1],"aria-hidden":"true",style:{position:"absolute",left:0,top:0,display:"block"},onPointerDown:Jt,onPointerMove:ui.handlePointerMove,onPointerLeave:ui.handlePointerLeave}),bt,
|
|
41
|
-
/* @__PURE__ */ro(Le,{width:Mt,height:At,totalWidth:wt[0],totalHeight:wt[1],margin:ut,title:$e,legend:
|
|
42
|
-
/* @__PURE__ */ro(me,{active:null!=Qt,hoverPoint:Qt?{x:Qt.x,y:Qt.y}:null,margin:ut,size:wt,shape:Qt?.shape,width:Qt?.width,height:Qt?.height,pathData:Qt?.pathData}),Ri]})]})})),"StreamPhysicsFrame"),yo=mo;import{scaleLinear as fo}from"d3-scale";function go(e){let{data:t,valueAccessor:r,bins:n,ballRadius:s,seed:d,size:c,valueExtent:h}=e,{rows:m}=p(t,"galton"),y=i(c),f=m.map((e,t)=>l(a(e,t,r))).filter(e=>null!=e),g=u(h),[b,v]=g??(f.length?Te(f):[0,1]),x=v===b?1:v-b,w=fo().domain([0,n]).range([y.plot.x,y.plot.x+y.plot.width]),I=Array.from({length:n},()=>0),k=[];m.forEach((e,t)=>{let i=l(a(e,t,r));if(null==i)return;let o=Math.max(0,Math.min(n-1,Math.floor((i-b)/x*n)));I[o]+=1,k.push({id:String(e.id??`galton-${t}`),x:w(o+.5),y:y.plot.y+s+2,vx:8*(t%5-2),vy:0,mass:1,shape:{type:"circle",radius:s},datum:{...e,value:i,bin:o}})});let S=y.plot.y+y.plot.height,M=[...ci({x:y.plot.x,y:y.plot.y,width:y.plot.width,height:y.plot.height},{idPrefix:"galton",wallThickness:20,floorThickness:20}),...ui({idPrefix:"galton-bin",count:n,domainStart:0,domainStep:1,xScale:w,yTop:y.plot.y-400,yBottom:S,wallThickness:6})];return{config:o(d,M,"GaltonBoardChart"),initialSpawns:k,initialSpawnPacing:{pacing:{ratePerSec:55}},projectionRows:I.map((e,t)=>({label:String(t+1),value:e})),metadata:{kind:"galton-board",bins:n,plot:y.plot,valueExtent:[b,v]}}}import{scaleLinear as bo}from"d3-scale";function vo(e,t){let i=Math.max(5*t,Math.min(92,.13*e.plot.width));return{gutter:{x:e.plot.x,y:e.plot.y,width:i,height:e.plot.height},windowPlot:{x:e.plot.x+i,y:e.plot.y,width:Math.max(40,e.plot.width-i),height:e.plot.height},wallTop:e.plot.y+.48*e.plot.height}}function xo(e,t){let i=Math.max(0,Math.min(e.windowCount,e.closedWindowCount));if(!i)return[];let r=e.windowStart,n=e.windowStart+e.windowCount*e.windowSize,o=bo().domain([r,n]).range([e.windowPlot.x,e.windowPlot.x+e.windowPlot.width]),s=o(e.windowStart+i*e.windowSize),a=e.windowPlot.x,l=Math.max(18,Math.min(.3*e.windowPlot.height,s-a)),d=t+l,c=e=>s===a?t:d+(e-a)/(s-a)*(t-d),u=[];for(let t=0;t<i;t+=1){let i=e.windowStart+t*e.windowSize,r=i+e.windowSize,n=o(i),s=o(r);u.push({id:`eventdrop-lid-${t}`,windowIndex:t,x1:n,y1:c(n),x2:s,y2:c(s)})}return u}function wo(e){let{count:t,idPrefix:i,wallThickness:r,xScale:n,yBottom:o,yTop:s,yTopForIndex:a}=e;return Array.from({length:t+1},(e,t)=>{let l=Math.min(o-1,a?.(t)??s),d=Math.max(1,o-l);return{id:`${i}-wall-${t}`,shape:{type:"aabb",x:n(t),y:l+d/2,width:r,height:d}}})}function Io(e){let{data:t,timeAccessor:r,arrivalAccessor:n,windows:s,watermark:a,watermarkAtArrivalAccessor:d,ballRadius:c,seed:u,size:h,timeExtent:p,timeScale:m=1}=e,{events:y,watermarkValue:f}=g({data:t,timeAccessor:r,arrivalAccessor:n,watermark:a,watermarkAtArrivalAccessor:d,windowSize:s.size}),b=i(h),v=y.length?1/0:0,x=y.length?1/0:0,w=y.length?-1/0:s.size;for(let e of y)v=Math.min(v,e.arrivalTime),x=Math.min(x,e.eventTime),w=Math.max(w,e.eventTime);let I=l(p?.[0]),k=l(p?.[1]),S=Math.min(I??x,x),M=Math.max(k??w,w),A=Math.floor(S/s.size)*s.size,$=Math.max(1,Math.ceil((M-A+s.size)/s.size)),C=vo(b,c),P=A+$*s.size,R=bo().domain([A,P]).range([C.windowPlot.x,C.windowPlot.x+C.windowPlot.width]),D=0,B=Array.from({length:$},(e,t)=>(A+(t+1)*s.size<=f&&D++,{value:0,secondary:0})),T=[];y.forEach(({datum:e,index:t,eventTime:i,arrivalTime:r,watermarkAtArrival:n,late:o})=>{let a=Math.max(0,Math.min($-1,Math.floor((i-A)/s.size)));B[a].value+=o?0:1,B[a].secondary+=o?1:0,T.push({id:String(e.id??`event-${t}`),x:Mo(i,a,o,{windowStart:A,windowSize:s.size,gutter:C.gutter,closedWindowCount:D,windowPlot:C.windowPlot,windowCount:$},c),y:b.plot.y+c+2,vx:0,vy:0,mass:1,friction:.02,spawnAt:r,shape:{type:"circle",radius:c},datum:{...e,eventTime:i,arrivalTime:r,windowIndex:a,watermarkAtArrival:n,late:o}})});let j=b.plot.y+b.plot.height,O=b.plot.y+.28*b.plot.height,E={closedWindowCount:D,gutter:C.gutter,plot:b.plot,windowCount:$,windowPlot:C.windowPlot,windowSize:s.size,windowStart:A},N=xo(E,O);for(let e of T){let t=e.datum;e.y=ko({...E,lidSegments:N},t.windowIndex,t.late,c)}let F=e=>{if(e<0||e>D)return null;let t=0===e?N[0]?.y1:N[e-1]?.y2??N[e]?.y1;return"number"==typeof t&&Number.isFinite(t)?t:null},W=wo({idPrefix:"eventdrop-window",count:$,xScale:e=>R(A+e*s.size),yTop:C.wallTop,yTopForIndex:e=>{let t=F(e);return null==t?C.wallTop:t+1.25*c},yBottom:j,wallThickness:6}),q=[...ci({x:b.plot.x,y:b.plot.y,width:b.plot.width,height:b.plot.height},{idPrefix:"eventdrop",wallThickness:20,floorThickness:20}),...W,...N.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*c)},friction:.02,restitution:.01}))];return{config:o(u,q,"EventDropChart",{friction:.08}),initialSpawns:T,initialSpawnPacing:{pacing:"arrival",timeAccessor:e=>{let t=e.datum,i=t.windowIndex<D;return i&&!t.late||!i&&t.late?v:t.arrivalTime},timeScale:m},projectionRows:B.map((e,t)=>({label:`${A+t*s.size}-${A+(t+1)*s.size}`,value:e.value,secondary:e.secondary})),metadata:{kind:"event-drop",closedWindowCount:D,gutter:C.gutter,lidSegments:N,lateCount:B.reduce((e,t)=>e+t.secondary,0),plot:b.plot,windowPlot:C.windowPlot,windowWalls:W.map(({id:e,shape:t})=>({id:e,x:t.x-t.width/2,y:t.y-t.height/2,width:t.width,height:t.height})),watermarkValue:f,windowCount:$,windowSize:s.size,windowStart:A}}}function ko(e,t,i,r){let{windowPlot:n,lidSegments:o}=e,s=o[t];return i&&!s?Math.min(n.y+n.height-r,n.y+.48*n.height+2*r+4):!i&&s?Math.min(n.y+n.height-r,Math.max(s.y1,s.y2)+2*r+4):n.y+r+2}function So(e,t){let{windowPlot:i,gutter:r,windowCount:n,lidSegments:o}=e,s=Array(n).fill(0),a=i.y+i.height,l=i.y+.48*i.height,d=0,c=0;for(let e of t){if(e.x>=r.x&&e.x<i.x&&e.y>=(o[0]?.y1??l)&&e.y<=a){d++;continue}let t=Math.floor((e.x-i.x)/i.width*n),u=o[t],h=u?Math.max(u.y1,u.y2):l;t>=0&&t<n&&e.y>=h&&e.y<=a?s[t]++:c++}return{accepted:s,late:d,inFlight:c,total:t.length}}function Mo(e,t,i,r,n){let{windowPlot:o,windowCount:s,windowStart:a,windowSize:l}=r;if(i&&t>=r.closedWindowCount)return r.gutter.x+r.gutter.width/2;let d=o.width/s,c=i?o.x:o.x+t*d,u=i?o.x+o.width:c+d,h=Math.min((u-c)/2,n+(i?0:3)),p=o.x+(e-a)/l*d;return Math.max(c+h,Math.min(u-h,p))}function Ao(e,t,i){let r=Math.max(1,t),n=e.width/r,o=Math.max(2,2*i),s=Math.min(.7*n,Math.max(3.2*o,o+8)),a=Math.max(1,Math.floor(s/o));return{laneWidth:n,tubeWidth:s,ballDiameter:o,perRow:a,centerX:t=>e.x+(t+.5)*n,pileHeight:e=>Math.ceil(Math.max(0,e)/a)*o}}function $o(e){let{data:t,categoryAccessor:r,valueAccessor:n,unitValue:s,ballRadius:d,seed:u,size:h}=e,m=c(s,1),{rows:f}=p(t,"pile"),g=i(h),b=[],v=/* @__PURE__ */new Map,x=/* @__PURE__ */new Map,w=[];function I(e){let t=v.get(e);return null==t&&(t=b.length,b.push(e),v.set(e,t)),t}f.forEach((e,t)=>{I(String(a(e,t,r)??"unknown"))});let k=Math.max(1,b.length),S=Ao(g.plot,k,d),M=Math.max(0,S.tubeWidth/2-d-1),A=b.map(()=>[]);f.forEach((e,t)=>{let i=String(a(e,t,r)??"unknown"),o=I(i),s=n?l(a(e,t,n)):1,c=Math.max(0,s??0);x.set(i,(x.get(i)??0)+c);let u=y(c,m),h=S.centerX(o);for(let r=0;r<u;r+=1){let n=A[o].length,s=r===u-1?c-r*m:m,a=Math.min(1,s/m),l=S.perRow>1?n%S.perRow:0,p=S.perRow>1?(l/(S.perRow-1)*2-1)*M:0;A[o].push({id:`${String(e.id??`pile-${t}`)}-${r}`,x:h+p,y:g.plot.y+d+2,vx:(r%3-1)*d/2,vy:0,mass:1,shape:{type:"circle",radius:d*Math.sqrt(a)},datum:{...e,category:i,unitIndex:r,unitValue:m,representedValue:s,unitFraction:a}})}});let $=A.reduce((e,t)=>Math.max(e,t.length),0);for(let e=0;e<$;e+=1)for(let t of A)e<t.length&&w.push(t[e]);let C=g.plot.y+g.plot.height,P=[...ci({x:g.plot.x,y:g.plot.y,width:g.plot.width,height:g.plot.height},{idPrefix:"pile",wallThickness:20,floorThickness:20})],R=g.plot.y-400;for(let e=0;e<k;e+=1){let t=S.centerX(e);for(let i of[-1,1])P.push({id:`pile-tube-${e}-${i<0?"l":"r"}`,shape:{type:"aabb",x:t+i*(S.tubeWidth+6)/2,y:(R+C)/2,width:6,height:C-R}})}return{config:o(u,P,"UnitPileChart"),initialSpawns:w,initialSpawnPacing:{pacing:{ratePerSec:20}},projectionRows:b.map(e=>({label:e,value:x.get(e)??0}))}}import{scaleLinear as Co}from"d3-scale";function Po(e,t,i,r){let n=(t+i)/2,o=[];for(let s of e){let a=o.filter(e=>Math.abs(s.x-e.x)<s.radius+e.radius+.5),l=[n];for(let e of a){let t=s.radius+e.radius+.5,i=Math.sqrt(t**2-(s.x-e.x)**2);l.push(e.y-i,e.y+i)}let d=r()<.5?-1:1;l.sort((e,t)=>Math.abs(e-n)-Math.abs(t-n)||d*(e-t));let c=l.find(e=>e-s.radius>=t&&e+s.radius<=i&&a.every(t=>(s.x-t.x)**2+(e-t.y)**2>=(s.radius+t.radius+.5)**2-1e-6));if(null==c){let r=e.reduce((e,t)=>Math.max(e,t.radius),-1/0),o=Math.max(0,i-t-2*r);return{positions:e.map((t,i)=>n+(1===e.length?0:i/(e.length-1)-.5)*o),overlapping:!0,entryOffset:0}}o.push({...s,y:c})}return{positions:o.map(e=>e.y),overlapping:!1,entryOffset:Math.max(0,o.reduce((e,i)=>Math.min(e,i.y-i.radius-t),36))}}function Ro(e){let{data:t,xAccessor:r,groupAccessor:n,radiusAccessor:s,pointRadius:c,seed:u,size:h,xExtent:m,collisionIterations:y,settle:f}=e,{rows:g}=p(t,"collision-swarm"),v=i(h),x=b(u),w=[],I=[],k=/* @__PURE__ */new Map;function S(e){let t=k.get(e);return null==t&&(t=I.length,I.push(e),k.set(e,t)),t}g.forEach((e,t)=>{let i=l(a(e,t,r));if(null==i)return;let o=n?String(a(e,t,n)??"All"):"All",u=s?l(a(e,t,s)):null,h=d(null!=u&&u>0?u:c,2,18);S(o),w.push({datum:e,index:t,value:i,group:o,radius:h})});let M=m?l(m[0]):null,A=m?l(m[1]):null,$=w.reduce((e,t)=>Math.min(e,t.value),w.length?1/0:0),C=w.reduce((e,t)=>Math.max(e,t.value),w.length?-1/0:1),P=M??$,R=A??C;if(P===R&&(P-=.5,R+=.5),P>R){let e=R;R=P,P=e}let D=w.reduce((e,t)=>Math.max(e,t.radius),c),B=v.plot.x+D+8,T=v.plot.x+v.plot.width-D-8,j=Co().domain([P,R]).range([B,T]),O=Math.max(1,I.length),E=v.plot.height/O,N=Math.min(6,.05*E),F=e=>v.plot.y+((k.get(e)??0)+.5)*E,W=/* @__PURE__ */new Map,q=/* @__PURE__ */new Set,z=/* @__PURE__ */new Map;for(let e of I){let t=w.filter(t=>t.group===e),i=F(e),r=t.map(e=>({x:j(e.value),radius:e.radius})),n=Po(r,i-E/2+N,i+E/2-N,x);W.set(e,t.length),n.overlapping&&q.add(e),t.forEach((e,t)=>z.set(e.index,{x:r[t].x,y:n.positions[t],entryOffset:n.entryOffset}))}let H=w.map((e,t)=>{let i=z.get(e.index),r=i.x,n=i.y,o=q.has(e.group);return{id:String(e.datum.id??`collision-swarm-${t}`),x:r,y:n-(f?0:i.entryOffset),vx:0,vy:0,fixedPosition:{x:r},bodyCollisions:!o,mass:1,shape:{type:"circle",radius:e.radius},datum:{...e.datum,xValue:e.value,group:e.group,radius:e.radius,targetX:r,targetY:n,overlapping:o},springs:[{target:{type:"point",x:r,y:n},restLength:0,stiffness:34,damping:12}]}}),L=ci({x:v.plot.x,y:v.plot.y,width:v.plot.width,height:v.plot.height},{idPrefix:"collision-swarm",includeCeiling:!1,wallThickness:20,floorThickness:20});return{config:o(u,L,"CollisionSwarmChart",{gravity:{x:0,y:0},cellSize:Math.max(24,4*D),collisionIterations:Math.max(1,Math.round(y??6)),velocityDamping:.992,restitution:.02,friction:.18,sleepSpeed:3,sleepAfter:.5}),initialSpawns:H,projectionRows:I.map(e=>({label:e,value:W.get(e)??0})),metadata:{kind:"collision-swarm",xExtent:[P,R],xRange:[B,T],groups:I.map(e=>({label:e,y:F(e),count:W.get(e)??0,overlapping:q.has(e)})),plot:v.plot}}}function Do(e){if(Array.isArray(e)&&e.length>=2){let t=l(e[0]),i=l(e[1]);return null!=t&&null!=i?{x:t,y:i}:null}if(e&&"object"==typeof e){let t=e,i=l(t.x),r=l(t.y);return null!=i&&null!=r?{x:i,y:r}:null}return null}function Bo(e){return Array.isArray(e)?e.map(Do).filter(e=>null!=e):[]}function To(e,t){return"normalized"===e||"pixels"===e?e:t.length>0&&t.every(e=>e.x>=0&&e.x<=1&&e.y>=0&&e.y<=1)?"normalized":"pixels"}function jo(e,t,i){return"normalized"===i?{x:t.plot.x+e.x*t.plot.width,y:t.plot.y+e.y*t.plot.height}:{x:d(e.x,t.plot.x,t.plot.x+t.plot.width),y:d(e.y,t.plot.y,t.plot.y+t.plot.height)}}function Oo(e){let t=0;for(let i=1;i<e.length;i+=1){let r=e[i].x-e[i-1].x,n=e[i].y-e[i-1].y;t+=Math.hypot(r,n)}return t}function Eo(e,t){if(0===e.length)return{x:0,y:0};if(1===e.length)return{...e[0]};let i=d(t,0,1)*Oo(e),r=0;for(let t=1;t<e.length;t+=1){let n=e[t-1],o=e[t],s=Math.hypot(o.x-n.x,o.y-n.y);if(!(s<=0)){if(r+s>=i){let e=(i-r)/s;return{x:n.x+(o.x-n.x)*e,y:n.y+(o.y-n.y)*e}}r+=s}}return{...e[e.length-1]}}function No(e,t){let i=Eo(e,Math.max(0,t-.02)),r=Eo(e,Math.min(1,t+.02)),n=r.x-i.x,o=r.y-i.y,s=Math.hypot(n,o)||1;return{x:n/s,y:o/s}}function Fo(e){let{coordinateMode:t,flowSpeed:r,links:n,maxParticles:s,nodeIdAccessor:u,nodeXAccessor:p,nodeYAccessor:m,nodes:y,particleRadius:f,particleRate:g,pathAccessor:v,pathConstraint:x="path",reducedMotion:w,seed:I,size:k,sourceAccessor:S,targetAccessor:M,throughputAccessor:A}=e,$=i(k),C=b(I),P=/* @__PURE__ */new Map,R=/* @__PURE__ */new Map,D=[];function B(e){if(e&&"object"==typeof e){let t=e;if("function"==typeof u){let e=u(t,0);if(null!=e)return String(e)}if("string"==typeof u&&null!=t[u])return String(t[u]);if(null!=t.id)return String(t.id)}return String(e??"unknown")}y.forEach((e,t)=>{let i=String(a(e,t,u)??e.id??t),r=l(a(e,t,p)),n=l(a(e,t,m));if(null!=r&&null!=n){let e={x:r,y:n};P.set(i,e),D.push(e)}R.set(i,String(e.label??e.name??i))});let T=[];n.forEach((e,t)=>{let i=B(a(e,t,S)),r=B(a(e,t,M)),n=Math.max(0,l(a(e,t,A))??0),o=Bo(v?a(e,t,v):void 0),s=o.length?o:Bo(e.path??e.points??e.route);s.forEach(e=>D.push(e)),T.push({id:String(e.id??`physical-flow-${i}-${r}-${t}`),link:e,index:t,source:i,target:r,throughput:n,rawPath:s})});let j=To(t,D),O=/* @__PURE__ */new Map;for(let[e,t]of P)O.set(e,jo(t,$,j));let E=[];for(let e of T){let t=e.rawPath.map(e=>jo(e,$,j));if(t.length>=2)O.has(e.source)||O.set(e.source,t[0]),O.has(e.target)||O.set(e.target,t[t.length-1]);else{let i=O.get(e.source),r=O.get(e.target);i&&r&&(t=[i,r])}t.length<2||e.throughput<=0||(R.has(e.source)||R.set(e.source,e.source),R.has(e.target)||R.set(e.target,e.target),E.push({...e,path:t,packetCount:0}))}let N=c(g,.12),F=Math.max(1,Math.round(s)),W=E.map(e=>Math.max(1,Math.round(e.throughput*N))),q=W.reduce((e,t)=>e+t,0),z=q>F?F/q:1;E.forEach((e,t)=>{e.packetCount=Math.max(1,Math.floor(W[t]*z))});let H=E.reduce((e,t)=>e+t.packetCount,0);for(;H>F;){let e=E.reduce((e,t,i)=>t.packetCount<=1?e:-1===e||t.packetCount>E[e].packetCount?i:e,-1);if(-1===e)break;E[e].packetCount-=1,H-=1}let L=/* @__PURE__ */new Map,Y=/* @__PURE__ */new Map,_=[],X=c(r,90),G=c(f,4);E.forEach((e,t)=>{L.set(e.target,(L.get(e.target)??0)+e.throughput),Y.set(e.source,(Y.get(e.source)??0)+e.throughput);let i=Oo(e.path);for(let r=0;r<e.packetCount;r+=1){let n=(r+.5)/e.packetCount,o=w?n:d(.12+.84*n+.04*(C()-.5),.04,.98),s=w?o:Math.max(0,o-(.18+.12*C())),a=Eo(e.path,s),l=Eo(e.path,o),c=No(e.path,s),u={x:-c.y,y:c.x},h=(C()-.5)*G*1.5,p=`${e.id}-packet-${r}`;_.push({id:p,x:a.x+u.x*h,y:a.y+u.y*h,vx:w?0:c.x*X+10*(C()-.5),vy:w?0:c.y*X+10*(C()-.5),mass:.8,spawnAt:w?0:.04*t+r/32,shape:{type:"circle",radius:G},datum:{...e.link,source:e.source,target:e.target,throughput:e.throughput,packetIndex:r,packetCount:e.packetCount,routeProgress:o,flowPath:e.path,flowPathLength:i,flowRouteId:e.id,flowSpeed:X,sourceLabel:R.get(e.source)??e.source,targetLabel:R.get(e.target)??e.target},springs:"none"!==x&&w?[{target:{type:"point",x:l.x,y:l.y},restLength:.7*G,stiffness:26,damping:4.25}]:void 0})}});let V=Math.max(18,5*G),U=Array.from(O,([e,t])=>({nodeId:e,label:R.get(e)??e,sensorId:`physical-flow-node-${h(e)}`,point:t})),K=U.map(e=>({id:e.sensorId,sensor:!0,shape:{type:"aabb",x:e.point.x,y:e.point.y,width:V,height:V}})),Q=Object.fromEntries(U.map(e=>[e.sensorId,{binId:e.label,enterType:"physics-proximity-enter",exitType:"physics-proximity-exit"}])),J=[...ci({x:$.plot.x,y:$.plot.y,width:$.plot.width,height:$.plot.height},{idPrefix:"physical-flow",wallThickness:18,floorThickness:18}),...K],Z=o(I,J,"PacketFlowChart",{gravity:{x:0,y:0},cellSize:Math.max(24,7*G),collisionIterations:3,velocityDamping:.994,restitution:.01,friction:.16,sleepSpeed:2.5,sleepAfter:.7});Z.bodyLimit=F,Z.eviction="oldest",Z.observation={...Z.observation,sensors:Q};let ee=Array.from(O,([e,t])=>({id:e,label:R.get(e)??e,x:t.x,y:t.y,sensorId:`physical-flow-node-${h(e)}`,incoming:L.get(e)??0,outgoing:Y.get(e)??0})),te=E.map(e=>({id:e.id,source:e.source,target:e.target,sourceLabel:R.get(e.source)??e.source,targetLabel:R.get(e.target)??e.target,throughput:e.throughput,packetCount:e.packetCount,path:e.path}));return{config:Z,initialSpawns:_,projectionRows:ee.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:_.length,totalThroughput:E.reduce((e,t)=>e+t.throughput,0),plot:$.plot,nodes:ee,links:te}}}function Wo(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function qo(e){if(!e||"object"!=typeof e)return!1;let t=e;return"string"==typeof t.id&&(null==t.label||"string"==typeof t.label)&&"number"==typeof t.count&&Number.isFinite(t.count)&&Array.isArray(t.bodyIds)&&t.bodyIds.every(e=>"string"==typeof e)}function zo(e,t){if("region-enter"!==t.type)return e;let i=t.region.id,r=Wo(e,i),n=qo(r)?r:{id:i,label:t.region.label??i,count:0,bodyIds:[]};if(n.bodyIds.includes(t.bodyId))return e;let o=[...n.bodyIds,t.bodyId];return{...e,[i]:{...n,count:o.length,bodyIds:o}}}function Ho(e,t){return(t??Object.keys(e)).map(t=>Wo(e,t)).filter(qo).map(e=>({label:e.label??e.id,value:e.count}))}function Lo(e,t){let i=t instanceof Set?t:new Set(t);return e.map(e=>{let t=e.bodyIds??[],r=t.filter(e=>!i.has(e)),n=t.length-r.length,o=e.completion?.mode??"allMembersAbsorbed",s=e.completion?.valueByBodyId,a=e=>{let t=s?Wo(s,e):void 0;return"number"==typeof t&&Number.isFinite(t)&&t>=0?t:1},l=t.reduce((e,t)=>e+a(t),0),d=t.reduce((e,t)=>e+(i.has(t)?a(t):0),0),c=e.completion?.threshold,u="threshold"===o?Number.isFinite(c)&&Number(c)>=0?Number(c):l:void 0,h=t.length>0&&("anyAbsorbed"===o?n>0:"threshold"===o?d>=(u??l):0===r.length);return{id:e.id,label:e.label??e.id,mode:o,complete:h,absorbed:n,total:t.length,absorbedValue:d,totalValue:l,threshold:u,missing:r}})}function Yo(e){let t=e.reduce((e,t)=>e+(t.share??1),0);return t>0?t:e.length}function _o(e,t,i,r,n,o={}){return{id:e,friction:o.friction,restitution:o.restitution,bodyFilter:o.bodyFilter,shape:{type:"segment",x1:t,y1:i,x2:r,y2:n,thickness:o.thickness??8}}}function Xo(e,t,i,r){return{type:"aabb",x:e,y:t,width:i,height:r}}function Go(e){let t=e.shape??"lane",i=Math.max(1,Math.round(e.width)),r=Math.max(1,Math.round(e.height)),n=e.padX??46,o=e.padY??72,s=n,a=i-n,l=o,d=r-Math.max(24,Math.round(.45*o)),c=(l+d)/2,u=Math.max(1,d-l),h=q(e.pinchRatio??.18,.06,.5),p=Number(e.pinchHeightOffset??0),m=Number.isFinite(p)?p:0,y=q(u*h+m,.06*u,.5*u),f=y/2,g=c-f,b=c+f,v=e.idPrefix??"process",x=e.friction??.58,w=e.restitution??.18,I=e.wallThickness??8,k=e.stages;if(!k.length)throw new Error("processStageLayout requires at least one stage");let S=q(e.centerStageIndex??Math.floor(k.length/2),0,k.length-1),M=Yo(k),A=a-s,$=s,C=k.map((e,t)=>{let i=(e.share??1)/M*A,r=$,n=t===k.length-1?a:$+i;return $=n,{id:e.id,label:e.label,description:e.description,kind:e.kind??"stage",index:t,x0:r,x1:n,x:(r+n)/2,width:n-r,y:c,height:u}}),P=C[S],R=P.x0,D=P.x1,B=(e,i)=>{if("lane"===t)return"top"===i?l:d;if("funnel"===t){let t=q((e-s)/Math.max(1,a-s),0,1);return"top"===i?l+(g-l)*t:d+(b-d)*t}if(e<=R){let t=q((e-s)/Math.max(1,R-s),0,1);return"top"===i?l+(g-l)*t:d+(b-d)*t}if(e<=D)return"top"===i?g:b;let r=q((e-D)/Math.max(1,a-D),0,1);return"top"===i?g+(l-g)*r:b+(d-b)*r},T=C.map(e=>{let t=Math.min(B(e.x0,"top"),B(e.x1,"top")),i=Math.max(B(e.x0,"bottom"),B(e.x1,"bottom"));return{...e,y:(t+i)/2,height:Math.max(1,i-t)}}),j={thickness:I,friction:x,restitution:w},O=[];"lane"===t?O.push(_o(`${v}-top`,s,l,a,l,j),_o(`${v}-bottom`,s,d,a,d,j),_o(`${v}-left`,s,l,s,d,{...j,thickness:Math.max(6,I-2)}),_o(`${v}-right`,a,l,a,d,{...j,thickness:Math.max(6,I)})):"funnel"===t?O.push(_o(`${v}-top`,s,l,a,g,j),_o(`${v}-bottom`,s,d,a,b,j),_o(`${v}-left`,s,l,s,d,{...j,thickness:Math.max(6,I-2)}),_o(`${v}-right`,a,g,a,b,{...j,thickness:Math.max(6,I)})):O.push(_o(`${v}-left-top`,s,l,R,g,j),_o(`${v}-left-bottom`,s,d,R,b,j),_o(`${v}-center-top`,R,g,D,g,j),_o(`${v}-center-bottom`,R,b,D,b,j),_o(`${v}-right-top`,D,g,a,l,j),_o(`${v}-right-bottom`,D,b,a,d,j),_o(`${v}-left`,s,l,s,d,{...j,thickness:Math.max(6,I-2)}),_o(`${v}-right`,a,l,a,d,{...j,thickness:Math.max(6,I)}));let E=e.membraneDampingScale??.5,N=s,F=Math.max(1,("bowtie"===t?R:a)-N),W=(e.membranes??[]).map(e=>{let t=N+q(e.offset,0,1)*F,i=e.width??18+18*e.cost,r=u-16,n=c+.25*(e.wobble??0);return{...e,x:t,y:n,width:i,height:r}}),z=!1===e.includeMembraneRegions?[]:W.map(e=>Qo({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:i,height:r,padX:n,padY:o,left:s,right:a,topY:l,bottomY:d,midY:c,centerLeft:R,centerRight:D,pinchHeight:y,pinchTop:g,pinchBottom:b,stages:T,membranes:W,colliders:O,regionEffects:z,boundaryY:B}}function Vo(e,t,i){return"function"==typeof t?r=>({...i,...t(r),primitive:e}):{...i,...t,primitive:e}}function Uo(e,t,i,r){return{id:e.id,label:e.label,description:e.description,kind:e.kind??t,shape:Xo(e.x,e.y,e.width,e.height),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:i?Vo(i,e.attributes,r):e.attributes,onEnter:e.onEnter,onExit:e.onExit}}function Ko(e,t={}){let i=t.idPrefix??"stage",r=Math.max(0,t.insetX??0),n=Math.max(0,t.insetY??1);return e.stages.map(e=>{let o="function"==typeof t.metadata?t.metadata(e):t.metadata??{};return{...Uo({id:i?`${i}:${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*r),height:Math.max(1,e.height-2*n),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 Qo(e){let t=e.dampingScale??.5,i=e.energyScale??1,r=q(e.cost,0,2);return{...Uo(e,"membrane","membrane",{membraneCost:r}),damping:r*t,energyDelta:-r*i}}function Jo(e){return{...Uo(e,"charge-gate","chargeGate"),charge:e.charge??!0,energyDelta:e.energyDelta,impulseOnEnter:e.impulseOnEnter}}function Zo(e){let t="number"==typeof e.force?{x:e.force,y:0}:e.force??{x:12,y:0};return{...Uo(e,"force-field","routeSurface"),force:t,damping:e.damping??.015}}function es(e){let t=e.pressure??e.occupancy??0,i=e.baseDamping??.08,r=e.dampingPerUnit??.12,n=e.energyPerUnit??0;return{...Uo(e,"membrane","pressureField",{pressure:t}),damping:i+t*r,energyDelta:n?-t*n:void 0,force:e.force}}function ts(e){let t="number"==typeof e.force?{x:e.force,y:0}:e.force;return{...Uo(e,"force-field","capacitatedSensor",{capacity:e.capacity,unitsPerSecond:e.unitsPerSecond??e.capacity}),force:t,damping:e.damping,charge:e.charge??e.capacity}}function is(e){return{...Uo(e,"force-field","portal",{targetStage:e.targetStage}),force:e.force,impulseOnEnter:e.impulseOnEnter,damping:e.damping??.08}}function rs(e){let t="number"==typeof e.force?{x:e.force,y:0}:e.force??{x:24,y:0};return{...Uo(e,"sink","absorb"),force:t,damping:e.damping??.02,charge:e.charge??"absorbed"}}function ns(e){return{...Uo(e,"force-field","forceField"),force:e.force,damping:e.damping,energyDelta:e.energyDelta}}function os(e){let t=e.x??e.anchor?.x??0,i=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:i,width:e.width,height:e.height,anchor:e.anchor??{x:t,y:i},completion:e.completion,tether:e.tether,semanticItem:e.semanticItem}}function ss(e){let t=e.idPrefix??"lane",i={thickness:e.thickness??8,friction:e.friction??.5,restitution:e.restitution??.16},r=[_o(`${t}-top`,e.left,e.top,e.right,e.top,i),_o(`${t}-bottom`,e.left,e.bottom,e.right,e.bottom,i)];return e.openEnds||r.push(_o(`${t}-left`,e.left,e.top,e.left,e.bottom,i),_o(`${t}-right`,e.right,e.top,e.right,e.bottom,i)),r}function as(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 ls(e,t){let i={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 rs({...i,kind:e.kind??"sink",force:as(e.force,28),damping:e.damping??.04,charge:"absorbed",attributes:{...i.attributes,primitive:"absorb"}});if(e.portal){let t=e.portal.force??e.force??{x:-40,y:0};return is({...i,kind:e.kind??"force-field",force:as(t,-40),damping:e.damping??.1,targetStage:e.portal.targetStageId,attributes:{...i.attributes,primitive:"portal",targetStage:e.portal.targetStageId}})}if(e.capacity){let t=Math.max(.1,e.capacity.unitsPerSecond);return ts({...i,kind:e.kind??"force-field",capacity:t,unitsPerSecond:t,force:as(e.force,10+.8*t),damping:e.damping??Math.max(.04,.32-.01*t),attributes:{...i.attributes,unitAccessor:e.capacity.unitAccessor,reviewerCapacity:t}})}if(e.pressure){let t="object"==typeof e.pressure&&e.pressure?e.pressure:{};return es({...i,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:as(e.force,8),attributes:{...i.attributes,primitive:"pressureField"}})}return null!=e.force||null!=e.damping?Zo({...i,kind:e.kind??"force-field",force:as(e.force,14),damping:e.damping??.02,attributes:{...i.attributes,primitive:"routeSurface"}}):ns({...i,kind:e.kind??"force-field",force:{x:10,y:0},damping:.02,attributes:{...i.attributes,primitive:"forceField"}})}function ds(e){let t=e.stages;if(!t.length)throw new Error("buildProcessFlowPhysics requires at least one stage");let r=e.size,n=i(r),o=d(e.ballRadius??6,2,18),s=e.seed??1,c=b(s),u=e.idAccessor,h=e.stageAccessor??"stage",p=e.groupBy,m=e.groupLabelAccessor,y=e.workAccessor,f=e.radiusAccessor,g=e.groupCompletion??(p?"allAbsorbed":"none"),v=e.springStiffness??.28,x=e.springDamping??.72,w=!0===e.settle,I=t.map(e=>({id:e.id,label:e.label??e.id,description:e.description,share:e.share})),k=Go({width:r[0],height:r[1],shape:"lane",padX:Math.max(28,n.plot.x),padY:Math.max(36,n.plot.y+8),stages:I,idPrefix:"process-flow",includeMembraneRegions:!1,friction:.48,restitution:.14}),S=new Map(k.stages.map((e,t)=>[e.id,t])),M=new Map(k.stages.map(e=>[e.id,e])),A=k.stages[0].id,$=k.stages[0],C=new Set(t.filter(e=>e.absorb).map(e=>e.id)),P=t.map(e=>{let t=M.get(e.id)??$;return ls(e,{x:t.x,y:k.midY,width:t.width,height:k.bottomY-k.topY})});P.unshift(Zo({id:"process-flow-route",label:"process route",description:"Baseline conveyor along the process lane.",x:(k.left+k.right)/2,y:k.midY,width:k.right-k.left,height:k.bottomY-k.topY-12,force:8,damping:.012,semanticItem:!1}));let R=/* @__PURE__ */new Map;for(let e of k.stages)R.set(e.id,0);let D=[];e.data.forEach((e,t)=>{let i=String(u?a(e,t,u)??e.id??`process-flow-${t}`:e.id??`process-flow-${t}`),r=String(a(e,t,h)??A),n=S.has(r)?r:A;R.set(n,(R.get(n)??0)+1);let s=p?String(a(e,t,p)??""):void 0,c=s&&m?String(a(e,t,m)??s):s,g=y?l(a(e,t,y))??1:1,b=f?l(a(e,t,f)):null,v=d(null!=b&&b>0?b:o,2,18);D.push({datum:e,id:i,stageId:n,groupId:s||void 0,groupLabel:c||void 0,work:g,radius:v,index:t})});let B=/* @__PURE__ */new Map,T=/* @__PURE__ */new Map;for(let e of D){if(!e.groupId)continue;let t=B.get(e.groupId)??[];t.push(e.id),B.set(e.groupId,t),e.groupLabel&&T.set(e.groupId,e.groupLabel)}let j=d(e.groupAnchorAlong??.55,.15,.9),O=k.left+(k.right-k.left)*j,E=Array.from(B.keys()),N=E.map((e,i)=>{let r=B.get(e)??[],n=E.length<=1?k.midY:k.topY+28+i/Math.max(1,E.length-1)*(k.bottomY-k.topY-56);return os({id:e,label:T.get(e)??e,bodyIds:r,anchor:{x:O,y:n},x:O,y:n,completion:"allAbsorbed"===g?{mode:"allMembersAbsorbed",targetZone:t.find(e=>e.absorb)?.id??"merged"}:void 0,tether:{stiffness:.06,visible:!0,restLength:18}})}),F=Lo(N,D.filter(e=>C.has(e.stageId)).map(e=>e.id)),W=new Map(N.map(e=>[e.id,e])),q=D.map((e,t)=>{let i=M.get(e.stageId)??$,r=i.x+(c()-.5)*Math.min(24,.2*i.width),n=k.boundaryY(r,"top")+e.radius+10,o=k.boundaryY(r,"bottom")-e.radius-10,s=o<=n?k.midY:n+c()*Math.max(1,o-n),a=w?r:k.left+18+t%7*4,l=w?s:k.midY+(c()-.5)*(k.bottomY-k.topY)*.35,d=[{target:{type:"point",x:r,y:s},restLength:.45*e.radius,stiffness:v,damping:x}];if(e.groupId){let t=W.get(e.groupId);t?.anchor&&!C.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:a,y:l,vx:w?0:40+40*c(),vy:w?0:20*(c()-.5),mass:1,shape:{type:"circle",radius:e.radius},spawnAt:w?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}}}),z={kernel:{seed:s,gravity:{x:e.gravityX??22,y:e.gravityY??0},restitution:.14,friction:.48,velocityDamping:.988,maxVelocity:420,sleepSpeed:8,sleepAfter:.9,collisionIterations:4},colliders:k.colliders,fixedDt:1/60,maxSubsteps:8},H=k.stages.map(e=>({label:e.label??e.id,value:R.get(e.id)??0})),L=t.map(e=>{let t=M.get(e.id)??$;return{id:e.id,label:e.label??e.id,x:t.x,width:t.width,count:R.get(e.id)??0,capacity:e.capacity?.unitsPerSecond,absorb:!0===e.absorb,portalTarget:e.portal?.targetStageId}});return{config:z,initialSpawns:q,initialSpawnPacing:w?void 0:{pacing:"arrival",timeAccessor:"spawnAt",timeScale:1},projectionRows:H,metadata:{kind:"process-flow",plot:n.plot,volume:k,stages:L,groups:N,groupCompletion:F,regionEffects:P}}}import{forwardRef as cs,useCallback as us,useMemo as hs,useRef as ps}from"react";import{useEffect as ms,useImperativeHandle as ys,useLayoutEffect as fs,useRef as gs,useState as bs}from"react";function vs(e){let{datum:t,spawnAt:i,...r}=e;return JSON.stringify(r)}function xs(e,t,i,r=!1){let n=new Map(t.initialSpawns.map(e=>[e.id,e])),o=new Map(i.initialSpawns.map(e=>[e.id,e])),s=/* @__PURE__ */new Set,a=new Map(e.world.bodies.map(e=>[e.id,e]));for(let[e,r]of n){let n=o.get(e),l=n&&"event-drop"===i.metadata?.kind&&r.datum?.late!==n.datum?.late,d=n&&"event-drop"===t.metadata?.kind&&"event-drop"===i.metadata?.kind&&JSON.stringify(t.metadata.windowPlot)===JSON.stringify(i.metadata.windowPlot)&&!1===r.datum?.late&&!1===n.datum?.late&&(a.get(e)?.y??-1/0)>=n.y&&vs({...r,y:n.y})===vs(n);(!n||l||!d&&vs(r)!==vs(n))&&s.add(e)}let l=new qi;l.restore({...e,world:{...e.world,bodies:e.world.bodies.map(e=>({...e,datum:o.get(e.id)?.datum??e.datum}))},queue:e.queue.map(e=>({...e,datum:o.get(e.id)?.datum??e.datum}))});let d=new Set(t.config.colliders?.map(e=>e.id)),c=e.world.colliders.filter(e=>!d.has(e.id));l.updateConfig({...i.config,colliders:[...i.config.colliders??[],...c]}),l.remove(Array.from(s));let u=i.initialSpawns.filter(e=>!n.has(e.id)||s.has(e.id)).map(e=>({...e,spawnAt:void 0}));return l.enqueue(u,r&&!e.paused?i.initialSpawnPacing:void 0),l.materializeDueSpawns(),l.snapshot()}var ws=[],Is=typeof window>"u"?ms:fs;function ks(e){let{ref:t,frameRef:i,idPrefix:r,buildLayout:n}=e,o=e.data??ws,[s,a]=bs(()=>p(o,r)),l=s;s.seed!==o&&(l=p(o,r),a(l));let d=gs(l);d.current=l;let c=gs(n);c.current=n;let u=gs(null);function h(e){return(u.current?.rows!==e||u.current.build!==c.current)&&(u.current={rows:e,build:c.current,layout:c.current(e)}),u.current.layout}let m=h(l.rows),y=gs(null);function f(e,t=!0){let r=i.current;if(!r)return;let n=r.getStore();y.current?.store===n&&y.current.layout!==e&&r.restore(xs(r.snapshot(),y.current.layout,e,t)),y.current={store:n,layout:e}}return Is(()=>{f(m)}),ys(t,()=>{function e(e){let t=d.current.seed;t!==ws&&0===t.length||(d.current=e,f(h(e.rows),!1),a(e))}function t(t){if(!t.length)return;let i=d.current;e({...p([...i.rows,...t],r,i.nextId),seed:i.seed})}return{push:e=>t([e]),pushMany:t,remove:t=>{let i=new Set(Array.isArray(t)?t:[t]),r=d.current,n=r.rows.filter(e=>i.has(String(e.id)));return n.length&&e({...r,rows:r.rows.filter(e=>!i.has(String(e.id)))}),n},update:(t,i)=>{let r=new Set(Array.isArray(t)?t:[t]),n=d.current,o=[],s=new Map(n.rows.map(e=>[String(e.id),e]));for(let e of n.rows){if(!r.has(String(e.id)))continue;o.push(e);let t=i(e),n=t.id??e.id;String(n)!==String(e.id)&&s.delete(String(e.id)),s.set(String(n),{...t,id:n})}return o.length&&e({...n,rows:Array.from(s.values())}),o},clear:()=>{i.current?.clear(),e({...d.current,rows:[]})},getData:()=>d.current.rows.slice(),getScales:()=>null,getCustomLayout:()=>i.current?.snapshot()??null,popBodies:(e,t)=>i.current?.popBodies(e,t)??[]}}),{layout:m,resetSeed:()=>{let e=p(d.current.seed,r);d.current=e,a(e)}}}import{useCallback as Ss,useEffect as Ms,useMemo as As,useRef as $s,useState as Cs}from"react";function Ps(e,t){return e?"sparkline"===t?{top:2,right:2,bottom:2,left:2}:{top:8,right:8,bottom:8,left:8}:{top:0,right:0,bottom:0,left:0}}import{Fragment as Rs,jsx as Ds,jsxs as Bs}from"react/jsx-runtime";function Ts(e){return!!e&&"string"==typeof e.name}function js(e,t=!1){if(!e?.datum)return null;let i=e.datum,r=i.sourceDatum;return t&&r&&"object"==typeof r?r:i}function Os(e){let{selection:t,linkedHover:i,colorBy:r,chartType:n,chartId:o,onBodyHover:s,fallbackFields:a,unwrapSourceDatum:l}=e,d="string"==typeof r?r:void 0,c=Ts(t)?t:void 0,{activeSelectionHook:u,customHoverBehavior:h}=T({emitObservations:!1,selection:c,linkedHover:i,fallbackFields:d?[d]:a,onObservation:e.onObservation,onClick:e.onClick,chartType:n,chartId:o,colorByField:d}),p=Ts(t)?null:t??null,m=As(()=>{if(p)return p;if(!u?.isActive)return null;let e=u.predicate;return{isActive:!0,predicate:t=>{let i=js(t,l);return null!=i&&e(i)}}},[u?.isActive,u?.predicate,p,l]),y=As(()=>{if(i||s)return(e,t)=>{if(s?.(e,t),!i)return;let r=js(e,l);h(r&&t?{...t,data:r}:null)}},[h,s,i,l]);return As(()=>({selection:m,onBodyHover:y}),[y,m])}var Es=/* @__PURE__ */new Set(["sample","mechanical"]);function Ns(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0?e:null}function Fs(e,t,i,r,n){let[o,s]=Cs(0),a=$s(null),l=$s(!1),d=Ns(t),c=$s(d),u=$s(!!i),h=$s(r);c.current=d,u.current=!!i,h.current=r;let p=Ss(()=>{null!=a.current&&(clearTimeout(a.current),a.current=null)},[]),m=Ss(()=>{p();let e=c.current;null==e||u.current||!l.current||(a.current=setTimeout(()=>{a.current=null,l.current=!1,h.current?.(),s(e=>e+1)},e))},[p]);Ms(()=>{null==d||i?p():l.current&&m()},[p,d,i,m]),Ms(()=>p,[p]);let y=e?.observation?.onSimulationStateChange,f=Ss((e,t)=>{if(y?.(e,t),n!==y&&n?.(e,t),"running"===e)return l.current=!1,void p();"settled"!==e||"running"!==t||(l.current=!0,m())},[p,n,y,m]);return{config:As(()=>null!=d||n?{...e,observation:{...e?.observation,onSimulationStateChange:f}}:e,[f,e,d,n]),rerunKey:o}}function Ws(e){let t=e=>"string"==typeof e&&Es.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"}}function qs(e,t,i,r){return e??[t??r[0],i??r[1]]}function zs(e,t,i){let r=i?.hasSimulationMode?Ws({mode:e.mode,simulationMode:e.simulationMode}):{chartMode:"sample"===e.mode||"mechanical"===e.mode?void 0:e.mode,simulationMode:"sample"},n=F(r.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],l=t[1],d=Hs(As(()=>qs(null!=o&&null!=s?[o,s]:void 0,n.width,n.height,[a,l]),[l,a,n.height,n.width,s,o]),e.responsiveWidth,e.responsiveHeight),c=d.size,u=Ps(n.compactMode,r.chartMode),h=e.showProjection??!n.compactMode,p=e.showChrome??!n.compactMode,m=Xs(e.tooltip,void 0),y=void 0!==m.enableHover?m.enableHover:n.enableHover,f=n.compactMode?n.title:n.title??e.title,g=r.chartMode&&"primary"!==r.chartMode?`semiotic-physics--${r.chartMode}`:null,b=[e.className,g].filter(Boolean).join(" ")||void 0;return{chartMode:r.chartMode,simulationMode:r.simulationMode,resolved:n,chartSize:c,responsiveContainerRef:d.containerRef,responsiveWidth:d.responsiveWidth,responsiveHeight:d.responsiveHeight,margin:u,showProjection:h,showChrome:p,enableHover:y,title:f,description:n.description??e.description,summary:n.summary??e.summary,accessibleTable:n.accessibleTable??e.accessibleTable,className:b,compactMode:n.compactMode,mobileInteraction:n.mobileInteraction,mobileSemantics:n.mobileSemantics}}function Hs(e,t,i){let[r,n]=P(e,t,i),o=Math.max(1,n[0]),s=Math.max(1,n[1]);return{containerRef:r,size:As(()=>[o,s],[s,o]),responsiveWidth:!!t,responsiveHeight:!!i}}function Ls(e){let[t,i]=e.size;return Z(e.loading,t,i,e.loadingContent)||Q(e.data,t,i,e.emptyContent)}function Ys(e,t,i,r){let n=r?.responsiveWidth||r?.responsiveHeight?/* @__PURE__ */Ds("div",{ref:r.responsiveContainerRef,"data-semiotic-physics-responsive-host":"true",style:{position:"relative",width:r.responsiveWidth?"100%":t[0],height:r.responsiveHeight?"100%":t[1]},children:i}):i;/* @__PURE__ */
|
|
43
|
-
return
|
|
44
|
-
return
|
|
45
|
-
return
|
|
46
|
-
/* @__PURE__ */
|
|
47
|
-
/* @__PURE__ */
|
|
48
|
-
return
|
|
49
|
-
return
|
|
50
|
-
/* @__PURE__ */
|
|
51
|
-
return
|
|
52
|
-
/* @__PURE__ */
|
|
53
|
-
/* @__PURE__ */
|
|
54
|
-
/* @__PURE__ */
|
|
55
|
-
return
|
|
56
|
-
/* @__PURE__ */
|
|
57
|
-
/* @__PURE__ */
|
|
58
|
-
/* @__PURE__ */
|
|
59
|
-
/* @__PURE__ */
|
|
60
|
-
/* @__PURE__ */
|
|
61
|
-
/* @__PURE__ */
|
|
62
|
-
return
|
|
63
|
-
/* @__PURE__ */
|
|
64
|
-
return
|
|
65
|
-
/* @__PURE__ */
|
|
66
|
-
/* @__PURE__ */
|
|
67
|
-
/* @__PURE__ */
|
|
68
|
-
/* @__PURE__ */
|
|
69
|
-
return
|
|
70
|
-
/* @__PURE__ */
|
|
71
|
-
/* @__PURE__ */
|
|
72
|
-
/* @__PURE__ */
|
|
73
|
-
/* @__PURE__ */
|
|
74
|
-
/* @__PURE__ */
|
|
75
|
-
/* @__PURE__ */
|
|
76
|
-
/* @__PURE__ */
|
|
77
|
-
/* @__PURE__ */
|
|
78
|
-
/* @__PURE__ */
|
|
79
|
-
/* @__PURE__ */
|
|
80
|
-
/* @__PURE__ */Ha(yo,{...d,...G,...V,ref:j,onBodyHover:L,config:F.config,foregroundGraphics:_s(_,d?.foregroundGraphics),initialSpawns:E.initialSpawns,paused:p,responsiveHeight:!1,responsiveWidth:!1,size:k,bodyStyle:z},`${k[0]}x${k[1]}:${F.rerunKey}`),I)});function _a(e,t={}){let i=t.id??"physics-process-boundary",r={bodyFilter:t.bodyFilter,friction:t.friction,restitution:t.restitution};if("segment"===e.type)return[{...r,id:i,shape:e}];let n=t.thickness??8,o=e.x-e.width/2,s=e.x+e.width/2,a=e.y-e.height/2,l=e.y+e.height/2;return[{...r,id:`${i}-top`,shape:{type:"segment",x1:o,y1:a,x2:s,y2:a,thickness:n}},{...r,id:`${i}-right`,shape:{type:"segment",x1:s,y1:a,x2:s,y2:l,thickness:n}},{...r,id:`${i}-bottom`,shape:{type:"segment",x1:s,y1:l,x2:o,y2:l,thickness:n}},{...r,id:`${i}-left`,shape:{type:"segment",x1:o,y1:l,x2:o,y2:a,thickness:n}}]}function Xa(e){if(!1===e.semanticItem)return null;let t=e.semanticItem??{},i=e.shape,r="aabb"===i.type?{id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"region",x:i.x,y:i.y,width:i.width,height:i.height}:{id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"region",x:(i.x1+i.x2)/2,y:(i.y1+i.y2)/2,pathData:`M ${i.x1} ${i.y1} L ${i.x2} ${i.y2}`};return{...r,...t,id:t.id??r.id}}function Ga(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 Va(e){return e.flatMap(e=>{if(!1===e.semanticItem)return[];let t=e.semanticItem??{},i={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[{...i,...t,id:t.id??i.id}]})}function Ua(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 Ka(e){return Array.isArray(e)}function Qa(e,t){return t?Ka(t)?[...t]:t.ids?[...t.ids]:t.candidates?t.candidates.filter(t=>e.includes(t)).slice(0,t.count??1):[]:[]}function Ja(e,t){return Qa(e.activePositiveIds,t.popPositive)}function Za(e){let t=Number(e.budget),i=Number.isFinite(t)?Math.max(0,t):0,r=e.properties instanceof Map?e.properties:new Map(e.properties.map(e=>[e.id,e])),n=e.candidates?new Set(e.candidates):null,o=e.attachedIds.map((e,t)=>{let i=r.get(e),n=Number(i?.work??1),o=Number(i?.priority??t);return{id:e,index:t,priority:Number.isFinite(o)?o:t,work:Number.isFinite(n)&&n>0?n:1}}).filter(e=>!n||n.has(e.id)).sort((e,t)=>e.priority-t.priority||e.index-t.index),s=[],a=[],l=0;for(let e of o)l+e.work>i+Number.EPSILON?a.push(e.id):(s.push(e.id),l+=e.work);return{ids:s,used:l,budget:i,remaining:Math.max(0,i-l),skippedIds:a}}function el(e,t){if(!t.from||!t.to||t.from===t.to)return{};let i=Math.max(0,Math.floor(Number(t.count??1)||0)),r=e.negativeIds.filter(e=>e===t.from).length,n=Math.min(i,r);return n?{addNegative:{[t.to]:n},popNegative:{ids:Array.from({length:n},()=>t.from)}}:{}}function tl(e,t){let i=Qa(e.negativeIds,t.popNegative);if(!i.length)return[];let r=/* @__PURE__ */new Map;for(let e of i)r.set(e,(r.get(e)??0)+1);let n=[];return e.negativeIds.forEach((e,t)=>{let i=r.get(e)??0;i<=0||(n.push({propertyId:e,index:t}),r.set(e,i-1))}),n}function il(e,t,i){if(t.when&&!t.when(i))return e;let r={...e},n=Ja(r,t);n.length&&(r={...r,activePositiveIds:r.activePositiveIds.filter(e=>!n.includes(e)),poppedPositiveIds:Array.from(/* @__PURE__ */new Set([...r.poppedPositiveIds,...n]))});let o=tl(r,t);if(o.length){let e=new Set(o.map(e=>e.index));r={...r,negativeIds:r.negativeIds.filter((t,i)=>!e.has(i)),poppedNegativeIds:[...r.poppedNegativeIds,...o.map(e=>e.propertyId)]}}let s=Ua(t.addPositive);s.length&&(r={...r,activePositiveIds:Array.from(/* @__PURE__ */new Set([...r.activePositiveIds,...s])),missingPositiveIds:r.missingPositiveIds.filter(e=>!s.includes(e))});let a=Ua(t.addNegative);if(a.length&&(r={...r,negativeIds:[...r.negativeIds,...a]}),t.delayDelta&&(r={...r,delay:r.delay+t.delayDelta}),t.metricsDelta){let e={...r.metrics};for(let[i,r]of Object.entries(t.metricsDelta))e[i]=Number(e[i]??0)+r;r={...r,metrics:e}}return t.viabilityDelta&&(r={...r,viability:r.viability+t.viabilityDelta}),t.stage&&(r={...r,stage:t.stage}),t.outcome&&(r={...r,outcome:t.outcome}),r}function rl(e,t){return{id:e.id,label:e.label??e.id,summary:e.summary??t.find(e=>e.summary)?.summary,time:e.time}}function nl(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}}var ol="gauntlet-core",sl="gauntlet-positive",al="gauntlet-negative",ll=[];function dl(e){let t=fl(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 cl(e,t,i,r){return i?"function"==typeof i?i(e,t):e[i]??r:r}function ul(e){return e?.label??e?.id??"property"}function hl(e){return`gauntlet:${e}:core`}function pl(e,t){return`gauntlet:${e}:positive:${t}`}function ml(e,t,i){return`gauntlet:${e}:negative:${t}:${i}`}var yl={left:28,top:76,rightInset:30,thickness:8};function fl(e){let t=e.height??e.floorY+36;if(!(e.width<220||t<160))return yl;let i=Math.max(1,Math.min(e.width,t)),r=Math.max(2,.04*e.width);return{left:r,top:Math.max(2,.08*t),rightInset:r,thickness:Math.max(1,Math.min(4,.04*i))}}function gl(e){let t=e.height??e.floorY+36;return Math.max(.12,Math.min(1,e.width/500,t/260))}function bl(e,t,i,r){let n=fl(r),o=Math.max(2,i+2),s=n.left+n.thickness/2+o,a=r.width-n.rightInset-n.thickness/2-o,l=n.top+n.thickness/2+o,d=r.floorY-o,c=(e,t,i)=>t<=i?Math.max(t,Math.min(i,e)):(t+i)/2;return{x:c(e,s,a),y:c(t,l,d)}}function vl(e,t,i){let[r,n]=e,o=r<220||n<160,s=Math.round(.48*n),a=o?n-Math.max(3,Math.min(12,.1*n)):n-36,l=(t??[]).filter(e=>!1!==e.enabled),d=Math.max(1,l.length),c=.22*r,u=d<=1?0:(.78*r-c)/(d-1),h=o?Math.max(Math.round(.12*r),.08*r+6):Math.max(Math.round(.14*r),110);return{crashY:a-(o?Math.min(i,Math.max(3,.22*n)):i),floorY:a,gates:l.map((e,t)=>({...e,id:e.id,x:e.x??Math.round(c+t*u),width:e.width??Math.max(o?8:54,Math.round(.07*r))})),graveyardX:Math.round(r*(o?.72:.84)),graveyardY:a-4,height:n,routeY:s,socketX:Math.round(r*(o?.82:.92)),startX:h,width:r}}function xl(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 wl(e,t,i,r){let n=xl(i),o=r?.(e,t,i)??{};return{...n,...o,startY:o.startY??o.routeY??n.startY,socketY:o.socketY??o.routeY??n.socketY,graveyardY:o.graveyardY??n.graveyardY}}function Il(e,t,i=1){let r=[...e].sort((e,t)=>e.localeCompare(t)),n=Math.max(0,r.indexOf(t)),o=r.length>1?n/(r.length-1):.5;return{angle:.82*-Math.PI+o*Math.PI*.64,index:n,radius:(48+n%2*6)*i}}function kl(e,t,i){let r=e.activePositiveIds.reduce((e,i)=>e+(t.get(i)?.value??1),0),n=e.missingPositiveIds.length+e.poppedPositiveIds.length,o=e.negativeIds.reduce((e,t)=>e+(i.get(t)?.load??1),0);return Math.max(0,Math.min(100,75+3*r-8*o-1.2*e.delay-5*n))}function Sl(e,t,i,r,n){let o=String(cl(e,t,i.idAccessor,null!=e.id?String(e.id):`project-${t}`)),s=r.map(e=>e.id),a=[...cl(e,t,i.positiveAccessor,s)],l=[...cl(e,t,i.negativeAccessor,[])].filter(e=>n.has(e));return{id:o,activePositiveIds:a,datum:e,delay:0,eventsApplied:[],eventHistory:[],killed:!1,metrics:{...cl(e,t,i.metricsAccessor,{})},missingPositiveIds:s.filter(e=>!a.includes(e)),negativeIds:l,outcome:"in_process",poppedPositiveIds:[],poppedNegativeIds:[],startedAt:Math.max(0,Number(cl(e,t,i.startTimeAccessor,0))||0),stage:"project filed",viability:cl(e,t,i.initialViability,100)}}function Ml(e,t,i,r,n,o,s){let a=gl(i),l=Math.max(3,28*a),d=r.startX,c=r.startY+(r.startY===i.routeY?38*t*a:0),u=s?.(e,t,i,r)??{},h=u.x??d,p=u.y??c,m={__gauntlet:!0,kind:ol,projectId:e.id,sourceDatum:e.datum},y=[{...u,id:hl(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:l},spawnAt:u.spawnAt??e.startedAt,datum:m}],f=bl(h,p,u.shape&&"radius"in u.shape&&Number(u.shape.radius)||l,i);y[0].x=f.x,y[0].y=f.y;for(let t of e.activePositiveIds){let r=n.get(t);if(!r)continue;let o=Il(e.activePositiveIds,t,a),s=r.radius??Math.max(2,10*a),l=bl(f.x+Math.cos(o.angle)*o.radius,f.y+Math.sin(o.angle)*o.radius,s,i);y.push({id:pl(e.id,t),x:l.x,y:l.y,vx:18*Math.cos(o.angle),vy:18*Math.sin(o.angle),mass:r.mass??.75,bodyCollisions:!1,shape:{type:"circle",radius:s},spawnAt:u.spawnAt??e.startedAt,datum:{__gauntlet:!0,kind:sl,projectId:e.id,property:r,sourceDatum:e.datum},springs:!1===r.spring?[]:[{target:{type:"body",bodyId:hl(e.id)},stiffness:.56,damping:.9,restLength:Math.max(6,(52+o.index%2*4)*a),...r.spring??{}}]})}return e.negativeIds.forEach((t,r)=>{let n=o.get(t);n&&y.push(Al(e,n,r,f.x,f.y,i,u.spawnAt??e.startedAt))}),y}function Al(e,t,i,r,n,o,s){let a=gl(o),l=t.radius??Math.max(2,7.2*a),d=bl(r+(i%4*12-12)*a,n+(54+12*Math.floor(i/4))*a,l,o);return{id:ml(e.id,t.id,i),x:d.x,y:d.y,vx:10,vy:6,mass:t.mass??.72,bodyCollisions:!1,shape:{type:"circle",radius:l},spawnAt:s,datum:{__gauntlet:!0,kind:al,projectId:e.id,property:t,sourceDatum:e.datum},springs:!1===t.spring?[]:[{target:{type:"body",bodyId:hl(e.id)},stiffness:.62,damping:.92,restLength:Math.max(6,(52+i%4*3)*a),...t.spring??{}}]}}import{forwardRef as $l,useCallback as Cl,useEffect as Pl,useImperativeHandle as Rl,useMemo as Dl,useRef as Bl,useState as Tl}from"react";function jl(e,t){return e.length===t.length&&e.every((e,i)=>{let r=t[i];return!!r&&e.regionId===r.regionId&&e.queueDepth===r.queueDepth&&e.blockedDepth===r.blockedDepth&&e.processedCount===r.processedCount&&e.metricRevision===r.metricRevision})}function Ol(e){let{dataKey:t,gates:i,statesRef:r,processedGateVisitsRef:n}=e;return i.flatMap(e=>{if(!e.capacity||e.capacity.unitsPerSecond<=0)return[];let i=`gauntlet-gate-${e.id}`;return[Yi({id:`gauntlet-capacity-${t}-${e.id}`,regionId:i,unitsPerSecond:e.capacity.unitsPerSecond,bodyFilter:{property:"datum.kind",equals:ol},maxQueue:e.capacity.maxQueue,queueLayout:e.capacity.queueLayout,queueSlotSpacing:e.capacity.queueSlotSpacing,queueStiffness:e.capacity.queueStiffness??24,releaseImpulse:{x:36,y:0},unitAccessor:t=>{let i,n=t.datum,o=n?.sourceDatum,s=e.capacity?.unitAccessor,a=r.current.find(e=>e.id===n?.projectId);"function"==typeof s?i=a?s(a):void 0:s&&(i=o?.[s]);let l=o?.reviewWork??o?.work??a?.metrics.reviewWork??o?.points,d=Number(i??l);return Number.isFinite(d)&&d>0?d:1},onProcessed:t=>{let i=t.datum;if(!i?.projectId)return;let r=`${i.projectId}:${e.id}`;n.current.set(r,(n.current.get(r)??0)+1)}})]})}function El(e){let{statesRef:t,setStates:i,elapsedRef:r,frameRef:n,layout:o,projectPlacement:s,positiveById:a,negativeById:l,coreBody:d,createState:c}=e;return{push:e=>{let u=c(e,t.current.length,r.current),h=wl(u,t.current.length,o,s),p=Ml(u,t.current.length,o,h,a,l,d),m=[...t.current,u];t.current=m,i(m),n.current?.pushMany(p),n.current?.step(0)},pushMany:e=>{let u=[...t.current],h=[],p=r.current;e.forEach(e=>{let t=c(e,u.length,p),i=wl(t,u.length,o,s);h.push(...Ml(t,u.length,o,i,a,l,d)),u.push(t)}),t.current=u,i(u),h.length&&n.current?.pushMany(h),n.current?.step(0)},remove:e=>{let r=Array.isArray(e)?e:[e],o=[],s=[];for(let e of r){let i=t.current.find(t=>t.id===e);i&&(o.push(i.datum),s.push(hl(i.id),...i.activePositiveIds.map(e=>pl(i.id,e))),i.negativeIds.forEach((e,t)=>{s.push(ml(i.id,e,t))}))}return t.current=t.current.filter(e=>!r.includes(e.id)),i(t.current),n.current?.remove(s),o},update:(e,u)=>{let h=Array.isArray(e)?e:[e],p=[];for(let e of h){let i=t.current.find(t=>t.id===e);if(!i)continue;let h=t.current.findIndex(t=>t.id===e);p.push(i.datum);let m=u(i.datum),y=c(m,h<0?t.current.length:h,i.startedAt??r.current),f=wl(y,h<0?t.current.length:h,o,s);n.current?.remove([hl(i.id),...i.activePositiveIds.map(e=>pl(i.id,e)),...i.negativeIds.map((e,t)=>ml(i.id,e,t))]),n.current?.pushMany(Ml(y,h<0?t.current.length:h,o,f,a,l,d)),t.current=t.current.map(t=>t.id===e?y:t)}return i(t.current),p},clear:()=>{t.current=[],i([]),n.current?.clear()},getData:()=>t.current.map(e=>e.datum),getScales:()=>null,getCustomLayout:()=>n.current?.snapshot()??null,popBodies:(e,t)=>n.current?.popBodies(e,t)??[]}}function Nl(e,t,i){let{frameProps:r,elapsedRef:n,statesRef:o,crashDetection:s,layout:a,projectEvents:l,gateById:d,capacityEventReady:c,addBodiesForEffect:u,updateProjectState:h,viability:p,positiveById:m,negativeById:y,outcome:f,reportCapacity:g}=i;r.onTick?.(e,t),n.current=e.elapsedSeconds??t.snapshot().elapsedSeconds,g();for(let e of o.current){let i=t.readBodies().find(t=>t.id===hl(e.id));if(!i)continue;let r="circle"===i.shape.type?i.shape.radius:28;if(s&&!e.killed&&i.y+r>=a.crashY){t.readBodies().forEach(i=>{let r=i.datum;!r?.__gauntlet||r.projectId!==e.id||t.applyImpulse(i.id,-i.vx*i.mass,0)}),h(e.id,e=>{let t={appliedAt:Math.max(0,n.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,n.current-(e.startedAt??0))};return{...e,crashX:i.x,eventHistory:[...e.eventHistory??[],t],killed:!0,lastEvent:t,metrics:{...e.metrics,lastX:i.x},outcome:"bad_design_crash",stage:"Crash Line",viability:Math.min(0,e.viability)}});continue}if(e.killed)continue;let o=Math.max(0,n.current-(e.startedAt??0)),g=l(e),b=g.filter(t=>t.time<=o&&!e.eventsApplied.includes(t.id)&&c(e,t,g)),v=e;for(let i of b){let r=i.gateId?d.get(i.gateId):void 0,n=i.effects??[];for(let e of n){let n={event:i,gate:r,negativeProperties:y,positiveProperties:m,project:v};e.when&&!e.when(n)||(u(v,e,t),v=il(v,e,n))}let s={...rl(i,n),appliedAt:o};v=nl(v,s),h(e.id,e=>{let t=nl(e,s);if(t===e)return e;for(let e of n)t=il(t,e,{event:i,gate:r,negativeProperties:y,positiveProperties:m,project:t});let o=p?.(t,{negativeProperties:y,positiveProperties:m})??kl(t,m,y);return t={...t,viability:o},i.final&&(t={...t,outcome:i.outcome??f?.(t,{layout:a,negativeProperties:y,positiveProperties:m})??(t.viability>20?"built":"approved_not_built")}),t})}}}function Fl(e,t){let i=e.datum;return!(!i?.__gauntlet||i.projectId!==t||i.kind!==al)}function Wl(e){let t=e.id.slice(e.id.lastIndexOf(":")+1),i=Number(t);return Number.isFinite(i)?i:-1}function ql(e,t){let i=-1;for(let r of t)Fl(r,e.id)&&(i=Math.max(i,Wl(r)));return Math.max(e.negativeIds.length,i+1)}function zl(e,t,i){let r=t.filter(t=>Fl(t,e.id)).sort((e,t)=>Wl(e)-Wl(t)||e.id.localeCompare(t.id)),n=/* @__PURE__ */new Set;return i.map(t=>{let i=r.find(e=>!n.has(e.id)&&e.datum.property?.id===t.propertyId);return i?(n.add(i.id),i.id):ml(e.id,t.propertyId,t.index)})}function Hl(e,t){return Math.hypot(e.vx,e.vy)<2&&Math.hypot(t.x,t.y)<4?null:t}function Ll(e){let{body:t,bodies:i,layout:r,states:n,projectPlacement:o,positiveById:s,negativeById:a,projectEvents:l,gateById:d,coreForceMode:c,terminalBehavior:u,elapsed:h}=e,p=t.datum;if(!p?.__gauntlet)return null;let m=n.findIndex(e=>e.id===p.projectId),y=m>=0?n[m]:void 0;if(!y)return null;let f=wl(y,m,r,o),g=i.find(e=>e.id===hl(y.id)),b=gl(r),v=y.negativeIds.reduce((e,t)=>e+(a.get(t)?.load??1),0),x=y.killed?0:58*Math.max(.25,b);if(p.kind!==ol){if(!g)return null;let e,n=p.property;if(n?.target){let o=i.filter(e=>{let t=e.datum;return t?.__gauntlet&&t.projectId===y.id&&t.kind===p.kind}).sort((e,t)=>String(e.id).localeCompare(String(t.id))),s=Math.max(0,o.findIndex(e=>e.id===t.id));e=n.target({body:t,bodies:i,core:g,index:s,layout:r,placement:f,project:y})??{x:g.x,y:g.y}}else if(p.kind===sl&&p.property){let t=Il(y.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{let r=i.filter(e=>e.datum?.kind===al&&e.datum.projectId===y.id).sort((e,t)=>String(e.id).localeCompare(String(t.id))),n=Math.max(0,r.findIndex(e=>e.id===t.id)),o=Math.floor(n/4),s=Math.min(4,r.length-4*o),a=n%4;e={x:g.x+18*(a-(s-1)/2)*b,y:g.y+(54+13*o)*b}}let o="circle"===t.shape.type?t.shape.radius:8;e=bl(e.x,e.y,o,r);let s=bl(t.x,t.y,o,r);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};let a=p.kind!==sl||y.killed?0:3.2*(n?.buoyancy??n?.value??1),l=p.kind===al?{x:.22*(n?.pull?.x??-8),y:.22*(n?.pull?.y??22)}:{x:0,y:0};return Hl(t,{x:28*(e.x-t.x)-3*(t.vx-g.vx)+l.x+.01*x,y:28*(e.y-t.y)-3*(t.vy-g.vy)+l.y-a})}if(y.killed){let e=y.crashX??y.metrics.lastX??t.x;return Hl(t,{x:44*(e-t.x)-9*t.vx,y:(160+12*v)*b-1.6*t.vy})}let w=l(y),I=_l(Math.max(0,h-(y.startedAt??0)),y,r,f,w,d,u),k=y.activePositiveIds.reduce((e,t)=>e+(s.get(t)?.buoyancy??s.get(t)?.value??1),0),S=13*v;if("net"===c){let e=32*(v-k);return Hl(t,{x:15*(I.x-t.x)-1.8*t.vx+.18*x,y:1.25*(f.routeY-t.y)-1.4*t.vy+e})}return Hl(t,{x:15*(I.x-t.x)-1.8*t.vx+.18*x,y:15*(I.y-t.y)-1.8*t.vy+S-2.2*k})}function Yl(e){let{project:t,effect:i,controls:r,layout:n,positiveById:o,negativeById:s,coreBody:a,popBodies:l,popScale:d}=e,c=r.readBodies().find(e=>e.id===hl(t.id)),u=r.readBodies(),h=c?.x??n.startX,p=c?.y??n.routeY,m=ql(t,u),y=Ua(i.addNegative).flatMap((e,i)=>{let r=s.get(e);return r?[Al(t,r,m+i,h,p,n)]:[]}),f=Ua(i.addPositive).flatMap(e=>{if(!o.get(e)||t.activePositiveIds.includes(e))return[];let i={...xl(n),routeY:p,socketY:p,startX:h,startY:p};return Ml({...t,activePositiveIds:[e],negativeIds:[]},0,n,i,o,s,a).filter(e=>e.id.includes(":positive:"))});(y.length||f.length)&&r.pushMany([...y,...f]);let g=Ja(t,i);for(let e of g){let i=o.get(e);l([pl(t.id,e)],{color:i?.popColor??i?.color,durationMs:900,radius:(i?.radius??10)+3,scale:d})}let b=tl(t,i),v=zl(t,u,b);b.forEach((e,t)=>{let i=s.get(e.propertyId);l([v[t]],{color:i?.popColor??i?.color,durationMs:900,radius:(i?.radius??7)+3,scale:d})})}function _l(e,t,i,r,n,o,s){let a=gl(i);if(t.killed)return{x:t.metrics.lastX??r.graveyardX,y:r.graveyardY};let l=n[n.length-1];if(!l)return{x:r.socketX,y:r.routeY};let d=n.find(i=>!(i.time>e||t.eventsApplied.includes(i.id)||!i.gateId||!o.get(i.gateId)?.capacity)),c=d?Math.min(e,d.time):e,u="built"===t.outcome||"built_diminished"===t.outcome;if(c>l.time+.85){if("hold-last"===s){let e=l.gateId?o.get(l.gateId):void 0;return{x:l.routeX??e?.x??r.socketX,y:l.routeY??r.routeY}}return u?{x:r.socketX,y:r.socketY}:{x:r.graveyardX,y:r.graveyardY-14}}let h=.85*t.delay+12*t.negativeIds.length+8*(t.poppedPositiveIds.length+t.missingPositiveIds.length),p=[{time:0,x:r.startX,y:r.startY},...n.map(e=>{let t=e.gateId?o.get(e.gateId):void 0;return{time:e.time,x:e.routeX??t?.x??r.startX,y:e.routeY??r.routeY+.28*Math.min(180,h)*a}})].sort((e,t)=>e.time-t.time),m=p[0],y=p[p.length-1];for(let e=1;e<p.length;e+=1){if(c<=p[e].time){y=p[e];break}m=p[e]}let f=Math.max(.1,y.time-m.time),g=Math.max(0,Math.min(1,(c-m.time)/f)),b=g*g*(3-2*g);return{x:m.x+(y.x-m.x)*b,y:m.y+(y.y-m.y)*b+7*Math.sin(2.6*c)*a}}import{Fragment as Xl,jsx as Gl,jsxs as Vl}from"react/jsx-runtime";var Ul="var(--semiotic-surface, var(--semiotic-bg, #fff))";function Kl(e){let t=e.data;if(!t?.__gauntlet)return null;let i="string"==typeof t.sourceDatum?.label?t.sourceDatum.label:t.projectId;/* @__PURE__ */
|
|
81
|
-
return
|
|
82
|
-
/* @__PURE__ */
|
|
83
|
-
/* @__PURE__ */
|
|
84
|
-
return
|
|
85
|
-
/* @__PURE__ */
|
|
86
|
-
/* @__PURE__ */
|
|
87
|
-
/* @__PURE__ */
|
|
88
|
-
/* @__PURE__ */
|
|
89
|
-
/* @__PURE__ */
|
|
90
|
-
/* @__PURE__ */
|
|
91
|
-
/* @__PURE__ */
|
|
92
|
-
/* @__PURE__ */
|
|
93
|
-
/* @__PURE__ */
|
|
94
|
-
/* @__PURE__ */
|
|
95
|
-
/* @__PURE__ */
|
|
96
|
-
/* @__PURE__ */
|
|
97
|
-
return
|
|
98
|
-
/* @__PURE__ */
|
|
99
|
-
return
|
|
100
|
-
/* @__PURE__ */
|
|
101
|
-
/* @__PURE__ */
|
|
102
|
-
/* @__PURE__ */
|
|
103
|
-
return
|
|
104
|
-
return
|
|
105
|
-
/* @__PURE__ */
|
|
106
|
-
/* @__PURE__ */
|
|
107
|
-
/* @__PURE__ */
|
|
108
|
-
return
|
|
109
|
-
/* @__PURE__ */
|
|
110
|
-
/* @__PURE__ */
|
|
111
|
-
/* @__PURE__ */
|
|
112
|
-
/* @__PURE__ */
|
|
113
|
-
/* @__PURE__ */
|
|
114
|
-
return
|
|
115
|
-
/* @__PURE__ */
|
|
116
|
-
/* @__PURE__ */
|
|
117
|
-
/* @__PURE__ */
|
|
118
|
-
/* @__PURE__ */
|
|
119
|
-
/* @__PURE__ */
|
|
120
|
-
/* @__PURE__ */
|
|
121
|
-
return
|
|
122
|
-
/* @__PURE__ */
|
|
123
|
-
/* @__PURE__ */
|
|
124
|
-
/* @__PURE__ */
|
|
125
|
-
/* @__PURE__ */
|
|
126
|
-
/* @__PURE__ */
|
|
127
|
-
return
|
|
128
|
-
return
|
|
129
|
-
/* @__PURE__ */
|
|
130
|
-
/* @__PURE__ */Qd(yo,{...c,...ve,...xe,key:`${W[0]}x${W[1]}:${he.rerunKey}`,ref:Q,onBodyHover:me,controllers:ne,regionEffects:we,selection:pe??c.selection,backgroundGraphics:_s(fe,c.backgroundGraphics),foregroundGraphics:_s(ge,c.foregroundGraphics),initialSpawns:ee.initialSpawns,initialSpawnPacing:b??ee.initialSpawnPacing,onTick:ce,paused:A,responsiveHeight:!1,responsiveWidth:!1,size:W,bodyStyle:ue,config:he.config}),F)}),"ProcessFlowChart");function ec(e=[]){let t=/* @__PURE__ */Object.create(null);for(let[i,r]of e)t[i]=r;return t}function tc(...e){let t=ec();for(let i of e)for(let[e,r]of Object.entries(i??{}))t[e]=r;return t}function ic(e){return tc(e)}function rc(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 nc(e){let t=ec(Object.entries(e.components).map(([e,t])=>[e,{...t,initialMetrics:ic(t.initialMetrics),metrics:ic(t.metrics),productIds:[...t.productIds],history:rc(t.history)}])),i=ec(Object.entries(e.products).map(([e,t])=>[e,{...t,metrics:ic(t.metrics),sourceIds:[...t.sourceIds],history:rc(t.history)}])),r=ec(Object.entries(e.relations).map(([e,t])=>[e,{...t,sourceIds:[...t.sourceIds],metrics:t.metrics?ic(t.metrics):void 0}]));return{...e,eventsApplied:[...e.eventsApplied],components:t,products:i,relations:r,input:{amount:e.input.amount,metrics:ic(e.input.metrics)},metrics:ic(e.metrics),loss:{amount:e.loss.amount,metrics:ic(e.loss.metrics)},history:rc(e.history)}}var oc=1e-9;function sc(e,t){return e<t?-1:e>t?1:0}function ac(e,t,i,r,n){return{severity:e,code:t,message:i,path:r,ids:n?[...n]:void 0}}function lc(e){let t=/* @__PURE__ */new Set,i=/* @__PURE__ */new Set;for(let r of e)t.has(r)&&i.add(r),t.add(r);return[...i].sort(sc)}function dc(e,t){return e?Object.entries(e).flatMap(([e,i])=>Number.isFinite(i)?[]:[ac("error","invalid-metric",`Metric "${e}" must be a finite number.`,`${t}.${e}`)]):[]}function cc(e,t){for(let[i,r]of Object.entries(t))e[i]=Number(e[i]??0)+r}function uc(e){let t=ec();for(let i of e)cc(t,i.metrics);return t}function hc(e,t,i="selector"){let r=[],n=Object.values(e.components),o=new Set(n.map(e=>e.id)),s=(t.ids??[]).filter(e=>!o.has(e));if(s.length&&r.push(ac("error","unknown-component",`Selector references unknown component id${1===s.length?"":"s"}: ${s.join(", ")}.`,`${i}.ids`,s)),void 0!==t.count&&(!Number.isInteger(t.count)||t.count<0)&&r.push(ac("error","invalid-selector-count","Selector count must be a non-negative integer.",`${i}.count`)),r.some(e=>"error"===e.severity))return{ids:[],diagnostics:r};let a=t.ids?new Set(t.ids):null,l=t.categories?new Set(t.categories):null,d=t.statuses?new Set(t.statuses):null,c=t.outletIds?new Set(t.outletIds):null,u=n.filter(e=>!a||a.has(e.id)).filter(e=>!l||l.has(e.category)).filter(e=>!d||d.has(e.status)).filter(e=>!c||void 0!==e.outletId&&c.has(e.outletId)).map(e=>e.id).sort(sc);return void 0!==t.count&&(u=u.slice(0,t.count)),u.length||r.push(ac("warning","empty-selector","Selector matched no source components.",i)),{ids:u,diagnostics:r}}function pc(e,t,i={}){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,...i}}function mc(e,t){let i={...t,eventId:e.event.id};e.materializations.push(i),e.observations.push({...i,phaseId:e.context.phaseId,authoredAt:e.context.authoredAt,appliedAt:e.context.appliedAt})}function yc(e,t,i){return!(void 0!==t&&!e.outletIds.has(t)&&(e.diagnostics.push(ac("error","unknown-outlet",`Unknown outlet "${t}".`,i,[t])),1))}function fc(e,t,i){let r=lc(t);t.length||e.diagnostics.push(ac("error","empty-source-list","A product requires at least one source component.",i)),r.length&&e.diagnostics.push(ac("error","duplicate-source",`Source ids may appear only once: ${r.join(", ")}.`,i,r));let n=t.filter(t=>!e.state.components[t]);n.length&&e.diagnostics.push(ac("error","unknown-component",`Unknown source component id${1===n.length?"":"s"}: ${n.join(", ")}.`,i,n));let o=t.filter(t=>(e.state.components[t]?.productIds.length??0)>0);o.length&&e.diagnostics.push(ac("error","source-already-assigned",`Source component${1===o.length?" is":"s are"} already assigned: ${o.join(", ")}.`,i,o));let s=t.filter(t=>"consumed"===e.state.components[t]?.status&&!o.includes(t));return s.length&&e.diagnostics.push(ac("error","source-unavailable",`Consumed source component${1===s.length?" is":"s are"} unavailable: ${s.join(", ")}.`,i,s)),e.diagnostics.some(e=>"error"===e.severity)?null:t.map(t=>e.state.components[t])}function gc(e,t,i){let r=lc(t),n=t.filter(t=>!e.state.components[t]);return t.length<2&&e.diagnostics.push(ac("error","insufficient-relation-sources","A relation requires at least two source components.",i)),r.length&&e.diagnostics.push(ac("error","duplicate-source",`Relation source ids must be unique: ${r.join(", ")}.`,i,r)),n.length&&e.diagnostics.push(ac("error","unknown-component",`Relation references unknown source component${1===n.length?"":"s"}: ${n.join(", ")}.`,i,n)),e.diagnostics.some(e=>"error"===e.severity)?null:t.map(t=>e.state.components[t])}function bc(e,t,i,r,n){let o=r?.amount??0;(!Number.isFinite(o)||o<0||o>t+oc)&&e.diagnostics.push(ac("error","invalid-loss","Loss amount must be finite, non-negative, and no greater than its sources.",`${n}.amount`)),e.diagnostics.push(...dc(r?.metrics,`${n}.metrics`));for(let[t,o]of Object.entries(r?.metrics??{}))(o<0||o>Number(i[t]??0)+oc)&&e.diagnostics.push(ac("error","invalid-metric-loss",`Metric loss "${t}" must be non-negative and no greater than its sources.`,`${n}.metrics.${t}`));return!e.diagnostics.some(e=>"error"===e.severity)}function vc(e,t,i,r){if(!t?.length)return[];let n=lc(t),o=t.filter(t=>!e.state.relations[t]),s=t.filter(t=>"resolved"===e.state.relations[t]?.status),a=new Set(i),l=t.filter(t=>(e.state.relations[t]?.sourceIds??[]).some(e=>!a.has(e)));return n.length&&e.diagnostics.push(ac("error","duplicate-relation","Basis relations must be unique.",r,n)),o.length&&e.diagnostics.push(ac("error","unknown-relation",`Unknown basis relation: ${o.join(", ")}.`,r,o)),s.length&&e.diagnostics.push(ac("error","resolved-relation",`Basis relation is already resolved: ${s.join(", ")}.`,r,s)),l.length&&e.diagnostics.push(ac("error","relation-source-mismatch",`Basis relation includes a source outside this product: ${l.join(", ")}.`,r,l)),e.diagnostics.some(e=>"error"===e.severity)?null:t.map(t=>e.state.relations[t])}function xc(e,t){if(t.length){for(let i of t)i.status="resolved",i.resolution="combined",i.resolvedByEventId=e.event.id,i.resolvedAt=e.context.appliedAt;mc(e,{type:"resolve-relation",relationIds:t.map(e=>e.id)})}}function wc(e,t,i){e.state.loss.amount+=i?.amount??0;for(let[r,n]of Object.entries(i?.metrics??{}))t[r]=Number(t[r]??0)-n,e.state.loss.metrics[r]=Number(e.state.loss.metrics[r]??0)+n}function Ic(e,t,i,r,n,o,s){let a=o&&void 0!==e.amount?e.amount:i;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:a,metrics:o&&e.metrics?tc(r,e.metrics):ic(r),status:o?"complete":"forming",sourceIds:[...t],outletId:o?e.outletId??(n.outletIds.has("product")?"product":void 0):void 0,createdByEventId:n.event.id,createdAt:n.context.appliedAt,completedByEventId:o?n.event.id:void 0,completedAt:o?n.context.appliedAt:void 0,history:[s]}}function kc(e,t,i,r){void 0!==t.amount&&Math.abs(t.amount-i)>oc&&e.diagnostics.push(ac("warning","declared-product-amount-mismatch",`Product "${t.id}" declares ${t.amount}, while its sources yield ${i}.`,r,[t.id]))}function Sc(e,t,i,r,n,o){let s=e.productDefinitions.get(t.id),a=i??s?.outletId??(e.outletIds.has("product")?"product":void 0);if(!yc(e,a,`${o}.outletId`))return;if("complete"===t.status)return void e.diagnostics.push(ac("error","product-already-complete",`Product "${t.id}" is already complete.`,o,[t.id]));s&&(kc(e,s,t.amount,`${o}.productId`),void 0!==s.amount&&(t.amount=s.amount),s.metrics&&(t.metrics=tc(t.metrics,s.metrics))),t.status="complete",t.outletId=a,t.reason=r,t.completedByEventId=e.event.id,t.completedAt=e.context.appliedAt;let l=pc(e,n,{sourceIds:[...t.sourceIds],productIds:[t.id],outletIds:a?[a]:void 0});t.history.push(l),e.state.history.push(l),mc(e,{type:"complete-product",sourceIds:[...t.sourceIds],productIds:[t.id],outletIds:a?[a]:void 0})}function Mc(e,t,i){let r=`events.${e.event.id}.effects.${i}`,n=e.state;if("set-state"===t.type){["queued","active","transformed","retained","ejected","failed","recovered"].includes(t.state)||e.diagnostics.push(ac("error","invalid-component-state",`set-state cannot assign "${String(t.state)}".`,`${r}.state`)),e.diagnostics.push(...dc(t.metricsDelta,`${r}.metricsDelta`)),yc(e,t.outletId,`${r}.outletId`);let i=hc(n,t.select,`${r}.select`);e.diagnostics.push(...i.diagnostics);let o=i.ids.filter(e=>n.components[e].productIds.length);if(o.length&&e.diagnostics.push(ac("error","source-already-assigned",`Assigned source components cannot be retargeted: ${o.join(", ")}.`,`${r}.select`,o)),e.diagnostics.some(e=>"error"===e.severity))return;let s=pc(e,t,{sourceIds:i.ids,outletIds:t.outletId?[t.outletId]:void 0});for(let e of i.ids){let i=n.components[e];i.status=t.state,i.outletId=t.outletId,i.reason=t.reason,t.metricsDelta&&cc(i.metrics,t.metricsDelta),i.history.push(s)}return n.history.push(s),void(i.ids.length&&mc(e,{type:"retarget-component",sourceIds:i.ids,outletIds:t.outletId?[t.outletId]:void 0}))}if("set-relation"===t.type){let{relation:i}=t;(!i.id||n.relations[i.id])&&e.diagnostics.push(ac("error","duplicate-relation",`Relation id "${i.id}" is missing or already active.`,`${r}.relation.id`,[i.id]));let o=gc(e,i.sourceIds,`${r}.relation.sourceIds`);if(e.diagnostics.push(...dc(i.metrics,`${r}.relation.metrics`)),!o||e.diagnostics.some(e=>"error"===e.severity))return;n.relations[i.id]={...i,sourceIds:[...i.sourceIds],metrics:i.metrics?ic(i.metrics):void 0,status:"active",createdByEventId:e.event.id,createdAt:e.context.appliedAt};let s=pc(e,t,{sourceIds:[...i.sourceIds],relationIds:[i.id]});return n.history.push(s),void mc(e,{type:"activate-relation",sourceIds:[...i.sourceIds],relationIds:[i.id]})}if("resolve-relation"===t.type){let i=lc(t.relationIds),o=t.relationIds.filter(e=>!n.relations[e]),s=t.relationIds.filter(e=>"resolved"===n.relations[e]?.status);if(i.length&&e.diagnostics.push(ac("error","duplicate-relation","Relation ids must be unique.",`${r}.relationIds`,i)),o.length&&e.diagnostics.push(ac("error","unknown-relation",`Unknown relation: ${o.join(", ")}.`,`${r}.relationIds`,o)),s.length&&e.diagnostics.push(ac("error","resolved-relation",`Relation is already resolved: ${s.join(", ")}.`,`${r}.relationIds`,s)),e.diagnostics.some(e=>"error"===e.severity))return;for(let i of t.relationIds){let r=n.relations[i];r.status="resolved",r.resolution=t.resolution,r.resolvedByEventId=e.event.id,r.resolvedAt=e.context.appliedAt,r.reason=t.reason}let a=pc(e,t,{relationIds:[...t.relationIds]});return n.history.push(a),void mc(e,{type:"resolve-relation",relationIds:[...t.relationIds]})}if("combine"===t.type||"contribute"===t.type){let i=e.productDefinitions.get(t.productId);i||e.diagnostics.push(ac("error","unknown-product",`Product "${t.productId}" has no declared mold.`,`${r}.productId`,[t.productId]));let o=n.products[t.productId];"combine"===t.type&&o&&e.diagnostics.push(ac("error","duplicate-product",`Product "${t.productId}" has already been formed.`,`${r}.productId`,[t.productId])),"contribute"===t.type&&(!o||"forming"!==o.status)&&e.diagnostics.push(ac("error","product-not-forming",`Contributions require an existing forming product "${t.productId}".`,`${r}.productId`,[t.productId]));let s=fc(e,t.sourceIds,`${r}.sourceIds`),a="contribute"===t.type&&o?[...o.sourceIds,...t.sourceIds]:t.sourceIds,l=vc(e,t.basisRelationIds,a,`${r}.basisRelationIds`);if(!s||!l||!i||e.diagnostics.some(e=>"error"===e.severity))return;let d=s.reduce((e,t)=>e+t.amount,0),c=uc(s);if(!bc(e,d,c,t.loss,`${r}.loss`))return;let u=d-(t.loss?.amount??0);wc(e,c,t.loss);let h,p="combine"===t.type&&!1!==t.complete,m=pc(e,t,{sourceIds:[...t.sourceIds],productIds:[t.productId],relationIds:t.basisRelationIds?[...t.basisRelationIds]:void 0});if("combine"===t.type){if(p&&kc(e,i,u,`${r}.productId`),h=Ic(i,t.sourceIds,u,c,e,p,m),p&&!yc(e,h.outletId,`${r}.productId`))return;n.products[t.productId]=h}else h=o,h.sourceIds.push(...t.sourceIds),h.amount+=u,cc(h.metrics,c),h.history.push(m);for(let e of s)e.productIds=[t.productId],e.status="consumed",e.outletId=void 0,e.history.push(m);return n.history.push(m),xc(e,l),mc(e,{type:"combine"===t.type?"form-product":"update-product",sourceIds:[...t.sourceIds],productIds:[t.productId],relationIds:t.basisRelationIds?[...t.basisRelationIds]:void 0,outletIds:h.outletId?[h.outletId]:void 0}),void(p&&mc(e,{type:"complete-product",sourceIds:[...h.sourceIds],productIds:[h.id],outletIds:h.outletId?[h.outletId]:void 0}))}if("complete-product"===t.type){let i=n.products[t.productId];return i?void Sc(e,i,t.outletId,t.reason,t,r):void e.diagnostics.push(ac("error","unknown-product-state",`Product "${t.productId}" has not been formed.`,`${r}.productId`,[t.productId]))}if("split"===t.type){let i=fc(e,[t.sourceId],`${r}.sourceId`);t.products.length||e.diagnostics.push(ac("error","empty-split","A split requires at least one product allocation.",`${r}.products`));let o=t.products.map(e=>e.productId),s=lc(o);s.length&&e.diagnostics.push(ac("error","duplicate-product","Split product ids must be unique.",`${r}.products`,s));let a=o.map(t=>e.productDefinitions.get(t)),l=o.filter((e,t)=>!a[t]),d=o.filter(e=>n.products[e]);l.length&&e.diagnostics.push(ac("error","unknown-product",`Split references undeclared product molds: ${l.join(", ")}.`,`${r}.products`,l)),d.length&&e.diagnostics.push(ac("error","duplicate-product",`Split products already exist: ${d.join(", ")}.`,`${r}.products`,d));for(let[i,n]of t.products.entries())void 0!==n.amount&&(!Number.isFinite(n.amount)||n.amount<0)&&e.diagnostics.push(ac("error","invalid-product-amount","Split allocation amounts must be finite and non-negative.",`${r}.products.${i}.amount`)),e.diagnostics.push(...dc(n.metrics,`${r}.products.${i}.metrics`));if(!i?.length||e.diagnostics.some(e=>"error"===e.severity))return;let c=i[0];if(!bc(e,c.amount,c.metrics,t.loss,`${r}.loss`))return;let u=c.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(ac("error","partial-split-allocation","Either every split product must declare an amount or none may do so.",`${r}.products`));let m=p?h:t.products.map(()=>u/t.products.length),y=m.reduce((e,t)=>e+t,0);if(Math.abs(y-u)>oc)return void e.diagnostics.push(ac("error","split-amount-mismatch",`Split allocations total ${y}, but ${u} remains after loss.`,`${r}.products`));let f=ic(c.metrics);for(let[e,i]of Object.entries(t.loss?.metrics??{}))f[e]=Number(f[e]??0)-i;let g=pc(e,t,{sourceIds:[c.id],productIds:o});if(t.products.forEach((i,o)=>{let s=a[o],l=u>oc?m[o]/u:1/t.products.length,d=ec(Object.entries(f).map(([e,t])=>[e,t*l])),h=i.metrics??s.metrics??d,p=Ic({...s,amount:m[o],metrics:h},[c.id],m[o],ic(h),e,!0,g);yc(e,p.outletId,`${r}.products.${o}.productId`)&&(n.products[p.id]=p)}),e.diagnostics.some(e=>"error"===e.severity))return;c.productIds=o,c.status="consumed",c.outletId=void 0,c.history.push(g),n.loss.amount+=t.loss?.amount??0;for(let[e,i]of Object.entries(t.loss?.metrics??{}))n.loss.metrics[e]=Number(n.loss.metrics[e]??0)+i;n.history.push(g),mc(e,{type:"split-source",sourceIds:[c.id],productIds:o});for(let t of o)mc(e,{type:"complete-product",sourceIds:[c.id],productIds:[t],outletIds:n.products[t].outletId?[n.products[t].outletId]:void 0});return}if("eject"===t.type){yc(e,t.outletId,`${r}.outletId`);let i=hc(n,t.select,`${r}.select`);e.diagnostics.push(...i.diagnostics);let o=i.ids.filter(e=>n.components[e].productIds.length);if(o.length&&e.diagnostics.push(ac("error","source-already-assigned",`Assigned source components cannot be ejected: ${o.join(", ")}.`,`${r}.select`,o)),e.diagnostics.some(e=>"error"===e.severity))return;let s=pc(e,t,{sourceIds:i.ids,outletIds:[t.outletId]});for(let e of i.ids){let i=n.components[e];i.status=t.state??"ejected",i.outletId=t.outletId,i.reason=t.reason,i.history.push(s)}return n.history.push(s),void(i.ids.length&&mc(e,{type:"retarget-component",sourceIds:i.ids,outletIds:[t.outletId]}))}if("set-metric"===t.type){if(e.diagnostics.push(...dc(t.metricsDelta,`${r}.metricsDelta`)),e.diagnostics.some(e=>"error"===e.severity))return;let i,o;if("run"===t.target)cc(n.metrics,t.metricsDelta);else if("components"in t.target){let o=hc(n,t.target.components,`${r}.target.components`);if(e.diagnostics.push(...o.diagnostics),e.diagnostics.some(e=>"error"===e.severity))return;i=o.ids;for(let e of o.ids)cc(n.components[e].metrics,t.metricsDelta)}else{o=[...t.target.productIds];let i=lc(o),s=o.filter(e=>!n.products[e]);if(i.length&&e.diagnostics.push(ac("error","duplicate-product","Metric target product ids must be unique.",`${r}.target.productIds`,i)),s.length&&e.diagnostics.push(ac("error","unknown-product-state",`Metric target product has not formed: ${s.join(", ")}.`,`${r}.target.productIds`,s)),e.diagnostics.some(e=>"error"===e.severity))return;for(let e of o)cc(n.products[e].metrics,t.metricsDelta)}return void n.history.push(pc(e,t,{sourceIds:i,productIds:o}))}t.outcome.trim()?(n.outcome=t.outcome,n.summary=t.summary,n.history.push(pc(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(ac("error","invalid-outcome","Outcome must be a non-empty string.",`${r}.outcome`))}function Ac(e,t,i){if(e.eventsApplied.includes(t.id))return{applied:!1,state:e,materializations:[],observations:[],diagnostics:[ac("warning","duplicate-event-application",`Event "${t.id}" has already been applied.`,`events.${t.id}`,[t.id])]};let r=nc(e),n={state:r,event:t,context:i,productDefinitions:new Map(i.products.map(e=>[e.id,e])),outletIds:new Set(i.outlets.map(e=>e.id)),diagnostics:[],materializations:[],observations:[]};for(let[i,r]of t.effects.entries())if(Mc(n,r,i),n.diagnostics.some(e=>"error"===e.severity))return{applied:!1,state:e,materializations:[],observations:[],diagnostics:n.diagnostics};return r.elapsed=Math.max(r.elapsed,i.appliedAt),r.phaseId=i.phaseId,r.eventsApplied.push(t.id),n.observations.unshift({type:"crucible-event",eventId:t.id,phaseId:i.phaseId,authoredAt:i.authoredAt,appliedAt:i.appliedAt}),{applied:!0,state:r,materializations:n.materializations,observations:n.observations,diagnostics:n.diagnostics}}function $c(e,t){return"product"===t?"product"===e.kind?e.id:"unassigned":"outlet"===t?e.outletId??"unassigned":"category"===t?e.category:e.status}function Cc(e,t={}){let i=t.groupBy??"outlet",r=/* @__PURE__ */new Map,n=e=>{let t=$c({...e,status:e.status??"active"},i),n=r.get(t);if(n)return n.count+=1,n.amount+=e.amount,void cc(n.metrics,e.metrics);r.set(t,{key:t,label:"product"===i&&"product"===e.kind?e.label:t,count:1,amount:e.amount,metrics:ic(e.metrics),status:"status"===i?e.status:void 0,outletId:"outlet"===i?e.outletId:void 0,category:"category"===i?e.category:void 0,productId:"product"===i&&"product"===e.kind?e.id:void 0})};for(let t of Object.values(e.components))t.productIds.length||"consumed"===t.status||n({kind:"component",id:t.id,label:t.label,status:t.status,outletId:t.outletId,category:t.category,amount:t.amount,metrics:t.metrics});for(let t of Object.values(e.products))n({kind:"product",id:t.id,label:t.label,status:t.status,outletId:t.outletId,category:t.category,amount:t.amount,metrics:t.metrics});let o=new Map((t.order??[]).map((e,t)=>[e,t]));return[...r.values()].sort((e,t)=>(o.get(e.key)??Number.MAX_SAFE_INTEGER)-(o.get(t.key)??Number.MAX_SAFE_INTEGER)||sc(e.key,t.key))}var Pc=Cc;function Rc(e,t={}){let i=t.field??"amount",r=e=>"amount"===i?e.amount:Number(e.metrics[i]??0),n="amount"===i?e.input.amount:Number(e.input.metrics[i]??0),o=Object.values(e.products).reduce((e,t)=>e+r(t),0),s=Object.values(e.components).filter(e=>!e.productIds.length&&"consumed"!==e.status).reduce((e,t)=>e+r(t),0),a="amount"===i?e.loss.amount:Number(e.loss.metrics[i]??0),l=o+s+a,d=l-n,c=Math.max(0,t.tolerance??1e-6);return{field:i,input:n,products:o,unassigned:s,loss:a,output:l,delta:d,conserved:Math.abs(d)<=c}}function Dc(e,t={}){return{history:rc(e.history),projection:Cc(e,t.projection),conservation:Rc(e,t.conservation)}}var Bc=900,Tc=520,jc=[900,520],Oc=[{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}],Ec=/* @__PURE__ */new Set(["queued","active","transformed","consumed","retained","ejected","failed","recovered"]),Nc=1e-9;function Fc(e,t){return e<t?-1:e>t?1:0}function Wc(e,t,i,r,n){return{severity:e,code:t,message:i,path:r,ids:n?[...n]:void 0}}function qc(e){let t=/* @__PURE__ */new Set,i=/* @__PURE__ */new Set;for(let r of e)t.has(r)&&i.add(r),t.add(r);return[...i].sort(Fc)}function zc(e){let t="number"==typeof e?e:Number(e);return Number.isFinite(t)?t:null}function Hc(e,t,i,r,n,o){if(!i)return r;try{return("function"==typeof i?i(e,t):e[i])??r}catch(e){return n.push(Wc("error","accessor-error",`Accessor threw: ${e instanceof Error?e.message:String(e)}.`,o)),r}}function Lc(e,t,i){if(!e||"object"!=typeof e||Array.isArray(e))return null!=e&&t.push(Wc("error","invalid-metrics","Metrics must be a numeric object.",i)),ec();let r=ec();for(let[n,o]of Object.entries(e)){let e=zc(o);null!=e?r[n]=e:t.push(Wc("error","invalid-metric",`Metric "${n}" must be finite.`,`${i}.${n}`))}return r}function Yc(e,t){for(let[i,r]of Object.entries(t))e[i]=Number(e[i]??0)+r}function _c(e){let t=[],i=ec(),r=[],n=0,o=ec();e.data.forEach((s,a)=>{let l=String(s.id??`component-${a}`),d=Hc(s,a,e.idAccessor,l,t,`data.${a}.id`),c=String(d??l).trim();if(!c)return void t.push(Wc("error","invalid-component-id","Component ids may not be empty.",`data.${a}.id`));r.push(c);let u=zc(Hc(s,a,e.amountAccessor,1,t,`data.${a}.amount`)),h=null!=u&&u>=0?u:0;(null==u||u<0)&&t.push(Wc("error","invalid-component-amount","Component amount must be finite and non-negative.",`data.${a}.amount`,[c]));let p=Lc(Hc(s,a,e.metricsAccessor,{},t,`data.${a}.metrics`),t,`data.${a}.metrics`),m=Hc(s,a,e.initialStateAccessor,"active",t,`data.${a}.status`),y=Ec.has(m)?m:"active";Ec.has(m)||t.push(Wc("error","invalid-component-status",`Unknown component status "${String(m)}".`,`data.${a}.status`,[c]));let f=String(Hc(s,a,e.labelAccessor,String(s.label??s.name??c),t,`data.${a}.label`)),g=String(Hc(s,a,e.categoryAccessor,"component",t,`data.${a}.category`));Object.hasOwn(i,c)||(i[c]={id:c,label:f,category:g,datum:s,status:y,initialAmount:h,amount:h,initialMetrics:tc(p),metrics:tc(p),productIds:[],history:[]},n+=h,Yc(o,p))});let s=qc(r);s.length&&t.push(Wc("error","duplicate-component-id",`Component ids must be unique: ${s.join(", ")}.`,"data",s));let a=Lc(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:i,products:ec(),relations:ec(),input:{amount:n,metrics:o},metrics:a,loss:{amount:0,metrics:ec()},history:[]},diagnostics:t}}function Xc(e){let t=[];e.length||t.push(Wc("error","empty-phase-program","CrucibleChart requires at least one phase.","phases"));let i=qc(e.map(e=>e.id));i.length&&t.push(Wc("error","duplicate-phase-id",`Phase ids must be unique: ${i.join(", ")}.`,"phases",i));let r=0;return{phases:e.map((e,i)=>{let n=zc(e.duration),o=null!=n&&n>0?n:0;e.id.trim()||t.push(Wc("error","invalid-phase-id","Phase ids may not be empty.",`phases.${i}.id`)),(null==n||n<=0)&&t.push(Wc("error","invalid-phase-duration","Phase duration must be finite and greater than zero.",`phases.${i}.duration`,[e.id])),void 0!==e.intensity&&!Number.isFinite(e.intensity)&&t.push(Wc("error","invalid-phase-intensity","Phase intensity must be finite.",`phases.${i}.intensity`,[e.id]));let s={...e,duration:o,intensity:void 0===e.intensity?.5:Number.isFinite(e.intensity)?Math.max(0,Math.min(1,e.intensity)):.5,motion:e.motion??"hold",index:i,start:r,end:r+o};return r=s.end,s}),diagnostics:t}}function Gc(e,t,i){let r=e.find(e=>Math.abs(e.start-i)<=Nc);if(r)return{phase:r,boundaryRank:1};let n=e.find(e=>i>=e.start&&i<e.end);return n?{phase:n,boundaryRank:0}:Math.abs(i-t)<=Nc&&e.length?{phase:e[e.length-1],boundaryRank:0}:{phase:void 0,boundaryRank:1}}function Vc(e,t,i){let r=[],n=qc(e.map(e=>e.id));n.length&&r.push(Wc("error","duplicate-event-id",`Event ids must be unique: ${n.join(", ")}.`,"events",n));let o=[];return e.forEach((e,n)=>{let s,a,l;if(e.id.trim()||r.push(Wc("error","invalid-event-id","Event ids may not be empty.",`events.${n}.id`)),"time"in e.at&&void 0!==e.at.time){let o=zc(e.at.time);if(null==o||o<0||o>i+Nc)return void r.push(Wc("error","event-time-out-of-range",`Event time must fall between 0 and ${i}.`,`events.${n}.at.time`,[e.id]));s=Math.max(0,Math.min(i,o));let d=Gc(t,i,s);a=d.phase,l=d.boundaryRank}else{if(a=t.find(t=>t.id===e.at.phaseId),!a)return void r.push(Wc("error","unknown-event-phase",`Event references unknown phase "${e.at.phaseId}".`,`events.${n}.at.phaseId`,[e.id,e.at.phaseId]));let i=e.at.progress??0;if(!Number.isFinite(i)||i<0||i>1)return void r.push(Wc("error","event-progress-out-of-range","Event phase progress must be between 0 and 1.",`events.${n}.at.progress`,[e.id]));s=a.start+a.duration*i,l=0===i?1:0}a?o.push({...e,index:n,authoredAt:s,phaseId:a.id,phaseIndex:a.index,boundaryRank:l}):r.push(Wc("error","event-without-phase","Event could not be assigned to a phase.",`events.${n}.at`,[e.id]))}),o.sort((e,t)=>e.authoredAt-t.authoredAt||e.boundaryRank-t.boundaryRank||e.index-t.index),{events:o,diagnostics:r}}function Uc(e,t){let i=[],r=new Set(t.map(e=>e.id)),n=qc(t.map(e=>e.id)),o=qc(e.map(e=>e.id));return n.length&&i.push(Wc("error","duplicate-outlet-id",`Outlet ids must be unique: ${n.join(", ")}.`,"outlets",n)),o.length&&i.push(Wc("error","duplicate-product-id",`Product ids must be unique: ${o.join(", ")}.`,"products",o)),t.forEach((e,t)=>{e.id.trim()||i.push(Wc("error","invalid-outlet-id","Outlet ids may not be empty.",`outlets.${t}.id`)),void 0!==e.order&&!Number.isFinite(e.order)&&i.push(Wc("error","invalid-outlet-order","Outlet order must be finite.",`outlets.${t}.order`,[e.id]))}),e.forEach((e,t)=>{e.id.trim()||i.push(Wc("error","invalid-product-id","Product ids may not be empty.",`products.${t}.id`)),void 0!==e.amount&&(!Number.isFinite(e.amount)||e.amount<0)&&i.push(Wc("error","invalid-product-amount","Declared product amount must be finite and non-negative.",`products.${t}.amount`,[e.id])),void 0!==e.outletId&&!r.has(e.outletId)&&i.push(Wc("error","unknown-outlet",`Product "${e.id}" references unknown outlet "${e.outletId}".`,`products.${t}.outletId`,[e.outletId])),Lc(e.metrics??{},i,`products.${t}.metrics`)}),i}function Kc(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 Qc(e=jc,t=Oc){let i=Math.max(1,zc(e[0])??900),r=Math.max(1,zc(e[1])??520),n=i<360||r<260,o=n?Math.max(4,.035*Math.min(i,r)):20,s=n?Math.max(10,.075*r):34,a={x:o,y:o,width:Math.max(1,i-2*o),height:s},l=n?Math.max(16,.14*r):Math.min(78,.16*r),d={x:o,y:r-o-l,width:Math.max(1,i-2*o),height:l},c=n?Math.max(12,.08*i):Math.min(150,.17*i),u=a.y+a.height+(n?12:38),h=d.y-(n?10:34),p={x:c,y:u,width:Math.max(24,i-2*c),height:Math.max(24,h-u)},m=Math.max(18,Math.min(.32*p.width,n?84:180)),y={x:p.x+(p.width-m)/2,y:p.y-(n?10:24),width:m,height:n?12:28},f=Kc(t),g={left:f.filter(e=>"left"===(e.side??"bottom")),right:f.filter(e=>"right"===e.side),bottom:f.filter(e=>"bottom"===(e.side??"bottom"))},b=[],v=(e,t)=>{let r=Math.max(8,c-1.5*o),s=p.height/Math.max(1,t.length);t.forEach((t,a)=>{b.push({...t,side:e,x:"left"===e?o:i-o-r,y:p.y+a*s,width:r,height:Math.max(8,s-(n?2:8))})})};v("left",g.left),v("right",g.right);let x=p.width/Math.max(1,g.bottom.length);return g.bottom.forEach((e,t)=>{b.push({...e,side:"bottom",x:p.x+t*x,y:p.y+p.height+(n?2:7),width:Math.max(8,x-(n?2:8)),height:Math.max(8,d.y-p.y-p.height-(n?4:12))})}),b.sort((e,t)=>f.findIndex(t=>t.id===e.id)-f.findIndex(e=>e.id===t.id)),{width:i,height:r,phaseRail:a,chamber:p,mouth:y,projection:d,outlets:b}}function Jc(e,t,i){let r=i.map(([i,r])=>[Math.max(e,Math.min(i,r)),Math.min(t,Math.max(i,r))]).filter(([e,t])=>t>e+Nc).sort((e,t)=>e[0]-t[0]||e[1]-t[1]),n=[],o=e;for(let[e,t]of r)e>o+Nc&&n.push([o,e]),o=Math.max(o,t);return t>o+Nc&&n.push([o,t]),n}function Zc(e){let{id:t,orientation:i,fixed:r,start:n,end:o,openings:s,thickness:a,friction:l,restitution:d}=e,c=Jc(n,o,s);return c.map(([e,n],o)=>({id:1===c.length?t:`${t}:${o}`,friction:l,restitution:d,shape:"horizontal"===i?{type:"segment",x1:e,y1:r,x2:n,y2:r,thickness:a}:{type:"segment",x1:r,y1:e,x2:r,y2:n,thickness:a}}))}function eu(e){let{chamber:t,mouth:i}=e,r=Math.max(2,Math.min(10,.018*Math.min(e.width,e.height))),n=Math.max(t.x,i.x),o=Math.min(t.x+t.width,i.x+i.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:n,y2:t.y,thickness:r}},{id:"crucible:wall:top-right",friction:.42,restitution:.1,shape:{type:"segment",x1:o,y1:t.y,x2:t.x+t.width,y2:t.y,thickness:r}}];a.push(...Zc({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:r,friction:.46,restitution:.12}),...Zc({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:r,friction:.46,restitution:.12}),...Zc({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:r,friction:.5,restitution:.08}));for(let 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 tu(e){return"number"==typeof e&&Number.isFinite(e)?e>>>0:"string"==typeof e?we(e):1}function iu(e,t){return{fixedDt:1/120,maxSubsteps:8,settleStepLimit:7200,colliders:t.map(e=>({...e,shape:{...e.shape}})),observation:{chartType:"crucible"},kernel:{seed:tu(e),gravity:{x:0,y:0},cellSize:42,collisionIterations:6,velocityDamping:.992,restitution:.12,friction:.42,sleepSpeed:4,sleepAfter:.5,maxVelocity:620}}}function ru(e){return`crucible:component:${encodeURIComponent(e)}`}function nu(e){return`crucible:product:${encodeURIComponent(e)}`}function ou(e,t){return`crucible:bond:${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function su(e,t,i,r){if(void 0!==i&&Number.isFinite(i)&&i>0)return i;let[n,o]=t;if(o-n<=Nc)return(r[0]+r[1])/2;let s=Math.sqrt(Math.max(0,e-n)/(o-n));return r[0]+(r[1]-r[0])*s}function au(e,t){let i=Math.max(.25,Math.min(1,t.width/900,t.height/520)),r=e?.[0]??7*i,n=e?.[1]??18*i,o=Math.max(1,Math.min(r,n));return[o,Math.max(o,Math.max(r,n))]}function lu(e,t,i={}){let r=Object.values(e.components).sort((e,t)=>Fc(e.id,t.id)),n=Te(r.map(e=>e.amount)),o=au(i.radiusRange,t),s=b(tu(i.seed)),a=t.mouth.x+t.mouth.width/2,l=t.chamber.y+Math.max(18,.18*t.chamber.height),d=Math.max(4,.28*t.chamber.width),c=Math.max(4,.12*t.chamber.height);return r.map((e,t)=>{let u=t/Math.max(1,r.length)*Math.PI*2+.18*(s()-.5),h=su(e.amount,n,i.bodyRadius,o),p={__crucible:!0,kind:"component",semanticId:e.id,sourceDatum:e.datum};return{id:ru(e.id),x:a+Math.cos(u)*d*(.45+.45*s()),y:l+Math.sin(u)*c*(.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 du(e,t){if(!e)return[];let i=Math.min(e,Math.max(1,Math.ceil(Math.sqrt(e*Math.max(.5,t.width/Math.max(1,t.height)))))),r=Math.max(1,Math.ceil(e/i));return Array.from({length:e},(e,n)=>({x:t.x+(n%i+.5)*(t.width/i),y:t.y+(Math.floor(n/i)+.5)*(t.height/r)}))}function cu(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 uu(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 hu(e,t){let i=/* @__PURE__ */new Map;for(let t of e){let e=t.outletId??"__chamber__",r=i.get(e)??[];r.push(t),i.set(e,r)}let r=/* @__PURE__ */new Map;for(let[e,n]of i){n.sort((e,t)=>(e.order??Number.MAX_SAFE_INTEGER)-(t.order??Number.MAX_SAFE_INTEGER)||Fc(e.id,t.id));let i=du(n.length,uu(t,"__chamber__"===e?void 0:e));n.forEach((e,t)=>r.set(e.id,i[t]))}return r}function pu(e,t,i={}){let r=Object.values(e.products).sort((e,t)=>Fc(e.id,t.id)),n=Object.values(e.components).sort((e,t)=>Fc(e.id,t.id)),o=Te([...n.map(e=>e.amount),...r.map(e=>e.amount)]),s=au(i.radiusRange,t),a=hu(r,t),l=r.map(e=>{let r=a.get(e.id)??{x:t.chamber.x+t.chamber.width/2,y:t.chamber.y+t.chamber.height/2},n=1.28*su(e.amount,o,i.bodyRadius,s),l={__crucible:!0,kind:"product",semanticId:e.id,product:e};return{id:nu(e.id),x:r.x,y:r.y,mass:Math.max(.25,n*n*.018),bodyCollisions:!1,shape:{type:"circle",radius:n},datum:l}}),d=/* @__PURE__ */new Map;for(let e of n.filter(e=>!e.productIds.length)){let t=cu(e)??"__chamber__",i=d.get(t)??[];i.push(e),d.set(t,i)}let c=/* @__PURE__ */new Map;for(let[e,i]of d){let r=du(i.length,uu(t,"__chamber__"===e?void 0:e));i.forEach((e,t)=>c.set(e.id,r[t]))}return[...n.map(e=>{let r=c.get(e.id);if(e.productIds.length){let i=e.productIds.map(e=>a.get(e)).filter(e=>!!e);if(i.length){r={x:i.reduce((e,t)=>e+t.x,0)/i.length,y:i.reduce((e,t)=>e+t.y,0)/i.length};let n=we(e.id)/4294967295*Math.PI*2,o=Math.min(20,Math.max(4,.012*t.width));r={x:r.x+Math.cos(n)*o,y:r.y+Math.sin(n)*o}}}r??(r={x:t.chamber.x+t.chamber.width/2,y:t.chamber.y+t.chamber.height/2});let n=su(e.amount,o,i.bodyRadius,s),l={__crucible:!0,kind:"component",semanticId:e.id,sourceDatum:e.datum};return{id:ru(e.id),x:r.x,y:r.y,mass:Math.max(.25,n*n*.015),shape:{type:"circle",radius:n},datum:l}}),...l]}var mu=pu;function yu(e){return Array.isArray(e)?e.map(yu):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e&&"function"!=typeof e).sort(([e],[t])=>Fc(e,t)).map(([e,t])=>[e,yu(t)])):e}function fu(e){return JSON.stringify(yu(e))}function gu(e,t){let i=zc(t)??0,r=Math.max(0,Math.min(e.duration,i));if(!e.phases.length)return{elapsed:r,phaseId:"",phaseIndex:-1,phaseElapsed:0,complete:!0};let n=r>=e.duration-Nc,o=n?e.phases[e.phases.length-1]:e.phases.find(e=>r>=e.start&&r<e.end)??e.phases[0];return{elapsed:r,phaseId:o.id,phaseIndex:o.index,phaseElapsed:n?o.duration:Math.max(0,r-o.start),complete:n}}function bu(e,t){if(void 0===t)return e.duration;if("number"==typeof t)return Math.max(0,Math.min(e.duration,zc(t)??0));let i=e.phases.find(e=>e.id===t.phaseId);if(!i)return e.duration;let r=Math.max(0,Math.min(1,zc(t.progress??0)??0));return i.start+i.duration*r}function vu(e,t=e.duration){let i=gu(e,t),r=nc(e.initialState),n=[],o=[],s=[];for(let t of e.events){if(t.authoredAt>i.elapsed+Nc)break;let a=Ac(r,t,{phaseId:t.phaseId,authoredAt:t.authoredAt,appliedAt:t.authoredAt,products:e.products,outlets:e.outlets});n.push(...a.diagnostics),o.push(...a.materializations),s.push(...a.observations),a.applied&&(r=a.state)}return r.elapsed=i.elapsed,r.phaseId=i.phaseId,r.phaseIndex=i.phaseIndex,r.phaseElapsed=i.phaseElapsed,r.complete=i.complete,i.complete&&"in_process"===r.outcome&&(r.outcome="complete"),r.playing=!1,{state:r,diagnostics:n,materializations:o,observations:s}}function xu(e){let t=Xc(e.phases),i=t.phases.at(-1)?.end??0,r=Kc(e.outlets??Oc),n=(e.products??[]).map(e=>({...e,metrics:e.metrics?tc(e.metrics):void 0})),o=Vc(e.events??[],t.phases,i),s=_c(e),a=Qc(e.size??jc,r),l=eu(a),d=Uc(n,r),c=fu({seed:e.seed??1,components:Object.values(s.state.components).sort((e,t)=>Fc(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:i,description:r,intensity:n,motion:o,color:s,metrics:a})=>({id:e,duration:t,label:i,description:r,intensity:n,motion:o,color:s,metrics:a})),products:n,outlets:r,events:o.events.map(({id:e,label:t,description:i,summary:r,authoredAt:n,phaseId:o,boundaryRank:s,effects:a})=>({id:e,label:t,description:i,summary:r,authoredAt:n,phaseId:o,boundaryRank:s,effects:a}))}),u=lu(s.state,a,{seed:e.seed,bodyRadius:e.bodyRadius,radiusRange:e.radiusRange}),h=[...t.diagnostics,...o.diagnostics,...s.diagnostics,...d],p={phases:t.phases,events:o.events,products:n,outlets:r,duration:i,initialState:s.state,terminalState:s.state,layout:a,colliders:l,config:iu(e.seed,l),initialSpawns:u,terminalSpawns:[],semanticKey:c,diagnostics:h},m=vu(p),y=Object.values(m.state.products).filter(e=>"forming"===e.status).map(e=>e.id),f=y.length?[Wc("warning","forming-product-at-end",`Products remain forming at the end of the tape: ${y.join(", ")}.`,"events",y)]:[];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,...f],p}function wu(e,t,i){return{id:e.id??t,at:{...e.at},effects:i,...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 Iu(e){if(e)return{...e,...e.metrics?{metrics:{...e.metrics}}:null}}function ku(e){let{productId:t,form:i,contributions:r=[],complete:n}=e,o=e.idPrefix??t,s=Iu(i.loss),a=[wu(i,`${o}-form`,[{type:"combine",sourceIds:[...i.sourceIds],productId:t,...i.basisRelationIds?{basisRelationIds:[...i.basisRelationIds]}:null,...s?{loss:s}:null,complete:!1}])];return r.forEach((e,i)=>{let r=Iu(e.loss);a.push(wu(e,`${o}-contribute-${i+1}`,[{type:"contribute",sourceIds:[...e.sourceIds],productId:t,...e.basisRelationIds?{basisRelationIds:[...e.basisRelationIds]}:null,...r?{loss:r}:null}]))}),a.push(wu(n,`${o}-complete`,[{type:"complete-product",productId:t,...void 0===n.outletId?null:{outletId:n.outletId},...void 0===n.reason?null:{reason:n.reason}}])),a}import{forwardRef as Su,useCallback as Mu,useEffect as Au,useImperativeHandle as $u,useMemo as Cu,useRef as Pu,useState as Ru}from"react";function Du(e,t){return e.playing=t&&!e.complete,e}function Bu(e,t){return bu(e,t)}function Tu(e,t,i=!1){let r=vu(e,t);return{...r,state:Du(r.state,i)}}function ju(e,t,i,r=t.playing){let n=Tu(e,i,r),o=new Set(t.eventsApplied);return{...n,observations:n.observations.filter(e=>!o.has(e.eventId)),materializations:n.materializations.filter(e=>!o.has(e.eventId))}}function Ou(e,t){return e.phases.find(e=>e.end>t+1e-7)?.end??e.duration}function Eu(e,t,i={}){return pu(t,e.layout,i)}function Nu(e,t){let i=new Set(e.readBodies().map(e=>e.id)),r=t.filter(e=>!i.has(e.id));return r.length&&e.pushMany([...r]),r.map(e=>e.id)}function Fu(e,t){return we(`${t}:${e}`)/4294967295}function Wu(e,t){return e.phases[t.phaseIndex]??e.phases.find(e=>e.id===t.phaseId)}function qu(e,t,i={}){return new Map(Eu(e,t,i).flatMap(e=>{let t=e.datum;return t?.__crucible?[[`${t.kind}:${t.semanticId}`,{x:e.x,y:e.y}]]:[]}))}function zu(e,t){let i=Object.values(e.terminalState.products).map(e=>e.id).sort(),r=Math.max(0,i.indexOf(t))/Math.max(1,i.length)*Math.PI*2-Math.PI/2,n=Math.min(58,.19*e.layout.chamber.width),o=Math.min(38,.16*e.layout.chamber.height);return{x:e.layout.chamber.x+e.layout.chamber.width/2+Math.cos(r)*n,y:e.layout.chamber.y+.52*e.layout.chamber.height+Math.sin(r)*o}}function Hu(e){let{body:t,plan:i,state:r,targets:n}=e,o=t.datum;if(!o?.__crucible)return null;let s=`${o.kind}:${o.semanticId}`,a=n.get(s);if(!a)return null;let l=Wu(i,r),d=Math.max(0,Math.min(2,Number(l?.intensity??.5))),c=l?.motion??"hold",u=r.elapsed;if("product"===o.kind){let e=r.products[o.semanticId];"forming"===e?.status&&(a=zu(i,e.id))}else{let e=r.components[o.semanticId],t=e?.productIds.map(e=>r.products[e]).find(e=>"forming"===e?.status);if(t){let r=zu(i,t.id),n=Fu(e.id,17)*Math.PI*2,o=Math.max(5,Math.min(18,.026*i.layout.width));a={x:r.x+Math.cos(n)*o,y:r.y+Math.sin(n)*o}}}let h=o.semanticId,p=Fu(h,23)*Math.PI*2,m=a.x>=i.layout.chamber.x&&a.x<=i.layout.chamber.x+i.layout.chamber.width&&a.y>=i.layout.chamber.y&&a.y<=i.layout.chamber.y+i.layout.chamber.height;if(!r.complete&&m)if("mix"===c){let e=Math.min(34,.1*i.layout.chamber.width)*d,t=Math.min(24,.09*i.layout.chamber.height)*d;a={x:a.x+Math.cos(u*(1.4+Fu(h,29))+p)*e,y:a.y+Math.sin(u*(1.8+Fu(h,31))+p)*t}}else if("press"===c){let e=i.layout.chamber.x+i.layout.chamber.width/2,t=i.layout.chamber.y+.56*i.layout.chamber.height;a={x:e+(a.x-e)*Math.max(.3,1-.32*d),y:t+(a.y-t)*Math.max(.35,1-.26*d)}}else if("separate"===c){let e=Fu(h,41)<.5?-1:1;a={x:a.x+e*Math.min(28,.075*i.layout.chamber.width)*d,y:a.y}}else if("bind"===c){let e=i.layout.chamber.x+i.layout.chamber.width/2,t=i.layout.chamber.y+.5*i.layout.chamber.height;a={x:e+.72*(a.x-e),y:t+.72*(a.y-t)}}else"charge"===c?a={x:a.x,y:a.y+4*Math.sin(2*u+p)*d}:"quench"===c&&(a={x:a.x+2*Math.sin(p)*d,y:a.y});return a}function Lu(e){let t=Hu(e);if(!t)return null;let{body:i,state:r}=e,n=t.x-i.x,o=t.y-i.y,s=Math.hypot(n,o),a=Math.hypot(i.vx,i.vy);if(r.complete&&s<.7&&a<.45)return null;let l=!r.complete&&"pour"===Wu(e.plan,r)?.motion,d=r.complete?.68:l?.72:.5,c=r.complete?.22:l?.18:.14,u=r.complete?42:l?72:56;return{x:Math.max(-u,Math.min(u,n*d-i.vx*c)),y:Math.max(-u,Math.min(u,o*d-i.vy*c))}}import*as Yu from"react";import{jsx as _u,jsxs as Xu}from"react/jsx-runtime";function Gu(e){return Number.isFinite(e)?Math.abs(e)>=1e3?e.toLocaleString():Number.isInteger(e)?String(e):e.toFixed(2).replace(/\.00$/,"").replace(/(\.\d)0$/,"$1"):"0"}function Vu(e){let t=e.productIds.length?` Contributes to ${e.productIds.join(", ")}.`:e.outletId?` Routed to ${e.outletId}.`:"",i=e.reason?` ${e.reason}.`:"";return`${Gu(e.amount)} amount; ${e.status}.${t}${i}`}function Uu(e){let t=e.outletId?` Routed to ${e.outletId}.`:"";return`${e.status} product with ${e.sourceIds.length} source${1===e.sourceIds.length?"":"s"} and ${Gu(e.amount)} amount.${t}`}function Ku(e,t){let i=e.datum;if(!i?.__crucible)return!1;if("component"===i.kind){let e=t.components[i.semanticId];return!!e&&{id:`crucible-component-${e.id}`,label:e.label,description:Vu(e),group:`source component · ${e.status}`,datum:e}}let r=t.products[i.semanticId];return!!r&&{id:`crucible-product-${r.id}`,label:r.label,description:Uu(r),group:`derived product · ${r.status}`,datum:r}}function Qu(e,t,i,r){let n=t.datum;if(!n?.__crucible)return;let o="circle"===t.shape.type?t.shape.radius:8,s="product"===n.kind?"#b8792d":"#356b63",a=r?.resolvePaint??((t,i)=>Ie(e,t,i)),l=a(i.fill,s),d=a(i.stroke,"#26323a");if(e.save(),e.translate(t.x,t.y),e.globalAlpha="number"==typeof i.opacity?i.opacity:.96,e.fillStyle=l,e.strokeStyle=d,e.lineWidth="number"==typeof i.strokeWidth?i.strokeWidth:1.25,"product"===n.kind){e.shadowColor="string"==typeof l?l:s,e.shadowBlur=10,e.beginPath();for(let t=0;t<6;t+=1){let i=-Math.PI/2+t/6*Math.PI*2,r=Math.cos(i)*o,n=Math.sin(i)*o;0===t?e.moveTo(r,n):e.lineTo(r,n)}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=a("var(--semiotic-bg, #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()}function Ju(e,t,i){let r=/* @__PURE__ */new Map;for(let e of t){let t=e.datum;t?.__crucible&&r.set(`${t.kind}:${t.semanticId}`,e)}e.save(),e.lineCap="round";for(let t of Object.values(i.relations)){if("active"!==t.status)continue;let i=t.sourceIds.map(e=>r.get(`component:${e}`)).filter(e=>!!e);i.length<2||(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(),i.forEach((t,i)=>{0===i?e.moveTo(t.x,t.y):e.lineTo(t.x,t.y)}),e.stroke())}e.setLineDash([]);for(let t of Object.values(i.products)){let i=r.get(`product:${t.id}`);if(i)for(let n of t.sourceIds){let o=r.get(`component:${n}`);o&&(e.strokeStyle=t.color??"#b8792d",e.globalAlpha="complete"===t.status?.5:.28,e.lineWidth="complete"===t.status?1.6:1,e.beginPath(),e.moveTo(o.x,o.y),e.lineTo(i.x,i.y),e.stroke())}}e.restore()}import{Fragment as Zu,jsx as eh,jsxs as th}from"react/jsx-runtime";var ih="var(--semiotic-text, #26323a)",rh="var(--semiotic-text-secondary, #6c7377)",nh="var(--semiotic-primary, #b8792d)",oh="var(--semiotic-danger, #9f3d35)",sh="var(--semiotic-success, #356b63)";function ah(e,t){let i=e.data;if(!i?.__crucible)return null;let r="component"===i.kind?t.components[i.semanticId]:t.products[i.semanticId];if(!r)return null;let n="product"===i.kind;/* @__PURE__ */
|
|
131
|
-
return
|
|
132
|
-
/* @__PURE__ */
|
|
133
|
-
/* @__PURE__ */
|
|
134
|
-
/* @__PURE__ */
|
|
135
|
-
return
|
|
136
|
-
/* @__PURE__ */
|
|
137
|
-
/* @__PURE__ */
|
|
138
|
-
/* @__PURE__ */
|
|
139
|
-
/* @__PURE__ */
|
|
140
|
-
/* @__PURE__ */
|
|
141
|
-
/* @__PURE__ */
|
|
142
|
-
/* @__PURE__ */
|
|
143
|
-
/* @__PURE__ */
|
|
144
|
-
/* @__PURE__ */
|
|
145
|
-
return
|
|
146
|
-
/* @__PURE__ */
|
|
147
|
-
/* @__PURE__ */
|
|
148
|
-
return
|
|
149
|
-
return
|
|
150
|
-
/* @__PURE__ */
|
|
151
|
-
/* @__PURE__ */
|
|
152
|
-
/* @__PURE__ */
|
|
153
|
-
return
|
|
154
|
-
/* @__PURE__ */
|
|
155
|
-
/* @__PURE__ */
|
|
156
|
-
/* @__PURE__ */
|
|
157
|
-
/* @__PURE__ */
|
|
158
|
-
/* @__PURE__ */
|
|
159
|
-
/* @__PURE__ */
|
|
160
|
-
/* @__PURE__ */
|
|
161
|
-
/* @__PURE__ */
|
|
162
|
-
/* @__PURE__ */
|
|
163
|
-
/* @__PURE__ */
|
|
164
|
-
/* @__PURE__ */
|
|
165
|
-
/* @__PURE__ */Sh(yo,{...h,...ot,...lt,key:`${oe[0]}x${oe[1]}:${de}:${ke}:${qe.rerunKey}:${pe?me:"replay"}`,ref:F,onBodyHover:at,accessibleTable:e.accessibleTable??h.accessibleTable,backgroundGraphics:dt,bodyForces:Ue,bodySemanticItems:Ze,bodyStyle:Je,beforePaint:tt,config:qe.config,continuous:!pe&&xe&&!$&&!ge.state.complete,enableHover:ot.enableHover??ie,foregroundGraphics:ct,hoverRadius:e.hoverRadius??h.hoverRadius??18,initialSpawns:ht,initialSpawnPacing:y,onClick:w?et:lt.onClick,onTick:Ve,paused:We,renderBody:h.renderBody??Qu,responsiveHeight:!1,responsiveWidth:!1,seed:fh(O),size:oe,tooltipContent:ot.tooltipContent??ut})]}))}),"CrucibleChart");function Ah(e,t){let i=/* @__PURE__ */new Map;for(let t of e)i.set(t.id,/* @__PURE__ */new Set);for(let e of t)i.has(e.source)||i.set(e.source,/* @__PURE__ */new Set),i.has(e.target)||i.set(e.target,/* @__PURE__ */new Set),i.get(e.source).add(e.target);return i}function $h(e,t,i={}){let r=/* @__PURE__ */new Set,n=[...e.get(t)??[]];for(let t=0;t<n.length;t++){let i=n[t];r.has(i)||(r.add(i),n.push(...e.get(i)??[]))}return i.includeStart&&r.add(t),r}function Ch(e,t,i){return J(i,e,t)}function Ph(e,t){return e<t?-1:e>t?1:0}function Rh(e,t){return`dependency:${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Dh(e,t){return`socket:${encodeURIComponent(e)}:${t}`}function Bh(e){let t=Number(e);return Number.isFinite(t)?Math.max(0,Math.min(1,t)):0}function Th(e){let t=[],i=/* @__PURE__ */new Map,r=[],n=/* @__PURE__ */new Set;e.data.forEach((o,s)=>{let a=String(Ch(o,s,e.taskIDAccessor)??"");if(!a)return void t.push({code:"duplicate-task-id",message:`Task row ${s} has an empty id.`,taskIDs:[]});if(i.has(a))return void t.push({code:"duplicate-task-id",message:`Task id "${a}" occurs more than once.`,taskIDs:[a]});let l=String(Ch(o,s,e.laneAccessor)??"Unassigned");n.has(l)||(n.add(l),r.push(l));let d=Ch(o,s,e.dependencyAccessor)??[],c=Array.from(new Set(Array.from(d,e=>String(e)))).sort(Ph),u=Ch(o,s,e.blockerAccessor),h=Ch(o,s,e.statusAccessor)??(u?"blocked":"waiting");i.set(a,{id:a,label:String(Ch(o,s,e.labelAccessor)??a),lane:l,laneIndex:0,level:0,index:s,datum:o,dependencyIDs:c,incomingEdgeIDs:[],outgoingEdgeIDs:[],socketIDs:[],start:Ch(o,s,e.startAccessor),end:Ch(o,s,e.endAccessor),progress:Bh(Ch(o,s,e.progressAccessor)),status:h,completionTime:Ch(o,s,e.completionTimeAccessor),blockerReason:u||void 0,milestone:!!Ch(o,s,e.milestoneAccessor)})});let o=e.laneOrder?[...e.laneOrder,...r.filter(t=>!e.laneOrder?.includes(t))]:r,s=new Map(o.map((e,t)=>[e,t]));for(let e of i.values())e.laneIndex=s.get(e.lane)??0;let a=/* @__PURE__ */new Map,l=/* @__PURE__ */new Map;for(let e of i.keys())a.set(e,[]),l.set(e,[]);let d=[],c=[...i.values()].sort((e,t)=>e.index-t.index);for(let e of c)e.dependencyIDs.forEach((r,n)=>{let o=i.get(r);if(!o)return void t.push({code:"missing-dependency",message:`Task "${e.id}" depends on missing task "${r}".`,taskIDs:[e.id,r]});let s={id:Rh(r,e.id),sourceID:r,targetID:e.id,sourceIndex:o.index,targetIndex:e.index,socketID:Dh(e.id,n),socketIndex:n};d.push(s),a.get(e.id)?.push(s),l.get(r)?.push(s),e.incomingEdgeIDs.push(s.id),e.socketIDs.push(s.socketID),o.outgoingEdgeIDs.push(s.id)});for(let e of a.values())e.sort((e,t)=>Ph(e.sourceID,t.sourceID)),e.forEach((e,t)=>{e.socketIndex=t,e.socketID=Dh(e.targetID,t)});for(let e of l.values())e.sort((e,t)=>Ph(e.targetID,t.targetID));for(let e of i.values()){let t=a.get(e.id)??[];e.incomingEdgeIDs=t.map(e=>e.id),e.socketIDs=t.map(e=>e.socketID),e.outgoingEdgeIDs=(l.get(e.id)??[]).map(e=>e.id)}let u=/* @__PURE__ */new Map,h=/* @__PURE__ */new Map;for(let e of i.keys())u.set(e,a.get(e)?.length??0),h.set(e,0);let p=[...i.keys()].filter(e=>0===u.get(e)).sort(Ph),m=0;for(;p.length;){let e=p.shift();m+=1;for(let t of l.get(e)??[]){let i=Math.max(h.get(t.targetID)??0,(h.get(e)??0)+1);h.set(t.targetID,i);let r=(u.get(t.targetID)??0)-1;if(u.set(t.targetID,r),0===r){let e=p.findIndex(e=>e>t.targetID);e<0?p.push(t.targetID):p.splice(e,0,t.targetID)}}}if(m!==i.size){let e=[...i.keys()].filter(e=>(u.get(e)??0)>0).sort(Ph);t.push({code:"cycle",message:`Dependency graph contains a cycle involving: ${e.join(", ")}.`,taskIDs:e})}let y=0,f=[...i.values()].sort((e,t)=>e.index-t.index);for(let e of f)e.level=h.get(e.id)??0,y=Math.max(y,e.level);return{nodes:f,edges:d,byID:i,incoming:a,outgoing:l,lanes:o,maxLevel:y,diagnostics:t,valid:0===t.length}}function jh(e){return e.filter((t,i)=>{let r=e[i-1];return!r||r.x!==t.x||r.y!==t.y})}function Oh(e,t,i={}){let r=Math.max(240,t.width),n=Math.max(220,t.height),o=t.paddingX??48,s=t.paddingTop??48,a=t.paddingBottom??44,l=Math.max(1,e.lanes.length),d=Math.max(70,(r-2*o)/l),c=Math.max(1,e.maxLevel+1),u=Math.max(76,(n-s-a)/c),h=Math.min(i.taskWidth??112,Math.max(58,.78*d)),p=Math.min(i.taskHeight??58,.64*u),m=i.socketRadius??5,y=Math.max(1,Math.round(i.gutterCount??3)),f=/* @__PURE__ */new Map;for(let t of e.nodes){let e=`${t.laneIndex}:${t.level}`,i=f.get(e)??[];i.push(t),f.set(e,i)}for(let e of f.values())e.sort((e,t)=>Ph(e.id,t.id));let g=.86*u,b=e=>e<=1?p:Math.max(22,Math.min(p,(g-4*(e-1))/e)),v=e.nodes.map(e=>{let t=f.get(`${e.laneIndex}:${e.level}`)??[e],i=Math.max(0,t.findIndex(t=>t.id===e.id))-(t.length-1)/2,r=b(t.length),n=i*(r+4);return{taskID:e.id,lane:e.lane,laneIndex:e.laneIndex,level:e.level,x:o+d*(e.laneIndex+.5),y:s+u*(e.level+.5)+n,width:h,height:r}}),x=new Map(v.map(e=>[e.taskID,e])),w=[],I=[];e.edges.forEach((t,i)=>{let r=x.get(t.sourceID),n=x.get(t.targetID);if(!r||!n)return;let o=e.incoming.get(t.targetID)??[],s=Math.min(.72*n.width,14*Math.max(1,o.length-1)),a=o.length<=1?n.x:n.x-s/2+s*t.socketIndex/(o.length-1),l=n.y-n.height/2-m-2,d={id:t.socketID,edgeID:t.id,taskID:n.taskID,index:t.socketIndex,x:a,y:l,radius:m};w.push(d);let c={x:r.x,y:r.y+r.height/2+3},u=Math.max(18,l-c.y),h=7*(i%y-(y-1)/2),p=Math.min(l-10,c.y+.48*u+h);I.push({edgeID:t.id,sourceID:t.sourceID,targetID:t.targetID,socketID:t.socketID,points:jh([c,{x:c.x,y:p},{x:a,y:p},{x:a,y:l}])})});let k=new Map(w.map(e=>[e.id,e])),S=new Map(I.map(e=>[e.edgeID,e]));return{tasks:v,sockets:w,routes:I,taskByID:x,socketByID:k,routeByEdgeID:S}}function Eh(e,t,i="all"){let r=Array.from(new Set(t)).sort(Ph),n=/* @__PURE__ */new Set,o=()=>r.every(e=>n.has(e));return{taskID:e,mode:i,incomingEdgeIDs:r,deliver:e=>(r.includes(e)&&n.add(e),o()),reset:(e=[])=>{n.clear();for(let t of e)r.includes(t)&&n.add(t)},isSatisfied:o,getSnapshot:()=>({taskID:e,mode:i,incomingEdgeIDs:[...r],deliveredEdgeIDs:[...n].sort(Ph),satisfied:o()})}}function Nh(e){return e instanceof Date?e.getTime():Number(e)}function Fh(e,t){let i=Nh("object"!=typeof t||t instanceof Date?t:t.currentTime),r=e.map((e,t)=>({event:e,index:t,time:Nh(e.at)})).filter(e=>Number.isFinite(e.time)&&e.time<=i).sort((e,t)=>e.time-t.time||e.index-t.index),n=/* @__PURE__ */new Set,o=/* @__PURE__ */new Map,s=/* @__PURE__ */new Set,a=/* @__PURE__ */new Set;for(let{event:e}of r)"task-completed"===e.type?(n.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:i,appliedEvents:r.map(e=>e.event),completedTaskIDs:n,blockedByTaskID:o,deliveredEdgeIDs:s,armedTaskIDs:a}}function Wh(e,t,i={}){let r=new Set(i.completedTaskIDs??[]),n=[...$h(Ah(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=>!(i.isComplete?i.isComplete(e):r.has(e.id)||"done"===e.status)).sort((e,t)=>e.index-t.index),o=Array.from(new Set(n.map(e=>e.lane)));return{blockerID:t,downstreamTaskCount:n.length,affectedLaneCount:o.length,downstreamTaskIDs:n.map(e=>e.id),affectedLanes:o}}import{forwardRef as qh,useCallback as zh,useEffect as Hh,useImperativeHandle as Lh,useMemo as Yh,useRef as _h,useState as Xh}from"react";var Gh=[];function Vh(e,t=0){if(e instanceof Date)return e.getTime();let i=Number(e);return Number.isFinite(i)?i:t}function Uh(e){if(null==e.completionTime)return null;let t=Vh(e.completionTime,Number.NaN);return Number.isFinite(t)?t:null}function Kh(e,t,i,r){let n=/* @__PURE__ */new Set;for(let o of e.nodes){let s=e.incoming.get(o.id)??[];(r.has(o.id)||!i.has(o.id)&&s.every(e=>t.has(e.id)))&&n.add(o.id)}return n}function Qh(e,t,i,r){let n=e.nodes.map(Uh).filter(e=>null!=e),o=n.length?n.reduce((e,t)=>Math.min(e,t),1/0)-1:0,s="replay"!==t||r?i:o,a=/* @__PURE__ */new Set,l=/* @__PURE__ */new Map;for(let i of e.nodes){let e=Uh(i),r=null!=e&&e<=s,n="done"===i.status&&"replay"!==t;(r||n)&&a.add(i.id),i.blockerReason&&!a.has(i.id)&&l.set(i.id,i.blockerReason)}let d=/* @__PURE__ */new Set;if("replay"!==t||r)for(let t of e.edges)a.has(t.sourceID)&&d.add(t.id);return{currentTime:s,playing:!1,completed:a,delivered:d,inFlight:/* @__PURE__ */new Set,armed:Kh(e,d,l,a),blockers:l,previewTaskID:null}}function Jh(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 Zh(e){let t=0;for(let i=1;i<e.length;i+=1)t+=Math.hypot(e[i].x-e[i-1].x,e[i].y-e[i-1].y);return t}function ep(e,t){if(e.length<2)return{point:e[0]??{x:0,y:0},tangent:{x:0,y:1}};let i=0;for(let r=1;r<e.length;r+=1){let n=e[r-1],o=e[r],s=o.x-n.x,a=o.y-n.y,l=Math.hypot(s,a);if(!(l<=0)){if(i+l>=t){let e=Math.max(0,Math.min(1,(t-i)/l));return{point:{x:n.x+s*e,y:n.y+a*e},tangent:{x:s/l,y:a/l}}}i+=l}}let r=e[e.length-2],n=e[e.length-1],o=n.x-r.x,s=n.y-r.y,a=Math.hypot(o,s)||1;return{point:n,tangent:{x:o/a,y:s/a}}}function tp(e,t){let i=Number.POSITIVE_INFINITY,r=0,n=0;for(let o=1;o<t.length;o+=1){let s=t[o-1],a=t[o],l=a.x-s.x,d=a.y-s.y,c=l*l+d*d,u=Math.sqrt(c);if(u<=0)continue;let h=Math.max(0,Math.min(1,((e.x-s.x)*l+(e.y-s.y)*d)/c)),p=s.x+l*h,m=s.y+d*h,y=Math.hypot(e.x-p,e.y-m);y<i&&(i=y,r=n+h*u),n+=u}return r}function ip(e){let t=e.datum;return"dependency-ball"===t?.kind&&Array.isArray(t.route)?t:null}function rp(e){let t=ip(e.body);if(!t||t.route.length<2)return null;let i=Zh(t.route),r=tp(e.body,t.route),n=ep(t.route,Math.min(i,r+22)),o=78*n.tangent.x,s=78*n.tangent.y;return{x:2.5*(o-e.body.vx)+8*(n.point.x-e.body.x),y:2.5*(s-e.body.vy)+8*(n.point.y-e.body.y)}}function np(e,t,i){let r=t.points[0]??{x:0,y:0},n=t.points[1]??r,o=n.x-r.x,s=n.y-r.y,a=Math.hypot(o,s)||1;return{id:`dependency-ball:${e.id}`,x:r.x,y:r.y,vx:o/a*42,vy:s/a*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,...i?{sourceDatum:i}:{}}}}function op(e,t,i){return e.nodes.flatMap(r=>{let n=t.taskByID.get(r.id);if(!n)return[];let o=e.incoming.get(r.id)??[],s=o.filter(e=>i.delivered.has(e.id)).length,a=i.blockers.get(r.id),l=i.completed.has(r.id)?"completed":a?`blocked: ${a}`:i.armed.has(r.id)?"armed":"waiting";return[{id:r.id,label:`${r.label}, ${r.lane}, ${Math.round(100*r.progress)}%, ${l}`,description:`${s} of ${o.length} prerequisites delivered.`,datum:r.datum,x:n.x,y:n.y,width:n.width,height:n.height,shape:"rect",group:r.lane}]})}import{jsx as sp,jsxs as ap}from"react/jsx-runtime";function lp(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-text-secondary, #75818a)"}function dp({machine:e,layout:t,runtime:i,downstreamSet:r,selectedSet:n,width:o,height:s,seed:a,reduced:l,onSelectTask:d}){let c=t.tasks.length?t.tasks.reduce((e,t)=>Math.min(e,t.y-t.height/2),1/0):60,u=Math.max(20,c-12),h=Math.max(26,c-6);/* @__PURE__ */
|
|
166
|
-
return
|
|
167
|
-
/* @__PURE__ */
|
|
168
|
-
return
|
|
169
|
-
/* @__PURE__ */
|
|
170
|
-
/* @__PURE__ */
|
|
171
|
-
return
|
|
172
|
-
return
|
|
173
|
-
/* @__PURE__ */
|
|
174
|
-
return
|
|
175
|
-
/* @__PURE__ */
|
|
176
|
-
/* @__PURE__ */
|
|
177
|
-
/* @__PURE__ */
|
|
178
|
-
/* @__PURE__ */
|
|
179
|
-
/* @__PURE__ */
|
|
180
|
-
/* @__PURE__ */
|
|
181
|
-
/* @__PURE__ */
|
|
182
|
-
/* @__PURE__ */
|
|
183
|
-
/* @__PURE__ */
|
|
184
|
-
return
|
|
185
|
-
/* @__PURE__ */
|
|
186
|
-
/* @__PURE__ */
|
|
187
|
-
/* @__PURE__ */
|
|
188
|
-
/* @__PURE__ */
|
|
189
|
-
/* @__PURE__ */
|
|
190
|
-
/* @__PURE__ */
|
|
191
|
-
/* @__PURE__ */
|
|
192
|
-
/* @__PURE__ */
|
|
193
|
-
/* @__PURE__ */
|
|
194
|
-
return
|
|
195
|
-
/* @__PURE__ */
|
|
196
|
-
/* @__PURE__ */
|
|
197
|
-
/* @__PURE__ */
|
|
198
|
-
/* @__PURE__ */
|
|
199
|
-
/* @__PURE__ */
|
|
200
|
-
/* @__PURE__ */
|
|
201
|
-
return
|
|
202
|
-
/* @__PURE__ */
|
|
203
|
-
/* @__PURE__ */
|
|
204
|
-
/* @__PURE__ */
|
|
205
|
-
/* @__PURE__ */
|
|
206
|
-
/* @__PURE__ */
|
|
41
|
+
/* @__PURE__ */ro(Le,{width:Mt,height:At,totalWidth:wt[0],totalHeight:wt[1],margin:ut,title:$e,legend:F,legendPosition:Y,legendLayout:L,legendHoverBehavior:H,legendClickBehavior:W,legendHighlightedCategory:q,legendIsolatedCategories:z,pointNodes:oi,annotations:r,onAnnotationActivate:n,onObservation:G,chartId:y,chartType:lo,autoPlaceAnnotations:o,svgAnnotationRules:Ae}),
|
|
42
|
+
/* @__PURE__ */ro(ce,{active:null!=Qt,hoverPoint:Qt?{x:Qt.x,y:Qt.y}:null,margin:ut,size:wt,shape:Qt?.shape,width:Qt?.width,height:Qt?.height,pathData:Qt?.pathData}),Di]})]})})),"StreamPhysicsFrame"),yo=mo;import{scaleLinear as fo}from"d3-scale";function go(e){let{data:t,valueAccessor:r,bins:n,ballRadius:s,seed:d,size:c,valueExtent:h}=e,{rows:m}=p(t,"galton"),y=i(c),f=m.map((e,t)=>l(a(e,t,r))).filter(e=>null!=e),g=u(h),[b,v]=g??(f.length?Te(f):[0,1]),x=v===b?1:v-b,w=fo().domain([0,n]).range([y.plot.x,y.plot.x+y.plot.width]),I=Array.from({length:n},()=>0),k=[];m.forEach((e,t)=>{let i=l(a(e,t,r));if(null==i)return;let o=Math.max(0,Math.min(n-1,Math.floor((i-b)/x*n)));I[o]+=1,k.push({id:String(e.id??`galton-${t}`),x:w(o+.5),y:y.plot.y+s+2,vx:8*(t%5-2),vy:0,mass:1,shape:{type:"circle",radius:s},datum:{...e,value:i,bin:o}})});let S=y.plot.y+y.plot.height,M=[...ci({x:y.plot.x,y:y.plot.y,width:y.plot.width,height:y.plot.height},{idPrefix:"galton",wallThickness:20,floorThickness:20}),...ui({idPrefix:"galton-bin",count:n,domainStart:0,domainStep:1,xScale:w,yTop:y.plot.y-400,yBottom:S,wallThickness:6})];return{config:o(d,M,"GaltonBoardChart"),initialSpawns:k,initialSpawnPacing:{pacing:{ratePerSec:55}},projectionRows:I.map((e,t)=>({label:String(t+1),value:e})),metadata:{kind:"galton-board",bins:n,plot:y.plot,valueExtent:[b,v]}}}import{scaleLinear as bo}from"d3-scale";function vo(e,t){let i=Math.max(5*t,Math.min(92,.13*e.plot.width));return{gutter:{x:e.plot.x,y:e.plot.y,width:i,height:e.plot.height},windowPlot:{x:e.plot.x+i,y:e.plot.y,width:Math.max(40,e.plot.width-i),height:e.plot.height},wallTop:e.plot.y+.48*e.plot.height}}function xo(e,t){let i=Math.max(0,Math.min(e.windowCount,e.closedWindowCount));if(!i)return[];let r=e.windowStart,n=e.windowStart+e.windowCount*e.windowSize,o=bo().domain([r,n]).range([e.windowPlot.x,e.windowPlot.x+e.windowPlot.width]),s=o(e.windowStart+i*e.windowSize),a=e.windowPlot.x,l=Math.max(18,Math.min(.3*e.windowPlot.height,s-a)),d=t+l,c=e=>s===a?t:d+(e-a)/(s-a)*(t-d),u=[];for(let t=0;t<i;t+=1){let i=e.windowStart+t*e.windowSize,r=i+e.windowSize,n=o(i),s=o(r);u.push({id:`eventdrop-lid-${t}`,windowIndex:t,x1:n,y1:c(n),x2:s,y2:c(s)})}return u}function wo(e){let{count:t,idPrefix:i,wallThickness:r,xScale:n,yBottom:o,yTop:s,yTopForIndex:a}=e;return Array.from({length:t+1},(e,t)=>{let l=Math.min(o-1,a?.(t)??s),d=Math.max(1,o-l);return{id:`${i}-wall-${t}`,shape:{type:"aabb",x:n(t),y:l+d/2,width:r,height:d}}})}function Io(e){let{data:t,timeAccessor:r,arrivalAccessor:n,windows:s,watermark:a,watermarkAtArrivalAccessor:d,ballRadius:c,seed:u,size:h,timeExtent:p,timeScale:m=1}=e,{events:y,watermarkValue:f}=g({data:t,timeAccessor:r,arrivalAccessor:n,watermark:a,watermarkAtArrivalAccessor:d,windowSize:s.size}),b=i(h),v=y.length?1/0:0,x=y.length?1/0:0,w=y.length?-1/0:s.size;for(let e of y)v=Math.min(v,e.arrivalTime),x=Math.min(x,e.eventTime),w=Math.max(w,e.eventTime);let I=l(p?.[0]),k=l(p?.[1]),S=Math.min(I??x,x),M=Math.max(k??w,w),A=Math.floor(S/s.size)*s.size,$=Math.max(1,Math.ceil((M-A+s.size)/s.size)),C=vo(b,c),P=A+$*s.size,R=bo().domain([A,P]).range([C.windowPlot.x,C.windowPlot.x+C.windowPlot.width]),D=0,B=Array.from({length:$},(e,t)=>(A+(t+1)*s.size<=f&&D++,{value:0,secondary:0})),T=[];y.forEach(({datum:e,index:t,eventTime:i,arrivalTime:r,watermarkAtArrival:n,late:o})=>{let a=Math.max(0,Math.min($-1,Math.floor((i-A)/s.size)));B[a].value+=o?0:1,B[a].secondary+=o?1:0,T.push({id:String(e.id??`event-${t}`),x:Mo(i,a,o,{windowStart:A,windowSize:s.size,gutter:C.gutter,closedWindowCount:D,windowPlot:C.windowPlot,windowCount:$},c),y:b.plot.y+c+2,vx:0,vy:0,mass:1,friction:.02,spawnAt:r,shape:{type:"circle",radius:c},datum:{...e,eventTime:i,arrivalTime:r,windowIndex:a,watermarkAtArrival:n,late:o}})});let j=b.plot.y+b.plot.height,O=b.plot.y+.28*b.plot.height,E={closedWindowCount:D,gutter:C.gutter,plot:b.plot,windowCount:$,windowPlot:C.windowPlot,windowSize:s.size,windowStart:A},N=xo(E,O);for(let e of T){let t=e.datum;e.y=ko({...E,lidSegments:N},t.windowIndex,t.late,c)}let F=e=>{if(e<0||e>D)return null;let t=0===e?N[0]?.y1:N[e-1]?.y2??N[e]?.y1;return"number"==typeof t&&Number.isFinite(t)?t:null},W=wo({idPrefix:"eventdrop-window",count:$,xScale:e=>R(A+e*s.size),yTop:C.wallTop,yTopForIndex:e=>{let t=F(e);return null==t?C.wallTop:t+1.25*c},yBottom:j,wallThickness:6}),q=[...ci({x:b.plot.x,y:b.plot.y,width:b.plot.width,height:b.plot.height},{idPrefix:"eventdrop",wallThickness:20,floorThickness:20}),...W,...N.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*c)},friction:.02,restitution:.01}))];return{config:o(u,q,"EventDropChart",{friction:.08}),initialSpawns:T,initialSpawnPacing:{pacing:"arrival",timeAccessor:e=>{let t=e.datum,i=t.windowIndex<D;return i&&!t.late||!i&&t.late?v:t.arrivalTime},timeScale:m},projectionRows:B.map((e,t)=>({label:`${A+t*s.size}-${A+(t+1)*s.size}`,value:e.value,secondary:e.secondary})),metadata:{kind:"event-drop",closedWindowCount:D,gutter:C.gutter,lidSegments:N,lateCount:B.reduce((e,t)=>e+t.secondary,0),plot:b.plot,windowPlot:C.windowPlot,windowWalls:W.map(({id:e,shape:t})=>({id:e,x:t.x-t.width/2,y:t.y-t.height/2,width:t.width,height:t.height})),watermarkValue:f,windowCount:$,windowSize:s.size,windowStart:A}}}function ko(e,t,i,r){let{windowPlot:n,lidSegments:o}=e,s=o[t];return i&&!s?Math.min(n.y+n.height-r,n.y+.48*n.height+2*r+4):!i&&s?Math.min(n.y+n.height-r,Math.max(s.y1,s.y2)+2*r+4):n.y+r+2}function So(e,t){let{windowPlot:i,gutter:r,windowCount:n,lidSegments:o}=e,s=Array(n).fill(0),a=i.y+i.height,l=i.y+.48*i.height,d=0,c=0;for(let e of t){if(e.x>=r.x&&e.x<i.x&&e.y>=(o[0]?.y1??l)&&e.y<=a){d++;continue}let t=Math.floor((e.x-i.x)/i.width*n),u=o[t],h=u?Math.max(u.y1,u.y2):l;t>=0&&t<n&&e.y>=h&&e.y<=a?s[t]++:c++}return{accepted:s,late:d,inFlight:c,total:t.length}}function Mo(e,t,i,r,n){let{windowPlot:o,windowCount:s,windowStart:a,windowSize:l}=r;if(i&&t>=r.closedWindowCount)return r.gutter.x+r.gutter.width/2;let d=o.width/s,c=i?o.x:o.x+t*d,u=i?o.x+o.width:c+d,h=Math.min((u-c)/2,n+(i?0:3)),p=o.x+(e-a)/l*d;return Math.max(c+h,Math.min(u-h,p))}function Ao(e,t,i){let r=Math.max(1,t),n=e.width/r,o=Math.max(2,2*i),s=Math.min(.7*n,Math.max(3.2*o,o+8)),a=Math.max(1,Math.floor(s/o));return{laneWidth:n,tubeWidth:s,ballDiameter:o,perRow:a,centerX:t=>e.x+(t+.5)*n,pileHeight:e=>Math.ceil(Math.max(0,e)/a)*o}}function $o(e){let{data:t,categoryAccessor:r,valueAccessor:n,unitValue:s,ballRadius:d,seed:u,size:h}=e,m=c(s,1),{rows:f}=p(t,"pile"),g=i(h),b=[],v=/* @__PURE__ */new Map,x=/* @__PURE__ */new Map,w=[];function I(e){let t=v.get(e);return null==t&&(t=b.length,b.push(e),v.set(e,t)),t}f.forEach((e,t)=>{I(String(a(e,t,r)??"unknown"))});let k=Math.max(1,b.length),S=Ao(g.plot,k,d),M=Math.max(0,S.tubeWidth/2-d-1),A=b.map(()=>[]);f.forEach((e,t)=>{let i=String(a(e,t,r)??"unknown"),o=I(i),s=n?l(a(e,t,n)):1,c=Math.max(0,s??0);x.set(i,(x.get(i)??0)+c);let u=y(c,m),h=S.centerX(o);for(let r=0;r<u;r+=1){let n=A[o].length,s=r===u-1?c-r*m:m,a=Math.min(1,s/m),l=S.perRow>1?n%S.perRow:0,p=S.perRow>1?(l/(S.perRow-1)*2-1)*M:0;A[o].push({id:`${String(e.id??`pile-${t}`)}-${r}`,x:h+p,y:g.plot.y+d+2,vx:(r%3-1)*d/2,vy:0,mass:1,shape:{type:"circle",radius:d*Math.sqrt(a)},datum:{...e,category:i,unitIndex:r,unitValue:m,representedValue:s,unitFraction:a}})}});let $=A.reduce((e,t)=>Math.max(e,t.length),0);for(let e=0;e<$;e+=1)for(let t of A)e<t.length&&w.push(t[e]);let C=g.plot.y+g.plot.height,P=[...ci({x:g.plot.x,y:g.plot.y,width:g.plot.width,height:g.plot.height},{idPrefix:"pile",wallThickness:20,floorThickness:20})],R=g.plot.y-400;for(let e=0;e<k;e+=1){let t=S.centerX(e);for(let i of[-1,1])P.push({id:`pile-tube-${e}-${i<0?"l":"r"}`,shape:{type:"aabb",x:t+i*(S.tubeWidth+6)/2,y:(R+C)/2,width:6,height:C-R}})}return{config:o(u,P,"UnitPileChart"),initialSpawns:w,initialSpawnPacing:{pacing:{ratePerSec:20}},projectionRows:b.map(e=>({label:e,value:x.get(e)??0}))}}import{scaleLinear as Co}from"d3-scale";function Po(e,t,i,r){let n=(t+i)/2,o=[];for(let s of e){let a=o.filter(e=>Math.abs(s.x-e.x)<s.radius+e.radius+.5),l=[n];for(let e of a){let t=s.radius+e.radius+.5,i=Math.sqrt(t**2-(s.x-e.x)**2);l.push(e.y-i,e.y+i)}let d=r()<.5?-1:1;l.sort((e,t)=>Math.abs(e-n)-Math.abs(t-n)||d*(e-t));let c=l.find(e=>e-s.radius>=t&&e+s.radius<=i&&a.every(t=>(s.x-t.x)**2+(e-t.y)**2>=(s.radius+t.radius+.5)**2-1e-6));if(null==c){let r=e.reduce((e,t)=>Math.max(e,t.radius),-1/0),o=Math.max(0,i-t-2*r);return{positions:e.map((t,i)=>n+(1===e.length?0:i/(e.length-1)-.5)*o),overlapping:!0,entryOffset:0}}o.push({...s,y:c})}return{positions:o.map(e=>e.y),overlapping:!1,entryOffset:Math.max(0,o.reduce((e,i)=>Math.min(e,i.y-i.radius-t),36))}}function Ro(e){let{data:t,xAccessor:r,groupAccessor:n,radiusAccessor:s,pointRadius:c,seed:u,size:h,xExtent:m,collisionIterations:y,settle:f}=e,{rows:g}=p(t,"collision-swarm"),v=i(h),x=b(u),w=[],I=[],k=/* @__PURE__ */new Map;function S(e){let t=k.get(e);return null==t&&(t=I.length,I.push(e),k.set(e,t)),t}g.forEach((e,t)=>{let i=l(a(e,t,r));if(null==i)return;let o=n?String(a(e,t,n)??"All"):"All",u=s?l(a(e,t,s)):null,h=d(null!=u&&u>0?u:c,2,18);S(o),w.push({datum:e,index:t,value:i,group:o,radius:h})});let M=m?l(m[0]):null,A=m?l(m[1]):null,$=w.reduce((e,t)=>Math.min(e,t.value),w.length?1/0:0),C=w.reduce((e,t)=>Math.max(e,t.value),w.length?-1/0:1),P=M??$,R=A??C;if(P===R&&(P-=.5,R+=.5),P>R){let e=R;R=P,P=e}let D=w.reduce((e,t)=>Math.max(e,t.radius),c),B=v.plot.x+D+8,T=v.plot.x+v.plot.width-D-8,j=Co().domain([P,R]).range([B,T]),O=Math.max(1,I.length),E=v.plot.height/O,N=Math.min(6,.05*E),F=e=>v.plot.y+((k.get(e)??0)+.5)*E,W=/* @__PURE__ */new Map,q=/* @__PURE__ */new Set,H=/* @__PURE__ */new Map;for(let e of I){let t=w.filter(t=>t.group===e),i=F(e),r=t.map(e=>({x:j(e.value),radius:e.radius})),n=Po(r,i-E/2+N,i+E/2-N,x);W.set(e,t.length),n.overlapping&&q.add(e),t.forEach((e,t)=>H.set(e.index,{x:r[t].x,y:n.positions[t],entryOffset:n.entryOffset}))}let z=w.map((e,t)=>{let i=H.get(e.index),r=i.x,n=i.y,o=q.has(e.group);return{id:String(e.datum.id??`collision-swarm-${t}`),x:r,y:n-(f?0:i.entryOffset),vx:0,vy:0,fixedPosition:{x:r},bodyCollisions:!o,mass:1,shape:{type:"circle",radius:e.radius},datum:{...e.datum,xValue:e.value,group:e.group,radius:e.radius,targetX:r,targetY:n,overlapping:o},springs:[{target:{type:"point",x:r,y:n},restLength:0,stiffness:34,damping:12}]}}),L=ci({x:v.plot.x,y:v.plot.y,width:v.plot.width,height:v.plot.height},{idPrefix:"collision-swarm",includeCeiling:!1,wallThickness:20,floorThickness:20});return{config:o(u,L,"CollisionSwarmChart",{gravity:{x:0,y:0},cellSize:Math.max(24,4*D),collisionIterations:Math.max(1,Math.round(y??6)),velocityDamping:.992,restitution:.02,friction:.18,sleepSpeed:3,sleepAfter:.5}),initialSpawns:z,projectionRows:I.map(e=>({label:e,value:W.get(e)??0})),metadata:{kind:"collision-swarm",xExtent:[P,R],xRange:[B,T],groups:I.map(e=>({label:e,y:F(e),count:W.get(e)??0,overlapping:q.has(e)})),plot:v.plot}}}function Do(e){if(Array.isArray(e)&&e.length>=2){let t=l(e[0]),i=l(e[1]);return null!=t&&null!=i?{x:t,y:i}:null}if(e&&"object"==typeof e){let t=e,i=l(t.x),r=l(t.y);return null!=i&&null!=r?{x:i,y:r}:null}return null}function Bo(e){return Array.isArray(e)?e.map(Do).filter(e=>null!=e):[]}function To(e,t){return"normalized"===e||"pixels"===e?e:t.length>0&&t.every(e=>e.x>=0&&e.x<=1&&e.y>=0&&e.y<=1)?"normalized":"pixels"}function jo(e,t,i){return"normalized"===i?{x:t.plot.x+e.x*t.plot.width,y:t.plot.y+e.y*t.plot.height}:{x:d(e.x,t.plot.x,t.plot.x+t.plot.width),y:d(e.y,t.plot.y,t.plot.y+t.plot.height)}}function Oo(e){let t=0;for(let i=1;i<e.length;i+=1){let r=e[i].x-e[i-1].x,n=e[i].y-e[i-1].y;t+=Math.hypot(r,n)}return t}function Eo(e,t){if(0===e.length)return{x:0,y:0};if(1===e.length)return{...e[0]};let i=d(t,0,1)*Oo(e),r=0;for(let t=1;t<e.length;t+=1){let n=e[t-1],o=e[t],s=Math.hypot(o.x-n.x,o.y-n.y);if(!(s<=0)){if(r+s>=i){let e=(i-r)/s;return{x:n.x+(o.x-n.x)*e,y:n.y+(o.y-n.y)*e}}r+=s}}return{...e[e.length-1]}}function No(e,t){let i=Eo(e,Math.max(0,t-.02)),r=Eo(e,Math.min(1,t+.02)),n=r.x-i.x,o=r.y-i.y,s=Math.hypot(n,o)||1;return{x:n/s,y:o/s}}function Fo(e){let{coordinateMode:t,flowSpeed:r,links:n,maxParticles:s,nodeIdAccessor:u,nodeXAccessor:p,nodeYAccessor:m,nodes:y,particleRadius:f,particleRate:g,pathAccessor:v,pathConstraint:x="path",reducedMotion:w,seed:I,size:k,sourceAccessor:S,targetAccessor:M,throughputAccessor:A}=e,$=i(k),C=b(I),P=/* @__PURE__ */new Map,R=/* @__PURE__ */new Map,D=[];function B(e){if(e&&"object"==typeof e){let t=e;if("function"==typeof u){let e=u(t,0);if(null!=e)return String(e)}if("string"==typeof u&&null!=t[u])return String(t[u]);if(null!=t.id)return String(t.id)}return String(e??"unknown")}y.forEach((e,t)=>{let i=String(a(e,t,u)??e.id??t),r=l(a(e,t,p)),n=l(a(e,t,m));if(null!=r&&null!=n){let e={x:r,y:n};P.set(i,e),D.push(e)}R.set(i,String(e.label??e.name??i))});let T=[];n.forEach((e,t)=>{let i=B(a(e,t,S)),r=B(a(e,t,M)),n=Math.max(0,l(a(e,t,A))??0),o=Bo(v?a(e,t,v):void 0),s=o.length?o:Bo(e.path??e.points??e.route);s.forEach(e=>D.push(e)),T.push({id:String(e.id??`physical-flow-${i}-${r}-${t}`),link:e,index:t,source:i,target:r,throughput:n,rawPath:s})});let j=To(t,D),O=/* @__PURE__ */new Map;for(let[e,t]of P)O.set(e,jo(t,$,j));let E=[];for(let e of T){let t=e.rawPath.map(e=>jo(e,$,j));if(t.length>=2)O.has(e.source)||O.set(e.source,t[0]),O.has(e.target)||O.set(e.target,t[t.length-1]);else{let i=O.get(e.source),r=O.get(e.target);i&&r&&(t=[i,r])}t.length<2||e.throughput<=0||(R.has(e.source)||R.set(e.source,e.source),R.has(e.target)||R.set(e.target,e.target),E.push({...e,path:t,packetCount:0}))}let N=c(g,.12),F=Math.max(1,Math.round(s)),W=E.map(e=>Math.max(1,Math.round(e.throughput*N))),q=W.reduce((e,t)=>e+t,0),H=q>F?F/q:1;E.forEach((e,t)=>{e.packetCount=Math.max(1,Math.floor(W[t]*H))});let z=E.reduce((e,t)=>e+t.packetCount,0);for(;z>F;){let e=E.reduce((e,t,i)=>t.packetCount<=1?e:-1===e||t.packetCount>E[e].packetCount?i:e,-1);if(-1===e)break;E[e].packetCount-=1,z-=1}let L=/* @__PURE__ */new Map,Y=/* @__PURE__ */new Map,_=[],X=c(r,90),G=c(f,4);E.forEach((e,t)=>{L.set(e.target,(L.get(e.target)??0)+e.throughput),Y.set(e.source,(Y.get(e.source)??0)+e.throughput);let i=Oo(e.path);for(let r=0;r<e.packetCount;r+=1){let n=(r+.5)/e.packetCount,o=w?n:d(.12+.84*n+.04*(C()-.5),.04,.98),s=w?o:Math.max(0,o-(.18+.12*C())),a=Eo(e.path,s),l=Eo(e.path,o),c=No(e.path,s),u={x:-c.y,y:c.x},h=(C()-.5)*G*1.5,p=`${e.id}-packet-${r}`;_.push({id:p,x:a.x+u.x*h,y:a.y+u.y*h,vx:w?0:c.x*X+10*(C()-.5),vy:w?0:c.y*X+10*(C()-.5),mass:.8,spawnAt:w?0:.04*t+r/32,shape:{type:"circle",radius:G},datum:{...e.link,source:e.source,target:e.target,throughput:e.throughput,packetIndex:r,packetCount:e.packetCount,routeProgress:o,flowPath:e.path,flowPathLength:i,flowRouteId:e.id,flowSpeed:X,sourceLabel:R.get(e.source)??e.source,targetLabel:R.get(e.target)??e.target},springs:"none"!==x&&w?[{target:{type:"point",x:l.x,y:l.y},restLength:.7*G,stiffness:26,damping:4.25}]:void 0})}});let V=Math.max(18,5*G),U=Array.from(O,([e,t])=>({nodeId:e,label:R.get(e)??e,sensorId:`physical-flow-node-${h(e)}`,point:t})),K=U.map(e=>({id:e.sensorId,sensor:!0,shape:{type:"aabb",x:e.point.x,y:e.point.y,width:V,height:V}})),Q=Object.fromEntries(U.map(e=>[e.sensorId,{binId:e.label,enterType:"physics-proximity-enter",exitType:"physics-proximity-exit"}])),J=[...ci({x:$.plot.x,y:$.plot.y,width:$.plot.width,height:$.plot.height},{idPrefix:"physical-flow",wallThickness:18,floorThickness:18}),...K],Z=o(I,J,"PacketFlowChart",{gravity:{x:0,y:0},cellSize:Math.max(24,7*G),collisionIterations:3,velocityDamping:.994,restitution:.01,friction:.16,sleepSpeed:2.5,sleepAfter:.7});Z.bodyLimit=F,Z.eviction="oldest",Z.observation={...Z.observation,sensors:Q};let ee=Array.from(O,([e,t])=>({id:e,label:R.get(e)??e,x:t.x,y:t.y,sensorId:`physical-flow-node-${h(e)}`,incoming:L.get(e)??0,outgoing:Y.get(e)??0})),te=E.map(e=>({id:e.id,source:e.source,target:e.target,sourceLabel:R.get(e.source)??e.source,targetLabel:R.get(e.target)??e.target,throughput:e.throughput,packetCount:e.packetCount,path:e.path}));return{config:Z,initialSpawns:_,projectionRows:ee.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:_.length,totalThroughput:E.reduce((e,t)=>e+t.throughput,0),plot:$.plot,nodes:ee,links:te}}}function Wo(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function qo(e){if(!e||"object"!=typeof e)return!1;let t=e;return"string"==typeof t.id&&(null==t.label||"string"==typeof t.label)&&"number"==typeof t.count&&Number.isFinite(t.count)&&Array.isArray(t.bodyIds)&&t.bodyIds.every(e=>"string"==typeof e)}function Ho(e,t){if("region-enter"!==t.type)return e;let i=t.region.id,r=Wo(e,i),n=qo(r)?r:{id:i,label:t.region.label??i,count:0,bodyIds:[]};if(n.bodyIds.includes(t.bodyId))return e;let o=[...n.bodyIds,t.bodyId];return{...e,[i]:{...n,count:o.length,bodyIds:o}}}function zo(e,t){return(t??Object.keys(e)).map(t=>Wo(e,t)).filter(qo).map(e=>({label:e.label??e.id,value:e.count}))}function Lo(e,t){let i=t instanceof Set?t:new Set(t);return e.map(e=>{let t=e.bodyIds??[],r=t.filter(e=>!i.has(e)),n=t.length-r.length,o=e.completion?.mode??"allMembersAbsorbed",s=e.completion?.valueByBodyId,a=e=>{let t=s?Wo(s,e):void 0;return"number"==typeof t&&Number.isFinite(t)&&t>=0?t:1},l=t.reduce((e,t)=>e+a(t),0),d=t.reduce((e,t)=>e+(i.has(t)?a(t):0),0),c=e.completion?.threshold,u="threshold"===o?Number.isFinite(c)&&Number(c)>=0?Number(c):l:void 0,h=t.length>0&&("anyAbsorbed"===o?n>0:"threshold"===o?d>=(u??l):0===r.length);return{id:e.id,label:e.label??e.id,mode:o,complete:h,absorbed:n,total:t.length,absorbedValue:d,totalValue:l,threshold:u,missing:r}})}function Yo(e){let t=e.reduce((e,t)=>e+(t.share??1),0);return t>0?t:e.length}function _o(e,t,i,r,n,o={}){return{id:e,friction:o.friction,restitution:o.restitution,bodyFilter:o.bodyFilter,shape:{type:"segment",x1:t,y1:i,x2:r,y2:n,thickness:o.thickness??8}}}function Xo(e,t,i,r){return{type:"aabb",x:e,y:t,width:i,height:r}}function Go(e){let t=e.shape??"lane",i=Math.max(1,Math.round(e.width)),r=Math.max(1,Math.round(e.height)),n=e.padX??46,o=e.padY??72,s=n,a=i-n,l=o,d=r-Math.max(24,Math.round(.45*o)),c=(l+d)/2,u=Math.max(1,d-l),h=N(e.pinchRatio??.18,.06,.5),p=Number(e.pinchHeightOffset??0),m=Number.isFinite(p)?p:0,y=N(u*h+m,.06*u,.5*u),f=y/2,g=c-f,b=c+f,v=e.idPrefix??"process",x=e.friction??.58,w=e.restitution??.18,I=e.wallThickness??8,k=e.stages;if(!k.length)throw new Error("processStageLayout requires at least one stage");let S=N(e.centerStageIndex??Math.floor(k.length/2),0,k.length-1),M=Yo(k),A=a-s,$=s,C=k.map((e,t)=>{let i=(e.share??1)/M*A,r=$,n=t===k.length-1?a:$+i;return $=n,{id:e.id,label:e.label,description:e.description,kind:e.kind??"stage",index:t,x0:r,x1:n,x:(r+n)/2,width:n-r,y:c,height:u}}),P=C[S],R=P.x0,D=P.x1,B=(e,i)=>{if("lane"===t)return"top"===i?l:d;if("funnel"===t){let t=N((e-s)/Math.max(1,a-s),0,1);return"top"===i?l+(g-l)*t:d+(b-d)*t}if(e<=R){let t=N((e-s)/Math.max(1,R-s),0,1);return"top"===i?l+(g-l)*t:d+(b-d)*t}if(e<=D)return"top"===i?g:b;let r=N((e-D)/Math.max(1,a-D),0,1);return"top"===i?g+(l-g)*r:b+(d-b)*r},T=C.map(e=>{let t=Math.min(B(e.x0,"top"),B(e.x1,"top")),i=Math.max(B(e.x0,"bottom"),B(e.x1,"bottom"));return{...e,y:(t+i)/2,height:Math.max(1,i-t)}}),j={thickness:I,friction:x,restitution:w},O=[];"lane"===t?O.push(_o(`${v}-top`,s,l,a,l,j),_o(`${v}-bottom`,s,d,a,d,j),_o(`${v}-left`,s,l,s,d,{...j,thickness:Math.max(6,I-2)}),_o(`${v}-right`,a,l,a,d,{...j,thickness:Math.max(6,I)})):"funnel"===t?O.push(_o(`${v}-top`,s,l,a,g,j),_o(`${v}-bottom`,s,d,a,b,j),_o(`${v}-left`,s,l,s,d,{...j,thickness:Math.max(6,I-2)}),_o(`${v}-right`,a,g,a,b,{...j,thickness:Math.max(6,I)})):O.push(_o(`${v}-left-top`,s,l,R,g,j),_o(`${v}-left-bottom`,s,d,R,b,j),_o(`${v}-center-top`,R,g,D,g,j),_o(`${v}-center-bottom`,R,b,D,b,j),_o(`${v}-right-top`,D,g,a,l,j),_o(`${v}-right-bottom`,D,b,a,d,j),_o(`${v}-left`,s,l,s,d,{...j,thickness:Math.max(6,I-2)}),_o(`${v}-right`,a,l,a,d,{...j,thickness:Math.max(6,I)}));let E=e.membraneDampingScale??.5,F=s,W=Math.max(1,("bowtie"===t?R:a)-F),q=(e.membranes??[]).map(e=>{let t=F+N(e.offset,0,1)*W,i=e.width??18+18*e.cost,r=u-16,n=c+.25*(e.wobble??0);return{...e,x:t,y:n,width:i,height:r}}),H=!1===e.includeMembraneRegions?[]:q.map(e=>Qo({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:i,height:r,padX:n,padY:o,left:s,right:a,topY:l,bottomY:d,midY:c,centerLeft:R,centerRight:D,pinchHeight:y,pinchTop:g,pinchBottom:b,stages:T,membranes:q,colliders:O,regionEffects:H,boundaryY:B}}function Vo(e,t,i){return"function"==typeof t?r=>({...i,...t(r),primitive:e}):{...i,...t,primitive:e}}function Uo(e,t,i,r){return{id:e.id,label:e.label,description:e.description,kind:e.kind??t,shape:Xo(e.x,e.y,e.width,e.height),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:i?Vo(i,e.attributes,r):e.attributes,onEnter:e.onEnter,onExit:e.onExit}}function Ko(e,t={}){let i=t.idPrefix??"stage",r=Math.max(0,t.insetX??0),n=Math.max(0,t.insetY??1);return e.stages.map(e=>{let o="function"==typeof t.metadata?t.metadata(e):t.metadata??{};return{...Uo({id:i?`${i}:${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*r),height:Math.max(1,e.height-2*n),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 Qo(e){let t=e.dampingScale??.5,i=e.energyScale??1,r=N(e.cost,0,2);return{...Uo(e,"membrane","membrane",{membraneCost:r}),damping:r*t,energyDelta:-r*i}}function Jo(e){return{...Uo(e,"charge-gate","chargeGate"),charge:e.charge??!0,energyDelta:e.energyDelta,impulseOnEnter:e.impulseOnEnter}}function Zo(e){let t="number"==typeof e.force?{x:e.force,y:0}:e.force??{x:12,y:0};return{...Uo(e,"force-field","routeSurface"),force:t,damping:e.damping??.015}}function es(e){let t=e.pressure??e.occupancy??0,i=e.baseDamping??.08,r=e.dampingPerUnit??.12,n=e.energyPerUnit??0;return{...Uo(e,"membrane","pressureField",{pressure:t}),damping:i+t*r,energyDelta:n?-t*n:void 0,force:e.force}}function ts(e){let t="number"==typeof e.force?{x:e.force,y:0}:e.force;return{...Uo(e,"force-field","capacitatedSensor",{capacity:e.capacity,unitsPerSecond:e.unitsPerSecond??e.capacity}),force:t,damping:e.damping,charge:e.charge??e.capacity}}function is(e){return{...Uo(e,"force-field","portal",{targetStage:e.targetStage}),force:e.force,impulseOnEnter:e.impulseOnEnter,damping:e.damping??.08}}function rs(e){let t="number"==typeof e.force?{x:e.force,y:0}:e.force??{x:24,y:0};return{...Uo(e,"sink","absorb"),force:t,damping:e.damping??.02,charge:e.charge??"absorbed"}}function ns(e){return{...Uo(e,"force-field","forceField"),force:e.force,damping:e.damping,energyDelta:e.energyDelta}}function os(e){let t=e.x??e.anchor?.x??0,i=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:i,width:e.width,height:e.height,anchor:e.anchor??{x:t,y:i},completion:e.completion,tether:e.tether,semanticItem:e.semanticItem}}function ss(e){let t=e.idPrefix??"lane",i={thickness:e.thickness??8,friction:e.friction??.5,restitution:e.restitution??.16},r=[_o(`${t}-top`,e.left,e.top,e.right,e.top,i),_o(`${t}-bottom`,e.left,e.bottom,e.right,e.bottom,i)];return e.openEnds||r.push(_o(`${t}-left`,e.left,e.top,e.left,e.bottom,i),_o(`${t}-right`,e.right,e.top,e.right,e.bottom,i)),r}function as(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 ls(e,t){let i={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 rs({...i,kind:e.kind??"sink",force:as(e.force,28),damping:e.damping??.04,charge:"absorbed",attributes:{...i.attributes,primitive:"absorb"}});if(e.portal){let t=e.portal.force??e.force??{x:-40,y:0};return is({...i,kind:e.kind??"force-field",force:as(t,-40),damping:e.damping??.1,targetStage:e.portal.targetStageId,attributes:{...i.attributes,primitive:"portal",targetStage:e.portal.targetStageId}})}if(e.capacity){let t=Math.max(.1,e.capacity.unitsPerSecond);return ts({...i,kind:e.kind??"force-field",capacity:t,unitsPerSecond:t,force:as(e.force,10+.8*t),damping:e.damping??Math.max(.04,.32-.01*t),attributes:{...i.attributes,unitAccessor:e.capacity.unitAccessor,reviewerCapacity:t}})}if(e.pressure){let t="object"==typeof e.pressure&&e.pressure?e.pressure:{};return es({...i,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:as(e.force,8),attributes:{...i.attributes,primitive:"pressureField"}})}return null!=e.force||null!=e.damping?Zo({...i,kind:e.kind??"force-field",force:as(e.force,14),damping:e.damping??.02,attributes:{...i.attributes,primitive:"routeSurface"}}):ns({...i,kind:e.kind??"force-field",force:{x:10,y:0},damping:.02,attributes:{...i.attributes,primitive:"forceField"}})}function ds(e){let t=e.stages;if(!t.length)throw new Error("buildProcessFlowPhysics requires at least one stage");let r=e.size,n=i(r),o=d(e.ballRadius??6,2,18),s=e.seed??1,c=b(s),u=e.idAccessor,h=e.stageAccessor??"stage",p=e.groupBy,m=e.groupLabelAccessor,y=e.workAccessor,f=e.radiusAccessor,g=e.groupCompletion??(p?"allAbsorbed":"none"),v=e.springStiffness??.28,x=e.springDamping??.72,w=!0===e.settle,I=t.map(e=>({id:e.id,label:e.label??e.id,description:e.description,share:e.share})),k=Go({width:r[0],height:r[1],shape:"lane",padX:Math.max(28,n.plot.x),padY:Math.max(36,n.plot.y+8),stages:I,idPrefix:"process-flow",includeMembraneRegions:!1,friction:.48,restitution:.14}),S=new Map(k.stages.map((e,t)=>[e.id,t])),M=new Map(k.stages.map(e=>[e.id,e])),A=k.stages[0].id,$=k.stages[0],C=new Set(t.filter(e=>e.absorb).map(e=>e.id)),P=t.map(e=>{let t=M.get(e.id)??$;return ls(e,{x:t.x,y:k.midY,width:t.width,height:k.bottomY-k.topY})});P.unshift(Zo({id:"process-flow-route",label:"process route",description:"Baseline conveyor along the process lane.",x:(k.left+k.right)/2,y:k.midY,width:k.right-k.left,height:k.bottomY-k.topY-12,force:8,damping:.012,semanticItem:!1}));let R=/* @__PURE__ */new Map;for(let e of k.stages)R.set(e.id,0);let D=[];e.data.forEach((e,t)=>{let i=String(u?a(e,t,u)??e.id??`process-flow-${t}`:e.id??`process-flow-${t}`),r=String(a(e,t,h)??A),n=S.has(r)?r:A;R.set(n,(R.get(n)??0)+1);let s=p?String(a(e,t,p)??""):void 0,c=s&&m?String(a(e,t,m)??s):s,g=y?l(a(e,t,y))??1:1,b=f?l(a(e,t,f)):null,v=d(null!=b&&b>0?b:o,2,18);D.push({datum:e,id:i,stageId:n,groupId:s||void 0,groupLabel:c||void 0,work:g,radius:v,index:t})});let B=/* @__PURE__ */new Map,T=/* @__PURE__ */new Map;for(let e of D){if(!e.groupId)continue;let t=B.get(e.groupId)??[];t.push(e.id),B.set(e.groupId,t),e.groupLabel&&T.set(e.groupId,e.groupLabel)}let j=d(e.groupAnchorAlong??.55,.15,.9),O=k.left+(k.right-k.left)*j,E=Array.from(B.keys()),N=E.map((e,i)=>{let r=B.get(e)??[],n=E.length<=1?k.midY:k.topY+28+i/Math.max(1,E.length-1)*(k.bottomY-k.topY-56);return os({id:e,label:T.get(e)??e,bodyIds:r,anchor:{x:O,y:n},x:O,y:n,completion:"allAbsorbed"===g?{mode:"allMembersAbsorbed",targetZone:t.find(e=>e.absorb)?.id??"merged"}:void 0,tether:{stiffness:.06,visible:!0,restLength:18}})}),F=Lo(N,D.filter(e=>C.has(e.stageId)).map(e=>e.id)),W=new Map(N.map(e=>[e.id,e])),q=D.map((e,t)=>{let i=M.get(e.stageId)??$,r=i.x+(c()-.5)*Math.min(24,.2*i.width),n=k.boundaryY(r,"top")+e.radius+10,o=k.boundaryY(r,"bottom")-e.radius-10,s=o<=n?k.midY:n+c()*Math.max(1,o-n),a=w?r:k.left+18+t%7*4,l=w?s:k.midY+(c()-.5)*(k.bottomY-k.topY)*.35,d=[{target:{type:"point",x:r,y:s},restLength:.45*e.radius,stiffness:v,damping:x}];if(e.groupId){let t=W.get(e.groupId);t?.anchor&&!C.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:a,y:l,vx:w?0:40+40*c(),vy:w?0:20*(c()-.5),mass:1,shape:{type:"circle",radius:e.radius},spawnAt:w?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}}}),H={kernel:{seed:s,gravity:{x:e.gravityX??22,y:e.gravityY??0},restitution:.14,friction:.48,velocityDamping:.988,maxVelocity:420,sleepSpeed:8,sleepAfter:.9,collisionIterations:4},colliders:k.colliders,fixedDt:1/60,maxSubsteps:8},z=k.stages.map(e=>({label:e.label??e.id,value:R.get(e.id)??0})),L=t.map(e=>{let t=M.get(e.id)??$;return{id:e.id,label:e.label??e.id,x:t.x,width:t.width,count:R.get(e.id)??0,capacity:e.capacity?.unitsPerSecond,absorb:!0===e.absorb,portalTarget:e.portal?.targetStageId}});return{config:H,initialSpawns:q,initialSpawnPacing:w?void 0:{pacing:"arrival",timeAccessor:"spawnAt",timeScale:1},projectionRows:z,metadata:{kind:"process-flow",plot:n.plot,volume:k,stages:L,groups:N,groupCompletion:F,regionEffects:P}}}var cs={width:700,height:420},us={width:700,height:380},hs={width:700,height:360},ps={width:760,height:360},ms={width:760,height:420},ys={width:900,height:420},fs={width:700,height:380},gs={width:900,height:520},bs={width:900,height:520},vs={width:920,height:620};import{forwardRef as xs,useCallback as ws,useMemo as Is,useRef as ks}from"react";import{useEffect as Ss,useImperativeHandle as Ms,useLayoutEffect as As,useRef as $s,useState as Cs}from"react";function Ps(e){let{datum:t,spawnAt:i,...r}=e;return JSON.stringify(r)}function Rs(e,t,i,r=!1){let n=new Map(t.initialSpawns.map(e=>[e.id,e])),o=new Map(i.initialSpawns.map(e=>[e.id,e])),s=/* @__PURE__ */new Set,a=new Map(e.world.bodies.map(e=>[e.id,e]));for(let[e,r]of n){let n=o.get(e),l=n&&"event-drop"===i.metadata?.kind&&r.datum?.late!==n.datum?.late,d=n&&"event-drop"===t.metadata?.kind&&"event-drop"===i.metadata?.kind&&JSON.stringify(t.metadata.windowPlot)===JSON.stringify(i.metadata.windowPlot)&&!1===r.datum?.late&&!1===n.datum?.late&&(a.get(e)?.y??-1/0)>=n.y&&Ps({...r,y:n.y})===Ps(n);(!n||l||!d&&Ps(r)!==Ps(n))&&s.add(e)}let l=new qi;l.restore({...e,world:{...e.world,bodies:e.world.bodies.map(e=>({...e,datum:o.get(e.id)?.datum??e.datum}))},queue:e.queue.map(e=>({...e,datum:o.get(e.id)?.datum??e.datum}))});let d=new Set(t.config.colliders?.map(e=>e.id)),c=e.world.colliders.filter(e=>!d.has(e.id));l.updateConfig({...i.config,colliders:[...i.config.colliders??[],...c]}),l.remove(Array.from(s));let u=i.initialSpawns.filter(e=>!n.has(e.id)||s.has(e.id)).map(e=>({...e,spawnAt:void 0}));return l.enqueue(u,r&&!e.paused?i.initialSpawnPacing:void 0),l.materializeDueSpawns(),l.snapshot()}var Ds=[],Bs=typeof window>"u"?Ss:As;function Ts(e){let{ref:t,frameRef:i,idPrefix:r,buildLayout:n}=e,o=e.data??Ds,[s,a]=Cs(()=>p(o,r)),l=s;s.seed!==o&&(l=p(o,r),a(l));let d=$s(l);d.current=l;let c=$s(n);c.current=n;let u=$s(null);function h(e){return(u.current?.rows!==e||u.current.build!==c.current)&&(u.current={rows:e,build:c.current,layout:c.current(e)}),u.current.layout}let m=h(l.rows),y=$s(null);function f(e,t=!0){let r=i.current;if(!r)return;let n=r.getStore();y.current?.store===n&&y.current.layout!==e&&r.restore(Rs(r.snapshot(),y.current.layout,e,t)),y.current={store:n,layout:e}}return Bs(()=>{f(m)}),Ms(t,()=>{function e(e){let t=d.current.seed;t!==Ds&&0===t.length||(d.current=e,f(h(e.rows),!1),a(e))}function t(t){if(!t.length)return;let i=d.current;e({...p([...i.rows,...t],r,i.nextId),seed:i.seed})}return{push:e=>t([e]),pushMany:t,remove:t=>{let i=new Set(Array.isArray(t)?t:[t]),r=d.current,n=r.rows.filter(e=>i.has(String(e.id)));return n.length&&e({...r,rows:r.rows.filter(e=>!i.has(String(e.id)))}),n},update:(t,i)=>{let r=new Set(Array.isArray(t)?t:[t]),n=d.current,o=[],s=new Map(n.rows.map(e=>[String(e.id),e]));for(let e of n.rows){if(!r.has(String(e.id)))continue;o.push(e);let t=i(e),n=t.id??e.id;String(n)!==String(e.id)&&s.delete(String(e.id)),s.set(String(n),{...t,id:n})}return o.length&&e({...n,rows:Array.from(s.values())}),o},clear:()=>{i.current?.clear(),e({...d.current,rows:[]})},getData:()=>d.current.rows.slice(),getScales:()=>null,getCustomLayout:()=>i.current?.snapshot()??null,popBodies:(e,t)=>i.current?.popBodies(e,t)??[]}}),{layout:m,resetSeed:()=>{let e=p(d.current.seed,r);d.current=e,a(e)}}}import{useCallback as js,useEffect as Os,useMemo as Es,useRef as Ns,useState as Fs}from"react";function Ws(e,t){return e?"sparkline"===t?{top:2,right:2,bottom:2,left:2}:{top:8,right:8,bottom:8,left:8}:{top:0,right:0,bottom:0,left:0}}import{Fragment as qs,jsx as Hs,jsxs as zs}from"react/jsx-runtime";function Ls(e){return!!e&&"string"==typeof e.name}function Ys(e,t=!1){if(!e?.datum)return null;let i=e.datum,r=i.sourceDatum;return t&&r&&"object"==typeof r?r:i}function _s(e){let{selection:t,linkedHover:i,colorBy:r,chartType:n,chartId:o,onBodyHover:s,fallbackFields:a,unwrapSourceDatum:l}=e,d="string"==typeof r?r:void 0,c=Ls(t)?t:void 0,{activeSelectionHook:u,customHoverBehavior:h}=P({emitObservations:!1,selection:c,linkedHover:i,fallbackFields:d?[d]:a,onObservation:e.onObservation,onClick:e.onClick,chartType:n,chartId:o,colorByField:d}),p=Ls(t)?null:t??null,m=Es(()=>{if(p)return p;if(!u?.isActive)return null;let e=u.predicate;return{isActive:!0,predicate:t=>{let i=Ys(t,l);return null!=i&&e(i)}}},[u?.isActive,u?.predicate,p,l]),y=Es(()=>{if(i||s)return(e,t)=>{if(s?.(e,t),!i)return;let r=Ys(e,l);h(r&&t?{...t,data:r}:null)}},[h,s,i,l]);return Es(()=>({selection:m,onBodyHover:y}),[y,m])}var Xs=/* @__PURE__ */new Set(["sample","mechanical"]);function Gs(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0?e:null}function Vs(e,t,i,r,n){let[o,s]=Fs(0),a=Ns(null),l=Ns(!1),d=Gs(t),c=Ns(d),u=Ns(!!i),h=Ns(r);c.current=d,u.current=!!i,h.current=r;let p=js(()=>{null!=a.current&&(clearTimeout(a.current),a.current=null)},[]),m=js(()=>{p();let e=c.current;null==e||u.current||!l.current||(a.current=setTimeout(()=>{a.current=null,l.current=!1,h.current?.(),s(e=>e+1)},e))},[p]);Os(()=>{null==d||i?p():l.current&&m()},[p,d,i,m]),Os(()=>p,[p]);let y=e?.observation?.onSimulationStateChange,f=js((e,t)=>{if(y?.(e,t),n!==y&&n?.(e,t),"running"===e)return l.current=!1,void p();"settled"!==e||"running"!==t||(l.current=!0,m())},[p,n,y,m]);return{config:Es(()=>null!=d||n?{...e,observation:{...e?.observation,onSimulationStateChange:f}}:e,[f,e,d,n]),rerunKey:o}}function Us(e){let t=e=>"string"==typeof e&&Xs.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"}}function Ks(e,t,i,r){return e??[t??r[0],i??r[1]]}function Qs(e,t,i){let r=Array.isArray(t)?t:[t.width,t.height],n=i?.hasSimulationMode?Us({mode:e.mode,simulationMode:e.simulationMode}):{chartMode:"sample"===e.mode||"mechanical"===e.mode?void 0:e.mode,simulationMode:"sample"},o=B(n.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:r[0],height:r[1]}),s=e.size?.[0],a=e.size?.[1],l=r[0],d=r[1],c=Js(Es(()=>Ks(null!=s&&null!=a?[s,a]:void 0,o.width,o.height,[l,d]),[d,l,o.height,o.width,a,s]),e.responsiveWidth,e.responsiveHeight),u=c.size,h=Ws(o.compactMode,n.chartMode),p=e.showProjection??!o.compactMode,m=e.showChrome??!o.compactMode,y=ia(e.tooltip,void 0),f=void 0!==y.enableHover?y.enableHover:o.enableHover,g=o.compactMode?o.title:o.title??e.title,b=n.chartMode&&"primary"!==n.chartMode?`semiotic-physics--${n.chartMode}`:null,v=[e.className,b].filter(Boolean).join(" ")||void 0;return{chartMode:n.chartMode,simulationMode:n.simulationMode,resolved:o,chartSize:u,responsiveContainerRef:c.containerRef,responsiveWidth:c.responsiveWidth,responsiveHeight:c.responsiveHeight,margin:h,showProjection:p,showChrome:m,enableHover:f,title:g,description:o.description??e.description,summary:o.summary??e.summary,accessibleTable:o.accessibleTable??e.accessibleTable,className:v,compactMode:o.compactMode,mobileInteraction:o.mobileInteraction,mobileSemantics:o.mobileSemantics}}function Js(e,t,i){let[r,n]=S(e,t,i),o=Math.max(1,n[0]),s=Math.max(1,n[1]);return{containerRef:r,size:Es(()=>[o,s],[s,o]),responsiveWidth:!!t,responsiveHeight:!!i}}function Zs(e){let[t,i]=e.size;return _(e.loading,t,i,e.loadingContent,e.responsive)||w(e.data,t,i,e.emptyContent,e.responsive)}function ea(e,t,i,r){let n=r?.responsiveWidth||r?.responsiveHeight?/* @__PURE__ */Hs("div",{ref:r.responsiveContainerRef,"data-semiotic-physics-responsive-host":"true",style:{position:"relative",width:r.responsiveWidth?"100%":t[0],height:r.responsiveHeight?"100%":t[1]},children:i}):i;/* */
|
|
43
|
+
return Hs(Y,{componentName:e,width:t[0],height:t[1],children:n})}function ta(e,t){return e?t?i=>/* @__PURE__ */zs(qs,{children:["function"==typeof e?e(i):e,"function"==typeof t?t(i):t]}):e:t}function ia(e,t,i={}){if(!1===e)return{enableHover:!1};let r=!E(e)||F(e)&&"function"==typeof e.content?e:"multi",n=q(r),o="function"==typeof n?i.unwrapSourceDatum?e=>{let t=e.data?.sourceDatum;return n({...e,data:t&&"object"==typeof t?t:e.data,__semioticHoverData:!0})}:n:t?.tooltipContent;return{enableHover:t?.enableHover,tooltipContent:o&&De(n)?Re(o):o}}function ra(e,t,i,r){return{accessibleTable:r?.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:r?.chartMode??t?.chartMode,className:r?.className??e.className??t?.className,color:e.color??t?.color,description:r?.description??e.description??t?.description,emphasis:e.emphasis??t?.emphasis,enableHover:r?.enableHover??t?.enableHover,hoverRadius:e.hoverRadius??t?.hoverRadius,legend:e.legend??t?.legend,legendLayout:e.legendLayout??t?.legendLayout,legendPosition:e.legendPosition??t?.legendPosition,margin:r?.margin??t?.margin,maxDevicePixelRatio:e.maxDevicePixelRatio??t?.maxDevicePixelRatio,onClick:null!=e.onClick?(t,i)=>{t&&e.onClick?.(t,{x:i.x,y:i.y})}:t?.onClick,onObservation:e.onObservation??t?.onObservation,onAnnotationActivate:t?.onAnnotationActivate,opacity:e.opacity??t?.opacity,selection:r?.selection??t?.selection,semanticItems:t?.semanticItems??i,stroke:e.stroke??t?.stroke,strokeWidth:e.strokeWidth??t?.strokeWidth,summary:r?.summary??e.summary??t?.summary,svgAnnotationRules:e.svgAnnotationRules??t?.svgAnnotationRules,title:r?.title??e.title??t?.title}}import{Fragment as na,jsx as oa,jsxs as sa}from"react/jsx-runtime";function aa(e,t,r,n,o){let s=Array.isArray(o)?o:o?[o]:[];if(!1!==r||0!==s.length)return({size:o})=>{let a=[Number(o[0])||700,Number(o[1])||420],l=i(a),d=Math.max(2,Math.round(t)),c=l.plot.width/d,u=l.plot.y+l.plot.height,h=e.reduce((e,t)=>Math.max(e,t.value),1),p=!1!==r,[m,y]=n?.valueExtent??[0,d],f=y===m?1:y-m,g=e.map((e,t)=>{let i=l.plot.x+(t+.5)*c,r=u-e.value/h*l.plot.height*.9;return`${0===t?"M":"L"} ${i.toFixed(1)} ${r.toFixed(1)}`}).join(" ");/* */
|
|
44
|
+
return sa("svg",{"aria-hidden":"true","data-testid":"galton-board-structure-overlay",width:a[0],height:a[1],viewBox:`0 0 ${a[0]} ${a[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[p?/* @__PURE__ */sa(na,{children:[Array.from({length:d+1},(e,t)=>{let i=l.plot.x+t*c;/* */
|
|
45
|
+
return oa("line",{"data-testid":"galton-board-bin-wall",x1:i,x2:i,y1:l.plot.y,y2:u,stroke:"var(--semiotic-border, #d1d5db)",strokeOpacity:.28,strokeWidth:1},`bin-wall-${t}`)}),
|
|
46
|
+
/* @__PURE__ */oa("line",{x1:l.plot.x,x2:l.plot.x+l.plot.width,y1:u,y2:u,stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:1.5}),
|
|
47
|
+
/* @__PURE__ */oa("path",{d:g,fill:"none",stroke:"var(--semiotic-primary, #4e79a7)",strokeOpacity:.7,strokeWidth:2,strokeLinejoin:"round"}),e.map((e,t)=>{if(e.value<=0)return null;let i=l.plot.x+(t+.5)*c,r=u-e.value/h*l.plot.height*.9;/* */
|
|
48
|
+
return oa("text",{x:i,y:Math.max(l.plot.y+10,r-6),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:e.value},`${e.label}-${t}`)})]}):null,s.map((e,t)=>{let i=Number(e.value);if(!Number.isFinite(i))return null;let r=Math.max(0,Math.min(1,(i-m)/f)),n=l.plot.x+r*l.plot.width,o=e.color??"var(--semiotic-warning, #f28e2b)",s="bottom"===e.labelPosition?Math.min(a[1]-8,u+16):l.plot.y+16;/* */
|
|
49
|
+
return sa("g",{className:e.className,"data-testid":"galton-board-reference-line",children:[
|
|
50
|
+
/* @__PURE__ */oa("line",{x1:n,x2:n,y1:l.plot.y+8,y2:u-4,stroke:o,strokeDasharray:e.strokeDasharray??"6 5",strokeWidth:e.strokeWidth??2}),null==e.label?null:/* @__PURE__ */oa("text",{x:Math.min(l.plot.x+l.plot.width-4,n+6),y:s,fill:o,fontSize:10,fontWeight:700,children:e.label})]},`galton-reference-${t}-${i}`)})]})}}function la(e,t,r){if(!1!==r&&t)return({size:r})=>{let n=[Number(r[0])||760,Number(r[1])||360],o=i(n),s=Math.max(1,t.windowCount),a=t.plot??o.plot,l=t.gutter??{x:a.x,y:a.y,width:0,height:a.height},d=t.windowPlot??a,c=d.width/s,u=a.y+a.height,h=a.y+.48*a.height,p=t.lidSegments[0]?.y1??h,m=t.windowStart,y=t.windowStart+s*t.windowSize,f=y===m?0:(t.watermarkValue-m)/(y-m),g=d.x+Math.max(0,Math.min(1,f))*d.width;/* */
|
|
51
|
+
return sa("svg",{"aria-hidden":"true","data-testid":"event-drop-window-overlay",width:n[0],height:n[1],viewBox:`0 0 ${n[0]} ${n[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[
|
|
52
|
+
/* @__PURE__ */oa("rect",{x:a.x,y:a.y,width:a.width,height:a.height,fill:"none",stroke:"var(--semiotic-border, #d1d5db)",strokeOpacity:.7,strokeWidth:1}),l.width>0?/* @__PURE__ */sa("g",{children:[
|
|
53
|
+
/* @__PURE__ */oa("rect",{x:l.x,y:p,width:l.width,height:u-p,fill:"var(--semiotic-danger, #e15759)",fillOpacity:.07}),
|
|
54
|
+
/* @__PURE__ */sa("text",{x:l.x+l.width/2,y:p-8,textAnchor:"middle",fill:"var(--semiotic-danger, #e15759)",fontSize:10,fontWeight:700,children:[t.lateCount," late"]})]}):null,Array.from({length:s},(i,r)=>{let o=e[r],s=d.x+r*c,a=r<t.closedWindowCount;/* */
|
|
55
|
+
return sa("g",{children:[
|
|
56
|
+
/* @__PURE__ */oa("rect",{x:s,y:h,width:c,height:u-h,fill:a?"var(--semiotic-danger, #e15759)":"var(--semiotic-primary, #4e79a7)",fillOpacity:a?.08:.06}),a?t.lidSegments.filter(e=>e.windowIndex===r).map(e=>/* @__PURE__ */oa("line",{x1:e.x1,x2:e.x2,y1:e.y1,y2:e.y2,stroke:"var(--semiotic-danger, #e15759)",strokeOpacity:.78,strokeWidth:2,strokeLinecap:"round"},e.id)):null,
|
|
57
|
+
/* @__PURE__ */oa("text",{x:s+c/2,y:h-8,textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:o?.value??0}),
|
|
58
|
+
/* @__PURE__ */oa("text",{x:s+c/2,y:Math.min(n[1]-8,u+16),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:o?.label??""})]},`window-${r}`)}),t.windowWalls?.map(({id:e,...t})=>/* @__PURE__ */oa("rect",{...t,fill:"var(--semiotic-border, #d1d5db)",fillOpacity:.68},e)),t.lidSegments.filter(e=>null==e.windowIndex).map(e=>/* @__PURE__ */oa("line",{x1:e.x1,x2:e.x2,y1:e.y1,y2:e.y2,stroke:"var(--semiotic-danger, #e15759)",strokeOpacity:.62,strokeWidth:2,strokeLinecap:"round"},e.id)),
|
|
59
|
+
/* @__PURE__ */oa("line",{x1:a.x,x2:a.x+a.width,y1:u,y2:u,stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:1.5}),
|
|
60
|
+
/* @__PURE__ */oa("line",{"data-testid":"event-drop-watermark",x1:g,x2:g,y1:a.y+8,y2:u,stroke:"var(--semiotic-warning, #f28e2b)",strokeDasharray:"5 4",strokeWidth:2}),
|
|
61
|
+
/* @__PURE__ */sa("text",{x:Math.min(a.x+a.width-4,g+6),y:a.y+16,fill:"var(--semiotic-warning, #f28e2b)",fontSize:10,fontWeight:700,children:["watermark ",Math.round(100*t.watermarkValue)/100]})]})}}function da(e,t,r,n=1){if(!1!==r&&0!==e.length)return({size:r})=>{let o=[Number(r[0])||700,Number(r[1])||380],s=i(o),a=Ao(s.plot,e.length,t),l=s.plot.y+s.plot.height;/* */
|
|
62
|
+
return sa("svg",{"aria-hidden":"true","data-testid":"physics-pile-projection-overlay",width:o[0],height:o[1],viewBox:`0 0 ${o[0]} ${o[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[
|
|
63
|
+
/* @__PURE__ */oa("line",{x1:s.plot.x,x2:s.plot.x+s.plot.width,y1:l,y2:l,stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:1}),e.map((e,t)=>{let i=Math.min(s.plot.height,a.pileHeight(e.value/n)),r=a.tubeWidth,d=a.centerX(t),c=l-i;/* */
|
|
64
|
+
return sa("g",{children:[
|
|
65
|
+
/* @__PURE__ */oa("rect",{x:d-r/2,y:c,width:r,height:i,rx:3,fill:"var(--semiotic-primary, #4e79a7)",fillOpacity:.08,stroke:"var(--semiotic-primary, #4e79a7)",strokeOpacity:.42,strokeWidth:1,strokeDasharray:"4 3"}),
|
|
66
|
+
/* @__PURE__ */oa("text",{x:d,y:Math.max(s.plot.y+12,c-6),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:11,fontWeight:700,children:e.value}),
|
|
67
|
+
/* @__PURE__ */oa("text",{x:d,y:Math.min(o[1]-8,l+16),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:e.label})]},`${e.label}-${t}`)}),
|
|
68
|
+
/* @__PURE__ */oa("text",{x:o[0]/2,y:o[1]-2,textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:`Full circle = ${n}; partial circles scaled by area`})]})}}function ca(e){return Math.abs(e)>=1e3||Math.abs(e)<.01?e.toLocaleString(void 0,{maximumFractionDigits:0}):e.toLocaleString(void 0,{maximumFractionDigits:2})}function ua(e,t){if(!1!==t&&e)return({size:t})=>{let r=[Number(t[0])||700,Number(t[1])||360],n=i(r),o=n.plot.y+n.plot.height,[s,a]=e.xExtent,l=s+(a-s)/2,d=[{label:ca(s),x:e.xRange[0]},{label:ca(l),x:e.xRange[0]+(e.xRange[1]-e.xRange[0])/2},{label:ca(a),x:e.xRange[1]}];/* */
|
|
69
|
+
return sa("svg",{"aria-hidden":"true","data-testid":"collision-swarm-projection-overlay",width:r[0],height:r[1],viewBox:`0 0 ${r[0]} ${r[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[e.groups.some(e=>e.overlapping)?/* @__PURE__ */oa("text",{"data-testid":"collision-swarm-overlap-warning",x:n.plot.x,y:Math.max(10,n.plot.y-9),fill:"var(--semiotic-warning, #b45309)",fontSize:10,children:r[0]<360?"Points overlap":"Points overlap. Reduce radius or increase height."}):null,e.groups.map(e=>/* @__PURE__ */sa("g",{children:[
|
|
70
|
+
/* @__PURE__ */oa("line",{x1:n.plot.x,x2:n.plot.x+n.plot.width,y1:e.y,y2:e.y,stroke:"var(--semiotic-border, #d1d5db)",strokeDasharray:"3 5",strokeWidth:1}),
|
|
71
|
+
/* @__PURE__ */oa("text",{x:n.plot.x+4,y:e.y-7,fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:e.label}),
|
|
72
|
+
/* @__PURE__ */sa("text",{x:n.plot.x+n.plot.width-4,y:e.y-7,textAnchor:"end",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:["n=",e.count,e.overlapping?" · overlaps":""]})]},e.label)),
|
|
73
|
+
/* @__PURE__ */oa("line",{x1:e.xRange[0],x2:e.xRange[1],y1:o,y2:o,stroke:"var(--semiotic-text-secondary, #555)",strokeWidth:1}),d.map(e=>/* @__PURE__ */sa("g",{children:[
|
|
74
|
+
/* @__PURE__ */oa("line",{x1:e.x,x2:e.x,y1:o,y2:o+5,stroke:"var(--semiotic-text-secondary, #555)",strokeWidth:1}),
|
|
75
|
+
/* @__PURE__ */oa("text",{x:e.x,y:Math.min(r[1]-8,o+18),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:e.label})]},`${e.label}-${e.x}`))]})}}import{jsx as ha}from"react/jsx-runtime";function pa(e){if(!e)return;let t=Number(e[0]),i=Number(e[1]);return Number.isFinite(t)&&Number.isFinite(i)?t<=i?[t,i]:[i,t]:void 0}var ma=/* @__PURE__ */xs(function(e,t){let{data:i,valueAccessor:o="value",styleRules:a,bins:l=21,ballRadius:d,colorBy:c,branchProbability:u=.5,emptyContent:h,frameProps:p,loading:m,loadingContent:y,mechanicalCount:g,paused:b,pegRows:v,referenceLines:x,rerunMS:w,seed:I=1,valueExtent:k}=e,S=re(k),M=Qs(e,cs,{hasSimulationMode:!0}),{chartSize:A,simulationMode:$,showProjection:C,className:P,title:R,chartMode:D,margin:B,enableHover:T,description:j,summary:O,accessibleTable:E}=M,N=d??("sparkline"===D?1.5:"context"===D?4:6),F=ks(null),W=Math.max(1,Math.round(v??l-1)),q=Is(()=>"mechanical"===$?[0,W]:pa(S),[W,$,S]),H=Is(()=>"mechanical"===$?f({bins:l,branchProbability:u,count:g,pegRows:W,seed:I}):i,[l,u,i,g,W,I,$]),z=ws(e=>go({data:e,valueAccessor:o,bins:l,ballRadius:N,seed:I,size:A,valueExtent:q}),[l,A,N,q,I,o]),{layout:L,resetSeed:Y}=Ts({ref:t,frameRef:F,data:H,idPrefix:"galton",buildLayout:z}),_=Vs(L.config,w,b,Y,e.onSimulationStateChange),X="mechanical"===$&&null==c?"side":c,G=Is(()=>n(X,"#4e79a7",{styleRules:a,valueAccessor:o}),[X,a,o]),V=Is(()=>r(G,p?.bodyStyle),[G,p?.bodyStyle]),U=Is(()=>s(L.projectionRows,A,"bin"),[A,L.projectionRows]),{selection:K,onBodyHover:Q}=_s({selection:e.selection,linkedHover:e.linkedHover,colorBy:c,chartType:"GaltonBoardChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:p?.onBodyHover,fallbackFields:"string"==typeof o?[o]:void 0}),J=Zs({responsive:e,data:"mechanical"===$?H:i,emptyContent:h,loading:m,loadingContent:y,size:A});if(J)return J;let Z=aa(L.projectionRows,l,C,L.metadata,x),ee=ia(e.tooltip,p),te=ra(e,p,U,{selection:K,chartMode:D,className:P,title:R,description:j,summary:O,accessibleTable:E,enableHover:T,margin:B});return ea("GaltonBoardChart",A,
|
|
76
|
+
/* @__PURE__ */ha(yo,{...p,...ee,...te,ref:F,onBodyHover:Q,config:_.config,foregroundGraphics:ta(Z,p?.foregroundGraphics),initialSpawns:L.initialSpawns,initialSpawnPacing:L.initialSpawnPacing,paused:b,responsiveHeight:!1,responsiveWidth:!1,size:A,bodyStyle:V},`${A[0]}x${A[1]}:${_.rerunKey}`),M)});import{forwardRef as ya,useCallback as fa,useMemo as ga,useRef as ba}from"react";import{createElement as va}from"react";function xa(e,t,i){if(!t)return s(e,i,"window");let r=t.windowPlot.width/Math.max(1,e.length),n=e.reduce((e,t)=>Math.max(e,t.value),1),o=.62*t.windowPlot.height,a=t.windowPlot.y+t.windowPlot.height;return[...e.map((e,i)=>{let s=Math.max(8,e.value/n*o),l=t.windowPlot.x+(i+.5)*r,d=a-s/2,c=e.secondary?`, ${e.secondary} late sent to the far-left bin`:"",u=`window ${e.label}: ${e.value} on time${c}`;return{id:`window-${e.label}`,label:u,description:u,datum:e,x:l,y:d,shape:"rect",width:Math.max(12,.58*r),height:s,group:"window"}}),{id:"eventdrop-late-bin",label:`far-left bin: ${t.lateCount} late events`,description:"Late events are collected here, outside their original event-time windows.",datum:{label:"Late",value:t.lateCount},x:t.gutter.x+t.gutter.width/2,y:a-o/2,shape:"rect",width:t.gutter.width,height:o,group:"late-bin"}]}var wa=/* @__PURE__ */ya(function(e,t){let{arrivalAccessor:i="arrivalTime",ballRadius:o=7,colorBy:s,styleRules:a,data:l,emptyContent:d,frameProps:c,loading:u,loadingContent:h,paused:p,rerunMS:m,seed:y=1,timeAccessor:f="time",timeExtent:g,timeScale:b=1,watermark:v,watermarkAtArrivalAccessor:x,windows:w}=e,I=re(w??{size:10}),k=re(v),S=re(g),M=Qs(e,ps),{chartSize:A,showProjection:$,className:C,title:P,chartMode:R,margin:D,enableHover:B,description:T,summary:j,accessibleTable:O}=M,E=ba(null),N=fa(e=>Io({data:e,timeAccessor:f,arrivalAccessor:i,windows:I,watermark:k,watermarkAtArrivalAccessor:x,ballRadius:o,seed:y,size:A,timeExtent:S,timeScale:b}),[i,o,A,y,f,S,b,k,x,I]),{layout:F,resetSeed:W}=Ts({ref:t,frameRef:E,data:l,idPrefix:"event",buildLayout:N}),q=Vs(F.config,m,p,W,e.onSimulationStateChange),H=F.metadata,z=ga(()=>n(s,"#4e79a7",{styleRules:a,valueAccessor:f}),[s,a,f]),L=ga(()=>r(z,c?.bodyStyle),[z,c?.bodyStyle]),Y=ga(()=>xa(F.projectionRows,H,A),[A,F.projectionRows,H]),{selection:_,onBodyHover:X}=_s({selection:e.selection,linkedHover:e.linkedHover,colorBy:s,chartType:"EventDropChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:c?.onBodyHover,fallbackFields:"string"==typeof f?[f]:void 0}),G=Zs({responsive:e,data:l,emptyContent:d,loading:u,loadingContent:h,size:A});if(G)return G;let V=la(F.projectionRows,F.metadata,$),U=ia(e.tooltip,c),K=ra(e,c,Y,{selection:_,chartMode:R,className:C,title:P,description:T,summary:j,accessibleTable:O,enableHover:B,margin:D});return ea("EventDropChart",A,
|
|
77
|
+
/* @__PURE__ */va(yo,{...c,...U,...K,ref:E,onBodyHover:X,key:q.rerunKey,config:q.config,foregroundGraphics:ta(V,c?.foregroundGraphics),initialSpawns:F.initialSpawns,initialSpawnPacing:F.initialSpawnPacing,paused:p,responsiveHeight:!1,responsiveWidth:!1,size:A,bodyStyle:L}),M)});import{forwardRef as Ia,useCallback as ka,useMemo as Sa,useRef as Ma}from"react";import{createElement as Aa}from"react";var $a=/* @__PURE__ */Ia(function(e,t){let{ballRadius:i=8,categoryAccessor:o="category",colorBy:a,data:l,emptyContent:d,frameProps:c,loading:u,loadingContent:h,mechanicalCategories:p,mechanicalCount:y,paused:f,rerunMS:g,seed:b=1,unitValue:v=1,valueAccessor:x,styleRules:w}=e,I=re(p),k=Qs(e,us,{hasSimulationMode:!0}),{chartSize:S,simulationMode:M,showProjection:A,className:$,title:C,chartMode:P,margin:R,enableHover:D,description:B,summary:T,accessibleTable:j}=k,O=Ma(null),E="mechanical"===M&&null==x?"value":x,N=Sa(()=>"mechanical"===M?m({categories:I,count:y,seed:b,unitValue:v}):l,[l,I,y,b,M,v]),F=ka(e=>$o({data:e,categoryAccessor:o,valueAccessor:E,unitValue:v,ballRadius:i,seed:b,size:S}),[i,o,S,E,b,v]),{layout:W,resetSeed:q}=Ts({ref:t,frameRef:O,data:N,idPrefix:"pile",buildLayout:F}),H=Vs(W.config,g,f,q,e.onSimulationStateChange),z="mechanical"===M&&null==a?"category":a,L=Sa(()=>n(z,"#4e79a7",{styleRules:w,valueAccessor:x}),[z,w,x]),Y=Sa(()=>r(L,c?.bodyStyle),[L,c?.bodyStyle]),_=Sa(()=>s(W.projectionRows,S,"category"),[S,W.projectionRows]),{selection:X,onBodyHover:G}=_s({selection:e.selection,linkedHover:e.linkedHover,colorBy:a,chartType:"UnitPileChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:c?.onBodyHover,fallbackFields:"string"==typeof o?[o]:void 0}),V=Zs({responsive:e,data:"mechanical"===M?N:l,emptyContent:d,loading:u,loadingContent:h,size:S});if(V)return V;let U=da(W.projectionRows,i,A,Number.isFinite(v)&&v>0?v:1),K=ia(e.tooltip,c),Q=ra(e,c,_,{selection:X,chartMode:P,className:$,title:C,description:B,summary:T,accessibleTable:j,enableHover:D,margin:R});return ea("UnitPileChart",S,
|
|
78
|
+
/* @__PURE__ */Aa(yo,{...c,...K,...Q,ref:O,onBodyHover:G,key:`${S[0]}x${S[1]}:${H.rerunKey}`,config:H.config,foregroundGraphics:ta(U,c?.foregroundGraphics),initialSpawns:W.initialSpawns,initialSpawnPacing:W.initialSpawnPacing,paused:f,responsiveHeight:!1,responsiveWidth:!1,size:S,bodyStyle:Y}),k)}),Ca=$a;import{forwardRef as Pa,useCallback as Ra,useMemo as Da,useRef as Ba}from"react";import{useImperativeHandle as Ta,useRef as ja}from"react";function Oa(e,t){if(!t?.length)return[e];let i=t.filter(t=>{let i=t.datum;return i&&"object"==typeof i&&null!=i.id?String(i.id)===e:t.id===e||t.id.startsWith(`${e}-`)}).map(e=>e.id);return i.length?i:[e]}function Ea(e,t,i){if("function"==typeof i)return String(i(e,t));if("string"==typeof i){let t=e[i];if(null!=t)return String(t)}return null!=e&&"object"==typeof e&&"id"in e&&null!=e.id?String(e.id):`physics-row-${t}`}function Na(e,t){let i=e?.getData().find(e=>e.id===t)?.datum;if(i&&"object"==typeof i)return i}function Fa(e,t){let{frameRef:i,spawnDatum:r,seedRows:n,idAccessor:o,bodyIdsForSeed:s,seedSpawns:a}=t,l=ja(/* @__PURE__ */new Map),d=ja(/* @__PURE__ */new Map),c=ja(""),u=ja(!1);u.current=!0===t.staticEmpty,u.current&&(l.current.clear(),d.current.clear(),c.current="");let h=n?n.map((e,t)=>Ea(e,t,o)).join("\0"):"";if(h!==c.current&&(c.current=h,n))for(let e=0;e<n.length;e+=1){let t=n[e],i=Ea(t,e,o);l.current.set(i,t),d.current.set(i,s?.(t,i,e)??Oa(i,a))}Ta(e,()=>{let e=l.current,t=d.current;function n(e,t){let i=r(e,t);return{datumId:i.datumId||Ea(e,t,o),spawns:i.spawns.map(e=>({...e,spawnAt:void 0}))}}function s(r){if(u.current)return;let n=i.current;if(!n)return void("production"!==process.env.NODE_ENV&&r.length&&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."));let o=[];for(let{datum:i,result:n}of r)e.set(n.datumId,i),t.set(n.datumId,n.spawns.map(e=>e.id)),o.push(...n.spawns);o.length&&(n.pushMany(o),n.step(0))}function a(r){let n=e.get(r);if(n)return n;let o=t.get(r)??[r];for(let n of o){let o=Na(i.current,n);if(o)return e.set(r,o),t.has(r)||t.set(r,[n]),o}}return{push:t=>{s([{datum:t,result:n(t,e.size)}])},pushMany:t=>{let i=e.size;s(t.map((e,t)=>({datum:e,result:n(e,i+t)})))},remove:r=>{let n=Array.isArray(r)?r:[r],o=[],s=[];for(let i of n){let r=a(i);r&&o.push(r),e.delete(i),s.push(...t.get(i)??[i]),t.delete(i)}return s.length&&i.current?.remove(s),o},update:(r,o)=>{let l=Array.isArray(r)?r:[r],d=[];for(let r of l){let l=a(r);if(!l)continue;d.push(l);let c=t.get(r)??[r];i.current?.remove(c),e.delete(r),t.delete(r);let u=o(l);s([{datum:u,result:n(u,e.size)}])}return d},clear:()=>{e.clear(),t.clear(),c.current="",i.current?.clear()},getData:()=>{let t=i.current;if(!t)return Array.from(e.values());let r=t.getData().map(e=>e.datum).filter(e=>!!e&&"object"==typeof e);return r.length?r:Array.from(e.values())},getScales:()=>null,getCustomLayout:()=>i.current?.snapshot()??null,popBodies:(e,t)=>i.current?.popBodies(e,t)??[]}},[i,o,r])}import{scaleLinear as Wa}from"d3-scale";function qa(e,t,i){let r=e?.observation;return{...e,observation:{...r,chartId:t??r?.chartId??"physics-custom",chartType:r?.chartType??"PhysicsCustomChart",onObservation:i??r?.onObservation}}}function Ha(e,t){let i=t.config??{},r=(t.sensors??[]).map(e=>({...e,sensor:!0})),n=[...t.colliders??[],...r],o=[...e.colliders??[],...i.colliders??[],...n];return{...e,...i,observation:{...e.observation,...i.observation},...o.length>0&&{colliders:o}}}function za(e,t){if(!t?.length)return e;let i=/* @__PURE__ */new Map;for(let e of t){let{bodyId:t,...r}=e,n=i.get(t)??[];n.push(r),i.set(t,n)}return e.map(e=>{let t=i.get(e.id);return t?.length?{...e,springs:[...e.springs??[],...t]}:e})}function La(e){let t=qa(e.config,e.chartId,e.onObservation),r=v(e.colorScheme,e.themeCategorical,he),n=i(e.size),o={data:e.data,scales:{x:Wa().domain(e.xExtent??[0,1]).range([n.plot.x,n.plot.x+n.plot.width]),y:Wa().domain(e.yExtent??[0,1]).range([n.plot.y+n.plot.height,n.plot.y])},dimensions:n,theme:{semantic:e.semantic,categorical:[...r]},resolveColor:x(r,e.colorScheme),config:e.layoutConfig??{},world:new qi(t)},s=e.skipLayout?{}:e.layout(o)??{},a=za([...s.initialSpawns??s.bodies??[]],s.constraints);return{config:Ha(t,s),context:o,initialSpawnPacing:s.initialSpawnPacing,initialSpawns:a,result:s}}import{createElement as Ya}from"react";function _a(e,t,i){return"function"==typeof i?i(e,t):e[i]}function Xa(e,t,i){return Array.isArray(i)?{datumId:String(e.id??i[0]?.id??`physics-custom-${t}`),spawns:i}:"spawns"in i?i:{datumId:String(e.id??i.id??`physics-custom-${t}`),spawns:[i]}}var Ga=/* @__PURE__ */L(/* @__PURE__ */Pa(function(e,t){let{chartId:i,color:r,colorBy:n,colorScheme:o,config:s,controllers:a,data:l,emptyContent:d,frameProps:c={},layout:u,layoutConfig:h,loading:p,loadingContent:m,onObservation:y,opacity:f,paused:g,spawnDatum:b,stroke:v,strokeWidth:x,title:w,xExtent:I,yExtent:k}=e,S=Qs(e,fs),{chartSize:M,className:A,title:$,chartMode:C,margin:P,enableHover:R,description:D,summary:B,accessibleTable:T}=S,j=Ba(null),O=Ba(null),E=Ba(""),{selection:N,onBodyHover:F}=_s({selection:e.selection,linkedHover:e.linkedHover,colorBy:n,chartType:"PhysicsCustomChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:c?.onBodyHover}),W=Zs({responsive:e,data:l,emptyContent:d,loading:p,loadingContent:m,size:M}),q=null!=W,H=Da(()=>X(l??[]),[l]),z=Me(e=>e.theme),L=Da(()=>Se(z)??{},[z]),Y=z?.colors?.categorical??ke.colors.categorical,_=Da(()=>[M[0],M[1],H.length,H.map((e,t)=>String(e.id??t)).join("|"),I?.join(",")??"",k?.join(",")??""].join("::"),[M,H,I,k]),G=Da(()=>La({chartId:i,colorScheme:o,config:s,data:H,layout:u,layoutConfig:h,onObservation:y,semantic:L,skipLayout:q,size:M,themeCategorical:Y,xExtent:I,yExtent:k}),[i,M,o,s,u,h,y,H,L,q,Y,I,k]),V=Vs(G.config,void 0,g,void 0,e.onSimulationStateChange).config;(E.current!==_||null==O.current)&&(E.current=_,O.current=G.initialSpawns);let U=O.current,K=Da(()=>{let e=[...G.result.controllers??[],...a??[],...c.controllers??[]];return e.length?e:void 0},[c.controllers,a,G.result.controllers]),Q=Da(()=>{let e=[...G.result.regionEffects??[],...c.regionEffects??[]];return e.length?e:void 0},[c.regionEffects,G.result.regionEffects]),J=Ra(e=>{let t=e.datum,i=t&&n?String(_a(t,0,n)):e.id;return{fill:r??G.context.resolveColor(i,t),stroke:v??"#111827",strokeWidth:x??1,opacity:f??.9}},[r,n,f,G.context,v,x]),Z=Ra((e,t)=>{let r=e;if(b)return Xa(e,t,b(r,t,G.context));let n=La({chartId:i,colorScheme:o,config:s,data:[r],layout:u,layoutConfig:h,onObservation:y,semantic:L,size:M,themeCategorical:Y,xExtent:I,yExtent:k}),a={id:String(e.id??`physics-custom-${t}`),x:n.context.dimensions.plot.x+n.context.dimensions.plot.width/2,y:n.context.dimensions.plot.y+12,mass:1,shape:{type:"circle",radius:5},datum:e},l=n.initialSpawns.length?n.initialSpawns:[a];return{datumId:String(e.id??l[0].id),spawns:l}},[i,M,o,s,b,u,h,y,G.context,L,Y,I,k]);Fa(t,{frameRef:j,staticEmpty:0===l?.length,spawnDatum:Z,seedRows:H,seedSpawns:U});let ee=Ra((e,t)=>{c.onBodyPointerDown?.(e,t)},[c]);if(W)return W;let te=ia(e.tooltip,c),ie=ra(e,c,G.result.semanticItems,{selection:N,chartMode:C,className:A,title:$??w,description:D,summary:B,accessibleTable:T,enableHover:R,margin:P});return ea("PhysicsCustomChart",M,
|
|
79
|
+
/* @__PURE__ */Ya(yo,{...c,...te,...ie,key:`${M[0]}x${M[1]}`,ref:j,onBodyHover:F,backgroundGraphics:ta(c.backgroundGraphics,G.result.backgroundOverlays),bodyForces:G.result.bodyForces??c.bodyForces,bodyStyle:G.result.bodyStyle??c.bodyStyle??J,config:V,controllers:K,foregroundGraphics:ta(c.foregroundGraphics,G.result.overlays),initialSpawnPacing:G.initialSpawnPacing,initialSpawns:U,onBodyPointerDown:ee,paused:g,regionEffects:Q,responsiveHeight:!1,responsiveWidth:!1,selectedBodyStyle:G.result.selectedBodyStyle??c.selectedBodyStyle,size:M}),S)}),"PhysicsCustomChart");import{forwardRef as Va,useCallback as Ua,useMemo as Ka,useRef as Qa}from"react";import{jsx as Ja}from"react/jsx-runtime";function Za(e){if(!e)return[];let t=Math.max(24,e.xRange[1]-e.xRange[0]),i=e.xRange[0]+t/2;return e.groups.map(e=>{let r=`${e.label} lane: ${e.count} points`;return{id:`collision-swarm-${e.label}`,label:r,description:e.overlapping?`${r}. Points overlap at this size. Reduce radius or increase height.`:r,datum:e,x:i,y:e.y,shape:"rect",width:t,height:28,group:"lane"}})}var el=/* @__PURE__ */Va(function(e,t){let{colorBy:i,styleRules:o,collisionIterations:s,data:a,emptyContent:l,frameProps:d,groupAccessor:c,loading:u,loadingContent:h,paused:p,pointRadius:m,radiusAccessor:y,rerunMS:f,seed:g=1,settle:b,xAccessor:v="x",xExtent:x}=e,w=re(x),I=Qs(e,hs),{chartSize:k,showProjection:S,className:M,title:A,chartMode:$,margin:C,enableHover:P,description:R,summary:D,accessibleTable:B}=I,T=m??("sparkline"===$?2:"context"===$?4:5),j=Qa(null),O=Ua(e=>Ro({data:e,xAccessor:v,groupAccessor:c,radiusAccessor:y,pointRadius:T,seed:g,size:k,xExtent:w,collisionIterations:s,settle:b}),[k,s,c,T,y,g,b,v,w]),{layout:E,resetSeed:N}=Ts({ref:t,frameRef:j,data:a,idPrefix:"collision-swarm",buildLayout:O}),F=Vs(E.config,f,p,N,e.onSimulationStateChange),W=i??c,q=Ka(()=>n(W,"#4e79a7",{styleRules:o,valueAccessor:v}),[W,o,v]),H=Ka(()=>r(q,d?.bodyStyle),[q,d?.bodyStyle]),{selection:z,onBodyHover:L}=_s({selection:e.selection,linkedHover:e.linkedHover,colorBy:W,chartType:"CollisionSwarmChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:d?.onBodyHover,fallbackFields:"string"==typeof v?[v]:void 0}),Y=Zs({responsive:e,data:a,emptyContent:l,loading:u,loadingContent:h,size:k});if(Y)return Y;let _=ua(E.metadata,S),X=Za(E.metadata),G=ia(e.tooltip,d),V=ra(e,d,X,{selection:z,chartMode:$,className:M,title:A,description:R,summary:D,accessibleTable:B,enableHover:P,margin:C});return ea("CollisionSwarmChart",k,
|
|
80
|
+
/* @__PURE__ */Ja(yo,{...d,...G,...V,ref:j,onBodyHover:L,config:F.config,foregroundGraphics:ta(_,d?.foregroundGraphics),initialSpawns:E.initialSpawns,paused:p,responsiveHeight:!1,responsiveWidth:!1,size:k,bodyStyle:H},`${k[0]}x${k[1]}:${F.rerunKey}`),I)});function tl(e,t={}){let i=t.id??"physics-process-boundary",r={bodyFilter:t.bodyFilter,friction:t.friction,restitution:t.restitution};if("segment"===e.type)return[{...r,id:i,shape:e}];let n=t.thickness??8,o=e.x-e.width/2,s=e.x+e.width/2,a=e.y-e.height/2,l=e.y+e.height/2;return[{...r,id:`${i}-top`,shape:{type:"segment",x1:o,y1:a,x2:s,y2:a,thickness:n}},{...r,id:`${i}-right`,shape:{type:"segment",x1:s,y1:a,x2:s,y2:l,thickness:n}},{...r,id:`${i}-bottom`,shape:{type:"segment",x1:s,y1:l,x2:o,y2:l,thickness:n}},{...r,id:`${i}-left`,shape:{type:"segment",x1:o,y1:l,x2:o,y2:a,thickness:n}}]}function il(e){if(!1===e.semanticItem)return null;let t=e.semanticItem??{},i=e.shape,r="aabb"===i.type?{id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"region",x:i.x,y:i.y,width:i.width,height:i.height}:{id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"region",x:(i.x1+i.x2)/2,y:(i.y1+i.y2)/2,pathData:`M ${i.x1} ${i.y1} L ${i.x2} ${i.y2}`};return{...r,...t,id:t.id??r.id}}function rl(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 nl(e){return e.flatMap(e=>{if(!1===e.semanticItem)return[];let t=e.semanticItem??{},i={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[{...i,...t,id:t.id??i.id}]})}function ol(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 sl(e){return Array.isArray(e)}function al(e,t){return t?sl(t)?[...t]:t.ids?[...t.ids]:t.candidates?t.candidates.filter(t=>e.includes(t)).slice(0,t.count??1):[]:[]}function ll(e,t){return al(e.activePositiveIds,t.popPositive)}function dl(e){let t=Number(e.budget),i=Number.isFinite(t)?Math.max(0,t):0,r=e.properties instanceof Map?e.properties:new Map(e.properties.map(e=>[e.id,e])),n=e.candidates?new Set(e.candidates):null,o=e.attachedIds.map((e,t)=>{let i=r.get(e),n=Number(i?.work??1),o=Number(i?.priority??t);return{id:e,index:t,priority:Number.isFinite(o)?o:t,work:Number.isFinite(n)&&n>0?n:1}}).filter(e=>!n||n.has(e.id)).sort((e,t)=>e.priority-t.priority||e.index-t.index),s=[],a=[],l=0;for(let e of o)l+e.work>i+Number.EPSILON?a.push(e.id):(s.push(e.id),l+=e.work);return{ids:s,used:l,budget:i,remaining:Math.max(0,i-l),skippedIds:a}}function cl(e,t){if(!t.from||!t.to||t.from===t.to)return{};let i=Math.max(0,Math.floor(Number(t.count??1)||0)),r=e.negativeIds.filter(e=>e===t.from).length,n=Math.min(i,r);return n?{addNegative:{[t.to]:n},popNegative:{ids:Array.from({length:n},()=>t.from)}}:{}}function ul(e,t){let i=al(e.negativeIds,t.popNegative);if(!i.length)return[];let r=/* @__PURE__ */new Map;for(let e of i)r.set(e,(r.get(e)??0)+1);let n=[];return e.negativeIds.forEach((e,t)=>{let i=r.get(e)??0;i<=0||(n.push({propertyId:e,index:t}),r.set(e,i-1))}),n}function hl(e,t,i){if(t.when&&!t.when(i))return e;let r={...e},n=ll(r,t);n.length&&(r={...r,activePositiveIds:r.activePositiveIds.filter(e=>!n.includes(e)),poppedPositiveIds:Array.from(/* @__PURE__ */new Set([...r.poppedPositiveIds,...n]))});let o=ul(r,t);if(o.length){let e=new Set(o.map(e=>e.index));r={...r,negativeIds:r.negativeIds.filter((t,i)=>!e.has(i)),poppedNegativeIds:[...r.poppedNegativeIds,...o.map(e=>e.propertyId)]}}let s=ol(t.addPositive);s.length&&(r={...r,activePositiveIds:Array.from(/* @__PURE__ */new Set([...r.activePositiveIds,...s])),missingPositiveIds:r.missingPositiveIds.filter(e=>!s.includes(e))});let a=ol(t.addNegative);if(a.length&&(r={...r,negativeIds:[...r.negativeIds,...a]}),t.delayDelta&&(r={...r,delay:r.delay+t.delayDelta}),t.metricsDelta){let e={...r.metrics};for(let[i,r]of Object.entries(t.metricsDelta))e[i]=Number(e[i]??0)+r;r={...r,metrics:e}}return t.viabilityDelta&&(r={...r,viability:r.viability+t.viabilityDelta}),t.stage&&(r={...r,stage:t.stage}),t.outcome&&(r={...r,outcome:t.outcome}),r}function pl(e,t){return{id:e.id,label:e.label??e.id,summary:e.summary??t.find(e=>e.summary)?.summary,time:e.time}}function ml(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}}var yl="gauntlet-core",fl="gauntlet-positive",gl="gauntlet-negative",bl=(gs.width,gs.height,[]);function vl(e){let t=Al(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 xl(e,t,i,r){return i?"function"==typeof i?i(e,t):e[i]??r:r}function wl(e){return e?.label??e?.id??"property"}function Il(e){return`gauntlet:${e}:core`}function kl(e,t){return`gauntlet:${e}:positive:${t}`}function Sl(e,t,i){return`gauntlet:${e}:negative:${t}:${i}`}var Ml={left:28,top:76,rightInset:30,thickness:8};function Al(e){let t=e.height??e.floorY+36;if(!(e.width<220||t<160))return Ml;let i=Math.max(1,Math.min(e.width,t)),r=Math.max(2,.04*e.width);return{left:r,top:Math.max(2,.08*t),rightInset:r,thickness:Math.max(1,Math.min(4,.04*i))}}function $l(e){let t=e.height??e.floorY+36;return Math.max(.12,Math.min(1,e.width/500,t/260))}function Cl(e,t,i,r){let n=Al(r),o=Math.max(2,i+2),s=n.left+n.thickness/2+o,a=r.width-n.rightInset-n.thickness/2-o,l=n.top+n.thickness/2+o,d=r.floorY-o,c=(e,t,i)=>t<=i?Math.max(t,Math.min(i,e)):(t+i)/2;return{x:c(e,s,a),y:c(t,l,d)}}function Pl(e,t,i){let[r,n]=e,o=r<220||n<160,s=Math.round(.48*n),a=o?n-Math.max(3,Math.min(12,.1*n)):n-36,l=(t??[]).filter(e=>!1!==e.enabled),d=Math.max(1,l.length),c=.22*r,u=d<=1?0:(.78*r-c)/(d-1),h=o?Math.max(Math.round(.12*r),.08*r+6):Math.max(Math.round(.14*r),110);return{crashY:a-(o?Math.min(i,Math.max(3,.22*n)):i),floorY:a,gates:l.map((e,t)=>({...e,id:e.id,x:e.x??Math.round(c+t*u),width:e.width??Math.max(o?8:54,Math.round(.07*r))})),graveyardX:Math.round(r*(o?.72:.84)),graveyardY:a-4,height:n,routeY:s,socketX:Math.round(r*(o?.82:.92)),startX:h,width:r}}function Rl(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 Dl(e,t,i,r){let n=Rl(i),o=r?.(e,t,i)??{};return{...n,...o,startY:o.startY??o.routeY??n.startY,socketY:o.socketY??o.routeY??n.socketY,graveyardY:o.graveyardY??n.graveyardY}}function Bl(e,t,i=1){let r=[...e].sort((e,t)=>e.localeCompare(t)),n=Math.max(0,r.indexOf(t)),o=r.length>1?n/(r.length-1):.5;return{angle:.82*-Math.PI+o*Math.PI*.64,index:n,radius:(48+n%2*6)*i}}function Tl(e,t,i){let r=e.activePositiveIds.reduce((e,i)=>e+(t.get(i)?.value??1),0),n=e.missingPositiveIds.length+e.poppedPositiveIds.length,o=e.negativeIds.reduce((e,t)=>e+(i.get(t)?.load??1),0);return Math.max(0,Math.min(100,75+3*r-8*o-1.2*e.delay-5*n))}function jl(e,t,i,r,n){let o=String(xl(e,t,i.idAccessor,null!=e.id?String(e.id):`project-${t}`)),s=r.map(e=>e.id),a=[...xl(e,t,i.positiveAccessor,s)],l=[...xl(e,t,i.negativeAccessor,[])].filter(e=>n.has(e));return{id:o,activePositiveIds:a,datum:e,delay:0,eventsApplied:[],eventHistory:[],killed:!1,metrics:{...xl(e,t,i.metricsAccessor,{})},missingPositiveIds:s.filter(e=>!a.includes(e)),negativeIds:l,outcome:"in_process",poppedPositiveIds:[],poppedNegativeIds:[],startedAt:Math.max(0,Number(xl(e,t,i.startTimeAccessor,0))||0),stage:"project filed",viability:xl(e,t,i.initialViability,100)}}function Ol(e,t,i,r,n,o,s){let a=$l(i),l=Math.max(3,28*a),d=r.startX,c=r.startY+(r.startY===i.routeY?38*t*a:0),u=s?.(e,t,i,r)??{},h=u.x??d,p=u.y??c,m={__gauntlet:!0,kind:yl,projectId:e.id,sourceDatum:e.datum},y=[{...u,id:Il(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:l},spawnAt:u.spawnAt??e.startedAt,datum:m}],f=Cl(h,p,u.shape&&"radius"in u.shape&&Number(u.shape.radius)||l,i);y[0].x=f.x,y[0].y=f.y;for(let t of e.activePositiveIds){let r=n.get(t);if(!r)continue;let o=Bl(e.activePositiveIds,t,a),s=r.radius??Math.max(2,10*a),l=Cl(f.x+Math.cos(o.angle)*o.radius,f.y+Math.sin(o.angle)*o.radius,s,i);y.push({id:kl(e.id,t),x:l.x,y:l.y,vx:18*Math.cos(o.angle),vy:18*Math.sin(o.angle),mass:r.mass??.75,bodyCollisions:!1,shape:{type:"circle",radius:s},spawnAt:u.spawnAt??e.startedAt,datum:{__gauntlet:!0,kind:fl,projectId:e.id,property:r,sourceDatum:e.datum},springs:!1===r.spring?[]:[{target:{type:"body",bodyId:Il(e.id)},stiffness:.56,damping:.9,restLength:Math.max(6,(52+o.index%2*4)*a),...r.spring??{}}]})}return e.negativeIds.forEach((t,r)=>{let n=o.get(t);n&&y.push(El(e,n,r,f.x,f.y,i,u.spawnAt??e.startedAt))}),y}function El(e,t,i,r,n,o,s){let a=$l(o),l=t.radius??Math.max(2,7.2*a),d=Cl(r+(i%4*12-12)*a,n+(54+12*Math.floor(i/4))*a,l,o);return{id:Sl(e.id,t.id,i),x:d.x,y:d.y,vx:10,vy:6,mass:t.mass??.72,bodyCollisions:!1,shape:{type:"circle",radius:l},spawnAt:s,datum:{__gauntlet:!0,kind:gl,projectId:e.id,property:t,sourceDatum:e.datum},springs:!1===t.spring?[]:[{target:{type:"body",bodyId:Il(e.id)},stiffness:.62,damping:.92,restLength:Math.max(6,(52+i%4*3)*a),...t.spring??{}}]}}import{forwardRef as Nl,useCallback as Fl,useEffect as Wl,useImperativeHandle as ql,useMemo as Hl,useRef as zl,useState as Ll}from"react";function Yl(e,t){return e.length===t.length&&e.every((e,i)=>{let r=t[i];return!!r&&e.regionId===r.regionId&&e.queueDepth===r.queueDepth&&e.blockedDepth===r.blockedDepth&&e.processedCount===r.processedCount&&e.metricRevision===r.metricRevision})}function _l(e){let{dataKey:t,gates:i,statesRef:r,processedGateVisitsRef:n}=e;return i.flatMap(e=>{if(!e.capacity||e.capacity.unitsPerSecond<=0)return[];let i=`gauntlet-gate-${e.id}`;return[Yi({id:`gauntlet-capacity-${t}-${e.id}`,regionId:i,unitsPerSecond:e.capacity.unitsPerSecond,bodyFilter:{property:"datum.kind",equals:yl},maxQueue:e.capacity.maxQueue,queueLayout:e.capacity.queueLayout,queueSlotSpacing:e.capacity.queueSlotSpacing,queueStiffness:e.capacity.queueStiffness??24,releaseImpulse:{x:36,y:0},unitAccessor:t=>{let i,n=t.datum,o=n?.sourceDatum,s=e.capacity?.unitAccessor,a=r.current.find(e=>e.id===n?.projectId);"function"==typeof s?i=a?s(a):void 0:s&&(i=o?.[s]);let l=o?.reviewWork??o?.work??a?.metrics.reviewWork??o?.points,d=Number(i??l);return Number.isFinite(d)&&d>0?d:1},onProcessed:t=>{let i=t.datum;if(!i?.projectId)return;let r=`${i.projectId}:${e.id}`;n.current.set(r,(n.current.get(r)??0)+1)}})]})}function Xl(e){let{statesRef:t,setStates:i,elapsedRef:r,frameRef:n,layout:o,projectPlacement:s,positiveById:a,negativeById:l,coreBody:d,createState:c}=e;return{push:e=>{let u=c(e,t.current.length,r.current),h=Dl(u,t.current.length,o,s),p=Ol(u,t.current.length,o,h,a,l,d),m=[...t.current,u];t.current=m,i(m),n.current?.pushMany(p),n.current?.step(0)},pushMany:e=>{let u=[...t.current],h=[],p=r.current;e.forEach(e=>{let t=c(e,u.length,p),i=Dl(t,u.length,o,s);h.push(...Ol(t,u.length,o,i,a,l,d)),u.push(t)}),t.current=u,i(u),h.length&&n.current?.pushMany(h),n.current?.step(0)},remove:e=>{let r=Array.isArray(e)?e:[e],o=[],s=[];for(let e of r){let i=t.current.find(t=>t.id===e);i&&(o.push(i.datum),s.push(Il(i.id),...i.activePositiveIds.map(e=>kl(i.id,e))),i.negativeIds.forEach((e,t)=>{s.push(Sl(i.id,e,t))}))}return t.current=t.current.filter(e=>!r.includes(e.id)),i(t.current),n.current?.remove(s),o},update:(e,u)=>{let h=Array.isArray(e)?e:[e],p=[];for(let e of h){let i=t.current.find(t=>t.id===e);if(!i)continue;let h=t.current.findIndex(t=>t.id===e);p.push(i.datum);let m=u(i.datum),y=c(m,h<0?t.current.length:h,i.startedAt??r.current),f=Dl(y,h<0?t.current.length:h,o,s);n.current?.remove([Il(i.id),...i.activePositiveIds.map(e=>kl(i.id,e)),...i.negativeIds.map((e,t)=>Sl(i.id,e,t))]),n.current?.pushMany(Ol(y,h<0?t.current.length:h,o,f,a,l,d)),t.current=t.current.map(t=>t.id===e?y:t)}return i(t.current),p},clear:()=>{t.current=[],i([]),n.current?.clear()},getData:()=>t.current.map(e=>e.datum),getScales:()=>null,getCustomLayout:()=>n.current?.snapshot()??null,popBodies:(e,t)=>n.current?.popBodies(e,t)??[]}}function Gl(e,t,i){let{frameProps:r,elapsedRef:n,statesRef:o,crashDetection:s,layout:a,projectEvents:l,gateById:d,capacityEventReady:c,addBodiesForEffect:u,updateProjectState:h,viability:p,positiveById:m,negativeById:y,outcome:f,reportCapacity:g}=i;r.onTick?.(e,t),n.current=e.elapsedSeconds??t.snapshot().elapsedSeconds,g();for(let e of o.current){let i=t.readBodies().find(t=>t.id===Il(e.id));if(!i)continue;let r="circle"===i.shape.type?i.shape.radius:28;if(s&&!e.killed&&i.y+r>=a.crashY){t.readBodies().forEach(i=>{let r=i.datum;!r?.__gauntlet||r.projectId!==e.id||t.applyImpulse(i.id,-i.vx*i.mass,0)}),h(e.id,e=>{let t={appliedAt:Math.max(0,n.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,n.current-(e.startedAt??0))};return{...e,crashX:i.x,eventHistory:[...e.eventHistory??[],t],killed:!0,lastEvent:t,metrics:{...e.metrics,lastX:i.x},outcome:"bad_design_crash",stage:"Crash Line",viability:Math.min(0,e.viability)}});continue}if(e.killed)continue;let o=Math.max(0,n.current-(e.startedAt??0)),g=l(e),b=g.filter(t=>t.time<=o&&!e.eventsApplied.includes(t.id)&&c(e,t,g)),v=e;for(let i of b){let r=i.gateId?d.get(i.gateId):void 0,n=i.effects??[];for(let e of n){let n={event:i,gate:r,negativeProperties:y,positiveProperties:m,project:v};e.when&&!e.when(n)||(u(v,e,t),v=hl(v,e,n))}let s={...pl(i,n),appliedAt:o};v=ml(v,s),h(e.id,e=>{let t=ml(e,s);if(t===e)return e;for(let e of n)t=hl(t,e,{event:i,gate:r,negativeProperties:y,positiveProperties:m,project:t});let o=p?.(t,{negativeProperties:y,positiveProperties:m})??Tl(t,m,y);return t={...t,viability:o},i.final&&(t={...t,outcome:i.outcome??f?.(t,{layout:a,negativeProperties:y,positiveProperties:m})??(t.viability>20?"built":"approved_not_built")}),t})}}}function Vl(e,t){let i=e.datum;return!(!i?.__gauntlet||i.projectId!==t||i.kind!==gl)}function Ul(e){let t=e.id.slice(e.id.lastIndexOf(":")+1),i=Number(t);return Number.isFinite(i)?i:-1}function Kl(e,t){let i=-1;for(let r of t)Vl(r,e.id)&&(i=Math.max(i,Ul(r)));return Math.max(e.negativeIds.length,i+1)}function Ql(e,t,i){let r=t.filter(t=>Vl(t,e.id)).sort((e,t)=>Ul(e)-Ul(t)||e.id.localeCompare(t.id)),n=/* @__PURE__ */new Set;return i.map(t=>{let i=r.find(e=>!n.has(e.id)&&e.datum.property?.id===t.propertyId);return i?(n.add(i.id),i.id):Sl(e.id,t.propertyId,t.index)})}function Jl(e,t){return Math.hypot(e.vx,e.vy)<2&&Math.hypot(t.x,t.y)<4?null:t}function Zl(e){let{body:t,bodies:i,layout:r,states:n,projectPlacement:o,positiveById:s,negativeById:a,projectEvents:l,gateById:d,coreForceMode:c,terminalBehavior:u,elapsed:h}=e,p=t.datum;if(!p?.__gauntlet)return null;let m=n.findIndex(e=>e.id===p.projectId),y=m>=0?n[m]:void 0;if(!y)return null;let f=Dl(y,m,r,o),g=i.find(e=>e.id===Il(y.id)),b=$l(r),v=y.negativeIds.reduce((e,t)=>e+(a.get(t)?.load??1),0),x=y.killed?0:58*Math.max(.25,b);if(p.kind!==yl){if(!g)return null;let e,n=p.property;if(n?.target){let o=i.filter(e=>{let t=e.datum;return t?.__gauntlet&&t.projectId===y.id&&t.kind===p.kind}).sort((e,t)=>String(e.id).localeCompare(String(t.id))),s=Math.max(0,o.findIndex(e=>e.id===t.id));e=n.target({body:t,bodies:i,core:g,index:s,layout:r,placement:f,project:y})??{x:g.x,y:g.y}}else if(p.kind===fl&&p.property){let t=Bl(y.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{let r=i.filter(e=>e.datum?.kind===gl&&e.datum.projectId===y.id).sort((e,t)=>String(e.id).localeCompare(String(t.id))),n=Math.max(0,r.findIndex(e=>e.id===t.id)),o=Math.floor(n/4),s=Math.min(4,r.length-4*o),a=n%4;e={x:g.x+18*(a-(s-1)/2)*b,y:g.y+(54+13*o)*b}}let o="circle"===t.shape.type?t.shape.radius:8;e=Cl(e.x,e.y,o,r);let s=Cl(t.x,t.y,o,r);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};let a=p.kind!==fl||y.killed?0:3.2*(n?.buoyancy??n?.value??1),l=p.kind===gl?{x:.22*(n?.pull?.x??-8),y:.22*(n?.pull?.y??22)}:{x:0,y:0};return Jl(t,{x:28*(e.x-t.x)-3*(t.vx-g.vx)+l.x+.01*x,y:28*(e.y-t.y)-3*(t.vy-g.vy)+l.y-a})}if(y.killed){let e=y.crashX??y.metrics.lastX??t.x;return Jl(t,{x:44*(e-t.x)-9*t.vx,y:(160+12*v)*b-1.6*t.vy})}let w=l(y),I=td(Math.max(0,h-(y.startedAt??0)),y,r,f,w,d,u),k=y.activePositiveIds.reduce((e,t)=>e+(s.get(t)?.buoyancy??s.get(t)?.value??1),0),S=13*v;if("net"===c){let e=32*(v-k);return Jl(t,{x:15*(I.x-t.x)-1.8*t.vx+.18*x,y:1.25*(f.routeY-t.y)-1.4*t.vy+e})}return Jl(t,{x:15*(I.x-t.x)-1.8*t.vx+.18*x,y:15*(I.y-t.y)-1.8*t.vy+S-2.2*k})}function ed(e){let{project:t,effect:i,controls:r,layout:n,positiveById:o,negativeById:s,coreBody:a,popBodies:l,popScale:d}=e,c=r.readBodies().find(e=>e.id===Il(t.id)),u=r.readBodies(),h=c?.x??n.startX,p=c?.y??n.routeY,m=Kl(t,u),y=ol(i.addNegative).flatMap((e,i)=>{let r=s.get(e);return r?[El(t,r,m+i,h,p,n)]:[]}),f=ol(i.addPositive).flatMap(e=>{if(!o.get(e)||t.activePositiveIds.includes(e))return[];let i={...Rl(n),routeY:p,socketY:p,startX:h,startY:p};return Ol({...t,activePositiveIds:[e],negativeIds:[]},0,n,i,o,s,a).filter(e=>e.id.includes(":positive:"))});(y.length||f.length)&&r.pushMany([...y,...f]);let g=ll(t,i);for(let e of g){let i=o.get(e);l([kl(t.id,e)],{color:i?.popColor??i?.color,durationMs:900,radius:(i?.radius??10)+3,scale:d})}let b=ul(t,i),v=Ql(t,u,b);b.forEach((e,t)=>{let i=s.get(e.propertyId);l([v[t]],{color:i?.popColor??i?.color,durationMs:900,radius:(i?.radius??7)+3,scale:d})})}function td(e,t,i,r,n,o,s){let a=$l(i);if(t.killed)return{x:t.metrics.lastX??r.graveyardX,y:r.graveyardY};let l=n[n.length-1];if(!l)return{x:r.socketX,y:r.routeY};let d=n.find(i=>!(i.time>e||t.eventsApplied.includes(i.id)||!i.gateId||!o.get(i.gateId)?.capacity)),c=d?Math.min(e,d.time):e,u="built"===t.outcome||"built_diminished"===t.outcome;if(c>l.time+.85){if("hold-last"===s){let e=l.gateId?o.get(l.gateId):void 0;return{x:l.routeX??e?.x??r.socketX,y:l.routeY??r.routeY}}return u?{x:r.socketX,y:r.socketY}:{x:r.graveyardX,y:r.graveyardY-14}}let h=.85*t.delay+12*t.negativeIds.length+8*(t.poppedPositiveIds.length+t.missingPositiveIds.length),p=[{time:0,x:r.startX,y:r.startY},...n.map(e=>{let t=e.gateId?o.get(e.gateId):void 0;return{time:e.time,x:e.routeX??t?.x??r.startX,y:e.routeY??r.routeY+.28*Math.min(180,h)*a}})].sort((e,t)=>e.time-t.time),m=p[0],y=p[p.length-1];for(let e=1;e<p.length;e+=1){if(c<=p[e].time){y=p[e];break}m=p[e]}let f=Math.max(.1,y.time-m.time),g=Math.max(0,Math.min(1,(c-m.time)/f)),b=g*g*(3-2*g);return{x:m.x+(y.x-m.x)*b,y:m.y+(y.y-m.y)*b+7*Math.sin(2.6*c)*a}}import{Fragment as id,jsx as rd,jsxs as nd}from"react/jsx-runtime";var od="var(--semiotic-surface, var(--semiotic-bg, #fff))";function sd(e){let t=e.data;if(!t?.__gauntlet)return null;let i="string"==typeof t.sourceDatum?.label?t.sourceDatum.label:t.projectId;/* */
|
|
81
|
+
return nd("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:[
|
|
82
|
+
/* @__PURE__ */rd("strong",{children:t.kind===yl?i:wl(t.property)}),
|
|
83
|
+
/* @__PURE__ */rd("div",{children:t.kind===fl?"Positive property":t.kind===gl?"Negative property":"Project core"})]})}function ad(e,t,i,r){let n=t.datum;if(!n?.__gauntlet)return;let o="circle"===t.shape.type?t.shape.radius:8,s=r?.resolvePaint??((t,i)=>ge(e,t,i));if(e.save(),e.translate(t.x,t.y),n.kind===yl)e.fillStyle=s(i.fill,"#0f766e"),e.strokeStyle=s(i.stroke,"#fff"),e.lineWidth=2.4,e.beginPath(),e.arc(0,0,o,0,2*Math.PI),e.fill(),e.stroke();else{let t=n.property;e.fillStyle=s(i.fill??t?.color,"#38bdf8"),e.strokeStyle=s(i.stroke,"#0f172a"),e.lineWidth=1.1,e.beginPath(),n.kind===gl?e.rect(-o,-o,2*o,2*o):e.arc(0,0,o,0,2*Math.PI),e.fill(),e.stroke(),e.fillStyle=s(od,"#fff");let r=me(e,"var(--semiotic-font-family, sans-serif)")||"sans-serif";e.font=`900 ${n.kind===gl?9:8}px ${r}`,e.textAlign="center",e.textBaseline="middle",e.fillText(t?.short??t?.id?.slice(0,1).toUpperCase()??"?",0,.5)}e.restore()}function ld(e,t,i){let r=new Map(t.filter(e=>e.datum?.kind===yl).map(e=>[e.datum.projectId,e])),n=i?.resolvePaint??((t,i)=>ge(e,t,i)),o=n("var(--semiotic-danger, #ef4444)","#ef4444"),s=n("var(--semiotic-text-secondary, #64748b)","#64748b");e.save(),e.lineWidth=1.1,e.setLineDash([3,4]);for(let i of t){let t=i.datum;if(!t?.__gauntlet||t.kind===yl)continue;let n=r.get(t.projectId);n&&(e.globalAlpha=t.kind===gl?.24:.36,e.strokeStyle=t.kind===gl?o:s,e.beginPath(),e.moveTo(n.x,n.y),e.lineTo(i.x,i.y),e.stroke())}e.restore()}function dd({layout:e,compact:t,showLabels:i}){let r=t?Math.round(.14*e.height):Math.max(80,e.routeY-180),n=t?Math.max(6,Math.round(.72*e.height)):Math.min(360,e.height-170);/* */
|
|
84
|
+
return rd(id,{children:e.gates.map(o=>/* @__PURE__ */nd("g",{children:[
|
|
85
|
+
/* @__PURE__ */rd("rect",{x:o.x-o.width/2,y:r,width:o.width,height:n,rx:t?2:12,fill:o.color??"var(--semiotic-primary, #38bdf8)",fillOpacity:.1,stroke:o.color??"var(--semiotic-primary, #38bdf8)",strokeDasharray:"5 5",strokeOpacity:.7}),i?/* @__PURE__ */rd("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 cd({layout:e,states:t,compact:i=!1}){return i?/* @__PURE__ */rd("svg",{"aria-hidden":"true",viewBox:`0 0 ${e.width} ${e.height}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:/* @__PURE__ */rd(dd,{layout:e,compact:!0,showLabels:!1})}):/* @__PURE__ */nd("svg",{"aria-hidden":"true",viewBox:`0 0 ${e.width} ${e.height}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[
|
|
86
|
+
/* @__PURE__ */rd("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-primary, #38bdf8)",strokeDasharray:"18 12",strokeLinecap:"round",strokeOpacity:.45,strokeWidth:7}),
|
|
87
|
+
/* @__PURE__ */rd("line",{x1:Math.round(.06*e.width),x2:Math.round(.94*e.width),y1:e.crashY,y2:e.crashY,stroke:"var(--semiotic-danger, #ef4444)",strokeDasharray:"3 7",strokeOpacity:.64}),
|
|
88
|
+
/* @__PURE__ */rd("text",{x:Math.round(.07*e.width),y:e.crashY-8,fill:"var(--semiotic-danger, #ef4444)",fontSize:9,fontWeight:800,children:"CRASH LINE"}),
|
|
89
|
+
/* @__PURE__ */rd(dd,{layout:e,compact:!1,showLabels:!0}),
|
|
90
|
+
/* @__PURE__ */nd("g",{children:[
|
|
91
|
+
/* @__PURE__ */rd("rect",{x:e.socketX-52,y:e.routeY-56,width:104,height:112,rx:13,fill:"var(--semiotic-success, #22c55e)",fillOpacity:.12,stroke:"var(--semiotic-success, #22c55e)",strokeWidth:1.5}),
|
|
92
|
+
/* @__PURE__ */rd("text",{x:e.socketX,y:e.routeY-72,fill:"var(--semiotic-text-secondary, #64748b)",fontSize:10,fontWeight:800,textAnchor:"middle",children:"SOCKET"})]}),
|
|
93
|
+
/* @__PURE__ */nd("g",{children:[
|
|
94
|
+
/* @__PURE__ */rd("rect",{x:e.graveyardX-82,y:e.graveyardY-34,width:164,height:58,rx:11,fill:"var(--semiotic-danger, #ef4444)",fillOpacity:.16,stroke:"var(--semiotic-danger, #ef4444)",strokeOpacity:.7}),
|
|
95
|
+
/* @__PURE__ */rd("text",{x:e.graveyardX,y:e.graveyardY-8,fill:"var(--semiotic-danger, #ef4444)",fontSize:10,fontWeight:800,textAnchor:"middle",children:"GRAVEYARD"}),
|
|
96
|
+
/* @__PURE__ */rd("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 ud(e){let t=e.datum;return!!t?.__gauntlet&&(t.kind===yl?{label:`${t.projectId} project core`,group:"project",description:"Project core carrying positive and negative properties."}:{label:`${wl(t.property)} ${t.kind===fl?"positive":"negative"} property`,group:t.kind===fl?"positive property":"negative property",description:`${wl(t.property)} attached to ${t.projectId}.`})}function hd(e){return e.map(e=>({label:e.id,value:Math.max(0,Number(e.viability)||0),outcome:e.outcome||e.stage||"in-process"}))}function pd(e,t){if(!e.length)return[];let i=Math.max(40,(t.width-80)/e.length);return e.map((e,t)=>{let r=`${e.id}: viability ${Math.round(e.viability)}, ${e.outcome||e.stage}`;return{id:`gauntlet-projection-${e.id}`,label:r,description:r,datum:e,x:40+(t+.5)*i,y:28,shape:"rect",width:Math.max(16,.55*i),height:22,group:"settled projection"}})}function md({states:e,layout:t}){let i=hd(e);if(!i.length)return null;let r=i.reduce((e,t)=>Math.max(e,t.value),1),n=Math.max(40,(t.width-80)/i.length);/* */
|
|
97
|
+
return nd("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:[
|
|
98
|
+
/* @__PURE__ */rd("text",{x:36,y:18,fill:"var(--semiotic-text-secondary, #64748b)",fontSize:9,fontWeight:800,children:"SETTLED · viability / outcome"}),i.map((e,t)=>{let i=40+t*n,o=Math.max(2,e.value/r*28),s=/kill|crash|block|grave/i.test(e.outcome);/* */
|
|
99
|
+
return nd("g",{children:[
|
|
100
|
+
/* @__PURE__ */rd("rect",{x:i+.18*n,y:28-o+22,width:Math.max(10,.45*n),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}),
|
|
101
|
+
/* @__PURE__ */rd("text",{x:i+.4*n,y:62,textAnchor:"middle",fill:"var(--semiotic-text-secondary, #64748b)",fontSize:9,fontWeight:700,children:e.label})]},e.label)})]})}import{jsx as yd}from"react/jsx-runtime";import{createElement as fd}from"react";var gd=/* @__PURE__ */L(/* @__PURE__ */Nl(function(e,t){let{bodyGroups:i,coreBody:r,coreForceMode:n="route",crashDetection:o=!0,crashOffset:s=30,data:a,emptyContent:l,events:d,frameProps:c={},gates:u,initialSpawnPacing:h,loading:p,loadingContent:m,negativeProperties:y,onCapacityChange:f,onClick:g,onStateChange:b,outcome:v,paused:x,positiveProperties:w=bl,projectPlacement:I,rerunMS:k,seed:S,showTethers:M=!0,terminalBehavior:A="outcome",viability:$}=e,C=zl(null),P=Hl(()=>({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]),R=Qs(e,gs),{chartSize:D,showProjection:B,showChrome:T,className:j,title:O,chartMode:E,margin:N,enableHover:F,description:W,summary:q,accessibleTable:H}=R,{selection:z,onBodyHover:L}=_s({selection:e.selection,linkedHover:e.linkedHover,colorBy:void 0,chartType:"GauntletChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:c?.onBodyHover,fallbackFields:"string"==typeof e.idAccessor?[e.idAccessor]:["id"],unwrapSourceDatum:!0}),Y=Zs({responsive:e,data:a,emptyContent:l,loading:p,loadingContent:m,size:D}),_=Hl(()=>X(a??[]),[a]),G=Hl(()=>_.map((e,t)=>String(xl(e,t,P.idAccessor,null!=e.id?String(e.id):`project-${t}`))).join("|"),[_,P.idAccessor]),V=Hl(()=>new Map(w.map(e=>[e.id,e])),[w]),U=Hl(()=>new Map(y.map(e=>[e.id,e])),[y]),K=Hl(()=>Pl(D,u,s),[D,s,u]),Q=Hl(()=>new Map(K.gates.map(e=>[e.id,e])),[K.gates]),J=Hl(()=>K.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:yl}:e.regionEffect?.bodyFilter,shape:{type:"aabb",x:e.x,y:K.routeY,width:e.capacity?e.capacity.sensorWidth??Math.max(K.width<220?12:96,e.width*(K.width<220?2:6)):Math.max(e.width,K.width<220?10:54),height:Math.max(4,Math.min(360,K.height-(K.height<160?8:170)))}})),[K.gates,K.height,K.routeY,K.width]),Z=zl(_);Z.current=_;let ee=zl(b);ee.current=b;let te=zl({negativeById:U,positiveById:V,positiveProperties:w,stateAccessors:P,viability:$});te.current={negativeById:U,positiveById:V,positiveProperties:w,stateAccessors:P,viability:$};let ie=Fl((e,t,i=0)=>{let r=te.current,n=jl(e,t,r.stateAccessors,r.positiveProperties,r.negativeById);return r.stateAccessors.startTimeAccessor||(n.startedAt=Math.max(0,i)),{...n,viability:r.viability?.(n,{negativeProperties:r.negativeById,positiveProperties:r.positiveById})??Tl(n,r.positiveById,r.negativeById)}},[]),[re,ne]=Ll(()=>_.map((e,t)=>ie(e,t))),oe=zl(re),se=zl(0),ae=zl(/* @__PURE__ */new Map),le=zl([]),de=zl(f);de.current=f;let ce=Fl(()=>{ae.current.clear(),le.current=[],se.current=0;let e=Z.current.map((e,t)=>ie(e,t));oe.current=e,ne(e)},[ie]),ue=Vs(Hl(()=>({fixedDt:1/60,maxSubsteps:8,kernel:{gravity:{x:0,y:0},restitution:.16,friction:.44,velocityDamping:.982,maxVelocity:520,sleepAfter:.8,sleepSpeed:7,...null!=S&&{seed:S},...c.config?.kernel??{}},colliders:[...vl(K),...c.config?.colliders??[]]}),[c.config?.colliders,c.config?.kernel,K,S]),k,x,ce,e.onSimulationStateChange),he=Hl(()=>_l({dataKey:`${G}:${ue.rerunKey}`,gates:K.gates,statesRef:oe,processedGateVisitsRef:ae}),[G,K.gates,ue.rerunKey]),pe=Hl(()=>[...he,...c.controllers??[]],[he,c.controllers]),me=zl(G);if(me.current!==G){me.current=G,ae.current.clear(),le.current=[],se.current=0;let e=Z.current.map((e,t)=>ie(e,t));oe.current=e,ne(e)}Wl(()=>{ee.current?.(oe.current)},[re]);let ye=Fl(e=>[...("function"==typeof d?d(e,K):d)??[]].sort((e,t)=>e.time-t.time),[d,K]),fe=Fl((e,t,i)=>{if(!t.gateId||!Q.get(t.gateId)?.capacity)return!0;let r=Number(t.gateVisit),n=Number.isFinite(r)&&r>0?Math.floor(r):i.filter(e=>e.gateId===t.gateId).findIndex(e=>e.id===t.id)+1;return!(n<=0)&&(ae.current.get(`${e.id}:${t.gateId}`)??0)>=n},[Q]),ge=Fl(()=>{if(!he.length)return;let e=he.flatMap(e=>{let t=e.getSnapshot?.();return t?[t]:[]});Yl(le.current,e)||(le.current=e,de.current?.(e))},[he]),be=Hl(()=>re.flatMap((e,t)=>{let i=Dl(e,t,K,I);return Ol(e,t,K,i,V,U,r)}),[r,K,U,V,I,re]),ve=Fl((e,t)=>{let i=!1,r=oe.current.map(r=>{if(r.id!==e)return r;let n=t(r);return i=i||n!==r,n});i&&(oe.current=r,ne(r))},[]);ql(t,()=>Xl({statesRef:oe,setStates:ne,elapsedRef:se,frameRef:C,layout:K,projectPlacement:I,positiveById:V,negativeById:U,coreBody:r,createState:ie}),[r,ie,K,U,V,I]);let xe="sparkline"===E?.22:"mobile"===E?.55:1,we=Fl((e,t,i)=>{ed({project:e,effect:t,controls:i,layout:K,positiveById:V,negativeById:U,coreBody:r,popBodies:(e,t)=>C.current?.popBodies(e,t),popScale:xe})},[r,K,U,V,xe]),Ie=Fl(({body:e,bodies:t})=>Zl({body:e,bodies:t,layout:K,states:oe.current,projectPlacement:I,positiveById:V,negativeById:U,projectEvents:ye,gateById:Q,coreForceMode:n,terminalBehavior:A,elapsed:se.current}),[n,Q,K,U,V,ye,I,A]),ke=Fl((e,t)=>{Gl(e,t,{frameProps:c,elapsedRef:se,statesRef:oe,crashDetection:o,layout:K,projectEvents:ye,gateById:Q,capacityEventReady:fe,addBodiesForEffect:we,updateProjectState:ve,viability:$,positiveById:V,negativeById:U,outcome:v,reportCapacity:ge})},[we,fe,o,c,Q,K,U,v,V,ye,ge,ve,$]),Se=Fl((e,t)=>{let i="function"==typeof c.bodyStyle?c.bodyStyle(e,t):c.bodyStyle,r=e.datum;return r?.__gauntlet?{fill:r.kind===yl?"var(--semiotic-primary, #0f766e)":r.property?.color??"var(--semiotic-primary, #38bdf8)",stroke:r.kind===yl?od:"var(--semiotic-text, #0f172a)",opacity:.96,...i}:i??{}},[c]),Me=Hl(()=>"function"==typeof i?i(re,K):i??[],[i,K,re]),Ae=Hl(()=>nl(Me),[Me]),$e=Hl(()=>B?pd(re,K):[],[K,B,re]),Ce=Hl(()=>[...$e,...Ae],[Ae,$e]),Pe=Fl((e,t)=>{c.onBodyPointerDown?.(e,t)},[c]),Re=Fl((e,t)=>{if(!g)return;let i=e;i&&"object"==typeof i&&i.__gauntlet?g(i.sourceDatum,{x:t.x,y:t.y}):e&&g(e,{x:t.x,y:t.y})},[g]),De=Fl((e,t,i)=>{c.beforePaint?.(e,t,i),M&&ld(e,t,i)},[c,M]),Be=Hl(()=>[...J,...c.regionEffects??[]],[c.regionEffects,J]);if(Y)return Y;let Te=ia(e.tooltip,c),je=ra(e,c,Ce,{selection:z,chartMode:E,className:j,title:O,description:W,summary:q,accessibleTable:H,enableHover:F,margin:N}),Oe=B?/* @__PURE__ */yd(md,{states:re,layout:K}):void 0,Ee=ta(T?/* @__PURE__ */yd(cd,{layout:K,states:re,compact:R.resolved.compactMode}):void 0,c.backgroundGraphics),Ne=ta(Oe,c.foregroundGraphics),Fe=c.renderBody??ad,We=Te.tooltipContent??sd;return ea("GauntletChart",D,
|
|
102
|
+
/* @__PURE__ */fd(yo,{...c,...Te,...je,key:`${D[0]}x${D[1]}:${G}:${ue.rerunKey}`,ref:C,onBodyHover:L,accessibleTable:e.accessibleTable??c.accessibleTable,backgroundGraphics:Ee,backgroundGraphicsBackdrop:c.backgroundGraphicsBackdrop??"var(--semiotic-bg, transparent)",bodyForces:Ie,bodySemanticItems:c.bodySemanticItems??ud,bodyStyle:Se,beforePaint:De,onClick:g?Re:je.onClick,config:ue.config,controllers:pe,enableHover:Te.enableHover??!0,foregroundGraphics:Ne,hoverRadius:e.hoverRadius??c.hoverRadius??18,initialSpawns:be,initialSpawnPacing:h,onBodyPointerDown:Pe,onTick:ke,paused:x,regionEffects:Be,renderBody:Fe,responsiveHeight:!1,responsiveWidth:!1,size:D,tooltipContent:We}),R)}),"GauntletChart"),bd=gd;import{forwardRef as vd,useCallback as xd,useMemo as wd,useRef as Id}from"react";function kd(e){return Math.abs(e)>=1e3?e.toLocaleString(void 0,{maximumFractionDigits:0}):e.toLocaleString(void 0,{maximumFractionDigits:1})}function Sd(e){return e.map((e,t)=>`${0===t?"M":"L"} ${e.x} ${e.y}`).join(" ")}import{jsx as Md,jsxs as Ad}from"react/jsx-runtime";function $d(e,t){let{showNodeLabels:i,showSensors:r,showStaticFlow:n}=t;if(e&&(n||r||i))return({size:t})=>{let o=[Number(t[0])||760,Number(t[1])||420],s=e.links.reduce((e,t)=>Math.max(e,t.throughput),1),a=new Set(e.nodes.map(e=>e.sensorId));/* */
|
|
103
|
+
return Ad("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:[n?e.links.map(e=>{let t=3+e.throughput/s*16,i=e.path[Math.floor(e.path.length/2)];/* */
|
|
104
|
+
return Ad("g",{children:[
|
|
105
|
+
/* @__PURE__ */Md("path",{d:Sd(e.path),fill:"none",stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:t+5,strokeLinecap:"round",strokeLinejoin:"round",opacity:.26}),
|
|
106
|
+
/* @__PURE__ */Md("path",{d:Sd(e.path),fill:"none",stroke:"var(--semiotic-primary, #4e79a7)",strokeWidth:t,strokeLinecap:"round",strokeLinejoin:"round",opacity:.16}),i?/* @__PURE__ */Md("text",{x:i.x,y:i.y-t/2-5,textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:kd(e.throughput)}):null]},e.id)}):null,e.nodes.map(e=>/* @__PURE__ */Ad("g",{children:[r&&a.has(e.sensorId)?/* @__PURE__ */Md("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,n?/* @__PURE__ */Md("circle",{cx:e.x,cy:e.y,r:6,fill:"var(--semiotic-bg, #fff)",stroke:"var(--semiotic-text-secondary, #555)",strokeWidth:1.2}):null,i?/* @__PURE__ */Md("text",{x:e.x,y:e.y-14,textAnchor:"middle",fill:"var(--semiotic-text, #111827)",fontSize:11,fontWeight:800,children:e.label}):null]},e.id))]})}}import{createElement as Cd}from"react";function Pd(e){if(!e||"object"!=typeof e)return null;let t=e,i=Number(t.x),r=Number(t.y);return Number.isFinite(i)&&Number.isFinite(r)?{x:i,y:r}:null}function Rd(e){if(!e||"object"!=typeof e)return[];let t=e.flowPath;return Array.isArray(t)?t.map(Pd).filter(e=>null!=e):[]}function Dd(e,t){if(t.length<2)return null;let i=0,r=[];for(let e=1;e<t.length;e+=1){let n=Math.hypot(t[e].x-t[e-1].x,t[e].y-t[e-1].y);r.push(n),i+=n}if(i<=0)return null;let n=null,o=0;for(let s=1;s<t.length;s+=1){let a=t[s-1],l=t[s],d=r[s-1];if(d<=0)continue;let c=l.x-a.x,u=l.y-a.y,h=Math.max(0,Math.min(1,((e.x-a.x)*c+(e.y-a.y)*u)/(d*d))),p={x:a.x+c*h,y:a.y+u*h},m={distance:Math.hypot(e.x-p.x,e.y-p.y),point:p,progress:(o+h*d)/i,tangent:{x:c/d,y:u/d},totalLength:i};(!n||m.distance<n.distance)&&(n=m),o+=d}return n}function Bd(e,t,i){if(0===e.length)return{x:0,y:0};if(1===e.length||i<=0)return{...e[0]};let r=0,n=Math.max(0,Math.min(1,t))*i;for(let t=1;t<e.length;t+=1){let i=e[t-1],o=e[t],s=Math.hypot(o.x-i.x,o.y-i.y);if(!(s<=0)){if(r+s>=n){let e=(n-r)/s;return{x:i.x+(o.x-i.x)*e,y:i.y+(o.y-i.y)*e}}r+=s}}return{...e[e.length-1]}}function Td(e){return"circle"===e.shape.type?e.shape.radius:Math.max(e.shape.width,e.shape.height)/2}function jd(e,t,i){let r=Math.hypot(e,t);if(r<=i||r<=0)return[e,t];let n=i/r;return[e*n,t*n]}function Od(e,t){let i=0;for(let t=0;t<e.length;t+=1)i=31*i+e.charCodeAt(t)>>>0;return(i%1e3/1e3-.5)*t*1.4}function Ed(e,t,i){let r=Dd({...e,x:t[0].x,y:t[0].y},t)?.tangent??{x:t[1].x-t[0].x,y:t[1].y-t[0].y},n=Math.hypot(r.x,r.y)||1,o={x:r.x/n,y:r.y/n},s=Td(e),a=Od(e.id,s),l=-o.y,d=o.x;return{id:e.id,x:t[0].x+l*a,y:t[0].y+d*a,vx:o.x*i,vy:o.y*i,mass:e.mass,shape:e.shape,datum:{...e.datum&&"object"==typeof e.datum?e.datum:{},routeProgress:0}}}function Nd(e,t){let i=e.readBodies(),r=[],n=[];for(let o of i){let i=Rd(o.datum);if(i.length<2)continue;let s=Dd(o,i);if(!s)continue;let a=o.datum,l=Number(a?.flowSpeed),d=Number.isFinite(l)&&l>0?l:t;if(s.progress>=.985||s.distance>Math.max(90,14*Td(o))){r.push(o.id),n.push(Ed(o,i,d));continue}let c=Bd(i,Math.min(1,s.progress+Math.max(.035,Math.min(.12,d/s.totalLength*.16))),s.totalLength),u=s.tangent,h=u.x*d,p=u.y*d,m=(h-o.vx)*o.mass*.16+(c.x-o.x)*o.mass*.045+(s.point.x-o.x)*o.mass*.08,y=(p-o.vy)*o.mass*.16+(c.y-o.y)*o.mass*.045+(s.point.y-o.y)*o.mass*.08,[f,g]=jd(m,y,o.mass*d*.35);e.applyImpulse(o.id,f,g)}r.length&&e.remove(r),n.length&&e.pushMany(n)}function Fd(e,t,i){return{...e,observation:{...e.observation,chartId:t??e.observation?.chartId??"physical-flow",chartType:"PacketFlowChart",onObservation:i??e.observation?.onObservation}}}var Wd=/* @__PURE__ */L(/* @__PURE__ */vd(function(e,t){let{chartId:o,colorBy:s,coordinateMode:a="auto",data:l,edges:d,emptyContent:c,flowSpeed:u=90,frameProps:h,links:p,loading:m,loadingContent:y,maxParticles:f=180,nodeIdAccessor:g="id",nodeXAccessor:b="x",nodeYAccessor:v="y",nodes:x,onObservation:w,particleRadius:I=4,particleRate:k=.16,pathAccessor:S="path",pathConstraint:M="path",paused:A,reducedMotion:$=!1,rerunMS:C,seed:P=1,showNodeLabels:R=!0,showSensors:D=!1,showStaticFlow:B=!0,sourceAccessor:T="source",styleRules:j,targetAccessor:O="target",throughputAccessor:E="value"}=e,N=Qs(e,ms),{chartSize:F,className:W,title:q,chartMode:H,margin:z,enableHover:L,description:Y,summary:_,accessibleTable:X}=N,G=Id(null),V=wd(()=>x??[],[x]),U=wd(()=>p??d??l??[],[l,d,p]),K=wd(()=>Fo({nodes:V,links:U,nodeIdAccessor:g,nodeXAccessor:b,nodeYAccessor:v,sourceAccessor:T,targetAccessor:O,throughputAccessor:E,pathAccessor:S,coordinateMode:a,particleRate:k,maxParticles:f,particleRadius:I,flowSpeed:u,pathConstraint:M,reducedMotion:$,seed:P,size:F}),[U,V,F,a,u,f,g,b,v,I,k,S,M,$,P,T,O,E]),Q=xd((e,t)=>{let r=Fo({nodes:V,links:[e],nodeIdAccessor:g,nodeXAccessor:b,nodeYAccessor:v,sourceAccessor:T,targetAccessor:O,throughputAccessor:E,pathAccessor:S,coordinateMode:a,particleRate:k,maxParticles:f,particleRadius:I,flowSpeed:u,pathConstraint:M,reducedMotion:$,seed:P+t+1,size:F}),n={id:String(e.id??`physical-flow-push-${t}`),x:i(F).plot.x,y:i(F).plot.y,mass:1,shape:{type:"circle",radius:I},datum:e},o=r.initialSpawns.length?r.initialSpawns:[n];return{datumId:String(e.id??o[0].id),spawns:o}},[V,F,a,u,f,g,b,v,I,k,S,M,$,P,T,O,E]);Fa(t,{frameRef:G,staticEmpty:0===(p??d??l)?.length,spawnDatum:Q,seedRows:U,seedSpawns:K.initialSpawns});let J=s??"source",Z=wd(()=>n(J,"#2563eb",{styleRules:j,valueAccessor:E}),[J,j,E]),ee=wd(()=>r(Z,h?.bodyStyle),[Z,h?.bodyStyle]),te=Vs(wd(()=>Fd(K.config,o,w),[o,K.config,w]),C,A,void 0,e.onSimulationStateChange),ie=Id(h?.onTick);ie.current=h?.onTick;let re=xd((e,t)=>{!$&&"none"!==M&&Nd(t,u),ie.current?.(e,t)},[u,M,$]),{selection:ne,onBodyHover:oe}=_s({selection:e.selection,linkedHover:e.linkedHover,colorBy:s,chartType:"PacketFlowChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:h?.onBodyHover,fallbackFields:"string"==typeof T?[T]:void 0}),se=Zs({responsive:e,data:null==p&&null==d&&null==l?void 0:U,emptyContent:c,loading:m,loadingContent:y,size:F});if(se)return se;let ae=$d(K.metadata,{showNodeLabels:R,showSensors:D,showStaticFlow:B}),le=(ue=K.metadata)?ue.links.map(e=>{let t=e.path[Math.floor(e.path.length/2)]??e.path[0],i=`${e.sourceLabel} to ${e.targetLabel}: ${kd(e.throughput)} throughput, ${e.packetCount} packets`;return{id:e.id,label:i,description:i,datum:e,x:t?.x??0,y:t?.y??0,shape:"path",pathData:Sd(e.path),group:"flow"}}):[],de=ia(e.tooltip,h),ce=ra(e,h,le,{selection:ne,chartMode:H,className:W,title:q,description:Y,summary:_,accessibleTable:X,enableHover:L,margin:z});var ue;return ea("PacketFlowChart",F,
|
|
107
|
+
/* @__PURE__ */Cd(yo,{...h,...de,...ce,key:`${F[0]}x${F[1]}:${te.rerunKey}`,ref:G,onBodyHover:oe,config:te.config,continuous:!$&&"none"!==M,foregroundGraphics:ta(ae,h?.foregroundGraphics),initialSpawns:K.initialSpawns,onTick:re,paused:A||$,responsiveHeight:!1,responsiveWidth:!1,simulationExecution:"none"===M?h?.simulationExecution:"sync",size:F,bodyStyle:ee,workerBodyThreshold:h?.workerBodyThreshold??Number.POSITIVE_INFINITY}),N)}),"PacketFlowChart"),qd=Wd;import{Fragment as Hd,jsx as zd,jsxs as Ld}from"react/jsx-runtime";var Yd={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"}};function _d(e){return 6.2*e.length}function Xd(e,t){let i=e.trim();if(i.length<=t)return i;if(t<=1)return i.slice(0,1);let r=i.split(/\s+/).filter(Boolean).map(e=>e[0]).join("").toUpperCase();return r.length>1&&r.length<=t?r:t<=3?i.slice(0,t).toUpperCase():`${i.slice(0,Math.max(1,t-2))}..`}function Gd(e,t,i="auto"){let r=Math.max(1,Math.floor(t/6.2)),n="compact"===i?Xd(e,r):"full"===i||_d(e)<=t?e:Xd(e,r);return{text:n,textLength:_d(n)>t?Math.max(4,t):void 0}}function Vd(e){return e.absorb?"absorb":e.portalTarget?"portal":null!=e.capacity?"capacity":"flow"}function Ud(e){if(null!=e.capacity){let t=null!=e.queueDepth?` · q ${e.queueDepth}`:"";return e.capacityLabel?`${e.capacityLabel}${t}`:`cap ${Number.isInteger(e.capacity)?String(e.capacity):e.capacity.toFixed(1)}${t}`}return e.absorb?"absorb":e.portalTarget?"portal":"flow"}function Kd(e,t={}){let{showFlowSpine:i=!0,showStageCounts:r=!0,showCapacityBadges:n=!0,showGroupSockets:o=!0,stageLabelMode:s="auto",outlineStages:a=!1,testId:l="process-flow-chrome"}=t,{width:d,height:c,left:u,right:h,topY:p,bottomY:m,midY:y,stages:f,groups:g=[]}=e,b=m-p;/* */
|
|
108
|
+
return Ld("svg",{"aria-hidden":"true","data-testid":l,"data-outline-stages":a?"true":void 0,width:d,height:c,viewBox:`0 0 ${d} ${c}`,style:{position:"absolute",inset:0,pointerEvents:"none"},className:["semiotic-process-chrome",a?"semiotic-process-chrome--outline-stages":null].filter(Boolean).join(" "),children:[
|
|
109
|
+
/* @__PURE__ */zd("defs",{children:/* @__PURE__ */Ld("linearGradient",{id:"semiotic-process-floor",x1:"0",x2:"0",y1:"0",y2:"1",children:[
|
|
110
|
+
/* @__PURE__ */zd("stop",{offset:"0%",stopColor:"var(--semiotic-process-floor, var(--semiotic-bg, #0f172a))",stopOpacity:"0.2"}),
|
|
111
|
+
/* @__PURE__ */zd("stop",{offset:"100%",stopColor:"var(--semiotic-process-lane, var(--semiotic-surface, #1e293b))",stopOpacity:"0.55"})]})}),
|
|
112
|
+
/* @__PURE__ */zd("rect",{x:0,y:0,width:d,height:c,fill:"url(#semiotic-process-floor)"}),
|
|
113
|
+
/* @__PURE__ */zd("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}),i?/* @__PURE__ */zd("line",{x1:u+8,x2:h-8,y1:y,y2:y,stroke:"var(--semiotic-process-border, var(--semiotic-border, #475569))",strokeWidth:2,strokeDasharray:"6 8",opacity:.55}):null,f.map((e,t)=>{let i=Vd(e),o=Yd[i],l=Math.max(12,e.width-8),d=N(l-8,22,88),u=Math.max(8,d-10),h=Gd(e.label,u,s),g="none"!==s&&l-8>=22,v=Ud(e),x=Gd(v,Math.max(16,l-10),"auto"),w=n&&!1!==e.showBadge&&l>=32,I=null!=e.count?`n=${e.count}${null!=e.processed?` done ${e.processed}`:""}`:"",k=Gd(I,Math.max(16,l-8),"auto"),S=Math.max(30,p-15),M=S-13;/* */
|
|
114
|
+
return Ld("g",{"data-stage":e.id,"data-role":i,children:[
|
|
115
|
+
/* @__PURE__ */zd("rect",{className:"semiotic-process-chrome__stage-bay",x:e.x0+4,y:p+6,width:l,height:b-12,rx:10,fill:a?"none":o.fill,stroke:o.stroke,strokeWidth:a?1.85:"flow"===i?1:1.6}),t<f.length-1?/* @__PURE__ */zd("polygon",{points:`${e.x1-2},${y-7} ${e.x1+8},${y} ${e.x1-2},${y+7}`,fill:o.accent,opacity:.85}):null,g?/* @__PURE__ */Ld(Hd,{children:[
|
|
116
|
+
/* @__PURE__ */zd("rect",{className:"semiotic-process-chrome__stage-label-bg",x:e.x-d/2,y:M,width:d,height:18,rx:9,fill:"var(--semiotic-bg, #0f172a)",fillOpacity:.75,stroke:o.stroke}),
|
|
117
|
+
/* @__PURE__ */Ld("text",{x:e.x,y:S,textAnchor:"middle",fill:o.accent,fontSize:10,fontWeight:800,className:"semiotic-process-chrome__stage-label",textLength:h.textLength,lengthAdjust:h.textLength?"spacingAndGlyphs":void 0,children:[
|
|
118
|
+
/* @__PURE__ */zd("title",{children:e.label}),h.text]})]}):null,w?/* @__PURE__ */Ld("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:[
|
|
119
|
+
/* @__PURE__ */zd("title",{children:v}),x.text]}):null,r&&null!=e.count?/* @__PURE__ */Ld("text",{x:e.x,y:Math.min(c-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:[
|
|
120
|
+
/* @__PURE__ */zd("title",{children:I}),k.text]}):null]},e.id)}),o?g.map((e,t)=>{let i=e.total??0,r=e.absorbed??0,n=e.complete??(i>0&&r>=i),o=!n&&i>0&&r/i>=.75,s=n?"rgba(52, 211, 153, 0.35)":o?"rgba(251, 191, 36, 0.28)":"rgba(15, 23, 42, 0.75)",a=n?"#34d399":o?"#fbbf24":"var(--semiotic-border, #64748b)",l=i>0?`${r}/${i}${n?" shipped":o?" almost":""}`:`feature ${t+1}`,d=N(Math.max(54,_d(e.label)+18,_d(l)+16),54,104),c=Gd(e.label,d-12,"auto"),u=Gd(l,d-12,"auto");/* */
|
|
121
|
+
return Ld("g",{"data-group":e.id,children:[
|
|
122
|
+
/* @__PURE__ */zd("rect",{x:e.x-d/2,y:e.y-22,width:d,height:44,rx:10,fill:s,stroke:a,strokeWidth:1.5}),
|
|
123
|
+
/* @__PURE__ */Ld("text",{x:e.x,y:e.y-4,textAnchor:"middle",fill:"var(--semiotic-process-text, var(--semiotic-text, #f8fafc))",fontSize:10,fontWeight:800,textLength:c.textLength,lengthAdjust:c.textLength?"spacingAndGlyphs":void 0,children:[
|
|
124
|
+
/* @__PURE__ */zd("title",{children:e.label}),c.text]}),
|
|
125
|
+
/* @__PURE__ */Ld("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:[
|
|
126
|
+
/* @__PURE__ */zd("title",{children:l}),u.text]})]},e.id)}):null]})}import{forwardRef as Qd,useCallback as Jd,useEffect as Zd,useMemo as ec,useRef as tc,useState as ic}from"react";import{jsx as rc}from"react/jsx-runtime";function nc(e,t,i={},r){if(!1===t||!e)return;let{volume:n,stages:o,groups:s,groupCompletion:a}=e,l=new Map(n.stages.map(e=>[e.id,e])),d=new Map(a.map(e=>[e.id,e]));return({size:e})=>{let t=Number(e[0])||n.width,a=Number(e[1])||n.height,c=o.map(e=>{let t=l.get(e.id),r=i[`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:r?.queueDepth,processed:r?.processedCount}}),u=s.map(e=>{let t=d.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 Kd({width:t,height:a,left:n.left,right:n.right,topY:n.topY,bottomY:n.bottomY,midY:n.midY,stages:c,groups:u},{showCapacityBadges:!0,showGroupSockets:!0,...r})}}function oc(e,t,r){if(!1===r||!t||0===e.length)return;let n=new Map(t.volume.stages.map(e=>[e.id,e]));return({size:r})=>{let o=[Number(r[0])||t.volume.width,Number(r[1])||t.volume.height],s=i(o),a=e.reduce((e,t)=>Math.max(e,t.value),1),l=Math.min(48,.18*s.plot.height),d=s.plot.y+6;/* */
|
|
127
|
+
return rc("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,i)=>{let r=e[i];if(!r)return null;let o=n.get(t.id);if(!o)return null;let s=Math.max(2,r.value/a*l),c=Math.max(8,.35*o.width);/* */
|
|
128
|
+
return rc("rect",{x:o.x-c/2,y:d,width:c,height:s,rx:2,fill:"var(--semiotic-primary, #4e79a7)",fillOpacity:.18,stroke:"var(--semiotic-primary, #4e79a7)",strokeOpacity:.45,strokeWidth:1},t.id)})})}}import{jsx as sc}from"react/jsx-runtime";import{createElement as ac}from"react";function lc(e,t){let i=Object.keys(e),r=Object.keys(t);if(i.length!==r.length)return!1;for(let r of i){let i=e[r],n=t[r];if(!n||i.queueDepth!==n.queueDepth||i.blockedDepth!==n.blockedDepth||i.processedCount!==n.processedCount||i.unitsPerSecond!==n.unitsPerSecond||i.regionId!==n.regionId||i.metricRevision!==n.metricRevision)return!1}return!0}var dc=/* @__PURE__ */L(/* @__PURE__ */Qd(function(e,t){let{ballRadius:r=6,chromeOptions:o,colorBy:a,data:l,emptyContent:d,frameProps:c={},groupAnchorAlong:u,groupBy:h,groupCompletion:p,groupLabelAccessor:m,gravityX:y,gravityY:f,idAccessor:g,initialSpawnPacing:b,liveCapacity:v=!0,onCapacityChange:x,selection:w,bodyLimit:I,bodyMark:k,loading:S,loadingContent:M,paused:A,radiusAccessor:$,rerunMS:C,route:P="horizontal",seed:R=1,settle:D,springDamping:B,springStiffness:T,stageAccessor:j="stage",stages:O,styleRules:E,workAccessor:N}=e,F=Qs(e,ys),{chartSize:W,showProjection:q,showChrome:H,className:z,title:L,chartMode:Y,margin:_,enableHover:G,description:V,summary:U,accessibleTable:K}=F,Q=tc(null),J=ec(()=>X(l??[]),[l]),Z=ec(()=>({data:J,stages:O,size:W,idAccessor:g,stageAccessor:j,groupBy:h,groupLabelAccessor:m,workAccessor:N,radiusAccessor:$,ballRadius:r,seed:R,route:P,groupCompletion:p,groupAnchorAlong:u,springStiffness:T,springDamping:B,gravityX:y,gravityY:f,settle:D}),[r,W,y,f,u,h,p,m,g,$,P,J,R,D,B,T,j,O,N]),ee=ec(()=>ds(Z),[Z]),te=ee.metadata,ie=Jd((e,t)=>{let n=ds({...Z,data:[e],seed:R+t+1,settle:!0}).initialSpawns[0]??{id:String(e.id??`process-flow-push-${t}`),x:i(W).plot.x,y:i(W).plot.y,mass:1,shape:{type:"circle",radius:r},datum:e};return{datumId:String(e.id??n.id),spawns:[n]}},[r,Z,W,R]);Fa(t,{frameRef:Q,staticEmpty:0===l?.length,spawnDatum:ie,seedRows:J,seedSpawns:ee.initialSpawns});let re=ec(()=>n(a,void 0,{styleRules:E,valueAccessor:N}),[a,E,N]),ne=ec(()=>{if(!v)return c.controllers;let e=[...O.filter(e=>e.capacity&&e.capacity.unitsPerSecond>0).map(e=>{let t=e.capacity.unitsPerSecond;return Yi({id:`process-capacity-${e.id}`,regionId:`process-stage-${e.id}`,unitsPerSecond:t,unitAccessor:e.capacity.unitAccessor??(N?"string"==typeof N?N:e=>{let t=e.datum;if(!t)return 1;try{return Number(N(t,0))||1}catch{return 1}}:"work"),releaseImpulse:{x:70+Math.min(40,2*t),y:0},queueLayout:"lane",continuous:!0})}),...c.controllers??[]];return e.length?e:void 0},[c.controllers,v,O,N]),[oe,se]=ic({}),ae=tc(ne);ae.current=ne;let le=tc(c.onTick);le.current=c.onTick;let de=!1!==H||null!=x;Zd(()=>{if(!x)return;let e=Object.values(oe);e.length&&x(e)},[oe,x]);let ce=Jd((e,t)=>{if(le.current?.(e,t),!de)return;let i=ae.current;if(!i?.length)return;let r={};for(let e of i){let t=e.getSnapshot?.();t&&"string"==typeof t.regionId&&(r[t.regionId]=t)}se(e=>lc(e,r)?e:r)},[de]),ue=ec(()=>{let e=re,t=c.bodyStyle;return k||t?(i,r)=>{let n="function"==typeof t?t(i,r):t;return{..."function"==typeof e?e(i):e,...n,mark:n?.mark??i.datum?.__physicsMark??i.datum?.mark??k}}:e},[k,re,c.bodyStyle]),he=Vs(ec(()=>({...ee.config,...null!=I?{bodyLimit:I,eviction:"oldest"}:{},...c.config}),[I,c.config,ee.config]),C,A,void 0,e.onSimulationStateChange),{selection:pe,onBodyHover:me}=_s({selection:w,linkedHover:e.linkedHover,colorBy:a,chartType:"ProcessFlowChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:c?.onBodyHover,fallbackFields:"string"==typeof j?[j]:void 0}),ye=Zs({responsive:e,data:l,emptyContent:d,loading:S,loadingContent:M,size:W});if(ye)return ye;if(!O?.length)return ea("ProcessFlowChart",W,
|
|
129
|
+
/* @__PURE__ */sc("div",{role:"status",style:{width:W[0],height:W[1],display:"grid",placeItems:"center",color:"var(--semiotic-text-secondary, #64748b)"},children:"ProcessFlowChart requires a non-empty stages array."}),F);let fe=nc(te,H,oe,o),ge=oc(ee.projectionRows,te,q),be=[...s(ee.projectionRows,W,"stage"),...nl(te?.groups??[])],ve=ia(e.tooltip,c),xe=ra(e,c,be,{chartMode:Y,className:z,title:L,description:V,summary:U,accessibleTable:K,enableHover:G,margin:_}),we=[...te?.regionEffects??[],...c.regionEffects??[]];return ea("ProcessFlowChart",W,
|
|
130
|
+
/* @__PURE__ */ac(yo,{...c,...ve,...xe,key:`${W[0]}x${W[1]}:${he.rerunKey}`,ref:Q,onBodyHover:me,controllers:ne,regionEffects:we,selection:pe??c.selection,backgroundGraphics:ta(fe,c.backgroundGraphics),foregroundGraphics:ta(ge,c.foregroundGraphics),initialSpawns:ee.initialSpawns,initialSpawnPacing:b??ee.initialSpawnPacing,onTick:ce,paused:A,responsiveHeight:!1,responsiveWidth:!1,size:W,bodyStyle:ue,config:he.config}),F)}),"ProcessFlowChart");function cc(e=[]){let t=/* @__PURE__ */Object.create(null);for(let[i,r]of e)t[i]=r;return t}function uc(...e){let t=cc();for(let i of e)for(let[e,r]of Object.entries(i??{}))t[e]=r;return t}function hc(e){return uc(e)}function pc(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 mc(e){let t=cc(Object.entries(e.components).map(([e,t])=>[e,{...t,initialMetrics:hc(t.initialMetrics),metrics:hc(t.metrics),productIds:[...t.productIds],history:pc(t.history)}])),i=cc(Object.entries(e.products).map(([e,t])=>[e,{...t,metrics:hc(t.metrics),sourceIds:[...t.sourceIds],history:pc(t.history)}])),r=cc(Object.entries(e.relations).map(([e,t])=>[e,{...t,sourceIds:[...t.sourceIds],metrics:t.metrics?hc(t.metrics):void 0}]));return{...e,eventsApplied:[...e.eventsApplied],components:t,products:i,relations:r,input:{amount:e.input.amount,metrics:hc(e.input.metrics)},metrics:hc(e.metrics),loss:{amount:e.loss.amount,metrics:hc(e.loss.metrics)},history:pc(e.history)}}var yc=1e-9;function fc(e,t){return e<t?-1:e>t?1:0}function gc(e,t,i,r,n){return{severity:e,code:t,message:i,path:r,ids:n?[...n]:void 0}}function bc(e){let t=/* @__PURE__ */new Set,i=/* @__PURE__ */new Set;for(let r of e)t.has(r)&&i.add(r),t.add(r);return[...i].sort(fc)}function vc(e,t){return e?Object.entries(e).flatMap(([e,i])=>Number.isFinite(i)?[]:[gc("error","invalid-metric",`Metric "${e}" must be a finite number.`,`${t}.${e}`)]):[]}function xc(e,t){for(let[i,r]of Object.entries(t))e[i]=Number(e[i]??0)+r}function wc(e){let t=cc();for(let i of e)xc(t,i.metrics);return t}function Ic(e,t,i="selector"){let r=[],n=Object.values(e.components),o=new Set(n.map(e=>e.id)),s=(t.ids??[]).filter(e=>!o.has(e));if(s.length&&r.push(gc("error","unknown-component",`Selector references unknown component id${1===s.length?"":"s"}: ${s.join(", ")}.`,`${i}.ids`,s)),void 0!==t.count&&(!Number.isInteger(t.count)||t.count<0)&&r.push(gc("error","invalid-selector-count","Selector count must be a non-negative integer.",`${i}.count`)),r.some(e=>"error"===e.severity))return{ids:[],diagnostics:r};let a=t.ids?new Set(t.ids):null,l=t.categories?new Set(t.categories):null,d=t.statuses?new Set(t.statuses):null,c=t.outletIds?new Set(t.outletIds):null,u=n.filter(e=>!a||a.has(e.id)).filter(e=>!l||l.has(e.category)).filter(e=>!d||d.has(e.status)).filter(e=>!c||void 0!==e.outletId&&c.has(e.outletId)).map(e=>e.id).sort(fc);return void 0!==t.count&&(u=u.slice(0,t.count)),u.length||r.push(gc("warning","empty-selector","Selector matched no source components.",i)),{ids:u,diagnostics:r}}function kc(e,t,i={}){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,...i}}function Sc(e,t){let i={...t,eventId:e.event.id};e.materializations.push(i),e.observations.push({...i,phaseId:e.context.phaseId,authoredAt:e.context.authoredAt,appliedAt:e.context.appliedAt})}function Mc(e,t,i){return!(void 0!==t&&!e.outletIds.has(t)&&(e.diagnostics.push(gc("error","unknown-outlet",`Unknown outlet "${t}".`,i,[t])),1))}function Ac(e,t,i){let r=bc(t);t.length||e.diagnostics.push(gc("error","empty-source-list","A product requires at least one source component.",i)),r.length&&e.diagnostics.push(gc("error","duplicate-source",`Source ids may appear only once: ${r.join(", ")}.`,i,r));let n=t.filter(t=>!e.state.components[t]);n.length&&e.diagnostics.push(gc("error","unknown-component",`Unknown source component id${1===n.length?"":"s"}: ${n.join(", ")}.`,i,n));let o=t.filter(t=>(e.state.components[t]?.productIds.length??0)>0);o.length&&e.diagnostics.push(gc("error","source-already-assigned",`Source component${1===o.length?" is":"s are"} already assigned: ${o.join(", ")}.`,i,o));let s=t.filter(t=>"consumed"===e.state.components[t]?.status&&!o.includes(t));return s.length&&e.diagnostics.push(gc("error","source-unavailable",`Consumed source component${1===s.length?" is":"s are"} unavailable: ${s.join(", ")}.`,i,s)),e.diagnostics.some(e=>"error"===e.severity)?null:t.map(t=>e.state.components[t])}function $c(e,t,i){let r=bc(t),n=t.filter(t=>!e.state.components[t]);return t.length<2&&e.diagnostics.push(gc("error","insufficient-relation-sources","A relation requires at least two source components.",i)),r.length&&e.diagnostics.push(gc("error","duplicate-source",`Relation source ids must be unique: ${r.join(", ")}.`,i,r)),n.length&&e.diagnostics.push(gc("error","unknown-component",`Relation references unknown source component${1===n.length?"":"s"}: ${n.join(", ")}.`,i,n)),e.diagnostics.some(e=>"error"===e.severity)?null:t.map(t=>e.state.components[t])}function Cc(e,t,i,r,n){let o=r?.amount??0;(!Number.isFinite(o)||o<0||o>t+yc)&&e.diagnostics.push(gc("error","invalid-loss","Loss amount must be finite, non-negative, and no greater than its sources.",`${n}.amount`)),e.diagnostics.push(...vc(r?.metrics,`${n}.metrics`));for(let[t,o]of Object.entries(r?.metrics??{}))(o<0||o>Number(i[t]??0)+yc)&&e.diagnostics.push(gc("error","invalid-metric-loss",`Metric loss "${t}" must be non-negative and no greater than its sources.`,`${n}.metrics.${t}`));return!e.diagnostics.some(e=>"error"===e.severity)}function Pc(e,t,i,r){if(!t?.length)return[];let n=bc(t),o=t.filter(t=>!e.state.relations[t]),s=t.filter(t=>"resolved"===e.state.relations[t]?.status),a=new Set(i),l=t.filter(t=>(e.state.relations[t]?.sourceIds??[]).some(e=>!a.has(e)));return n.length&&e.diagnostics.push(gc("error","duplicate-relation","Basis relations must be unique.",r,n)),o.length&&e.diagnostics.push(gc("error","unknown-relation",`Unknown basis relation: ${o.join(", ")}.`,r,o)),s.length&&e.diagnostics.push(gc("error","resolved-relation",`Basis relation is already resolved: ${s.join(", ")}.`,r,s)),l.length&&e.diagnostics.push(gc("error","relation-source-mismatch",`Basis relation includes a source outside this product: ${l.join(", ")}.`,r,l)),e.diagnostics.some(e=>"error"===e.severity)?null:t.map(t=>e.state.relations[t])}function Rc(e,t){if(t.length){for(let i of t)i.status="resolved",i.resolution="combined",i.resolvedByEventId=e.event.id,i.resolvedAt=e.context.appliedAt;Sc(e,{type:"resolve-relation",relationIds:t.map(e=>e.id)})}}function Dc(e,t,i){e.state.loss.amount+=i?.amount??0;for(let[r,n]of Object.entries(i?.metrics??{}))t[r]=Number(t[r]??0)-n,e.state.loss.metrics[r]=Number(e.state.loss.metrics[r]??0)+n}function Bc(e,t,i,r,n,o,s){let a=o&&void 0!==e.amount?e.amount:i;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:a,metrics:o&&e.metrics?uc(r,e.metrics):hc(r),status:o?"complete":"forming",sourceIds:[...t],outletId:o?e.outletId??(n.outletIds.has("product")?"product":void 0):void 0,createdByEventId:n.event.id,createdAt:n.context.appliedAt,completedByEventId:o?n.event.id:void 0,completedAt:o?n.context.appliedAt:void 0,history:[s]}}function Tc(e,t,i,r){void 0!==t.amount&&Math.abs(t.amount-i)>yc&&e.diagnostics.push(gc("warning","declared-product-amount-mismatch",`Product "${t.id}" declares ${t.amount}, while its sources yield ${i}.`,r,[t.id]))}function jc(e,t,i,r,n,o){let s=e.productDefinitions.get(t.id),a=i??s?.outletId??(e.outletIds.has("product")?"product":void 0);if(!Mc(e,a,`${o}.outletId`))return;if("complete"===t.status)return void e.diagnostics.push(gc("error","product-already-complete",`Product "${t.id}" is already complete.`,o,[t.id]));s&&(Tc(e,s,t.amount,`${o}.productId`),void 0!==s.amount&&(t.amount=s.amount),s.metrics&&(t.metrics=uc(t.metrics,s.metrics))),t.status="complete",t.outletId=a,t.reason=r,t.completedByEventId=e.event.id,t.completedAt=e.context.appliedAt;let l=kc(e,n,{sourceIds:[...t.sourceIds],productIds:[t.id],outletIds:a?[a]:void 0});t.history.push(l),e.state.history.push(l),Sc(e,{type:"complete-product",sourceIds:[...t.sourceIds],productIds:[t.id],outletIds:a?[a]:void 0})}function Oc(e,t,i){let r=`events.${e.event.id}.effects.${i}`,n=e.state;if("set-state"===t.type){["queued","active","transformed","retained","ejected","failed","recovered"].includes(t.state)||e.diagnostics.push(gc("error","invalid-component-state",`set-state cannot assign "${String(t.state)}".`,`${r}.state`)),e.diagnostics.push(...vc(t.metricsDelta,`${r}.metricsDelta`)),Mc(e,t.outletId,`${r}.outletId`);let i=Ic(n,t.select,`${r}.select`);e.diagnostics.push(...i.diagnostics);let o=i.ids.filter(e=>n.components[e].productIds.length);if(o.length&&e.diagnostics.push(gc("error","source-already-assigned",`Assigned source components cannot be retargeted: ${o.join(", ")}.`,`${r}.select`,o)),e.diagnostics.some(e=>"error"===e.severity))return;let s=kc(e,t,{sourceIds:i.ids,outletIds:t.outletId?[t.outletId]:void 0});for(let e of i.ids){let i=n.components[e];i.status=t.state,i.outletId=t.outletId,i.reason=t.reason,t.metricsDelta&&xc(i.metrics,t.metricsDelta),i.history.push(s)}return n.history.push(s),void(i.ids.length&&Sc(e,{type:"retarget-component",sourceIds:i.ids,outletIds:t.outletId?[t.outletId]:void 0}))}if("set-relation"===t.type){let{relation:i}=t;(!i.id||n.relations[i.id])&&e.diagnostics.push(gc("error","duplicate-relation",`Relation id "${i.id}" is missing or already active.`,`${r}.relation.id`,[i.id]));let o=$c(e,i.sourceIds,`${r}.relation.sourceIds`);if(e.diagnostics.push(...vc(i.metrics,`${r}.relation.metrics`)),!o||e.diagnostics.some(e=>"error"===e.severity))return;n.relations[i.id]={...i,sourceIds:[...i.sourceIds],metrics:i.metrics?hc(i.metrics):void 0,status:"active",createdByEventId:e.event.id,createdAt:e.context.appliedAt};let s=kc(e,t,{sourceIds:[...i.sourceIds],relationIds:[i.id]});return n.history.push(s),void Sc(e,{type:"activate-relation",sourceIds:[...i.sourceIds],relationIds:[i.id]})}if("resolve-relation"===t.type){let i=bc(t.relationIds),o=t.relationIds.filter(e=>!n.relations[e]),s=t.relationIds.filter(e=>"resolved"===n.relations[e]?.status);if(i.length&&e.diagnostics.push(gc("error","duplicate-relation","Relation ids must be unique.",`${r}.relationIds`,i)),o.length&&e.diagnostics.push(gc("error","unknown-relation",`Unknown relation: ${o.join(", ")}.`,`${r}.relationIds`,o)),s.length&&e.diagnostics.push(gc("error","resolved-relation",`Relation is already resolved: ${s.join(", ")}.`,`${r}.relationIds`,s)),e.diagnostics.some(e=>"error"===e.severity))return;for(let i of t.relationIds){let r=n.relations[i];r.status="resolved",r.resolution=t.resolution,r.resolvedByEventId=e.event.id,r.resolvedAt=e.context.appliedAt,r.reason=t.reason}let a=kc(e,t,{relationIds:[...t.relationIds]});return n.history.push(a),void Sc(e,{type:"resolve-relation",relationIds:[...t.relationIds]})}if("combine"===t.type||"contribute"===t.type){let i=e.productDefinitions.get(t.productId);i||e.diagnostics.push(gc("error","unknown-product",`Product "${t.productId}" has no declared mold.`,`${r}.productId`,[t.productId]));let o=n.products[t.productId];"combine"===t.type&&o&&e.diagnostics.push(gc("error","duplicate-product",`Product "${t.productId}" has already been formed.`,`${r}.productId`,[t.productId])),"contribute"===t.type&&(!o||"forming"!==o.status)&&e.diagnostics.push(gc("error","product-not-forming",`Contributions require an existing forming product "${t.productId}".`,`${r}.productId`,[t.productId]));let s=Ac(e,t.sourceIds,`${r}.sourceIds`),a="contribute"===t.type&&o?[...o.sourceIds,...t.sourceIds]:t.sourceIds,l=Pc(e,t.basisRelationIds,a,`${r}.basisRelationIds`);if(!s||!l||!i||e.diagnostics.some(e=>"error"===e.severity))return;let d=s.reduce((e,t)=>e+t.amount,0),c=wc(s);if(!Cc(e,d,c,t.loss,`${r}.loss`))return;let u=d-(t.loss?.amount??0);Dc(e,c,t.loss);let h,p="combine"===t.type&&!1!==t.complete,m=kc(e,t,{sourceIds:[...t.sourceIds],productIds:[t.productId],relationIds:t.basisRelationIds?[...t.basisRelationIds]:void 0});if("combine"===t.type){if(p&&Tc(e,i,u,`${r}.productId`),h=Bc(i,t.sourceIds,u,c,e,p,m),p&&!Mc(e,h.outletId,`${r}.productId`))return;n.products[t.productId]=h}else h=o,h.sourceIds.push(...t.sourceIds),h.amount+=u,xc(h.metrics,c),h.history.push(m);for(let e of s)e.productIds=[t.productId],e.status="consumed",e.outletId=void 0,e.history.push(m);return n.history.push(m),Rc(e,l),Sc(e,{type:"combine"===t.type?"form-product":"update-product",sourceIds:[...t.sourceIds],productIds:[t.productId],relationIds:t.basisRelationIds?[...t.basisRelationIds]:void 0,outletIds:h.outletId?[h.outletId]:void 0}),void(p&&Sc(e,{type:"complete-product",sourceIds:[...h.sourceIds],productIds:[h.id],outletIds:h.outletId?[h.outletId]:void 0}))}if("complete-product"===t.type){let i=n.products[t.productId];return i?void jc(e,i,t.outletId,t.reason,t,r):void e.diagnostics.push(gc("error","unknown-product-state",`Product "${t.productId}" has not been formed.`,`${r}.productId`,[t.productId]))}if("split"===t.type){let i=Ac(e,[t.sourceId],`${r}.sourceId`);t.products.length||e.diagnostics.push(gc("error","empty-split","A split requires at least one product allocation.",`${r}.products`));let o=t.products.map(e=>e.productId),s=bc(o);s.length&&e.diagnostics.push(gc("error","duplicate-product","Split product ids must be unique.",`${r}.products`,s));let a=o.map(t=>e.productDefinitions.get(t)),l=o.filter((e,t)=>!a[t]),d=o.filter(e=>n.products[e]);l.length&&e.diagnostics.push(gc("error","unknown-product",`Split references undeclared product molds: ${l.join(", ")}.`,`${r}.products`,l)),d.length&&e.diagnostics.push(gc("error","duplicate-product",`Split products already exist: ${d.join(", ")}.`,`${r}.products`,d));for(let[i,n]of t.products.entries())void 0!==n.amount&&(!Number.isFinite(n.amount)||n.amount<0)&&e.diagnostics.push(gc("error","invalid-product-amount","Split allocation amounts must be finite and non-negative.",`${r}.products.${i}.amount`)),e.diagnostics.push(...vc(n.metrics,`${r}.products.${i}.metrics`));if(!i?.length||e.diagnostics.some(e=>"error"===e.severity))return;let c=i[0];if(!Cc(e,c.amount,c.metrics,t.loss,`${r}.loss`))return;let u=c.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(gc("error","partial-split-allocation","Either every split product must declare an amount or none may do so.",`${r}.products`));let m=p?h:t.products.map(()=>u/t.products.length),y=m.reduce((e,t)=>e+t,0);if(Math.abs(y-u)>yc)return void e.diagnostics.push(gc("error","split-amount-mismatch",`Split allocations total ${y}, but ${u} remains after loss.`,`${r}.products`));let f=hc(c.metrics);for(let[e,i]of Object.entries(t.loss?.metrics??{}))f[e]=Number(f[e]??0)-i;let g=kc(e,t,{sourceIds:[c.id],productIds:o});if(t.products.forEach((i,o)=>{let s=a[o],l=u>yc?m[o]/u:1/t.products.length,d=cc(Object.entries(f).map(([e,t])=>[e,t*l])),h=i.metrics??s.metrics??d,p=Bc({...s,amount:m[o],metrics:h},[c.id],m[o],hc(h),e,!0,g);Mc(e,p.outletId,`${r}.products.${o}.productId`)&&(n.products[p.id]=p)}),e.diagnostics.some(e=>"error"===e.severity))return;c.productIds=o,c.status="consumed",c.outletId=void 0,c.history.push(g),n.loss.amount+=t.loss?.amount??0;for(let[e,i]of Object.entries(t.loss?.metrics??{}))n.loss.metrics[e]=Number(n.loss.metrics[e]??0)+i;n.history.push(g),Sc(e,{type:"split-source",sourceIds:[c.id],productIds:o});for(let t of o)Sc(e,{type:"complete-product",sourceIds:[c.id],productIds:[t],outletIds:n.products[t].outletId?[n.products[t].outletId]:void 0});return}if("eject"===t.type){Mc(e,t.outletId,`${r}.outletId`);let i=Ic(n,t.select,`${r}.select`);e.diagnostics.push(...i.diagnostics);let o=i.ids.filter(e=>n.components[e].productIds.length);if(o.length&&e.diagnostics.push(gc("error","source-already-assigned",`Assigned source components cannot be ejected: ${o.join(", ")}.`,`${r}.select`,o)),e.diagnostics.some(e=>"error"===e.severity))return;let s=kc(e,t,{sourceIds:i.ids,outletIds:[t.outletId]});for(let e of i.ids){let i=n.components[e];i.status=t.state??"ejected",i.outletId=t.outletId,i.reason=t.reason,i.history.push(s)}return n.history.push(s),void(i.ids.length&&Sc(e,{type:"retarget-component",sourceIds:i.ids,outletIds:[t.outletId]}))}if("set-metric"===t.type){if(e.diagnostics.push(...vc(t.metricsDelta,`${r}.metricsDelta`)),e.diagnostics.some(e=>"error"===e.severity))return;let i,o;if("run"===t.target)xc(n.metrics,t.metricsDelta);else if("components"in t.target){let o=Ic(n,t.target.components,`${r}.target.components`);if(e.diagnostics.push(...o.diagnostics),e.diagnostics.some(e=>"error"===e.severity))return;i=o.ids;for(let e of o.ids)xc(n.components[e].metrics,t.metricsDelta)}else{o=[...t.target.productIds];let i=bc(o),s=o.filter(e=>!n.products[e]);if(i.length&&e.diagnostics.push(gc("error","duplicate-product","Metric target product ids must be unique.",`${r}.target.productIds`,i)),s.length&&e.diagnostics.push(gc("error","unknown-product-state",`Metric target product has not formed: ${s.join(", ")}.`,`${r}.target.productIds`,s)),e.diagnostics.some(e=>"error"===e.severity))return;for(let e of o)xc(n.products[e].metrics,t.metricsDelta)}return void n.history.push(kc(e,t,{sourceIds:i,productIds:o}))}t.outcome.trim()?(n.outcome=t.outcome,n.summary=t.summary,n.history.push(kc(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(gc("error","invalid-outcome","Outcome must be a non-empty string.",`${r}.outcome`))}function Ec(e,t,i){if(e.eventsApplied.includes(t.id))return{applied:!1,state:e,materializations:[],observations:[],diagnostics:[gc("warning","duplicate-event-application",`Event "${t.id}" has already been applied.`,`events.${t.id}`,[t.id])]};let r=mc(e),n={state:r,event:t,context:i,productDefinitions:new Map(i.products.map(e=>[e.id,e])),outletIds:new Set(i.outlets.map(e=>e.id)),diagnostics:[],materializations:[],observations:[]};for(let[i,r]of t.effects.entries())if(Oc(n,r,i),n.diagnostics.some(e=>"error"===e.severity))return{applied:!1,state:e,materializations:[],observations:[],diagnostics:n.diagnostics};return r.elapsed=Math.max(r.elapsed,i.appliedAt),r.phaseId=i.phaseId,r.eventsApplied.push(t.id),n.observations.unshift({type:"crucible-event",eventId:t.id,phaseId:i.phaseId,authoredAt:i.authoredAt,appliedAt:i.appliedAt}),{applied:!0,state:r,materializations:n.materializations,observations:n.observations,diagnostics:n.diagnostics}}function Nc(e,t){return"product"===t?"product"===e.kind?e.id:"unassigned":"outlet"===t?e.outletId??"unassigned":"category"===t?e.category:e.status}function Fc(e,t={}){let i=t.groupBy??"outlet",r=/* @__PURE__ */new Map,n=e=>{let t=Nc({...e,status:e.status??"active"},i),n=r.get(t);if(n)return n.count+=1,n.amount+=e.amount,void xc(n.metrics,e.metrics);r.set(t,{key:t,label:"product"===i&&"product"===e.kind?e.label:t,count:1,amount:e.amount,metrics:hc(e.metrics),status:"status"===i?e.status:void 0,outletId:"outlet"===i?e.outletId:void 0,category:"category"===i?e.category:void 0,productId:"product"===i&&"product"===e.kind?e.id:void 0})};for(let t of Object.values(e.components))t.productIds.length||"consumed"===t.status||n({kind:"component",id:t.id,label:t.label,status:t.status,outletId:t.outletId,category:t.category,amount:t.amount,metrics:t.metrics});for(let t of Object.values(e.products))n({kind:"product",id:t.id,label:t.label,status:t.status,outletId:t.outletId,category:t.category,amount:t.amount,metrics:t.metrics});let o=new Map((t.order??[]).map((e,t)=>[e,t]));return[...r.values()].sort((e,t)=>(o.get(e.key)??Number.MAX_SAFE_INTEGER)-(o.get(t.key)??Number.MAX_SAFE_INTEGER)||fc(e.key,t.key))}var Wc=Fc;function qc(e,t={}){let i=t.field??"amount",r=e=>"amount"===i?e.amount:Number(e.metrics[i]??0),n="amount"===i?e.input.amount:Number(e.input.metrics[i]??0),o=Object.values(e.products).reduce((e,t)=>e+r(t),0),s=Object.values(e.components).filter(e=>!e.productIds.length&&"consumed"!==e.status).reduce((e,t)=>e+r(t),0),a="amount"===i?e.loss.amount:Number(e.loss.metrics[i]??0),l=o+s+a,d=l-n,c=Math.max(0,t.tolerance??1e-6);return{field:i,input:n,products:o,unassigned:s,loss:a,output:l,delta:d,conserved:Math.abs(d)<=c}}function Hc(e,t={}){return{history:pc(e.history),projection:Fc(e,t.projection),conservation:qc(e,t.conservation)}}var zc=bs.width,Lc=bs.height,Yc=[zc,Lc],_c=[{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}],Xc=/* @__PURE__ */new Set(["queued","active","transformed","consumed","retained","ejected","failed","recovered"]),Gc=1e-9;function Vc(e,t){return e<t?-1:e>t?1:0}function Uc(e,t,i,r,n){return{severity:e,code:t,message:i,path:r,ids:n?[...n]:void 0}}function Kc(e){let t=/* @__PURE__ */new Set,i=/* @__PURE__ */new Set;for(let r of e)t.has(r)&&i.add(r),t.add(r);return[...i].sort(Vc)}function Qc(e){let t="number"==typeof e?e:Number(e);return Number.isFinite(t)?t:null}function Jc(e,t,i,r,n,o){if(!i)return r;try{return("function"==typeof i?i(e,t):e[i])??r}catch(e){return n.push(Uc("error","accessor-error",`Accessor threw: ${e instanceof Error?e.message:String(e)}.`,o)),r}}function Zc(e,t,i){if(!e||"object"!=typeof e||Array.isArray(e))return null!=e&&t.push(Uc("error","invalid-metrics","Metrics must be a numeric object.",i)),cc();let r=cc();for(let[n,o]of Object.entries(e)){let e=Qc(o);null!=e?r[n]=e:t.push(Uc("error","invalid-metric",`Metric "${n}" must be finite.`,`${i}.${n}`))}return r}function eu(e,t){for(let[i,r]of Object.entries(t))e[i]=Number(e[i]??0)+r}function tu(e){let t=[],i=cc(),r=[],n=0,o=cc();e.data.forEach((s,a)=>{let l=String(s.id??`component-${a}`),d=Jc(s,a,e.idAccessor,l,t,`data.${a}.id`),c=String(d??l).trim();if(!c)return void t.push(Uc("error","invalid-component-id","Component ids may not be empty.",`data.${a}.id`));r.push(c);let u=Qc(Jc(s,a,e.amountAccessor,1,t,`data.${a}.amount`)),h=null!=u&&u>=0?u:0;(null==u||u<0)&&t.push(Uc("error","invalid-component-amount","Component amount must be finite and non-negative.",`data.${a}.amount`,[c]));let p=Zc(Jc(s,a,e.metricsAccessor,{},t,`data.${a}.metrics`),t,`data.${a}.metrics`),m=Jc(s,a,e.initialStateAccessor,"active",t,`data.${a}.status`),y=Xc.has(m)?m:"active";Xc.has(m)||t.push(Uc("error","invalid-component-status",`Unknown component status "${String(m)}".`,`data.${a}.status`,[c]));let f=String(Jc(s,a,e.labelAccessor,String(s.label??s.name??c),t,`data.${a}.label`)),g=String(Jc(s,a,e.categoryAccessor,"component",t,`data.${a}.category`));Object.hasOwn(i,c)||(i[c]={id:c,label:f,category:g,datum:s,status:y,initialAmount:h,amount:h,initialMetrics:uc(p),metrics:uc(p),productIds:[],history:[]},n+=h,eu(o,p))});let s=Kc(r);s.length&&t.push(Uc("error","duplicate-component-id",`Component ids must be unique: ${s.join(", ")}.`,"data",s));let a=Zc(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:i,products:cc(),relations:cc(),input:{amount:n,metrics:o},metrics:a,loss:{amount:0,metrics:cc()},history:[]},diagnostics:t}}function iu(e){let t=[];e.length||t.push(Uc("error","empty-phase-program","CrucibleChart requires at least one phase.","phases"));let i=Kc(e.map(e=>e.id));i.length&&t.push(Uc("error","duplicate-phase-id",`Phase ids must be unique: ${i.join(", ")}.`,"phases",i));let r=0;return{phases:e.map((e,i)=>{let n=Qc(e.duration),o=null!=n&&n>0?n:0;e.id.trim()||t.push(Uc("error","invalid-phase-id","Phase ids may not be empty.",`phases.${i}.id`)),(null==n||n<=0)&&t.push(Uc("error","invalid-phase-duration","Phase duration must be finite and greater than zero.",`phases.${i}.duration`,[e.id])),void 0!==e.intensity&&!Number.isFinite(e.intensity)&&t.push(Uc("error","invalid-phase-intensity","Phase intensity must be finite.",`phases.${i}.intensity`,[e.id]));let s={...e,duration:o,intensity:void 0===e.intensity?.5:Number.isFinite(e.intensity)?Math.max(0,Math.min(1,e.intensity)):.5,motion:e.motion??"hold",index:i,start:r,end:r+o};return r=s.end,s}),diagnostics:t}}function ru(e,t,i){let r=e.find(e=>Math.abs(e.start-i)<=Gc);if(r)return{phase:r,boundaryRank:1};let n=e.find(e=>i>=e.start&&i<e.end);return n?{phase:n,boundaryRank:0}:Math.abs(i-t)<=Gc&&e.length?{phase:e[e.length-1],boundaryRank:0}:{phase:void 0,boundaryRank:1}}function nu(e,t,i){let r=[],n=Kc(e.map(e=>e.id));n.length&&r.push(Uc("error","duplicate-event-id",`Event ids must be unique: ${n.join(", ")}.`,"events",n));let o=[];return e.forEach((e,n)=>{let s,a,l;if(e.id.trim()||r.push(Uc("error","invalid-event-id","Event ids may not be empty.",`events.${n}.id`)),"time"in e.at&&void 0!==e.at.time){let o=Qc(e.at.time);if(null==o||o<0||o>i+Gc)return void r.push(Uc("error","event-time-out-of-range",`Event time must fall between 0 and ${i}.`,`events.${n}.at.time`,[e.id]));s=Math.max(0,Math.min(i,o));let d=ru(t,i,s);a=d.phase,l=d.boundaryRank}else{if(a=t.find(t=>t.id===e.at.phaseId),!a)return void r.push(Uc("error","unknown-event-phase",`Event references unknown phase "${e.at.phaseId}".`,`events.${n}.at.phaseId`,[e.id,e.at.phaseId]));let i=e.at.progress??0;if(!Number.isFinite(i)||i<0||i>1)return void r.push(Uc("error","event-progress-out-of-range","Event phase progress must be between 0 and 1.",`events.${n}.at.progress`,[e.id]));s=a.start+a.duration*i,l=0===i?1:0}a?o.push({...e,index:n,authoredAt:s,phaseId:a.id,phaseIndex:a.index,boundaryRank:l}):r.push(Uc("error","event-without-phase","Event could not be assigned to a phase.",`events.${n}.at`,[e.id]))}),o.sort((e,t)=>e.authoredAt-t.authoredAt||e.boundaryRank-t.boundaryRank||e.index-t.index),{events:o,diagnostics:r}}function ou(e,t){let i=[],r=new Set(t.map(e=>e.id)),n=Kc(t.map(e=>e.id)),o=Kc(e.map(e=>e.id));return n.length&&i.push(Uc("error","duplicate-outlet-id",`Outlet ids must be unique: ${n.join(", ")}.`,"outlets",n)),o.length&&i.push(Uc("error","duplicate-product-id",`Product ids must be unique: ${o.join(", ")}.`,"products",o)),t.forEach((e,t)=>{e.id.trim()||i.push(Uc("error","invalid-outlet-id","Outlet ids may not be empty.",`outlets.${t}.id`)),void 0!==e.order&&!Number.isFinite(e.order)&&i.push(Uc("error","invalid-outlet-order","Outlet order must be finite.",`outlets.${t}.order`,[e.id]))}),e.forEach((e,t)=>{e.id.trim()||i.push(Uc("error","invalid-product-id","Product ids may not be empty.",`products.${t}.id`)),void 0!==e.amount&&(!Number.isFinite(e.amount)||e.amount<0)&&i.push(Uc("error","invalid-product-amount","Declared product amount must be finite and non-negative.",`products.${t}.amount`,[e.id])),void 0!==e.outletId&&!r.has(e.outletId)&&i.push(Uc("error","unknown-outlet",`Product "${e.id}" references unknown outlet "${e.outletId}".`,`products.${t}.outletId`,[e.outletId])),Zc(e.metrics??{},i,`products.${t}.metrics`)}),i}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=Yc,t=_c){let i=Math.max(1,Qc(e[0])??zc),r=Math.max(1,Qc(e[1])??Lc),n=i<360||r<260,o=n?Math.max(4,.035*Math.min(i,r)):20,s=n?Math.max(10,.075*r):34,a={x:o,y:o,width:Math.max(1,i-2*o),height:s},l=n?Math.max(16,.14*r):Math.min(78,.16*r),d={x:o,y:r-o-l,width:Math.max(1,i-2*o),height:l},c=n?Math.max(12,.08*i):Math.min(150,.17*i),u=a.y+a.height+(n?12:38),h=d.y-(n?10:34),p={x:c,y:u,width:Math.max(24,i-2*c),height:Math.max(24,h-u)},m=Math.max(18,Math.min(.32*p.width,n?84:180)),y={x:p.x+(p.width-m)/2,y:p.y-(n?10:24),width:m,height:n?12:28},f=su(t),g={left:f.filter(e=>"left"===(e.side??"bottom")),right:f.filter(e=>"right"===e.side),bottom:f.filter(e=>"bottom"===(e.side??"bottom"))},b=[],v=(e,t)=>{let r=Math.max(8,c-1.5*o),s=p.height/Math.max(1,t.length);t.forEach((t,a)=>{b.push({...t,side:e,x:"left"===e?o:i-o-r,y:p.y+a*s,width:r,height:Math.max(8,s-(n?2:8))})})};v("left",g.left),v("right",g.right);let x=p.width/Math.max(1,g.bottom.length);return g.bottom.forEach((e,t)=>{b.push({...e,side:"bottom",x:p.x+t*x,y:p.y+p.height+(n?2:7),width:Math.max(8,x-(n?2:8)),height:Math.max(8,d.y-p.y-p.height-(n?4:12))})}),b.sort((e,t)=>f.findIndex(t=>t.id===e.id)-f.findIndex(e=>e.id===t.id)),{width:i,height:r,phaseRail:a,chamber:p,mouth:y,projection:d,outlets:b}}function lu(e,t,i){let r=i.map(([i,r])=>[Math.max(e,Math.min(i,r)),Math.min(t,Math.max(i,r))]).filter(([e,t])=>t>e+Gc).sort((e,t)=>e[0]-t[0]||e[1]-t[1]),n=[],o=e;for(let[e,t]of r)e>o+Gc&&n.push([o,e]),o=Math.max(o,t);return t>o+Gc&&n.push([o,t]),n}function du(e){let{id:t,orientation:i,fixed:r,start:n,end:o,openings:s,thickness:a,friction:l,restitution:d}=e,c=lu(n,o,s);return c.map(([e,n],o)=>({id:1===c.length?t:`${t}:${o}`,friction:l,restitution:d,shape:"horizontal"===i?{type:"segment",x1:e,y1:r,x2:n,y2:r,thickness:a}:{type:"segment",x1:r,y1:e,x2:r,y2:n,thickness:a}}))}function cu(e){let{chamber:t,mouth:i}=e,r=Math.max(2,Math.min(10,.018*Math.min(e.width,e.height))),n=Math.max(t.x,i.x),o=Math.min(t.x+t.width,i.x+i.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:n,y2:t.y,thickness:r}},{id:"crucible:wall:top-right",friction:.42,restitution:.1,shape:{type:"segment",x1:o,y1:t.y,x2:t.x+t.width,y2:t.y,thickness:r}}];a.push(...du({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:r,friction:.46,restitution:.12}),...du({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:r,friction:.46,restitution:.12}),...du({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:r,friction:.5,restitution:.08}));for(let 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 uu(e){return"number"==typeof e&&Number.isFinite(e)?e>>>0:"string"==typeof e?fe(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 yu(e,t){return`crucible:bond:${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function fu(e,t,i,r){if(void 0!==i&&Number.isFinite(i)&&i>0)return i;let[n,o]=t;if(o-n<=Gc)return(r[0]+r[1])/2;let s=Math.sqrt(Math.max(0,e-n)/(o-n));return r[0]+(r[1]-r[0])*s}function gu(e,t){let i=Math.max(.25,Math.min(1,t.width/900,t.height/520)),r=e?.[0]??7*i,n=e?.[1]??18*i,o=Math.max(1,Math.min(r,n));return[o,Math.max(o,Math.max(r,n))]}function bu(e,t,i={}){let r=Object.values(e.components).sort((e,t)=>Vc(e.id,t.id)),n=Te(r.map(e=>e.amount)),o=gu(i.radiusRange,t),s=b(uu(i.seed)),a=t.mouth.x+t.mouth.width/2,l=t.chamber.y+Math.max(18,.18*t.chamber.height),d=Math.max(4,.28*t.chamber.width),c=Math.max(4,.12*t.chamber.height);return r.map((e,t)=>{let u=t/Math.max(1,r.length)*Math.PI*2+.18*(s()-.5),h=fu(e.amount,n,i.bodyRadius,o),p={__crucible:!0,kind:"component",semanticId:e.id,sourceDatum:e.datum};return{id:pu(e.id),x:a+Math.cos(u)*d*(.45+.45*s()),y:l+Math.sin(u)*c*(.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 vu(e,t){if(!e)return[];let i=Math.min(e,Math.max(1,Math.ceil(Math.sqrt(e*Math.max(.5,t.width/Math.max(1,t.height)))))),r=Math.max(1,Math.ceil(e/i));return Array.from({length:e},(e,n)=>({x:t.x+(n%i+.5)*(t.width/i),y:t.y+(Math.floor(n/i)+.5)*(t.height/r)}))}function xu(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 Iu(e,t){let i=/* @__PURE__ */new Map;for(let t of e){let e=t.outletId??"__chamber__",r=i.get(e)??[];r.push(t),i.set(e,r)}let r=/* @__PURE__ */new Map;for(let[e,n]of i){n.sort((e,t)=>(e.order??Number.MAX_SAFE_INTEGER)-(t.order??Number.MAX_SAFE_INTEGER)||Vc(e.id,t.id));let i=vu(n.length,wu(t,"__chamber__"===e?void 0:e));n.forEach((e,t)=>r.set(e.id,i[t]))}return r}function ku(e,t,i={}){let r=Object.values(e.products).sort((e,t)=>Vc(e.id,t.id)),n=Object.values(e.components).sort((e,t)=>Vc(e.id,t.id)),o=Te([...n.map(e=>e.amount),...r.map(e=>e.amount)]),s=gu(i.radiusRange,t),a=Iu(r,t),l=r.map(e=>{let r=a.get(e.id)??{x:t.chamber.x+t.chamber.width/2,y:t.chamber.y+t.chamber.height/2},n=1.28*fu(e.amount,o,i.bodyRadius,s),l={__crucible:!0,kind:"product",semanticId:e.id,product:e};return{id:mu(e.id),x:r.x,y:r.y,mass:Math.max(.25,n*n*.018),bodyCollisions:!1,shape:{type:"circle",radius:n},datum:l}}),d=/* @__PURE__ */new Map;for(let e of n.filter(e=>!e.productIds.length)){let t=xu(e)??"__chamber__",i=d.get(t)??[];i.push(e),d.set(t,i)}let c=/* @__PURE__ */new Map;for(let[e,i]of d){let r=vu(i.length,wu(t,"__chamber__"===e?void 0:e));i.forEach((e,t)=>c.set(e.id,r[t]))}return[...n.map(e=>{let r=c.get(e.id);if(e.productIds.length){let i=e.productIds.map(e=>a.get(e)).filter(e=>!!e);if(i.length){r={x:i.reduce((e,t)=>e+t.x,0)/i.length,y:i.reduce((e,t)=>e+t.y,0)/i.length};let n=fe(e.id)/4294967295*Math.PI*2,o=Math.min(20,Math.max(4,.012*t.width));r={x:r.x+Math.cos(n)*o,y:r.y+Math.sin(n)*o}}}r??(r={x:t.chamber.x+t.chamber.width/2,y:t.chamber.y+t.chamber.height/2});let n=fu(e.amount,o,i.bodyRadius,s),l={__crucible:!0,kind:"component",semanticId:e.id,sourceDatum:e.datum};return{id:pu(e.id),x:r.x,y:r.y,mass:Math.max(.25,n*n*.015),shape:{type:"circle",radius:n},datum:l}}),...l]}var Su=ku;function Mu(e){return Array.isArray(e)?e.map(Mu):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e&&"function"!=typeof e).sort(([e],[t])=>Vc(e,t)).map(([e,t])=>[e,Mu(t)])):e}function Au(e){return JSON.stringify(Mu(e))}function $u(e,t){let i=Qc(t)??0,r=Math.max(0,Math.min(e.duration,i));if(!e.phases.length)return{elapsed:r,phaseId:"",phaseIndex:-1,phaseElapsed:0,complete:!0};let n=r>=e.duration-Gc,o=n?e.phases[e.phases.length-1]:e.phases.find(e=>r>=e.start&&r<e.end)??e.phases[0];return{elapsed:r,phaseId:o.id,phaseIndex:o.index,phaseElapsed:n?o.duration:Math.max(0,r-o.start),complete:n}}function Cu(e,t){if(void 0===t)return e.duration;if("number"==typeof t)return Math.max(0,Math.min(e.duration,Qc(t)??0));let i=e.phases.find(e=>e.id===t.phaseId);if(!i)return e.duration;let r=Math.max(0,Math.min(1,Qc(t.progress??0)??0));return i.start+i.duration*r}function Pu(e,t=e.duration){let i=$u(e,t),r=mc(e.initialState),n=[],o=[],s=[];for(let t of e.events){if(t.authoredAt>i.elapsed+Gc)break;let a=Ec(r,t,{phaseId:t.phaseId,authoredAt:t.authoredAt,appliedAt:t.authoredAt,products:e.products,outlets:e.outlets});n.push(...a.diagnostics),o.push(...a.materializations),s.push(...a.observations),a.applied&&(r=a.state)}return r.elapsed=i.elapsed,r.phaseId=i.phaseId,r.phaseIndex=i.phaseIndex,r.phaseElapsed=i.phaseElapsed,r.complete=i.complete,i.complete&&"in_process"===r.outcome&&(r.outcome="complete"),r.playing=!1,{state:r,diagnostics:n,materializations:o,observations:s}}function Ru(e){let t=iu(e.phases),i=t.phases.at(-1)?.end??0,r=su(e.outlets??_c),n=(e.products??[]).map(e=>({...e,metrics:e.metrics?uc(e.metrics):void 0})),o=nu(e.events??[],t.phases,i),s=tu(e),a=au(e.size??Yc,r),l=cu(a),d=ou(n,r),c=Au({seed:e.seed??1,components:Object.values(s.state.components).sort((e,t)=>Vc(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:i,description:r,intensity:n,motion:o,color:s,metrics:a})=>({id:e,duration:t,label:i,description:r,intensity:n,motion:o,color:s,metrics:a})),products:n,outlets:r,events:o.events.map(({id:e,label:t,description:i,summary:r,authoredAt:n,phaseId:o,boundaryRank:s,effects:a})=>({id:e,label:t,description:i,summary:r,authoredAt:n,phaseId:o,boundaryRank:s,effects:a}))}),u=bu(s.state,a,{seed:e.seed,bodyRadius:e.bodyRadius,radiusRange:e.radiusRange}),h=[...t.diagnostics,...o.diagnostics,...s.diagnostics,...d],p={phases:t.phases,events:o.events,products:n,outlets:r,duration:i,initialState:s.state,terminalState:s.state,layout:a,colliders:l,config:hu(e.seed,l),initialSpawns:u,terminalSpawns:[],semanticKey:c,diagnostics:h},m=Pu(p),y=Object.values(m.state.products).filter(e=>"forming"===e.status).map(e=>e.id),f=y.length?[Uc("warning","forming-product-at-end",`Products remain forming at the end of the tape: ${y.join(", ")}.`,"events",y)]:[];return p.terminalState=m.state,p.terminalSpawns=Su(m.state,a,{seed:e.seed,bodyRadius:e.bodyRadius,radiusRange:e.radiusRange}),p.diagnostics=[...h,...m.diagnostics,...f],p}function Du(e,t,i){return{id:e.id??t,at:{...e.at},effects:i,...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 Bu(e){if(e)return{...e,...e.metrics?{metrics:{...e.metrics}}:null}}function Tu(e){let{productId:t,form:i,contributions:r=[],complete:n}=e,o=e.idPrefix??t,s=Bu(i.loss),a=[Du(i,`${o}-form`,[{type:"combine",sourceIds:[...i.sourceIds],productId:t,...i.basisRelationIds?{basisRelationIds:[...i.basisRelationIds]}:null,...s?{loss:s}:null,complete:!1}])];return r.forEach((e,i)=>{let r=Bu(e.loss);a.push(Du(e,`${o}-contribute-${i+1}`,[{type:"contribute",sourceIds:[...e.sourceIds],productId:t,...e.basisRelationIds?{basisRelationIds:[...e.basisRelationIds]}:null,...r?{loss:r}:null}]))}),a.push(Du(n,`${o}-complete`,[{type:"complete-product",productId:t,...void 0===n.outletId?null:{outletId:n.outletId},...void 0===n.reason?null:{reason:n.reason}}])),a}import{forwardRef as ju,useCallback as Ou,useEffect as Eu,useImperativeHandle as Nu,useMemo as Fu,useRef as Wu,useState as qu}from"react";function Hu(e,t){return e.playing=t&&!e.complete,e}function zu(e,t){return Cu(e,t)}function Lu(e,t,i=!1){let r=Pu(e,t);return{...r,state:Hu(r.state,i)}}function Yu(e,t,i,r=t.playing){let n=Lu(e,i,r),o=new Set(t.eventsApplied);return{...n,observations:n.observations.filter(e=>!o.has(e.eventId)),materializations:n.materializations.filter(e=>!o.has(e.eventId))}}function _u(e,t){return e.phases.find(e=>e.end>t+1e-7)?.end??e.duration}function Xu(e,t,i={}){return ku(t,e.layout,i)}function Gu(e,t){let i=new Set(e.readBodies().map(e=>e.id)),r=t.filter(e=>!i.has(e.id));return r.length&&e.pushMany([...r]),r.map(e=>e.id)}function Vu(e,t){return fe(`${t}:${e}`)/4294967295}function Uu(e,t){return e.phases[t.phaseIndex]??e.phases.find(e=>e.id===t.phaseId)}function Ku(e,t,i={}){return new Map(Xu(e,t,i).flatMap(e=>{let t=e.datum;return t?.__crucible?[[`${t.kind}:${t.semanticId}`,{x:e.x,y:e.y}]]:[]}))}function Qu(e,t){let i=Object.values(e.terminalState.products).map(e=>e.id).sort(),r=Math.max(0,i.indexOf(t))/Math.max(1,i.length)*Math.PI*2-Math.PI/2,n=Math.min(58,.19*e.layout.chamber.width),o=Math.min(38,.16*e.layout.chamber.height);return{x:e.layout.chamber.x+e.layout.chamber.width/2+Math.cos(r)*n,y:e.layout.chamber.y+.52*e.layout.chamber.height+Math.sin(r)*o}}function Ju(e){let{body:t,plan:i,state:r,targets:n}=e,o=t.datum;if(!o?.__crucible)return null;let s=`${o.kind}:${o.semanticId}`,a=n.get(s);if(!a)return null;let l=Uu(i,r),d=Math.max(0,Math.min(2,Number(l?.intensity??.5))),c=l?.motion??"hold",u=r.elapsed;if("product"===o.kind){let e=r.products[o.semanticId];"forming"===e?.status&&(a=Qu(i,e.id))}else{let e=r.components[o.semanticId],t=e?.productIds.map(e=>r.products[e]).find(e=>"forming"===e?.status);if(t){let r=Qu(i,t.id),n=Vu(e.id,17)*Math.PI*2,o=Math.max(5,Math.min(18,.026*i.layout.width));a={x:r.x+Math.cos(n)*o,y:r.y+Math.sin(n)*o}}}let h=o.semanticId,p=Vu(h,23)*Math.PI*2,m=a.x>=i.layout.chamber.x&&a.x<=i.layout.chamber.x+i.layout.chamber.width&&a.y>=i.layout.chamber.y&&a.y<=i.layout.chamber.y+i.layout.chamber.height;if(!r.complete&&m)if("mix"===c){let e=Math.min(34,.1*i.layout.chamber.width)*d,t=Math.min(24,.09*i.layout.chamber.height)*d;a={x:a.x+Math.cos(u*(1.4+Vu(h,29))+p)*e,y:a.y+Math.sin(u*(1.8+Vu(h,31))+p)*t}}else if("press"===c){let e=i.layout.chamber.x+i.layout.chamber.width/2,t=i.layout.chamber.y+.56*i.layout.chamber.height;a={x:e+(a.x-e)*Math.max(.3,1-.32*d),y:t+(a.y-t)*Math.max(.35,1-.26*d)}}else if("separate"===c){let e=Vu(h,41)<.5?-1:1;a={x:a.x+e*Math.min(28,.075*i.layout.chamber.width)*d,y:a.y}}else if("bind"===c){let e=i.layout.chamber.x+i.layout.chamber.width/2,t=i.layout.chamber.y+.5*i.layout.chamber.height;a={x:e+.72*(a.x-e),y:t+.72*(a.y-t)}}else"charge"===c?a={x:a.x,y:a.y+4*Math.sin(2*u+p)*d}:"quench"===c&&(a={x:a.x+2*Math.sin(p)*d,y:a.y});return a}function Zu(e){let t=Ju(e);if(!t)return null;let{body:i,state:r}=e,n=t.x-i.x,o=t.y-i.y,s=Math.hypot(n,o),a=Math.hypot(i.vx,i.vy);if(r.complete&&s<.7&&a<.45)return null;let l=!r.complete&&"pour"===Uu(e.plan,r)?.motion,d=r.complete?.68:l?.72:.5,c=r.complete?.22:l?.18:.14,u=r.complete?42:l?72:56;return{x:Math.max(-u,Math.min(u,n*d-i.vx*c)),y:Math.max(-u,Math.min(u,o*d-i.vy*c))}}import*as eh from"react";import{jsx as th,jsxs as ih}from"react/jsx-runtime";function rh(e){return Number.isFinite(e)?Math.abs(e)>=1e3?e.toLocaleString():Number.isInteger(e)?String(e):e.toFixed(2).replace(/\.00$/,"").replace(/(\.\d)0$/,"$1"):"0"}function nh(e){let t=e.productIds.length?` Contributes to ${e.productIds.join(", ")}.`:e.outletId?` Routed to ${e.outletId}.`:"",i=e.reason?` ${e.reason}.`:"";return`${rh(e.amount)} amount; ${e.status}.${t}${i}`}function oh(e){let t=e.outletId?` Routed to ${e.outletId}.`:"";return`${e.status} product with ${e.sourceIds.length} source${1===e.sourceIds.length?"":"s"} and ${rh(e.amount)} amount.${t}`}function sh(e,t){let i=e.datum;if(!i?.__crucible)return!1;if("component"===i.kind){let e=t.components[i.semanticId];return!!e&&{id:`crucible-component-${e.id}`,label:e.label,description:nh(e),group:`source component · ${e.status}`,datum:e}}let r=t.products[i.semanticId];return!!r&&{id:`crucible-product-${r.id}`,label:r.label,description:oh(r),group:`derived product · ${r.status}`,datum:r}}function ah(e,t,i,r){let n=t.datum;if(!n?.__crucible)return;let o="circle"===t.shape.type?t.shape.radius:8,s="product"===n.kind?"#b8792d":"#356b63",a=r?.resolvePaint??((t,i)=>ge(e,t,i)),l=a(i.fill,s),d=a(i.stroke,"#26323a");if(e.save(),e.translate(t.x,t.y),e.globalAlpha="number"==typeof i.opacity?i.opacity:.96,e.fillStyle=l,e.strokeStyle=d,e.lineWidth="number"==typeof i.strokeWidth?i.strokeWidth:1.25,"product"===n.kind){e.shadowColor="string"==typeof l?l:s,e.shadowBlur=10,e.beginPath();for(let t=0;t<6;t+=1){let i=-Math.PI/2+t/6*Math.PI*2,r=Math.cos(i)*o,n=Math.sin(i)*o;0===t?e.moveTo(r,n):e.lineTo(r,n)}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=a("var(--semiotic-bg, #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()}function lh(e,t,i){let r=/* @__PURE__ */new Map;for(let e of t){let t=e.datum;t?.__crucible&&r.set(`${t.kind}:${t.semanticId}`,e)}e.save(),e.lineCap="round";for(let t of Object.values(i.relations)){if("active"!==t.status)continue;let i=t.sourceIds.map(e=>r.get(`component:${e}`)).filter(e=>!!e);i.length<2||(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(),i.forEach((t,i)=>{0===i?e.moveTo(t.x,t.y):e.lineTo(t.x,t.y)}),e.stroke())}e.setLineDash([]);for(let t of Object.values(i.products)){let i=r.get(`product:${t.id}`);if(i)for(let n of t.sourceIds){let o=r.get(`component:${n}`);o&&(e.strokeStyle=t.color??"#b8792d",e.globalAlpha="complete"===t.status?.5:.28,e.lineWidth="complete"===t.status?1.6:1,e.beginPath(),e.moveTo(o.x,o.y),e.lineTo(i.x,i.y),e.stroke())}}e.restore()}import{Fragment as dh,jsx as ch,jsxs as uh}from"react/jsx-runtime";var hh="var(--semiotic-text, #26323a)",ph="var(--semiotic-text-secondary, #6c7377)",mh="var(--semiotic-primary, #b8792d)",yh="var(--semiotic-danger, #9f3d35)",fh="var(--semiotic-success, #356b63)";function gh(e,t){let i=e.data;if(!i?.__crucible)return null;let r="component"===i.kind?t.components[i.semanticId]:t.products[i.semanticId];if(!r)return null;let n="product"===i.kind;/* */
|
|
131
|
+
return uh("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:[
|
|
132
|
+
/* @__PURE__ */ch("strong",{children:r.label}),
|
|
133
|
+
/* @__PURE__ */ch("div",{style:{opacity:.78,fontSize:11,letterSpacing:"0.06em",textTransform:"uppercase"},children:n?`Product · ${r.status}`:`Source · ${r.status}`}),
|
|
134
|
+
/* @__PURE__ */ch("div",{style:{marginTop:4},children:n?oh(r):nh(r)})]})}function bh(e){let{x:t,y:i,width:r,height:n}=e.chamber,o=Math.min(.14*r,48),s=i+n;return[`M ${t} ${i}`,`L ${t+o} ${s-.16*n}`,`Q ${t+r/2} ${s+.1*n} ${t+r-o} ${s-.16*n}`,`L ${t+r} ${i}`].join(" ")}function vh({layout:e,phases:t,state:i,compact:r=!1}){let n=Math.max(1,t.reduce((e,t)=>e+Math.max(0,t.duration),0));/* */
|
|
135
|
+
return uh("svg",{"aria-hidden":"true","data-testid":"crucible-chrome",viewBox:`0 0 ${e.width} ${e.height}`,style:{inset:0,pointerEvents:"none",position:"absolute"},children:[
|
|
136
|
+
/* @__PURE__ */uh("defs",{children:[
|
|
137
|
+
/* @__PURE__ */uh("linearGradient",{id:"semiotic-crucible-heat",x1:"0",x2:"0",y1:"0",y2:"1",children:[
|
|
138
|
+
/* @__PURE__ */ch("stop",{offset:"0",stopColor:mh,stopOpacity:"0.03"}),
|
|
139
|
+
/* @__PURE__ */ch("stop",{offset:"0.66",stopColor:mh,stopOpacity:"0.1"}),
|
|
140
|
+
/* @__PURE__ */ch("stop",{offset:"1",stopColor:yh,stopOpacity:"0.18"})]}),
|
|
141
|
+
/* @__PURE__ */ch("pattern",{id:"semiotic-crucible-hatch",width:"7",height:"7",patternUnits:"userSpaceOnUse",patternTransform:"rotate(20)",children:/* @__PURE__ */ch("line",{x1:"0",x2:"0",y1:"0",y2:"7",stroke:hh,strokeOpacity:"0.08",strokeWidth:"1"})})]}),
|
|
142
|
+
/* @__PURE__ */ch("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:hh,strokeOpacity:"0.52",strokeWidth:r?1:2.2}),
|
|
143
|
+
/* @__PURE__ */ch("path",{d:bh(e),fill:"url(#semiotic-crucible-hatch)",stroke:"none"}),
|
|
144
|
+
/* @__PURE__ */ch("line",{x1:e.mouth.x,x2:e.mouth.x+e.mouth.width,y1:e.mouth.y,y2:e.mouth.y,stroke:hh,strokeLinecap:"round",strokeOpacity:"0.72",strokeWidth:r?2:5}),r?null:/* @__PURE__ */ch("g",{"data-testid":"crucible-phase-rail",children:t.map((r,o)=>{let s=t.slice(0,o).reduce((e,t)=>e+Math.max(0,t.duration),0),a=e.phaseRail.x+s/n*e.phaseRail.width,l=Math.max(0,r.duration)/n*e.phaseRail.width,d=r.id===i.phaseId,c=i.phaseIndex>o||i.complete;/* */
|
|
145
|
+
return uh("g",{children:[
|
|
146
|
+
/* @__PURE__ */ch("rect",{x:a,y:e.phaseRail.y,width:Math.max(1,l-2),height:e.phaseRail.height,rx:2,fill:d?r.color??mh:c?fh:hh,fillOpacity:d?.68:c?.28:.09}),l>=46?/* @__PURE__ */ch("text",{x:a+l/2,y:e.phaseRail.y+e.phaseRail.height+13,fill:d?hh:ph,fontFamily:"var(--semiotic-font-family, system-ui, sans-serif)",fontSize:8.5,fontWeight:d?800:650,letterSpacing:"0.04em",textAnchor:"middle",children:(r.label??r.id).toUpperCase()}):null]},r.id)})}),e.outlets.map(e=>/* @__PURE__ */uh("g",{children:[
|
|
147
|
+
/* @__PURE__ */ch("rect",{x:e.x,y:e.y,width:e.width,height:e.height,rx:3,fill:e.color??("left"===e.side?yh:fh),fillOpacity:"0.1",stroke:e.color??("left"===e.side?yh:fh),strokeDasharray:"3 3",strokeOpacity:"0.62"}),r?null:/* @__PURE__ */ch("text",{x:e.x+e.width/2,y:e.y+Math.min(13,e.height/2+3),fill:ph,fontFamily:"var(--semiotic-font-family, system-ui, sans-serif)",fontSize:8,fontWeight:750,letterSpacing:"0.05em",textAnchor:"middle",children:(e.label??e.id).toUpperCase()})]},e.id))]})}function xh(e,t){return"count"===t?e.count:"amount"===t?e.amount:Number(e.metrics[t]??0)}function wh(e,t,i,r){if(!e.length)return[];let n=i.measure??"count",o=t.projection.width/Math.max(1,e.length);return e.map((e,i)=>{let s=xh(e,n),a="amount"===n&&r?`${rh(s)} ${r}`:`${rh(s)} ${n}`;return{id:`crucible-projection-${e.key}`,label:`${e.label}: ${a}`,description:`${e.count} source component${1===e.count?"":"s"}; ${rh(e.amount)} amount.`,datum:e,group:"settled composition",x:t.projection.x+(i+.5)*o,y:t.projection.y+t.projection.height/2,shape:"rect",width:Math.max(12,.62*o),height:Math.max(8,t.projection.height-8)}})}function Ih({rows:e,layout:t,projection:i,amountLabel:r}){if(!e.length)return null;let n=i.measure??"count",o=e.map(e=>Math.max(0,xh(e,n))),s=o.reduce((e,t)=>Math.max(e,t),1),a=t.projection.width/Math.max(1,e.length),l=t.projection.height>48?21:4,d=Math.max(5,t.projection.height-l-5);/* */
|
|
148
|
+
return ch("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,i)=>{let c=o[i],u=Math.max(c>0?2:0,c/s*d),h=t.projection.x+i*a+.18*a,p=t.projection.y+d-u;/* */
|
|
149
|
+
return uh("g",{children:[
|
|
150
|
+
/* @__PURE__ */ch("rect",{x:h,y:p,width:Math.max(3,.64*a),height:u,rx:2,fill:"failed"===e.status||"ejected"===e.status?yh:"complete"===e.status?mh:fh,fillOpacity:"0.68"}),l>4&&a>=34?/* @__PURE__ */uh(dh,{children:[
|
|
151
|
+
/* @__PURE__ */ch("text",{x:h+.32*a,y:t.projection.y+d+10,fill:ph,fontFamily:"var(--semiotic-font-family, system-ui, sans-serif)",fontSize:7.5,fontWeight:700,textAnchor:"middle",children:e.label.length>13?`${e.label.slice(0,12)}…`:e.label}),
|
|
152
|
+
/* @__PURE__ */uh("text",{x:h+.32*a,y:t.projection.y+d+19,fill:hh,fontFamily:"var(--semiotic-font-family, system-ui, sans-serif)",fontSize:8,fontWeight:850,textAnchor:"middle",children:[rh(c),"amount"===n&&r?` ${r}`:""]})]}):null]},e.key)})})}function kh({controls:e,duration:t,elapsed:i,phaseLabel:r,playing:n,complete:o,playbackRate:s,disabled:a,onPlayPause:l,onReset:d,onStepPhase:c,onPlaybackRateChange:u}){let h=t>0?Math.min(1,Math.max(0,i/t)):1;/* */
|
|
153
|
+
return uh("div",{"aria-label":"Crucible replay controls",className:"semiotic-crucible-controls",style:{alignItems:"center",color:hh,display:"flex",flexWrap:"wrap",fontFamily:"system-ui, sans-serif",fontSize:11,gap:6,marginBottom:7},children:[e.playPause?/* @__PURE__ */ch("button",{type:"button",disabled:a,onClick:l,"aria-pressed":n,children:n?"Pause":o?"Replay":"Play"}):null,e.stepPhase?/* @__PURE__ */ch("button",{type:"button",disabled:a,onClick:c,children:"Next phase"}):null,e.reset?/* @__PURE__ */ch("button",{type:"button",disabled:a,onClick:d,children:"Reset"}):null,e.timeline?/* @__PURE__ */uh("div",{style:{alignItems:"center",display:"flex",flex:"1 1 150px",gap:7,minWidth:130},children:[
|
|
154
|
+
/* @__PURE__ */ch("span",{style:{fontWeight:750,whiteSpace:"nowrap"},children:r}),
|
|
155
|
+
/* @__PURE__ */ch("span",{"aria-hidden":"true",style:{background:"rgba(38,50,58,0.14)",borderRadius:2,flex:1,height:4,overflow:"hidden"},children:/* @__PURE__ */ch("span",{style:{background:mh,display:"block",height:"100%",transform:`scaleX(${h})`,transformOrigin:"left center"}})}),
|
|
156
|
+
/* @__PURE__ */uh("span",{style:{color:ph,fontVariantNumeric:"tabular-nums"},children:[i.toFixed(1),"s"]})]}):null,e.speed?/* @__PURE__ */uh("label",{style:{alignItems:"center",display:"flex",gap:4},children:["Speed",
|
|
157
|
+
/* @__PURE__ */uh("select",{disabled:a,value:s,onChange:e=>u(Number(e.currentTarget.value)),children:[
|
|
158
|
+
/* @__PURE__ */ch("option",{value:.25,children:"¼×"}),
|
|
159
|
+
/* @__PURE__ */ch("option",{value:.5,children:"½×"}),
|
|
160
|
+
/* @__PURE__ */ch("option",{value:1,children:"1×"}),
|
|
161
|
+
/* @__PURE__ */ch("option",{value:2,children:"2×"})]})]}):null]})}function Sh(e,t,i,r){let n="function"==typeof r?r(t,i):r,o=t.datum;return{fill:e,stroke:"product"===o?.kind?"var(--semiotic-bg, #fffaf0)":hh,strokeWidth:"product"===o?.kind?1.8:1.1,opacity:.96,...n}}var Mh=["#356b63","#a34b43","#c08b38","#3e5f83","#785b7c","#6e7740","#8f5c3a","#41717b"];function Ah(e){return"number"==typeof e&&Number.isFinite(e)?e:fe(String(e??"crucible"))}function $h(e){let t=Number(e);return Number.isFinite(t)&&t>0?Math.max(.05,Math.min(8,t)):1}function Ch(e,t,i){let r="function"==typeof e?e(t,i):t[e];return String(r??"unassigned")}function Ph(e,t,i){return"category"===t?e.category:"status"===t?e.status:"outlet"===t?e.outletId??"in chamber":"product"===t?e.productIds[0]??"unalloyed":Ch(t,e.datum,i)}function Rh(e){return Mh[fe(e)%Mh.length]}function Dh(e,t){let i=Object.keys(e.components).length,r=Object.keys(e.products).length,n=Object.values(e.products).reduce((e,t)=>e+t.amount,0),o=t?` ${t}`:" amount",s=e.outcome?` Outcome: ${e.outcome}.`:"";return`${i} source component${1===i?"":"s"}; ${r} product${1===r?"":"s"}; ${n.toLocaleString()}${o} in products.${s}`}import{jsx as Bh,jsxs as Th}from"react/jsx-runtime";import{createElement as jh}from"react";var Oh=/* @__PURE__ */L(/* @__PURE__ */ju(function(e,t){let{amountAccessor:i,amountLabel:r,bodyRadius:n,categoryAccessor:o,colorBy:s="category",conservation:a,controls:l,data:d,emptyContent:c,events:u,frameProps:h={},idAccessor:p,initialStateAccessor:m,initialSpawnPacing:y,labelAccessor:f,loading:g,loadingContent:b,metrics:v,metricsAccessor:x,onClick:w,onConservation:I,onCrucibleObservation:k,onDiagnostic:S,onStateChange:M,outlets:A,paused:$,phases:C,playback:P="replay",playbackRate:R=1,products:D,projection:B,radiusRange:T,rerunMS:j,seed:O,showBonds:E=!0,snapshotAt:N}=e,F=Wu(null),W=Wu($);W.current=$;let q=Be(),H=ee(),z=Qs(e,bs),{chartMode:L,chartSize:Y,responsiveContainerRef:_,responsiveHeight:G,responsiveWidth:V,showChrome:U,showProjection:K,className:Q,title:J,description:Z,summary:te,accessibleTable:ie,enableHover:re,margin:ne}=z,oe=Y,se=Fu(()=>X(d??[]),[d]),ae=Fu(()=>Ru({data:se,phases:C,products:D,outlets:A,events:u,idAccessor:p,labelAccessor:f,categoryAccessor:o,amountAccessor:i,metricsAccessor:x,initialStateAccessor:m,metrics:v,size:oe,seed:O,bodyRadius:n,radiusRange:T}),[i,n,o,u,p,m,f,v,x,A,C,D,T,oe,se,O]),le=Object.values(ae.initialState.components).map((e,t)=>Ph(e,s,t)).join("\0"),de=`${ae.semanticKey}:${oe[0]}x${oe[1]}:${String(n??"auto")}:${T?.join(",")??"auto"}:${le}`,ce=Wu(ae),ue=Wu(de);ue.current!==de&&(ue.current=de,ce.current=ae);let he=ce.current,pe="snapshot"===P||q||H,me=pe?zu(he,N):0,ye=!pe,fe=Fu(()=>Lu(he,me,ye&&!$),[ue.current,me,ye]),[ge,be]=qu(fe),ve=Wu(ge),[xe,we]=qu(ye),Ie=Wu(xe),[ke,Se]=qu(0),[Me,Ae]=qu(()=>$h(R)),$e=Wu(Ku(he,fe.state,{seed:O,bodyRadius:n,radiusRange:T})),Ce=Wu(""),Pe=Wu(M),Re=Wu(k),De=Wu(S),Te=Wu(I);Pe.current=M,Re.current=k,De.current=S,Te.current=I;let je=Wu({seed:O,bodyRadius:n,radiusRange:T});je.current={seed:O,bodyRadius:n,radiusRange:T};let Oe=Ou((e,t=!1)=>{if(ve.current=e,$e.current=Ku(ce.current,e.state,je.current),be(e),t)for(let t of e.observations)Re.current?.(t)},[]);Eu(()=>{Ae($h(R))},[R]);let Ee=Wu(fe);if(Ee.current!==fe){Ee.current=fe;let e=!pe,t=Lu(he,pe?me:0,e&&!W.current);Ie.current=e,we(e),Oe(t)}Eu(()=>{let e=ve.current,t=Ie.current&&!$&&!e.state.complete;if(e.state.playing===t)return;let i={...e,state:mc(e.state)};i.state.playing=t,Oe(i)},[Oe,$]),Eu(()=>{for(let e of he.diagnostics)De.current?.(e)},[de,he.diagnostics]),Eu(()=>{let e=ve.current.state;if(Pe.current?.(e),a){let t=!0===a?{}:a;Te.current?.(qc(e,t))}},[a,ge.state]);let Ne=Ou(()=>{Ce.current="";let e=!pe,t=Lu(ce.current,0,e&&!$);Ie.current=e,we(e),Oe(t)},[Oe,$,pe]),Fe=Fu(()=>({...he.config,...h.config,fixedDt:h.config?.fixedDt??he.config.fixedDt,maxSubsteps:h.config?.maxSubsteps??he.config.maxSubsteps,settleStepLimit:h.config?.settleStepLimit??he.config.settleStepLimit,timeScale:Me,colliders:[...he.config.colliders??[],...h.config?.colliders??[]],kernel:{...he.config.kernel,...h.config?.kernel,gravity:h.config?.kernel?.gravity??he.config.kernel?.gravity??{x:0,y:0}},observation:{...he.config.observation,...h.config?.observation,chartType:"CrucibleChart"}}),[h.config,Me,he.config]),We=pe||!!$||!xe&&!ge.state.complete,qe=Vs(Fe,j,We,Ne,e.onSimulationStateChange),He=Ou(()=>{if("number"!=typeof j||!Number.isFinite(j)||j<0)return;let e=`${de}:${ke}:${qe.rerunKey}`;Ce.current!==e&&(Ce.current=e,qe.config?.observation?.onSimulationStateChange?.("settled","running"))},[qe.config,qe.rerunKey,j,ke,de]),ze=Ou(()=>{let e=Lu(ce.current,0,!1);Ie.current=!1,we(!1),Oe(e),Se(e=>e+1)},[Oe]),Le=Ou(()=>{let e=ce.current,t=Yu(e,ve.current.state,e.duration,!1);Ie.current=!1,we(!1),Oe(t,!0);let i=Xu(e,t.state,je.current),r=F.current;r&&(r.clear(),r.pushMany(i),r.step(0),r.settle()),He()},[Oe,He]),Ye=Ou(()=>{Ie.current=!1,we(!1);let e={...ve.current,state:mc(ve.current.state)};e.state.playing=!1,Oe(e)},[Oe]),_e=Ou(()=>{if(Ce.current="",pe){let e=Lu(ce.current,me,!1);return Ie.current=!1,we(!1),Oe(e),void Se(e=>e+1)}let e=Lu(ce.current,0,!$);Ie.current=!0,we(!0),Oe(e),Se(e=>e+1)},[Oe,$,me,pe]),Xe=Ou(()=>{if(pe)return void _e();if(ve.current.state.complete)return void _e();Ie.current=!0,we(!0);let e={...ve.current,state:mc(ve.current.state)};e.state.playing=!$,Oe(e)},[Oe,$,_e,pe]),Ge=Ou(()=>{let e=ce.current,t=_u(e,ve.current.state.elapsed),i=Yu(e,ve.current.state,t,!1);Ie.current=!1,we(!1),Oe(i,!0);let r=F.current;r&&(r.clear(),r.pushMany(Xu(e,i.state,je.current)),r.step(0))},[Oe]);Nu(t,()=>({play:Xe,pause:Ye,reset:ze,replay:_e,stepPhase:Ge,settle:Le,getCrucibleState:()=>mc(ve.current.state)}),[Ye,Xe,_e,ze,Le,Ge]);let Ve=Ou((e,t)=>{if(h.onTick?.(e,t),pe||$||!Ie.current)return;let i=ve.current.state,r=Math.min(ce.current.duration,e.elapsedSeconds);if(r<=i.elapsed+.045&&r<ce.current.duration)return;let n=Yu(ce.current,i,r,r<ce.current.duration),o=n.state.eventsApplied.length!==i.eventsApplied.length;if(o&&Gu(t,Xu(ce.current,n.state,je.current)),n.state.complete){Ie.current=!1,we(!1);let e=Xu(ce.current,n.state,je.current);t.clear(),t.pushMany(e),t.step(0),t.settle()}Oe(n,o),n.state.complete&&He()},[Oe,h,$,He,pe]),Ue=Ou(({body:e})=>Zu({body:e,plan:ce.current,state:ve.current.state,targets:$e.current}),[]),Ke=Fu(()=>new Map(Object.keys(he.initialState.components).map((e,t)=>[e,t])),[he.initialState.components]),Qe=Ou(t=>{if(e.color)return e.color;let i=t.datum;if(!i?.__crucible)return"var(--semiotic-primary, #b8792d)";if("product"===i.kind){let e=ve.current.state.products[i.semanticId];return e?.color??Rh(e?.id??i.semanticId)}let r=ve.current.state.components[i.semanticId];return r?Rh(Ph(r,s,Ke.get(r.id)??0)):"var(--semiotic-primary, #356b63)"},[s,Ke,e.color]),Je=Ou((t,i)=>({...Sh(Qe(t),t,i,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}),[Qe,h.bodyStyle,e.opacity,e.stroke,e.strokeWidth]),Ze=Ou((e,t)=>("function"==typeof h.bodySemanticItems?h.bodySemanticItems(e,t):void 0)??sh(e,ve.current.state),[h]),et=Ou(e=>{if(!w||!e||"object"!=typeof e)return;let t=e;if(!t.__crucible)return;let i=ve.current.state,r="component"===t.kind?i.components[t.semanticId]:i.products[t.semanticId];r&&w(r)},[w]),tt=Ou((e,t,i)=>{h.beforePaint?.(e,t,i),E&&lh(e,t,ve.current.state)},[h,E]),it=Fu(()=>B??{groupBy:"outlet",measure:"count"},[B]),rt=Fu(()=>Fc(ge.state,it),[it,ge.state]),nt=Fu(()=>K?wh(rt,he.layout,it,r):[],[r,he.layout,it,rt,K]),ot=ia(e.tooltip,h),{selection:st,onBodyHover:at}=_s({selection:e.selection,linkedHover:e.linkedHover,colorBy:s,chartType:"CrucibleChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:h?.onBodyHover,unwrapSourceDatum:!0}),lt=ra({...e,onClick:void 0},h,nt,{selection:st,chartMode:L,className:Q,title:J??"Crucible",description:Z??"A bounded inventory is transformed by an authored phase and event tape; physics explains the motion but does not determine the outcome.",summary:te??Dh(ge.state,r),accessibleTable:ie,enableHover:re,margin:ne}),dt=ta(U?/* @__PURE__ */Bh(vh,{layout:he.layout,phases:he.phases,state:ge.state,compact:z.compactMode||oe[0]<360||oe[1]<260}):void 0,h.backgroundGraphics),ct=ta(K?/* @__PURE__ */Bh(Ih,{rows:rt,layout:he.layout,projection:it,amountLabel:r}):void 0,h.foregroundGraphics),ut=Ou(e=>gh(e,ve.current.state),[]),ht=pe?Xu(he,ge.state,je.current):he.initialSpawns,pt=(gt=l)?!0===gt?{playPause:!0,reset:!0,stepPhase:!0,timeline:!0,speed:!0}:{playPause:gt.playPause??!0,reset:gt.reset??!0,stepPhase:gt.stepPhase??!0,timeline:gt.timeline??!0,speed:gt.speed??!1}:{playPause:!1,reset:!1,stepPhase:!1,timeline:!1,speed:!1},mt=Object.values(pt).some(Boolean),yt=he.phases[ge.state.phaseIndex],ft=Zs({responsive:e,data:d,emptyContent:c,loading:g,loadingContent:b,size:oe});var gt;if(ft)return ft;let bt=he.diagnostics.filter(e=>"error"===e.severity);return bt.length?/* @__PURE__ */Th("div",{className:Q,role:"alert",style:{maxWidth:"100%",width:oe[0]},children:[
|
|
162
|
+
/* @__PURE__ */Bh("strong",{children:"CrucibleChart could not compile this treatment tape."}),
|
|
163
|
+
/* @__PURE__ */Bh("ul",{children:bt.map((e,t)=>/* @__PURE__ */Bh("li",{children:e.message},`${e.code}-${t}`))})]}):ea("CrucibleChart",oe,
|
|
164
|
+
/* @__PURE__ */Th("div",{ref:_,className:"semiotic-crucible-chart",style:{maxWidth:"100%",overflow:"hidden",position:"relative",width:V?"100%":oe[0],height:G?"100%":void 0},children:[mt?/* @__PURE__ */Bh(kh,{controls:pt,duration:he.duration,elapsed:ge.state.elapsed,phaseLabel:yt?.label??yt?.id??"Complete",playing:xe&&!$,complete:ge.state.complete,playbackRate:Me,disabled:pe,onPlayPause:xe?Ye:Xe,onReset:ze,onStepPhase:Ge,onPlaybackRateChange:Ae}):null,
|
|
165
|
+
/* @__PURE__ */jh(yo,{...h,...ot,...lt,key:`${oe[0]}x${oe[1]}:${de}:${ke}:${qe.rerunKey}:${pe?me:"replay"}`,ref:F,onBodyHover:at,accessibleTable:e.accessibleTable??h.accessibleTable,backgroundGraphics:dt,bodyForces:Ue,bodySemanticItems:Ze,bodyStyle:Je,beforePaint:tt,config:qe.config,continuous:!pe&&xe&&!$&&!ge.state.complete,enableHover:ot.enableHover??re,foregroundGraphics:ct,hoverRadius:e.hoverRadius??h.hoverRadius??18,initialSpawns:ht,initialSpawnPacing:y,onClick:w?et:lt.onClick,onTick:Ve,paused:We,renderBody:h.renderBody??ah,responsiveHeight:!1,responsiveWidth:!1,seed:Ah(O),size:oe,tooltipContent:ot.tooltipContent??ut})]}))}),"CrucibleChart");function Eh(e,t){let i=/* @__PURE__ */new Map;for(let t of e)i.set(t.id,/* @__PURE__ */new Set);for(let e of t)i.has(e.source)||i.set(e.source,/* @__PURE__ */new Set),i.has(e.target)||i.set(e.target,/* @__PURE__ */new Set),i.get(e.source).add(e.target);return i}function Nh(e,t,i={}){let r=/* @__PURE__ */new Set,n=[...e.get(t)??[]];for(let t=0;t<n.length;t++){let i=n[t];r.has(i)||(r.add(i),n.push(...e.get(i)??[]))}return i.includeStart&&r.add(t),r}function Fh(e,t,i){return V(i,e,t)}function Wh(e,t){return e<t?-1:e>t?1:0}function qh(e,t){return`dependency:${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Hh(e,t){return`socket:${encodeURIComponent(e)}:${t}`}function zh(e){let t=Number(e);return Number.isFinite(t)?Math.max(0,Math.min(1,t)):0}function Lh(e){let t=[],i=/* @__PURE__ */new Map,r=[],n=/* @__PURE__ */new Set;e.data.forEach((o,s)=>{let a=String(Fh(o,s,e.taskIDAccessor)??"");if(!a)return void t.push({code:"duplicate-task-id",message:`Task row ${s} has an empty id.`,taskIDs:[]});if(i.has(a))return void t.push({code:"duplicate-task-id",message:`Task id "${a}" occurs more than once.`,taskIDs:[a]});let l=String(Fh(o,s,e.laneAccessor)??"Unassigned");n.has(l)||(n.add(l),r.push(l));let d=Fh(o,s,e.dependencyAccessor)??[],c=Array.from(new Set(Array.from(d,e=>String(e)))).sort(Wh),u=Fh(o,s,e.blockerAccessor),h=Fh(o,s,e.statusAccessor)??(u?"blocked":"waiting");i.set(a,{id:a,label:String(Fh(o,s,e.labelAccessor)??a),lane:l,laneIndex:0,level:0,index:s,datum:o,dependencyIDs:c,incomingEdgeIDs:[],outgoingEdgeIDs:[],socketIDs:[],start:Fh(o,s,e.startAccessor),end:Fh(o,s,e.endAccessor),progress:zh(Fh(o,s,e.progressAccessor)),status:h,completionTime:Fh(o,s,e.completionTimeAccessor),blockerReason:u||void 0,milestone:!!Fh(o,s,e.milestoneAccessor)})});let o=e.laneOrder?[...e.laneOrder,...r.filter(t=>!e.laneOrder?.includes(t))]:r,s=new Map(o.map((e,t)=>[e,t]));for(let e of i.values())e.laneIndex=s.get(e.lane)??0;let a=/* @__PURE__ */new Map,l=/* @__PURE__ */new Map;for(let e of i.keys())a.set(e,[]),l.set(e,[]);let d=[],c=[...i.values()].sort((e,t)=>e.index-t.index);for(let e of c)e.dependencyIDs.forEach((r,n)=>{let o=i.get(r);if(!o)return void t.push({code:"missing-dependency",message:`Task "${e.id}" depends on missing task "${r}".`,taskIDs:[e.id,r]});let s={id:qh(r,e.id),sourceID:r,targetID:e.id,sourceIndex:o.index,targetIndex:e.index,socketID:Hh(e.id,n),socketIndex:n};d.push(s),a.get(e.id)?.push(s),l.get(r)?.push(s),e.incomingEdgeIDs.push(s.id),e.socketIDs.push(s.socketID),o.outgoingEdgeIDs.push(s.id)});for(let e of a.values())e.sort((e,t)=>Wh(e.sourceID,t.sourceID)),e.forEach((e,t)=>{e.socketIndex=t,e.socketID=Hh(e.targetID,t)});for(let e of l.values())e.sort((e,t)=>Wh(e.targetID,t.targetID));for(let e of i.values()){let t=a.get(e.id)??[];e.incomingEdgeIDs=t.map(e=>e.id),e.socketIDs=t.map(e=>e.socketID),e.outgoingEdgeIDs=(l.get(e.id)??[]).map(e=>e.id)}let u=/* @__PURE__ */new Map,h=/* @__PURE__ */new Map;for(let e of i.keys())u.set(e,a.get(e)?.length??0),h.set(e,0);let p=[...i.keys()].filter(e=>0===u.get(e)).sort(Wh),m=0;for(;p.length;){let e=p.shift();m+=1;for(let t of l.get(e)??[]){let i=Math.max(h.get(t.targetID)??0,(h.get(e)??0)+1);h.set(t.targetID,i);let r=(u.get(t.targetID)??0)-1;if(u.set(t.targetID,r),0===r){let e=p.findIndex(e=>e>t.targetID);e<0?p.push(t.targetID):p.splice(e,0,t.targetID)}}}if(m!==i.size){let e=[...i.keys()].filter(e=>(u.get(e)??0)>0).sort(Wh);t.push({code:"cycle",message:`Dependency graph contains a cycle involving: ${e.join(", ")}.`,taskIDs:e})}let y=0,f=[...i.values()].sort((e,t)=>e.index-t.index);for(let e of f)e.level=h.get(e.id)??0,y=Math.max(y,e.level);return{nodes:f,edges:d,byID:i,incoming:a,outgoing:l,lanes:o,maxLevel:y,diagnostics:t,valid:0===t.length}}function Yh(e){return e.filter((t,i)=>{let r=e[i-1];return!r||r.x!==t.x||r.y!==t.y})}function _h(e,t,i={}){let r=Math.max(240,t.width),n=Math.max(220,t.height),o=t.paddingX??48,s=t.paddingTop??48,a=t.paddingBottom??44,l=Math.max(1,e.lanes.length),d=Math.max(70,(r-2*o)/l),c=Math.max(1,e.maxLevel+1),u=Math.max(76,(n-s-a)/c),h=Math.min(i.taskWidth??112,Math.max(58,.78*d)),p=Math.min(i.taskHeight??58,.64*u),m=i.socketRadius??5,y=Math.max(1,Math.round(i.gutterCount??3)),f=/* @__PURE__ */new Map;for(let t of e.nodes){let e=`${t.laneIndex}:${t.level}`,i=f.get(e)??[];i.push(t),f.set(e,i)}for(let e of f.values())e.sort((e,t)=>Wh(e.id,t.id));let g=.86*u,b=e=>e<=1?p:Math.max(22,Math.min(p,(g-4*(e-1))/e)),v=e.nodes.map(e=>{let t=f.get(`${e.laneIndex}:${e.level}`)??[e],i=Math.max(0,t.findIndex(t=>t.id===e.id))-(t.length-1)/2,r=b(t.length),n=i*(r+4);return{taskID:e.id,lane:e.lane,laneIndex:e.laneIndex,level:e.level,x:o+d*(e.laneIndex+.5),y:s+u*(e.level+.5)+n,width:h,height:r}}),x=new Map(v.map(e=>[e.taskID,e])),w=[],I=[];e.edges.forEach((t,i)=>{let r=x.get(t.sourceID),n=x.get(t.targetID);if(!r||!n)return;let o=e.incoming.get(t.targetID)??[],s=Math.min(.72*n.width,14*Math.max(1,o.length-1)),a=o.length<=1?n.x:n.x-s/2+s*t.socketIndex/(o.length-1),l=n.y-n.height/2-m-2,d={id:t.socketID,edgeID:t.id,taskID:n.taskID,index:t.socketIndex,x:a,y:l,radius:m};w.push(d);let c={x:r.x,y:r.y+r.height/2+3},u=Math.max(18,l-c.y),h=7*(i%y-(y-1)/2),p=Math.min(l-10,c.y+.48*u+h);I.push({edgeID:t.id,sourceID:t.sourceID,targetID:t.targetID,socketID:t.socketID,points:Yh([c,{x:c.x,y:p},{x:a,y:p},{x:a,y:l}])})});let k=new Map(w.map(e=>[e.id,e])),S=new Map(I.map(e=>[e.edgeID,e]));return{tasks:v,sockets:w,routes:I,taskByID:x,socketByID:k,routeByEdgeID:S}}function Xh(e,t,i="all"){let r=Array.from(new Set(t)).sort(Wh),n=/* @__PURE__ */new Set,o=()=>r.every(e=>n.has(e));return{taskID:e,mode:i,incomingEdgeIDs:r,deliver:e=>(r.includes(e)&&n.add(e),o()),reset:(e=[])=>{n.clear();for(let t of e)r.includes(t)&&n.add(t)},isSatisfied:o,getSnapshot:()=>({taskID:e,mode:i,incomingEdgeIDs:[...r],deliveredEdgeIDs:[...n].sort(Wh),satisfied:o()})}}function Gh(e){return e instanceof Date?e.getTime():Number(e)}function Vh(e,t){let i=Gh("object"!=typeof t||t instanceof Date?t:t.currentTime),r=e.map((e,t)=>({event:e,index:t,time:Gh(e.at)})).filter(e=>Number.isFinite(e.time)&&e.time<=i).sort((e,t)=>e.time-t.time||e.index-t.index),n=/* @__PURE__ */new Set,o=/* @__PURE__ */new Map,s=/* @__PURE__ */new Set,a=/* @__PURE__ */new Set;for(let{event:e}of r)"task-completed"===e.type?(n.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:i,appliedEvents:r.map(e=>e.event),completedTaskIDs:n,blockedByTaskID:o,deliveredEdgeIDs:s,armedTaskIDs:a}}function Uh(e,t,i={}){let r=new Set(i.completedTaskIDs??[]),n=[...Nh(Eh(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=>!(i.isComplete?i.isComplete(e):r.has(e.id)||"done"===e.status)).sort((e,t)=>e.index-t.index),o=Array.from(new Set(n.map(e=>e.lane)));return{blockerID:t,downstreamTaskCount:n.length,affectedLaneCount:o.length,downstreamTaskIDs:n.map(e=>e.id),affectedLanes:o}}import{forwardRef as Kh,useCallback as Qh,useEffect as Jh,useImperativeHandle as Zh,useMemo as ep,useRef as tp,useState as ip}from"react";var rp=[];function np(e,t=0){if(e instanceof Date)return e.getTime();let i=Number(e);return Number.isFinite(i)?i:t}function op(e){if(null==e.completionTime)return null;let t=np(e.completionTime,Number.NaN);return Number.isFinite(t)?t:null}function sp(e,t,i,r){let n=/* @__PURE__ */new Set;for(let o of e.nodes){let s=e.incoming.get(o.id)??[];(r.has(o.id)||!i.has(o.id)&&s.every(e=>t.has(e.id)))&&n.add(o.id)}return n}function ap(e,t,i,r){let n=e.nodes.map(op).filter(e=>null!=e),o=n.length?n.reduce((e,t)=>Math.min(e,t),1/0)-1:0,s="replay"!==t||r?i:o,a=/* @__PURE__ */new Set,l=/* @__PURE__ */new Map;for(let i of e.nodes){let e=op(i),r=null!=e&&e<=s,n="done"===i.status&&"replay"!==t;(r||n)&&a.add(i.id),i.blockerReason&&!a.has(i.id)&&l.set(i.id,i.blockerReason)}let d=/* @__PURE__ */new Set;if("replay"!==t||r)for(let t of e.edges)a.has(t.sourceID)&&d.add(t.id);return{currentTime:s,playing:!1,completed:a,delivered:d,inFlight:/* @__PURE__ */new Set,armed:sp(e,d,l,a),blockers:l,previewTaskID:null}}function lp(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 dp(e){let t=0;for(let i=1;i<e.length;i+=1)t+=Math.hypot(e[i].x-e[i-1].x,e[i].y-e[i-1].y);return t}function cp(e,t){if(e.length<2)return{point:e[0]??{x:0,y:0},tangent:{x:0,y:1}};let i=0;for(let r=1;r<e.length;r+=1){let n=e[r-1],o=e[r],s=o.x-n.x,a=o.y-n.y,l=Math.hypot(s,a);if(!(l<=0)){if(i+l>=t){let e=Math.max(0,Math.min(1,(t-i)/l));return{point:{x:n.x+s*e,y:n.y+a*e},tangent:{x:s/l,y:a/l}}}i+=l}}let r=e[e.length-2],n=e[e.length-1],o=n.x-r.x,s=n.y-r.y,a=Math.hypot(o,s)||1;return{point:n,tangent:{x:o/a,y:s/a}}}function up(e,t){let i=Number.POSITIVE_INFINITY,r=0,n=0;for(let o=1;o<t.length;o+=1){let s=t[o-1],a=t[o],l=a.x-s.x,d=a.y-s.y,c=l*l+d*d,u=Math.sqrt(c);if(u<=0)continue;let h=Math.max(0,Math.min(1,((e.x-s.x)*l+(e.y-s.y)*d)/c)),p=s.x+l*h,m=s.y+d*h,y=Math.hypot(e.x-p,e.y-m);y<i&&(i=y,r=n+h*u),n+=u}return r}function hp(e){let t=e.datum;return"dependency-ball"===t?.kind&&Array.isArray(t.route)?t:null}function pp(e){let t=hp(e.body);if(!t||t.route.length<2)return null;let i=dp(t.route),r=up(e.body,t.route),n=cp(t.route,Math.min(i,r+22)),o=78*n.tangent.x,s=78*n.tangent.y;return{x:2.5*(o-e.body.vx)+8*(n.point.x-e.body.x),y:2.5*(s-e.body.vy)+8*(n.point.y-e.body.y)}}function mp(e,t,i){let r=t.points[0]??{x:0,y:0},n=t.points[1]??r,o=n.x-r.x,s=n.y-r.y,a=Math.hypot(o,s)||1;return{id:`dependency-ball:${e.id}`,x:r.x,y:r.y,vx:o/a*42,vy:s/a*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,...i?{sourceDatum:i}:{}}}}function yp(e,t,i){return e.nodes.flatMap(r=>{let n=t.taskByID.get(r.id);if(!n)return[];let o=e.incoming.get(r.id)??[],s=o.filter(e=>i.delivered.has(e.id)).length,a=i.blockers.get(r.id),l=i.completed.has(r.id)?"completed":a?`blocked: ${a}`:i.armed.has(r.id)?"armed":"waiting";return[{id:r.id,label:`${r.label}, ${r.lane}, ${Math.round(100*r.progress)}%, ${l}`,description:`${s} of ${o.length} prerequisites delivered.`,datum:r.datum,x:n.x,y:n.y,width:n.width,height:n.height,shape:"rect",group:r.lane}]})}import{jsx as fp,jsxs as gp}from"react/jsx-runtime";function bp(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-text-secondary, #75818a)"}function vp({machine:e,layout:t,runtime:i,downstreamSet:r,selectedSet:n,width:o,height:s,seed:a,reduced:l,onSelectTask:d}){let c=t.tasks.length?t.tasks.reduce((e,t)=>Math.min(e,t.y-t.height/2),1/0):60,u=Math.max(20,c-12),h=Math.max(26,c-6);/* */
|
|
166
|
+
return gp("svg",{"aria-hidden":"true",width:o,height:s,viewBox:`0 0 ${o} ${s}`,style:{position:"absolute",inset:0,overflow:"visible",pointerEvents:"none"},children:[
|
|
167
|
+
/* @__PURE__ */fp("defs",{children:/* @__PURE__ */fp("filter",{id:`chain-shadow-${a}`,x:"-20%",y:"-20%",width:"140%",height:"150%",children:/* @__PURE__ */fp("feDropShadow",{dx:"0",dy:"2",stdDeviation:"2",floodOpacity:"0.2"})})}),e.lanes.map((e,i)=>{let r=t.tasks.filter(e=>e.laneIndex===i)[0]?.x??0;/* */
|
|
168
|
+
return gp("g",{children:[
|
|
169
|
+
/* @__PURE__ */fp("line",{x1:r,x2:r,y1:h,y2:s-24,stroke:"var(--semiotic-grid, #d7dde0)",strokeWidth:1,strokeDasharray:"3 7"}),
|
|
170
|
+
/* @__PURE__ */fp("text",{x:r,y:u,textAnchor:"middle",fontSize:12,fontWeight:700,fill:"var(--semiotic-text, #243039)",children:e})]},e)}),t.routes.map(e=>{let t=i.delivered.has(e.edgeID),n=i.inFlight.has(e.edgeID),o=r.has(e.targetID)||r.has(e.sourceID),s=e.points.map(e=>`${e.x},${e.y}`).join(" ");/* */
|
|
171
|
+
return fp("polyline",{points:s,fill:"none",stroke:o?"var(--semiotic-selection-color, #e08a1e)":t?"var(--semiotic-success, #2b8a66)":"var(--semiotic-grid, #aeb8bd)",strokeWidth:o?4:n?3:2,strokeOpacity:t||n||o?.95:.48,strokeLinecap:"round",strokeLinejoin:"round"},e.edgeID)}),t.sockets.map(e=>{let t=i.delivered.has(e.edgeID);/* */
|
|
172
|
+
return gp("g",{children:[
|
|
173
|
+
/* @__PURE__ */fp("circle",{cx:e.x,cy:e.y,r:e.radius+2,fill:"var(--semiotic-bg, #fff)",stroke:"var(--semiotic-text, #243039)",strokeWidth:1.5}),t&&/* @__PURE__ */fp("circle",{cx:e.x,cy:e.y,r:e.radius-.5,fill:"var(--semiotic-success, #2b8a66)"})]},e.id)}),e.nodes.map(e=>{let o=t.taskByID.get(e.id);if(!o)return null;let s=i.completed.has(e.id),c=i.blockers.has(e.id),u=i.previewTaskID===e.id,h=n.has(e.id)||u,p=r.has(e.id),m=bp(e,i),y=o.x-o.width/2,f=o.y-o.height/2,g=Math.max(2,o.height*e.progress);/* */
|
|
174
|
+
return gp("g",{children:[
|
|
175
|
+
/* @__PURE__ */gp("g",{style:{transform:`rotate(${s?76:0}deg)`,transformBox:"fill-box",transformOrigin:"50% 100%",transition:l?"none":"transform 520ms cubic-bezier(.2,.8,.25,1)",filter:"url(#chain-shadow-"+a+")"},children:[
|
|
176
|
+
/* @__PURE__ */fp("rect",{x:y,y:f,width:o.width,height:o.height,rx:e.milestone?12:4,fill:"var(--semiotic-bg, #fff)",stroke:h||p?"var(--semiotic-selection-color, #e08a1e)":m,strokeWidth:h?4:p?3:2}),
|
|
177
|
+
/* @__PURE__ */fp("rect",{x:y+3,y:f+o.height-g+1,width:o.width-6,height:Math.max(0,g-4),rx:2,fill:m,opacity:s?.86:.46})]}),c&&/* @__PURE__ */gp("g",{opacity:u?.28:1,children:[
|
|
178
|
+
/* @__PURE__ */fp("line",{x1:y-8,x2:y+14,y1:o.y+9,y2:o.y-9,stroke:"var(--semiotic-error, #c64035)",strokeWidth:7,strokeLinecap:"round"}),
|
|
179
|
+
/* @__PURE__ */fp("circle",{cx:y-8,cy:o.y+9,r:3,fill:"var(--semiotic-error, #c64035)"})]}),
|
|
180
|
+
/* @__PURE__ */gp("g",{onPointerDown:()=>d(e.id),style:{cursor:"pointer",pointerEvents:"auto"},children:[
|
|
181
|
+
/* @__PURE__ */fp("rect",{x:y,y:f,width:o.width,height:o.height,fill:"transparent"}),
|
|
182
|
+
/* @__PURE__ */fp("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}),
|
|
183
|
+
/* @__PURE__ */gp("text",{x:o.x,y:o.y+12,textAnchor:"middle",fontSize:9.5,fill:"var(--semiotic-text-secondary, #5f6b72)",children:[Math.round(100*e.progress),"% · ",s?"done":c?"blocked":i.armed.has(e.id)?"ready":"waiting"]})]})]},e.id)})]})}import{jsx as xp,jsxs as wp}from"react/jsx-runtime";var Ip={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};function kp({blockerSummary:e,machine:t,runtime:i}){/* */
|
|
184
|
+
return wp("table",{style:Ip,children:[
|
|
185
|
+
/* @__PURE__ */xp("caption",{children:e}),
|
|
186
|
+
/* @__PURE__ */xp("thead",{children:/* @__PURE__ */wp("tr",{children:[
|
|
187
|
+
/* @__PURE__ */xp("th",{children:"Task"}),
|
|
188
|
+
/* @__PURE__ */xp("th",{children:"Lane"}),
|
|
189
|
+
/* @__PURE__ */xp("th",{children:"Progress"}),
|
|
190
|
+
/* @__PURE__ */xp("th",{children:"State"}),
|
|
191
|
+
/* @__PURE__ */xp("th",{children:"Waiting on"}),
|
|
192
|
+
/* @__PURE__ */xp("th",{children:"Downstream reach"})]})}),
|
|
193
|
+
/* @__PURE__ */xp("tbody",{children:t.nodes.map(e=>{let r=Uh(t,e.id,{completedTaskIDs:i.completed}),n=i.completed.has(e.id)?"Completed":i.blockers.has(e.id)?"Blocked":i.armed.has(e.id)?"Armed":"Waiting",o=i.blockers.get(e.id)??(e.dependencyIDs.filter(e=>!i.completed.has(e)).join(", ")||"None");/* */
|
|
194
|
+
return wp("tr",{children:[
|
|
195
|
+
/* @__PURE__ */xp("th",{scope:"row",children:e.label}),
|
|
196
|
+
/* @__PURE__ */xp("td",{children:e.lane}),
|
|
197
|
+
/* @__PURE__ */wp("td",{children:[Math.round(100*e.progress),"%"]}),
|
|
198
|
+
/* @__PURE__ */xp("td",{children:n}),
|
|
199
|
+
/* @__PURE__ */xp("td",{children:o}),
|
|
200
|
+
/* @__PURE__ */wp("td",{children:[r.downstreamTaskCount," tasks /"," ",r.affectedLaneCount," lanes"]})]},e.id)})})]})}import{jsx as Sp,jsxs as Mp}from"react/jsx-runtime";var Ap=/* @__PURE__ */L(/* @__PURE__ */Kh(function(e,t){let{data:i,taskIDAccessor:r,labelAccessor:n,laneAccessor:o,dependencyAccessor:s,startAccessor:a,endAccessor:l,progressAccessor:d,statusAccessor:c,completionTimeAccessor:u,blockerAccessor:h,milestoneAccessor:p,mode:m="snapshot",insight:y="blocker-amplification",currentTime:f,controls:g=!1,selectedTaskIDs:b,onSelectionChange:v,onObservation:x,onSimulationStateChange:w,reducedMotion:I,seed:k=31,width:S=vs.width,height:M=vs.height,responsiveWidth:A,responsiveHeight:$,title:C="Dependency chain reaction",description:P,className:R,accessibleTable:D=!0,enableHover:B=!0}=e,T=Js(ep(()=>[S,M],[M,S]),A,$),[j,O]=T.size,E=tp(null),[N,F]=ip([]),W=b?Array.from(b):N,q=ep(()=>new Set(W),[W]),H=np(f,Number.POSITIVE_INFINITY),z="settle"===I,L=ep(()=>Lh({data:i,taskIDAccessor:r,labelAccessor:n,laneAccessor:o,dependencyAccessor:s,startAccessor:a,endAccessor:l,progressAccessor:d,statusAccessor:c,completionTimeAccessor:u,blockerAccessor:h,milestoneAccessor:p}),[i,r,n,o,s,a,l,d,c,u,h,p]),Y=ep(()=>_h(L,{width:j,height:O}),[L,j,O]),[_,X]=ip(()=>ap(L,m,H,z)),G=tp(_),V=Qh(e=>{G.current=e,X(e)},[]),U=Qh(e=>x?.(e),[x]);Jh(()=>{let e=ap(L,m,H,z);E.current?.clear(),G.current=e,X(e)},[Y,L,m,H,z]);let K=Qh(e=>{let t=q.has(e)?W.filter(t=>t!==e):[e];b||F(t),v?.(t)},[b,v,q,W]),Q=Qh(e=>{if(z)return;let t=lp(G.current),i=[];for(let r of L.outgoing.get(e)??[]){if(t.delivered.has(r.id)||t.inFlight.has(r.id))continue;let e=Y.routeByEdgeID.get(r.id);e&&(t.inFlight.add(r.id),i.push(mp(r,e,L.byID.get(r.sourceID)?.datum)))}i.length&&(V(t),E.current?.pushMany(i,{pacing:{ratePerSec:8}}))},[V,Y,L,z]),J=Qh((e,t)=>{let i=L.byID.get(e),r=G.current;if(!i||r.completed.has(e))return;let n=lp(r);n.completed.add(e),n.blockers.delete(e),n.armed.add(e),null!=t&&(n.currentTime=t),V(n),U({type:"task-completed",taskID:e,datum:i.datum}),Q(e)},[V,U,L,Q]),Z=Qh(e=>{let t=lp(G.current),i=[],r=[];for(let r of e){if(t.delivered.has(r))continue;let e=L.edges.find(e=>e.id===r);e&&(t.delivered.add(r),t.inFlight.delete(r),i.push(e))}for(let e of i){let i=L.byID.get(e.targetID);!i||t.blockers.has(i.id)||t.armed.has(i.id)||(L.incoming.get(i.id)??[]).every(e=>t.delivered.has(e.id))&&(t.armed.add(i.id),r.push(i.id))}if(i.length){V(t);for(let e of i)U({type:"dependency-delivered",sourceID:e.sourceID,targetID:e.targetID});for(let e of r)U({type:"task-armed",taskID:e})}},[V,U,L]),ee=Qh((e,t)=>{let i=[],r=[];for(let e of t.readBodies()){let t=hp(e);if(!t||G.current.delivered.has(t.edgeID))continue;let n=t.route[t.route.length-1];n&&Math.hypot(e.x-n.x,e.y-n.y)<=9&&(i.push(t.edgeID),r.push(e.id))}r.length&&t.remove(r),i.length&&Z(i)},[Z]),te=Qh(()=>{let e=lp(G.current);for(let t of L.edges)e.completed.has(t.sourceID)&&e.delivered.add(t.id);e.inFlight.clear(),e.armed=sp(L,e.delivered,e.blockers,e.completed),e.playing=!1,E.current?.settle(),V(e),U({type:"machine-settled"})},[V,U,L]),ie=Qh(()=>{let e=lp(G.current);e.playing=!1,V(e)},[V]),re=Qh(()=>{let e=G.current,t=L.nodes.map(e=>({node:e,time:op(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 J(t.node.id,t.time);ie();let i=[...e.blockers.keys()].map(t=>Uh(L,t,{completedTaskIDs:e.completed})).sort((e,t)=>t.affectedLaneCount-e.affectedLaneCount||t.downstreamTaskCount-e.downstreamTaskCount);i[0]&&U({type:"machine-stalled",blockerID:i[0].blockerID,downstreamTaskCount:i[0].downstreamTaskCount,affectedLaneCount:i[0].affectedLaneCount})},[U,L,ie,J]),ne=Qh(()=>{if(z)return void te();let e=lp(G.current);e.playing=!0,V(e)},[V,z,te]);Jh(()=>{if(!_.playing||"replay"!==m||z)return;let e=window.setInterval(re,760);return()=>window.clearInterval(e)},[m,z,_.playing,re]);let oe=Qh(()=>{E.current?.clear(),V(ap(L,m,H,z))},[V,L,m,H,z]),se=Qh(e=>{if(!L.byID.has(e))return;let t=lp(G.current);t.previewTaskID=e,V(t);let i=Uh(L,e,{completedTaskIDs:t.completed});U({type:"blocker-previewed",blockerID:e,downstreamTaskIDs:i.downstreamTaskIDs})},[V,U,L]),le=Qh(()=>{let e=lp(G.current);e.previewTaskID=null,V(e)},[V]),de=Qh((e,t)=>{if(!L.byID.has(e))return;let i=lp(G.current);i.blockers.set(e,t),i.armed.delete(e),V(i)},[V,L]),ce=Qh(e=>{if(!L.byID.has(e))return;let t=lp(G.current);t.blockers.delete(e),(L.incoming.get(e)??[]).every(e=>t.delivered.has(e.id))&&t.armed.add(e),V(t)},[V,L]),ue=Qh(e=>Uh(L,e,{completedTaskIDs:G.current.completed}),[L]),he=Qh(()=>{let e=G.current;return{currentTime:e.currentTime,playing:e.playing,previewTaskID:e.previewTaskID,selectedTaskIDs:[...W],tasks:L.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:L.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"}))}},[L,W]);Zh(t,()=>({play:ne,pause:ie,step:re,reset:oe,settle:te,previewResolve:se,clearPreview:le,completeTask:J,blockTask:de,unblockTask:ce,getAmplification:ue,getMachineState:he}),[de,le,ue,he,ie,J,ne,se,oe,te,re,ce]);let pe=_.previewTaskID??W[0]??null,me=pe?Uh(L,pe,{completedTaskIDs:_.completed}):null,ye=ep(()=>new Set(me?.downstreamTaskIDs??[]),[me?.downstreamTaskIDs]),fe=ep(()=>yp(L,Y,_),[Y,L,_]),ge=ep(()=>/* @__PURE__ */Sp(vp,{machine:L,layout:Y,runtime:_,downstreamSet:ye,selectedSet:q,width:j,height:O,seed:k,reduced:z,onSelectTask:K}),[ye,O,Y,L,z,_,k,K,q,j]),be=ep(()=>{let e=[..._.blockers.keys()].map(e=>Uh(L,e,{completedTaskIDs:_.completed})).sort((e,t)=>t.affectedLaneCount-e.affectedLaneCount||t.downstreamTaskCount-e.downstreamTaskCount);return e.length?e.map(e=>`${L.byID.get(e.blockerID)?.label??e.blockerID} affects ${e.downstreamTaskCount} unfinished tasks across ${e.affectedLaneCount} lanes.`).join(" "):"No explicit blockers are active."},[L,_.blockers,_.completed]),ve=ep(()=>[{id:"chain-left",shape:{type:"segment",x1:2,y1:0,x2:2,y2:O,thickness:4}},{id:"chain-right",shape:{type:"segment",x1:j-2,y1:0,x2:j-2,y2:O,thickness:4}},{id:"chain-top",shape:{type:"segment",x1:0,y1:2,x2:j,y2:2,thickness:4}},{id:"chain-bottom",shape:{type:"segment",x1:0,y1:O-2,x2:j,y2:O-2,thickness:4}}],[O,j]),xe=!0===g?["play","pause","step","reset","settle"]:g||[],we=ia(e.tooltip,void 0,{unwrapSourceDatum:!0}),Ie=Qh(e=>{let t=e.data,i=String(t.sourceID??""),r=String(t.targetID??""),n=L.byID.get(i),o=L.byID.get(r);/* */
|
|
201
|
+
return Mp(Pe,{children:[
|
|
202
|
+
/* @__PURE__ */Mp("div",{style:{fontWeight:700},children:[n?.label??i," → ",o?.label??r]}),
|
|
203
|
+
/* @__PURE__ */Sp("div",{children:"Dependency in flight"}),o?.lane?/* @__PURE__ */Mp("div",{children:["Target lane: ",o.lane]}):null]})},[L]);return L.valid?/* @__PURE__ */Mp("div",{className:R,style:{width:A?"100%":j,maxWidth:"100%",position:"relative"},children:[xe.length>0&&/* @__PURE__ */Sp("div",{"aria-label":"Chain reaction replay controls",style:{display:"flex",flexWrap:"wrap",gap:6,marginBottom:8},children:xe.map(e=>/* @__PURE__ */Sp("button",{type:"button",onClick:"play"===e?ne:"pause"===e?ie:"step"===e?re:"reset"===e?oe:te,"aria-pressed":"play"===e?_.playing:void 0,children:e[0].toUpperCase()+e.slice(1)},e))}),
|
|
204
|
+
/* @__PURE__ */Sp("div",{ref:T.containerRef,"data-semiotic-physics-responsive-host":"true",style:{position:"relative",width:A?"100%":j,height:$?"100%":O},children:/* @__PURE__ */Sp(yo,{ref:E,size:[j,O],responsiveWidth:!1,responsiveHeight:!1,maxDevicePixelRatio:e.maxDevicePixelRatio,title:C,description:P??"Tasks are arranged by workstream and dependency depth. Balls represent satisfied prerequisites; task completion remains an explicit data event.",summary:`${be}${me&&"blocker-amplification"===y?` Selected task reaches ${me.downstreamTaskCount} unfinished tasks across ${me.affectedLaneCount} lanes.`:""}`,accessibleTable:!1,enableHover:we.enableHover??B,initialSpawns:rp,bodyForces:pp,bodyStyle:{fill:"var(--semiotic-primary, #f0a329)",stroke:"var(--semiotic-text, #243039)",strokeWidth:1.25},bodySemanticItems:!1,semanticItems:fe,onSemanticItemActivate:e=>e.id&&K(e.id),foregroundGraphics:()=>ge,paused:z,continuous:_.inFlight.size>0,onTick:ee,tooltipContent:!1===e.tooltip?void 0:we.tooltipContent??Ie,config:{bodyLimit:Math.max(16,L.edges.length+4),colliders:ve,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",onSimulationStateChange:w}}},`${j}x${O}`)}),D&&/* @__PURE__ */Sp(ae,{accessibleTable:D,children:/* @__PURE__ */Sp(kp,{blockerSummary:be,machine:L,runtime:_})})]}):/* @__PURE__ */Mp("div",{className:R,role:"alert",style:{width:j,maxWidth:"100%"},children:[
|
|
205
|
+
/* @__PURE__ */Sp("strong",{children:"ChainReactionChart could not compile this dependency graph."}),
|
|
206
|
+
/* @__PURE__ */Sp("ul",{children:L.diagnostics.map((e,t)=>/* @__PURE__ */Sp("li",{children:e.message},`${e.code}-${t}`))})]})}),"ChainReactionChart");export{Ee as a,Ne as b,Fe as c,Le as d,kt as e,Mt as f,Ct as g,Pt as h,zt as i,Lt as j,Xt as k,ci as l,ui as m,qi as n,Yi as o,Xi as p,Gi as q,mo as r,yo as s,go as t,Io as u,So as v,$o as w,Ro as x,Fo as y,Ho as z,zo as A,Lo as B,Go as C,Ko as D,Qo as E,Jo as F,Zo as G,es as H,ts as I,is as J,rs as K,ns as L,os as M,ss as N,ds as O,ma as P,wa as Q,$a as R,Ca as S,Ga as T,el as U,tl as V,il as W,rl as X,nl as Y,Tl as Z,dl as _,cl as $,hl as aa,pl as ba,ml as ca,gd as da,bd as ea,Wd as fa,qd as ga,Kd as ha,dc as ia,mc as ja,Ic as ka,Ec as la,Fc as ma,Wc as na,qc as oa,Hc as pa,zc as qa,Lc as ra,Yc as sa,_c as ta,tu as ua,au as va,cu as wa,hu as xa,pu as ya,mu as za,yu as Aa,bu as Ba,ku as Ca,Su as Da,Au as Ea,$u as Fa,Cu as Ga,Pu as Ha,Ru as Ia,Tu as Ja,Oh as Ka,Lh as La,_h as Ma,Xh as Na,Vh as Oa,Uh as Pa,Ap as Qa};
|