semiotic 3.8.5 → 3.8.6
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/CLAUDE.md +5 -4
- package/README.md +42 -42
- package/ai/behaviorContracts.cjs +2 -2
- package/ai/componentMetadata.cjs +1 -1
- package/ai/dist/mcp-server.js +2 -0
- package/ai/examples.md +44 -2
- package/ai/schema.json +385 -14
- package/ai/surface-manifest.json +6 -4
- package/ai/system-prompt.md +1 -1
- package/dist/{chunk-chartContainerDataAudit-74TLKIP6.module.min.js → chunk-chartContainerDataAudit-FEOD5GTQ.module.min.js} +1 -1
- package/dist/chunk-chunk-2CHN2TA3.module.min.js +1 -0
- package/dist/chunk-chunk-2JGJ5GUG.module.min.js +1 -0
- package/dist/chunk-chunk-3NGIKFD6.module.min.js +1 -0
- package/dist/chunk-chunk-3SHB24AG.module.min.js +1 -0
- package/dist/chunk-chunk-4MMOOYTX.module.min.js +2 -0
- package/dist/{chunk-chunk-KT2VAZMZ.module.min.js → chunk-chunk-75OTQSXS.module.min.js} +1 -1
- package/dist/chunk-chunk-A5GRQUOF.module.min.js +1 -0
- package/dist/chunk-chunk-AAF5LZAU.module.min.js +2 -0
- package/dist/{chunk-chunk-4AANPFOX.module.min.js → chunk-chunk-ARZGA4LJ.module.min.js} +1 -1
- package/dist/chunk-chunk-CAFLML4L.module.min.js +2 -0
- package/dist/chunk-chunk-FHBN7OEB.module.min.js +2 -0
- package/dist/{chunk-chunk-TMWIZL3K.module.min.js → chunk-chunk-GFTVACTO.module.min.js} +1 -1
- package/dist/chunk-chunk-IP2UE74X.module.min.js +1 -0
- package/dist/chunk-chunk-ITDWLZXV.module.min.js +2 -0
- package/dist/chunk-chunk-LPSPATPC.module.min.js +1 -0
- package/dist/chunk-chunk-OM6NWS4H.module.min.js +2 -0
- package/dist/chunk-chunk-PX5YQGDP.module.min.js +2 -0
- package/dist/chunk-chunk-Q2BS46W2.module.min.js +2 -0
- package/dist/{chunk-chunk-LJLS6DY7.module.min.js → chunk-chunk-RA7JCG7D.module.min.js} +1 -1
- package/dist/chunk-chunk-RNUHEXZA.module.min.js +2 -0
- package/dist/chunk-chunk-ROZWKEUG.module.min.js +1 -0
- package/dist/chunk-chunk-SMVD3EQJ.module.min.js +2 -0
- package/dist/chunk-chunk-T2FKJD4O.module.min.js +2 -0
- package/dist/{chunk-chunk-K3DMEW22.module.min.js → chunk-chunk-UDREYOLV.module.min.js} +1 -1
- package/dist/chunk-chunk-VOWE3SAP.module.min.js +2 -0
- package/dist/chunk-chunk-VQPNBUSW.module.min.js +2 -0
- package/dist/{chunk-chunk-N5DDKCCF.module.min.js → chunk-chunk-WAWCIHFJ.module.min.js} +1 -1
- package/dist/{chunk-chunk-XXWSHGPL.module.min.js → chunk-chunk-WYARAXHR.module.min.js} +1 -1
- package/dist/{chunk-chunk-I36PJ4OC.module.min.js → chunk-chunk-XP3OHHFX.module.min.js} +1 -1
- package/dist/chunk-chunk-XV3KGYTR.module.min.js +2 -0
- package/dist/chunk-chunk-YC2IVEPX.module.min.js +1 -0
- package/dist/components/ai/chartCapabilities.d.ts +2 -1
- package/dist/components/charts/custom/XYCustomChart.d.ts +3 -0
- package/dist/components/charts/geo/DistanceCartogram.d.ts +1 -1
- package/dist/components/charts/index.d.ts +3 -0
- package/dist/components/charts/ordinal/BarChart.d.ts +7 -14
- package/dist/components/charts/ordinal/GaugeChart.d.ts +3 -0
- package/dist/components/charts/ordinal/GroupedBarChart.d.ts +3 -0
- package/dist/components/charts/ordinal/StackedBarChart.d.ts +3 -0
- package/dist/components/charts/ordinal/SwimlaneChart.d.ts +4 -14
- package/dist/components/charts/shared/chartSpecCore.d.ts +2 -4
- package/dist/components/charts/shared/gaugeGradient.d.ts +4 -8
- package/dist/components/charts/shared/gradient.d.ts +35 -0
- package/dist/components/charts/shared/hatchFill.d.ts +3 -10
- package/dist/components/charts/shared/hooks.d.ts +2 -50
- package/dist/components/charts/shared/knownChartComponents.d.ts +1 -1
- package/dist/components/charts/shared/streamPropsHelpers.d.ts +1 -2
- package/dist/components/charts/shared/useChartLegend.d.ts +58 -0
- package/dist/components/charts/shared/useChartSetup.d.ts +5 -0
- package/dist/components/charts/shared/useCustomChartSetup.d.ts +6 -1
- package/dist/components/charts/shared/useNetworkChartSetup.d.ts +1 -0
- package/dist/components/charts/shared/useStreamingLegend.d.ts +1 -1
- package/dist/components/charts/xy/AreaChart.d.ts +25 -42
- package/dist/components/charts/xy/BumpChart.capability.d.ts +11 -0
- package/dist/components/charts/xy/BumpChart.d.ts +161 -0
- package/dist/components/charts/xy/DifferenceChart.d.ts +3 -10
- package/dist/components/charts/xy/Heatmap.d.ts +3 -0
- package/dist/components/charts/xy/LineChart.d.ts +6 -8
- package/dist/components/geometry/bumpRibbonGeometry.d.ts +36 -0
- package/dist/components/legendLayout.d.ts +19 -1
- package/dist/components/semiotic-ai.d.ts +2 -1
- package/dist/components/semiotic-geo.d.ts +1 -0
- package/dist/components/semiotic-network.d.ts +1 -0
- package/dist/components/semiotic-ordinal.d.ts +2 -0
- package/dist/components/semiotic-physics.d.ts +1 -0
- package/dist/components/semiotic-realtime-core.d.ts +1 -0
- package/dist/components/semiotic-server-edge.d.ts +1 -1
- package/dist/components/semiotic-server.d.ts +1 -1
- package/dist/components/semiotic-xy.d.ts +4 -0
- package/dist/components/semiotic.d.ts +4 -4
- package/dist/components/server/serverChartConfigs.d.ts +1 -0
- package/dist/components/server/serverChartConfigsXY.d.ts +1 -0
- package/dist/components/server/staticLegend.d.ts +4 -2
- package/dist/components/server/staticSVGChrome.d.ts +4 -4
- package/dist/components/stream/GeoSVGOverlay.d.ts +4 -10
- package/dist/components/stream/NetworkSVGOverlay.d.ts +2 -6
- package/dist/components/stream/OrdinalSVGOverlay.d.ts +2 -6
- package/dist/components/stream/SVGOverlay.d.ts +2 -6
- package/dist/components/stream/StalenessBadge.d.ts +2 -6
- package/dist/components/stream/geoTypes.d.ts +3 -6
- package/dist/components/stream/legendRenderer.d.ts +2 -6
- package/dist/components/stream/ordinalTypes.d.ts +7 -31
- package/dist/components/stream/physics/PhysicsKernel.d.ts +1 -0
- package/dist/components/stream/physics/PhysicsSVGOverlay.d.ts +2 -6
- package/dist/components/stream/physics/StreamPhysicsTypes.d.ts +2 -6
- package/dist/components/stream/pipelineConfig.d.ts +7 -15
- package/dist/components/stream/renderers/canvasRenderHelpers.d.ts +9 -69
- package/dist/components/stream/renderers/cornerRadii.d.ts +2 -9
- package/dist/components/stream/renderers/thresholdLineSegments.d.ts +12 -0
- package/dist/components/stream/sceneToSVGShared.d.ts +3 -5
- package/dist/components/stream/types.d.ts +32 -56
- package/dist/components/stream/xySceneBuilders/areaGradient.d.ts +4 -20
- package/dist/components/stream/xySceneBuilders/types.d.ts +6 -6
- package/dist/components/types/legendTypes.d.ts +15 -6
- package/dist/geo.min.js +1 -1
- package/dist/geo.module.min.js +1 -1
- package/dist/network.min.js +1 -1
- package/dist/network.module.min.js +1 -1
- package/dist/ordinal.min.js +1 -1
- package/dist/ordinal.module.min.js +1 -1
- package/dist/physics.min.js +1 -1
- package/dist/physics.module.min.js +1 -1
- package/dist/physicsWorker.js +1 -1
- package/dist/realtime.min.js +1 -1
- package/dist/realtime.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 -1
- package/dist/semiotic-ai.min.js +1 -1
- package/dist/semiotic-ai.module.min.js +1 -1
- package/dist/semiotic-experimental.min.js +1 -1
- package/dist/semiotic-experimental.module.min.js +1 -1
- package/dist/semiotic-geo.d.ts +1 -0
- package/dist/semiotic-network.d.ts +1 -0
- package/dist/semiotic-ordinal.d.ts +2 -0
- package/dist/semiotic-physics.d.ts +1 -0
- package/dist/semiotic-realtime-core.d.ts +1 -0
- package/dist/semiotic-realtime-core.min.js +1 -1
- package/dist/semiotic-realtime-core.module.min.js +1 -1
- package/dist/semiotic-recipes-core.module.min.js +1 -1
- package/dist/semiotic-recipes.module.min.js +1 -1
- package/dist/semiotic-server-edge.d.ts +1 -1
- package/dist/semiotic-server-edge.min.js +1 -1
- package/dist/semiotic-server-edge.module.min.js +1 -1
- package/dist/semiotic-server-node.min.js +1 -1
- package/dist/semiotic-server-node.module.min.js +1 -1
- package/dist/semiotic-server.d.ts +1 -1
- package/dist/semiotic-utils-core.min.js +1 -1
- package/dist/semiotic-utils-core.module.min.js +1 -1
- package/dist/semiotic-utils.min.js +1 -1
- package/dist/semiotic-utils.module.min.js +1 -1
- package/dist/semiotic-xy.d.ts +4 -0
- package/dist/semiotic.d.ts +4 -4
- package/dist/semiotic.min.js +1 -1
- package/dist/semiotic.module.min.js +1 -1
- package/dist/server.min.js +1 -1
- package/dist/server.module.min.js +1 -1
- package/dist/xy.min.js +1 -1
- package/dist/xy.module.min.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-chunk-5I3UZV4Q.module.min.js +0 -2
- package/dist/chunk-chunk-74CCPVXB.module.min.js +0 -1
- package/dist/chunk-chunk-ANYDWOZF.module.min.js +0 -1
- package/dist/chunk-chunk-AVBI6GDT.module.min.js +0 -1
- package/dist/chunk-chunk-BANTPINB.module.min.js +0 -2
- package/dist/chunk-chunk-C57LR3YG.module.min.js +0 -1
- package/dist/chunk-chunk-CKMD5NV3.module.min.js +0 -2
- package/dist/chunk-chunk-CWQ5YIHX.module.min.js +0 -2
- package/dist/chunk-chunk-E6TXX6MI.module.min.js +0 -1
- package/dist/chunk-chunk-L6EA5V3G.module.min.js +0 -2
- package/dist/chunk-chunk-LJPCLYSC.module.min.js +0 -2
- package/dist/chunk-chunk-LRIFN2HK.module.min.js +0 -1
- package/dist/chunk-chunk-NEVE562N.module.min.js +0 -1
- package/dist/chunk-chunk-NLO44TOS.module.min.js +0 -2
- package/dist/chunk-chunk-PZJ2SBLL.module.min.js +0 -2
- package/dist/chunk-chunk-QUJ6TTLY.module.min.js +0 -1
- package/dist/chunk-chunk-RBIDBUT4.module.min.js +0 -2
- package/dist/chunk-chunk-RFLAG356.module.min.js +0 -1
- package/dist/chunk-chunk-RPU4IZAV.module.min.js +0 -2
- package/dist/chunk-chunk-SKMBCFIL.module.min.js +0 -2
- package/dist/chunk-chunk-TAE7W424.module.min.js +0 -2
- package/dist/chunk-chunk-TUBMTZMU.module.min.js +0 -2
- package/dist/chunk-chunk-UFFEXJQY.module.min.js +0 -1
- package/dist/chunk-chunk-XSCHTS4D.module.min.js +0 -2
- package/dist/chunk-statisticalOverlays-QGDLRUHX.module.min.js +0 -1
- package/dist/chunk-statisticalOverlays-T77OKLDY.module.min.js +0 -1
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use client";
|
|
2
|
-
import{mulberry32 as t}from"./chunk-chunk-SIRIJ3DY.module.min.js";import{makeRuleValueResolver as e,resolveStyleRules as i}from"./chunk-chunk-EMO5NUGE.module.min.js";import{commonJsWorkerModuleUrl as n}from"./chunk-chunk-SV4XAZ3Q.module.min.js";import{buildResolveColor as o,resolveCustomLayoutPalette as r}from"./chunk-chunk-LJLS6DY7.module.min.js";import{ANNOTATION_DISCLOSURE_REVEAL_CSS as s,AriaLiveTooltip as a,CanvasFrameBackground as c,FlippingTooltip as d,FocusRing as l,SceneRevisionDiagnosticsObserver as u,ScreenReaderSummary as h,SkipToTableLink as p,UpdateResultTracker as m,annotationLayout as f,coerceCanvasFill as y,createDefaultAnnotationRules as g,defaultTooltipStyle as b,filterSparseArray as x,getDevicePixelRatio as v,isInteractiveKeyboardTarget as w,isServerEnvironment as I,normalizeTooltip as M,prepareCanvas as k,renderAnnotationPass as S,renderLegendFromConfig as A,resolveCSSColor as R,schemeCategory10 as P,useAnnotationActivationOptions as C,useChartMode as $,useDataSummary as j,useFrame as B,useFrameCanvasHost as O,useResponsiveSize as N,useSceneRevisionDiagnostics as T,xySceneNodeToSVG as E}from"./chunk-chunk-CWQ5YIHX.module.min.js";import{LIGHT_THEME as q,resolveThemeSemanticColors as F,useThemeSelector as W}from"./chunk-chunk-WCX6U47H.module.min.js";import{SafeRender as D,renderEmptyState as z,renderLoadingState as L,useHydration as Y,useWasHydratingFromSSR as _}from"./chunk-chunk-ACLDBMRH.module.min.js";import{useReducedMotion as H}from"./chunk-chunk-YHNZCPOZ.module.min.js";import*as X from"react";import{scaleLinear as G}from"d3-scale";import{Fragment as V,jsx as U,jsxs as K}from"react/jsx-runtime";function Q(t){return"circle"===t.shape.type?t.shape.radius:Math.max(t.shape.width,t.shape.height)/2}function Z(t){return t.map(t=>({pointId:t.id,x:t.x,y:t.y,r:Math.max(1,Q(t))}))}function J(t){const{width:e,height:i,pointNodes:n=[],data:o}=t;return{scales:{x:G().domain([0,Math.max(1,e)]).range([0,Math.max(1,e)]),y:G().domain([0,Math.max(1,i)]).range([0,Math.max(1,i)])},width:e,height:i,frameType:"network",pointNodes:n,data:o,xAccessor:"x",yAccessor:"y"}}function tt(t){return t?.length?t.map(t=>null!=t.pointId||null==t.bodyId?t:{...t,pointId:t.bodyId+""}):t}function et(t){const{width:e,height:i,totalWidth:n,totalHeight:o,margin:r,title:a,legend:c,legendHoverBehavior:d,legendClickBehavior:l,legendHighlightedCategory:u,legendIsolatedCategories:h,legendPosition:p="right",legendLayout:m,pointNodes:y=[],annotations:b,onAnnotationActivate:x,onObservation:v,chartId:w,chartType:I,autoPlaceAnnotations:M,svgAnnotationRules:k,children:R}=t,P=C({onAnnotationActivate:x,onObservation:v,chartId:w,chartType:I}),$=X.useMemo(()=>tt(b),[b]),j=X.useMemo(()=>J({width:e,height:i,pointNodes:y}),[i,y,e]),B=X.useMemo(()=>$&&M?f({annotations:$,context:j,..."object"==typeof M?M:{}}):$,[j,M,$]),O=X.useMemo(()=>g("network",P),[P]),N=B?S(B,O,k,j):null,T=!0===B?.some(t=>"widget"===t.type&&!0===t._annotationDeferred);return K(V,{children:[T?U("style",{children:s},"physics-annotation-disclosure-style"):null,K("svg",{className:"stream-physics-frame__overlay","data-testid":"stream-physics-overlay",role:"presentation",width:n,height:o,style:{position:"absolute",top:0,left:0,pointerEvents:"none",overflow:"visible"},children:[K("g",{transform:`translate(${r.left},${r.top})`,children:[N,R]}),a&&"string"==typeof a?U("text",{x:n/2,y:16,textAnchor:"middle",fontWeight:600,fill:"var(--semiotic-text, #333)",className:"semiotic-chart-title",style:{fontSize:"var(--semiotic-title-font-size, 14px)"},children:a}):a?U("foreignObject",{x:0,y:0,width:n,height:Math.max(r.top,28),children:a}):null,c?A({legend:c,totalWidth:n,totalHeight:o,margin:r,legendPosition:p,legendLayout:m,title:a,legendHoverBehavior:d,legendClickBehavior:l,legendHighlightedCategory:u,legendIsolatedCategories:h}):null]})]})}var it={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},nt=1e-9,ot=.005;function rt(t){return"circle"===t.type?{type:"circle",radius:t.radius}:{type:"aabb",width:t.width,height:t.height}}function st(t){return"aabb"===t.type?{type:"aabb",x:t.x,y:t.y,width:t.width,height:t.height}:{type:"segment",x1:t.x1,y1:t.y1,x2:t.x2,y2:t.y2,thickness:t.thickness}}function at(t,e,i){return Math.max(e,Math.min(i,t))}function ct(t){return 0>t?-1:1}function dt(t){if("circle"===t.shape.type){const e=t.shape.radius;return{minX:t.x-e,minY:t.y-e,maxX:t.x+e,maxY:t.y+e}}const e=t.shape.width/2,i=t.shape.height/2;return{minX:t.x-e,minY:t.y-i,maxX:t.x+e,maxY:t.y+i}}function lt(t){const e=t.shape;if("aabb"===e.type){const t=e.width/2,i=e.height/2;return{minX:e.x-t,minY:e.y-i,maxX:e.x+t,maxY:e.y+i}}const i=(e.thickness??0)/2;return{minX:Math.min(e.x1,e.x2)-i,minY:Math.min(e.y1,e.y2)-i,maxX:Math.max(e.x1,e.x2)+i,maxY:Math.max(e.y1,e.y2)+i}}function ut(t,e){return!(t.minX>e.maxX||e.minX>t.maxX||t.minY>e.maxY||e.minY>t.maxY)}function ht(t,e,i,n,o,r,s,a){const c=o-t,d=(i+s)/2-Math.abs(c);if(0>=d)return null;const l=r-e,u=(n+a)/2-Math.abs(l);return u>0?u>d?{nx:ct(c),ny:0,penetration:d}:{nx:0,ny:ct(l),penetration:u}:null}function pt(t,e,i,n,o,r,s){const a=r/2,c=s/2;let d=t-at(t,n-a,n+a),l=e-at(e,o-c,o+c);const u=d*d+l*l;if(u>i*i)return null;if(nt>=u){const r=Math.abs(t-(n-a)),s=Math.abs(t-(n+a)),u=Math.abs(e-(o-c)),h=Math.abs(e-(o+c)),p=Math.min(r,s,u,h);return p===r?(d=-1,l=0,{nx:d,ny:l,penetration:i+r}):p===s?(d=1,l=0,{nx:d,ny:l,penetration:i+s}):p===u?(d=0,l=-1,{nx:d,ny:l,penetration:i+u}):(d=0,l=1,{nx:d,ny:l,penetration:i+h})}const h=Math.sqrt(u);return{nx:d/h,ny:l/h,penetration:i-h}}function mt(t,e){if("circle"===t.shape.type&&"circle"===e.shape.type)return function(t,e,i,n,o,r){const s=n-t,a=o-e,c=i+r,d=s*s+a*a;if(d>=c*c)return null;if(nt>=d)return{nx:1,ny:0,penetration:c};const l=Math.sqrt(d);return{nx:s/l,ny:a/l,penetration:c-l}}(t.x,t.y,t.shape.radius,e.x,e.y,e.shape.radius);if("aabb"===t.shape.type&&"aabb"===e.shape.type)return ht(t.x,t.y,t.shape.width,t.shape.height,e.x,e.y,e.shape.width,e.shape.height);if("circle"===t.shape.type&&"aabb"===e.shape.type){const i=pt(t.x,t.y,t.shape.radius,e.x,e.y,e.shape.width,e.shape.height);return i?{nx:-i.nx,ny:-i.ny,penetration:i.penetration}:null}return"aabb"===t.shape.type&&"circle"===e.shape.type?pt(e.x,e.y,e.shape.radius,t.x,t.y,t.shape.width,t.shape.height):null}function ft(t,e){const i=e.shape;return"aabb"===i.type?"circle"===t.shape.type?pt(t.x,t.y,t.shape.radius,i.x,i.y,i.width,i.height):ht(i.x,i.y,i.width,i.height,t.x,t.y,t.shape.width,t.shape.height):function(t,e,i,n,o,r,s,a=0){const c=r-n,d=s-o,l=c*c+d*d,u=l>nt?at(((t-n)*c+(e-o)*d)/l,0,1):0,h=i+a/2,p=t-(n+c*u),m=e-(o+d*u),f=p*p+m*m;if(f>=h*h)return null;if(nt>=f){const t=Math.sqrt(l);return t>nt?{nx:-d/t,ny:c/t,penetration:h}:{nx:1,ny:0,penetration:h}}const y=Math.sqrt(f);return{nx:p/y,ny:m/y,penetration:h-y}}(t.x,t.y,"circle"===t.shape.type?t.shape.radius:Math.sqrt(t.shape.width*t.shape.width+t.shape.height*t.shape.height)/2,i.x1,i.y1,i.x2,i.y2,i.thickness??0)}function yt(t,e){return`${t}\0${e}`}function gt(t){const e=t.indexOf("\0");return{sensorId:t.slice(0,e),bodyId:t.slice(e+1)}}function bt(t){return{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,bodyCollisions:t.bodyCollisions,shape:rt(t.shape),sleeping:t.sleeping,datum:t.datum,index:t.index,sleepTime:t.sleepTime,restitution:t.restitution,friction:t.friction}}function xt(t){return t&&"function"!=typeof t?{property:t.property,equals:t.equals,notEquals:t.notEquals,oneOf:t.oneOf?.slice(),notOneOf:t.notOneOf?.slice()}:t}function vt(t){return{id:t.id,shape:st(t.shape),sensor:t.sensor,restitution:t.restitution,friction:t.friction,bodyFilter:xt(t.bodyFilter),index:t.index}}function wt(t,e){return!!e?.some(e=>Object.is(t,e))}function It(t,e){const i=t.bodyFilter;if(!i)return!0;if("function"==typeof i)return i(e);const n=function(t,e){if(!e)return;let i=t;for(const t of e.split(".")){if(null==i||"object"!=typeof i)return;i=i[t]}return i}(e,i.property);return!("equals"in i&&!Object.is(n,i.equals)||"notEquals"in i&&Object.is(n,i.notEquals)||i.oneOf&&!wt(n,i.oneOf)||i.notOneOf&&wt(n,i.notOneOf))}var Mt=class{constructor(e={}){this.capabilities={determinism:"strict",sensors:!0,joints:!1,ccd:!1,maxBodiesHint:5e3,worker:!1},this.bodies=new Map,this.colliders=new Map,this.springs=new Map,this.activeSensors=new Set,this.supportedThisStep=new Set,this.lastEvents=[],this.nextBodyIndex=0,this.nextColliderIndex=0,this.nextSpringIndex=0,this.options={...it,...e},this.random=t(this.options.seed)}init(e={}){this.options={...it,...e},this.random=t(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(t){const e={id:t.id,x:t.x,y:t.y,prevX:t.x,prevY:t.y,vx:t.vx??0,vy:t.vy??0,angle:t.angle??0,mass:Math.max(nt,t.mass??1),bodyCollisions:t.bodyCollisions??!0,shape:rt(t.shape),sleeping:!1,datum:t.datum,restitution:t.restitution,friction:t.friction,index:this.nextBodyIndex,sleepTime:0};this.nextBodyIndex+=1,this.bodies.set(t.id,e)}remove(t){for(const e of t){this.bodies.delete(e);for(const t of Array.from(this.activeSensors))gt(t).bodyId===e&&this.activeSensors.delete(t)}}setColliders(t){this.colliders.clear(),this.activeSensors.clear(),this.nextColliderIndex=0;for(const e of t)this.colliders.set(e.id,{...e,shape:st(e.shape),bodyFilter:xt(e.bodyFilter),index:this.nextColliderIndex}),this.nextColliderIndex+=1}setConstraint(t){const e=t.id??"spring-"+this.nextSpringIndex;return this.springs.set(e,{id:e,bodyId:t.bodyId,target:t.target,restLength:t.restLength??0,stiffness:t.stiffness??40,damping:t.damping??3}),this.nextSpringIndex+=1,e}removeConstraint(t){this.springs.delete(t)}applyImpulse(t,e,i){const n=this.bodies.get(t);n&&(n.vx+=e/n.mass,n.vy+=i/n.mass,this.wake(n))}step(t=this.options.fixedDt){const e=Math.max(0,t);if(this.lastEvents=[],0===e)return;const i=this.sortedBodies();for(const t of i)t.prevX=t.x,t.prevY=t.y;this.applySprings(e);const n=this.options.maxVelocity;for(const t of i)if(!t.sleeping){if(t.vx+=this.options.gravity.x*e,t.vy+=this.options.gravity.y*e,t.vx*=this.options.velocityDamping,t.vy*=this.options.velocityDamping,n>0){const e=Math.sqrt(t.vx*t.vx+t.vy*t.vy);if(e>n){const i=n/e;t.vx*=i,t.vy*=i}}t.x+=t.vx*e,t.y+=t.vy*e}this.supportedThisStep.clear();const o=this.bodyPairKeys(i),r=this.sortedColliders().filter(t=>!t.sensor);for(let t=0;this.options.collisionIterations>t;t+=1)this.resolveBodyPairs(i,o,0===t),this.resolveColliders(i,r,0===t);this.updateSensors(i),this.updateSleeping(i,e)}settle(t=1200,e=this.options.fixedDt){let i=0;for(;t>i&&!this.allSleeping();)this.step(e),i+=1;return i}readState(t=[]){t.length=0;for(const e of this.sortedBodies())t.push({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:rt(e.shape),sleeping:e.sleeping,datum:e.datum});return t}events(){return this.lastEvents.slice()}activeSensorPairs(){return Array.from(this.activeSensors).sort().map(gt)}allSleeping(){for(const t of this.bodies.values())if(!t.sleeping)return!1;return!0}snapshot(){return{options:{...this.options,gravity:{...this.options.gravity}},bodies:this.sortedBodies().map(bt),colliders:this.sortedColliders().map(vt),springs:Array.from(this.springs.values()).map(t=>({...t,target:{...t.target}})),activeSensors:Array.from(this.activeSensors).sort()}}restore(e){this.options={...e.options,gravity:{...e.options.gravity}},this.random=t(this.options.seed),this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors=new Set(e.activeSensors),this.lastEvents=[],this.nextBodyIndex=0;for(const t of e.bodies){const e=bt(t);this.bodies.set(e.id,e),this.nextBodyIndex=Math.max(this.nextBodyIndex,e.index+1)}this.nextColliderIndex=0;for(const t of e.colliders){const e=vt(t);this.colliders.set(e.id,e),this.nextColliderIndex=Math.max(this.nextColliderIndex,e.index+1)}this.nextSpringIndex=0;for(const t of e.springs){this.springs.set(t.id,{...t,target:{...t.target}});const e=/^spring-(\d+)$/.exec(t.id);e&&(this.nextSpringIndex=Math.max(this.nextSpringIndex,Number(e[1])+1))}}dispose(){this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors.clear(),this.lastEvents=[]}sortedBodies(){return Array.from(this.bodies.values()).sort((t,e)=>t.index-e.index)}sortedColliders(){return Array.from(this.colliders.values()).sort((t,e)=>t.index-e.index)}applySprings(t){for(const e of Array.from(this.springs.values()).sort((t,e)=>t.id.localeCompare(e.id))){const i=this.bodies.get(e.bodyId);if(!i||i.sleeping)continue;const n="point"===e.target.type?e.target:this.bodies.get(e.target.bodyId);if(!n)continue;const o=n.x-i.x,r=n.y-i.y,s=Math.sqrt(o*o+r*r);if(nt>=s)continue;const a=o/s,c=r/s,d=(s-e.restLength)*e.stiffness+((("vx"in n?n.vx:0)-i.vx)*a+(("vy"in n?n.vy:0)-i.vy)*c)*e.damping;i.vx+=d*a*t/i.mass,i.vy+=d*c*t/i.mass}}resolveBodyPairs(t,e,i){for(const n of e){const[e,o]=n.split(":").map(Number),r=t[e],s=t[o];if(!r||!s)continue;const a=mt(r,s);a&&(this.resolveDynamicCollision(r,s,a),i&&this.lastEvents.push({type:"contact",bodyId:r.id,otherId:s.id,sensor:!1}))}}bodyPairKeys(t){const e=Math.max(1,this.options.cellSize),i=new Map;for(let n=0;t.length>n;n+=1){if(!1===t[n].bodyCollisions)continue;const o=dt(t[n]),r=Math.floor(o.minX/e),s=Math.floor(o.maxX/e),a=Math.floor(o.minY/e),c=Math.floor(o.maxY/e);for(let t=r;s>=t;t+=1)for(let e=a;c>=e;e+=1){const o=`${t}:${e}`,r=i.get(o);r?r.push(n):i.set(o,[n])}}const n=new Set;for(const e of Array.from(i.keys()).sort()){const o=i.get(e)??[];o.sort((t,e)=>t-e);for(let e=0;o.length>e;e+=1)for(let i=e+1;o.length>i;i+=1){const r=o[e],s=o[i];!1!==t[r].bodyCollisions&&!1!==t[s].bodyCollisions&&ut(dt(t[r]),dt(t[s]))&&n.add(`${r}:${s}`)}}return Array.from(n).sort((t,e)=>{const[i,n]=t.split(":").map(Number),[o,r]=e.split(":").map(Number);return i===o?n-r:i-o})}resolveDynamicCollision(t,e,i){t.sleeping&&this.supportedThisStep.add(e.id),e.sleeping&&this.supportedThisStep.add(t.id);const n=t.sleeping?0:1/t.mass,o=e.sleeping?0:1/e.mass,r=n+o;if(nt>=r)return;const s=Math.max(0,i.penetration-ot)/r;t.x-=i.nx*s*n,t.y-=i.ny*s*n,e.x+=i.nx*s*o,e.y+=i.ny*s*o;const a=(e.vx-t.vx)*i.nx+(e.vy-t.vy)*i.ny;if(a>0)return;const c=Math.abs(a),d=-(1+Math.min(t.restitution??this.options.restitution,e.restitution??this.options.restitution))*a/r,l=d*i.nx,u=d*i.ny;t.vx-=l*n,t.vy-=u*n,e.vx+=l*o,e.vy+=u*o,this.applyFriction(t,e,i,d,n,o),c>this.options.contactWakeSpeed&&(this.wake(t),this.wake(e))}applyFriction(t,e,i,n,o,r){const s=-i.ny,a=i.nx,c=(e.vx-t.vx)*s+(e.vy-t.vy)*a,d=o+r;if(nt>=Math.abs(c)||nt>=d)return;const l=Math.max(0,Math.min(1,Math.max(t.friction??this.options.friction,e.friction??this.options.friction))),u=at(-c/d,-n*l,n*l),h=u*s,p=u*a;t.vx-=h*o,t.vy-=p*o,e.vx+=h*r,e.vy+=p*r}resolveColliders(t,e,i){for(const n of t)for(const t of e){if(!It(t,n))continue;if(!ut(dt(n),lt(t)))continue;const e=ft(n,t);e&&(this.resolveStaticCollision(n,t,e),this.supportedThisStep.add(n.id),i&&this.lastEvents.push({type:"contact",bodyId:n.id,otherId:t.id,sensor:!1}))}}resolveStaticCollision(t,e,i){t.x+=i.nx*Math.max(0,i.penetration-ot),t.y+=i.ny*Math.max(0,i.penetration-ot);const n=t.vx*i.nx+t.vy*i.ny;if(0>n){const o=Math.min(t.restitution??this.options.restitution,e.restitution??this.options.restitution);t.vx-=(1+o)*n*i.nx,t.vy-=(1+o)*n*i.ny;const r=-i.ny,s=i.nx,a=t.vx*r+t.vy*s,c=Math.max(0,Math.min(1,Math.max(t.friction??this.options.friction,e.friction??this.options.friction)));t.vx-=a*r*c,t.vy-=a*s*c}}updateSensors(t){const e=new Set,i=this.sortedColliders().filter(t=>t.sensor);for(const n of t){const t=dt(n);for(const o of i){if(!It(o,n))continue;if(!ut(t,lt(o)))continue;if(!ft(n,o))continue;const i=yt(o.id,n.id);e.add(i),this.activeSensors.has(i)||this.lastEvents.push({type:"sensor-enter",bodyId:n.id,sensorId:o.id})}}for(const t of Array.from(this.activeSensors).sort()){if(e.has(t))continue;const{sensorId:i,bodyId:n}=gt(t);this.lastEvents.push({type:"sensor-exit",bodyId:n,sensorId:i})}this.activeSensors=e}updateSleeping(t,e){const i=Math.hypot(this.options.gravity.x,this.options.gravity.y)>1;for(const n of t)Math.sqrt(n.vx*n.vx+n.vy*n.vy)>=this.options.sleepSpeed||Math.sqrt((n.x-n.prevX)*(n.x-n.prevX)+(n.y-n.prevY)*(n.y-n.prevY))>=this.options.sleepSpeed*e||i&&!this.supportedThisStep.has(n.id)?n.sleeping?this.wake(n):n.sleepTime=0:(n.sleepTime+=e,n.sleeping||this.options.sleepAfter>n.sleepTime||(n.sleeping=!0,n.vx=0,n.vy=0,this.lastEvents.push({type:"sleep",bodyId:n.id})))}wake(t){t.sleeping&&this.lastEvents.push({type:"wake",bodyId:t.id}),t.sleeping=!1,t.sleepTime=0}nextRandom(){return this.random()}},kt=class{constructor(t={}){this.id="builtin",this.capabilities={...(new Mt).capabilities,engine:"builtin"},this.world=new Mt(t)}init(t={}){this.world.init(t)}spawn(t){this.world.spawn(t)}remove(t){this.world.remove(t)}setColliders(t){this.world.setColliders(t)}setConstraint(t){return this.world.setConstraint(t)}removeConstraint(t){this.world.removeConstraint(t)}applyImpulse(t,e,i){this.world.applyImpulse(t,e,i)}step(t){this.world.step(t)}settle(t,e){return this.world.settle(t,e)}readState(t){return this.world.readState(t)}events(){return this.world.events()}activeSensorPairs(){return this.world.activeSensorPairs()}allSleeping(){return this.world.allSleeping()}snapshot(){return this.world.snapshot()}restore(t){this.world.restore(t)}nextRandom(){return this.world.nextRandom()}dispose(){this.world.dispose()}};function St(t={}){return new kt(t)}function At(t,e={}){return t?"function"==typeof t?t(e):(t.init(e),t):St(e)}var Rt=["binId","targetBin","category","windowIndex","lane","group"];function Pt(t,e){if(!Number.isFinite(e))return;t.count+=1,t.total+=e,t.min=Math.min(t.min,e),t.max=Math.max(t.max,e);const i=e-t.mean;t.mean+=i/t.count,t.m2+=i*(e-t.mean)}function Ct(t){return{count:t.count,total:t.total,mean:t.count>0?t.mean:0,min:t.count>0?t.min:0,max:t.count>0?t.max:0,variance:t.count>1?t.m2/(t.count-1):0}}function $t(t){return{count:t.count,total:t.total,mean:t.mean,m2:t.variance*Math.max(0,t.count-1),min:t.count>0?t.min:1/0,max:t.count>0?t.max:-1/0}}function jt(t,e){if(null!=t[e])return t[e];const i=t.datum;return i&&"object"==typeof i?i[e]:void 0}function Bt(t,e,i){return"function"==typeof t?t(e,i):"string"==typeof t?jt(e,t):void 0}function Ot(t){if(null==t)return;const e=t+"";return e.trim()?e:void 0}function Nt(t){const e=Ct(t.value);return{id:t.id,label:t.label,count:e.count,total:e.total,bodyIds:t.bodyIds.slice(),lastBodyId:t.lastBodyId,lastDatum:t.lastDatum,x:Ct(t.x),y:Ct(t.y),value:e}}var Tt=class{constructor(t=!1){this.bins=new Map,this.nextIndex=0,this.config=t}updateConfig(t){void 0!==t&&(this.config=t,!1===t&&this.clear())}isEnabled(){return!1!==this.config}add(t){if(!1===this.config)return null;const e=this.nextIndex;this.nextIndex+=1;const i=Ot(Bt(this.config.binAccessor,t,e))??function(t){for(const e of Rt){const i=Ot(jt(t,e));if(i)return i}return"sediment"}(t),n=Ot(Bt(this.config.labelAccessor,t,e))??i,o=function(t,e,i){if("number"==typeof t)return t;const n="function"==typeof t?t(e,i):"string"==typeof t?jt(e,t):1,o="number"==typeof n?n:Number(n);return Number.isFinite(o)?o:1}(this.config.valueAccessor,t,e),r=Math.max(0,Math.floor(this.config.retainBodyIds??12));let s=this.bins.get(i);return s||(s={id:i,label:n,bodyIds:[],x:{count:0,total:0,mean:0,m2:0,min:1/0,max:-1/0},y:{count:0,total:0,mean:0,m2:0,min:1/0,max:-1/0},value:{count:0,total:0,mean:0,m2:0,min:1/0,max:-1/0}},this.bins.set(i,s)),s.label=n,s.lastBodyId=t.id,s.lastDatum=t.datum,Pt(s.x,t.x),Pt(s.y,t.y),Pt(s.value,o),r>0&&(s.bodyIds.push(t.id),s.bodyIds.length>r&&(s.bodyIds=s.bodyIds.slice(s.bodyIds.length-r))),Nt(s)}clear(){this.bins.clear(),this.nextIndex=0}snapshot(){return Array.from(this.bins.values()).map(Nt)}restore(t=[]){this.bins.clear();for(const e of t)this.bins.set(e.id,{id:e.id,label:e.label,bodyIds:e.bodyIds.slice(),lastBodyId:e.lastBodyId,lastDatum:e.lastDatum,x:$t(e.x),y:$t(e.y),value:$t(e.value)});this.nextIndex=t.reduce((t,e)=>t+e.count,0)}totals(){const t=this.snapshot();return{bins:t.length,count:t.reduce((t,e)=>t+e.count,0),total:t.reduce((t,e)=>t+e.total,0)}}};function Et(t,e={}){const{baselineY:i=0,binWidth:n=24,gap:o=2,maxHeight:r=80,value:s="count",x:a}=e,c=Math.max(1,...t.map(t=>t[s]));return t.map((t,e)=>{const d=Math.max(0,t[s]/c*r),l=a?.(t,e)??e*(n+o);return{binId:t.id,label:t.label,index:e,count:t.count,total:t.total,x:l,y:i-d,width:n,height:d,meanX:t.x.mean,meanY:t.y.mean}})}function qt(t){const e=Number(t);if(Number.isFinite(e)&&e>0)return Math.floor(e)}function Ft(t){const e=Math.max(0,Math.floor(t.liveBodies)),i=Math.max(0,Math.floor(t.queuedBodies??0)),n=e+i,o=qt(t.bodyLimit),r=qt(t.engineMaxBodiesHint),s=function(t,e,i){if(!1===i)return;const n=qt(i?.warnAt);return null!=n?n:null!=t?Math.max(1,Math.floor(.8*t)):null!=e?Math.max(1,Math.floor(.8*e)):void 0}(o,r,t.options),a=null==o?0:Math.max(0,e-o),c=a>0?"overflow":null==s||s>n?"ok":"warning";return{action:"overflow"!==c?"continue":t.sedimentEnabled?"sediment":t.evictionEnabled?"evict":"retain",bodyLimit:o,engineMaxBodiesHint:r,liveBodies:e,overflow:a,projectedBodies:n,queuedBodies:i,state:c,warnAt:s}}var Wt={bodyLimit:1/0,eviction:"oldest",fixedDt:1/120,maxDeltaSeconds:.1,maxSubsteps:8,settleStepLimit:1200,timeScale:1},Dt={chartId:"physics",chartType:"physics",sensors:{},onObservation:void 0,onSimulationStateChange:void 0};function zt(t={},e=Dt){return{chartId:t.chartId??e.chartId,chartType:t.chartType??e.chartType,sensors:t.sensors??e.sensors,onObservation:t.onObservation??e.onObservation,onSimulationStateChange:t.onSimulationStateChange??e.onSimulationStateChange}}function Lt(t){return{...t,shape:{...t.shape},datum:t.datum,springs:t.springs?.map(t=>({...t,target:{...t.target}}))}}function Yt(t){if(t instanceof Date){const e=t.getTime();return Number.isFinite(e)?e:void 0}const e="number"==typeof t?t:"string"==typeof t&&t.trim()?Number(t):NaN;return Number.isFinite(e)?e:void 0}function _t(t,e){if(null!=t[e])return t[e];const i=t.datum;return i&&"object"==typeof i?i[e]:void 0}function Ht(t){return{...Lt(t),sequence:t.sequence,spawnAt:t.spawnAt}}function Xt(t){return t.map(t=>({...t,shape:{...t.shape},bodyFilter:t.bodyFilter&&"function"!=typeof t.bodyFilter?{...t.bodyFilter,oneOf:t.bodyFilter.oneOf?.slice(),notOneOf:t.bodyFilter.notOneOf?.slice()}:t.bodyFilter}))}function Gt(t){return!1!==t&&{...t}}function Vt(t,e){return t.spawnAt===e.spawnAt?t.sequence-e.sequence:t.spawnAt-e.spawnAt}function Ut(t){return{...t,gravity:{...t.gravity}}}function Kt(t,e,i,n){if("circle"===t.shape.type){const o=t.x-e,r=t.y-i,s=t.shape.radius+n,a=o*o+r*r;return a>s*s?null:a}const o=Math.max(Math.abs(e-t.x)-t.shape.width/2,0),r=Math.max(Math.abs(i-t.y)-t.shape.height/2,0),s=o*o+r*r;return s>n*n?null:s}function Qt(t){const e=t.indexOf("\0");return{sensorId:t.slice(0,e),bodyId:t.slice(e+1)}}function Zt(t,e={}){const{idPrefix:i="plot",includeFloor:n=!0,includeCeiling:o=!1,includeLeftWall:r=!0,includeRightWall:s=!0,wallThickness:a=20,floorThickness:c=a}=e,d=[],l=t.x+t.width/2,u=t.y+t.height/2;return n&&d.push({id:i+"-floor",shape:{type:"aabb",x:l,y:t.y+t.height+c/2,width:t.width+2*a,height:c}}),o&&d.push({id:i+"-ceiling",shape:{type:"aabb",x:l,y:t.y-c/2,width:t.width+2*a,height:c}}),r&&d.push({id:i+"-left-wall",shape:{type:"aabb",x:t.x-a/2,y:u,width:a,height:t.height+2*c}}),s&&d.push({id:i+"-right-wall",shape:{type:"aabb",x:t.x+t.width+a/2,y:u,width:a,height:t.height+2*c}}),d}function Jt(t){const{idPrefix:e="bin",count:i,domainStart:n,domainStep:o,xScale:r,yTop:s,yBottom:a,wallThickness:c=4,includeBoundaryWalls:d=!0,includeInteriorWalls:l=!0,closedBefore:u,lidY:h=s,lidThickness:p=Math.max(2,c)}=t,m=[],f=s+(a-s)/2,y=Math.abs(a-s),g=d?i:i-1;if(l||d)for(let t=d?0:1;g>=t;t+=1){if(!l&&t>0&&i>t)continue;const s=r(n+t*o);m.push({id:`${e}-wall-${t}`,shape:{type:"aabb",x:s,y:f,width:c,height:y}})}if(null!=u)for(let t=0;i>t;t+=1){const i=n+t*o,s=i+o;if(s>=u)continue;const a=r(i),d=r(s);m.push({id:`${e}-lid-${t}`,shape:{type:"segment",x1:Math.min(a,d)+c/2,y1:h,x2:Math.max(a,d)-c/2,y2:h,thickness:p}})}return m}import{quadtree as te}from"d3-quadtree";var ee=class{constructor(){this.maxSearchRadius=0,this.revision=-1,this.tree=null}hitTest(t,e,i,n,o,r=0){const s=this.ensure(t,e);if(!s)return null;let a=null,c=1/0;const d=Math.max(0,r)+this.maxSearchRadius,l=n-d,u=n+d,h=o-d,p=o+d;return s.visit((t,e,s,d,m)=>{if(l>d||e>u||h>m||s>p)return!0;if(t.length)return!1;let f=t;for(;f;){const t=f.data;if(t){const e=Kt(t,n,o,Math.max(0,r));null!=e&&(c>e||e===c&&i.indexOf(t.id)>i.indexOf(a?.id??""))&&(a=t,c=e)}f=f.next}return!1}),a}ensure(t,e){if(this.tree&&this.revision===e)return this.tree;const i=t.readState();return 0===i.length?(this.tree=null,this.maxSearchRadius=0,this.revision=e,null):(this.maxSearchRadius=i.reduce((t,e)=>Math.max(t,function(t){return"circle"===t.shape.type?t.shape.radius:Math.hypot(t.shape.width,t.shape.height)/2}(e)),0),this.tree=te().x(t=>t.x).y(t=>t.y).addAll(i),this.revision=e,this.tree)}},ie=["data","scene-geometry","data-paint","accessibility","evidence"],ne=["scene-geometry","data-paint","accessibility","evidence"],oe=["overlay","accessibility","evidence"],re=(t,e)=>({retainedData:t,invalidations:e}),se=["layout","scene-geometry","data-paint","overlay","accessibility","evidence"],ae=["scene-geometry","data-paint","accessibility","evidence"],ce=[],de={engine:re("rebuild",["scene-geometry","data-paint","accessibility","evidence"]),kernel:re("preserve",ae),colliders:re("preserve",ae),sediment:re("preserve",ae),bodyBudget:re("preserve",se),bodyLimit:re("preserve",se),eviction:re("preserve",se),fixedDt:re("preserve",ce),maxDeltaSeconds:re("preserve",ce),maxSubsteps:re("preserve",ce),settleStepLimit:re("preserve",ce),timeScale:re("preserve",ce),observation:re("preserve",ce)},le=re("preserve",se);function ue(t){let e="preserve";const i=new Set;for(const n of t){const t=de[n]??le;"rebuild"===t.retainedData&&(e="rebuild");for(const e of t.invalidations)i.add(e)}return{retainedData:e,invalidations:i}}var he=["seed","fixedDt","cellSize","collisionIterations","velocityDamping","sleepSpeed","sleepAfter","restitution","friction","maxVelocity","contactWakeSpeed"];function pe(t,e){return t===e||!(!t||!e)&&t.gravity?.x===e.gravity?.x&&t.gravity?.y===e.gravity?.y&&he.every(i=>t[i]===e[i])}function me(t,e,i,n){return t||!e?"paused":i||!n?"running":"settled"}var fe=class{constructor(){this.seconds=0,this.speed=8,this.scratch=[]}setKernelOptions(t){this.speed=function(t){const e=t?.sleepSpeed;return"number"==typeof e&&Number.isFinite(e)&&e>0?e:8}(t)}reset(){this.seconds=0}isAtRest(){return this.seconds>=.6}refresh(t,e,i){if(i>0)return void(this.seconds=0);const n=t.readState(this.scratch),o=this.speed*this.speed;let r=!0;for(const t of n)if(!t.sleeping&&t.vx*t.vx+t.vy*t.vy>=o){r=!1;break}this.seconds=r?this.seconds+Math.max(0,e):0}},ye=class{constructor(t={}){this.activeSensorPairs=new Set,this.accumulator=0,this.bodyBudgetObservationKey="ok",this.bodySpatialIndex=new ee,this.elapsedSeconds=0,this.liveBodyOrder=[],this.nextSequence=0,this.paused=!1,this.queue=[],this.revision=0,this.updateResults=new m,this.simulationState="settled",this.visible=!0,this.quiescence=new fe;const{bodyBudget:e,colliders:i,engine:n,kernel:o,observation:r,sediment:s,...a}=t;this.config={...Wt,...a},this.configInput={...t},this.bodyBudget=e??{},this.engineInput=n,this.observation=zt(r),this.sediment=new Tt(s??!1),this.world=At(n,{fixedDt:this.config.fixedDt,...o}),this.quiescence.setKernelOptions(o),i&&this.world.setColliders(Xt(i))}updateConfig(t){const e=function(t,e){return Object.keys(t).filter(i=>"kernel"===i?!pe(t.kernel,e.kernel):t[i]!==e[i])}(t,this.configInput),{colliders:i,bodyBudget:n,engine:o,kernel:r,observation:s,sediment:a,...c}=t;if(this.config={...this.config,...c},void 0!==n&&(this.bodyBudget=n,!1===n&&(this.bodyBudgetObservationKey="ok")),o&&o!==this.engineInput){const t=this.world.snapshot();this.world.dispose(),this.engineInput=o,this.world=At(o,t.options),this.world.restore(t),this.revision+=1}if(r&&!pe(r,this.configInput.kernel)){const t=this.world.snapshot(),e={...t.options,...r,gravity:{...t.options.gravity,...r.gravity}};this.world.restore({...t,options:e}),this.quiescence.setKernelOptions(e),this.revision+=1}s&&(this.observation=zt(s,this.observation)),this.sediment.updateConfig(a),i&&(this.world.setColliders(Xt(i)),this.revision+=1),this.configInput={...this.configInput,...t};const d=ue(e);this.updateResults.record({kind:"config",keys:e},d.invalidations)}updateConfigWithResult(t){return this.updateConfig(t),this.updateResults.last}setColliders(t){this.world.setColliders(Xt(t)),this.revision+=1,this.updateResults.record({kind:"config",keys:["colliders"]},ue(["colliders"]).invalidations)}enqueue(t,e){const i=Array.isArray(t)?t:[t],n=e?function(t,e={}){const i=Yt(e.startAt)??0,n=e.pacing??"immediate";if("arrival"===n){const n=t.map((t,i)=>function(t,e,i){return"function"==typeof i?Yt(i(t,e)):"string"==typeof i?Yt(_t(t,i)):Yt(t.spawnAt)??Yt(_t(t,"arrivalTime"))??Yt(_t(t,"timestamp"))??Yt(_t(t,"time"))??Yt(_t(t,"eventTime"))}(t,i,e.timeAccessor)),o=n.filter(t=>null!=t),r=o.length>0?Math.min(...o):0,s=Yt(e.timeScale)??1,a=s>0?s:1;return t.map((t,e)=>{const o=n[e],s=null==o?0:Math.max(0,o-r);return{...Lt(t),spawnAt:i+s/a}})}if("object"==typeof n){const e=Yt(n.ratePerSec);if(e&&e>0)return t.map((t,n)=>({...Lt(t),spawnAt:i+n/e}))}return t.map(t=>({...Lt(t),spawnAt:i}))}(i,{...e,startAt:e.startAt??this.elapsedSeconds}):i;for(const t of n)this.queue.push({...Lt(t),sequence:this.nextSequence,spawnAt:t.spawnAt??this.elapsedSeconds}),this.nextSequence+=1;this.queue.sort(Vt),n.length>0&&(this.revision+=1),this.updateResults.record({kind:"enqueue",count:n.length},n.length?ie:[])}enqueueWithResult(t,e){return this.enqueue(t,e),this.updateResults.last}spawnNow(t){this.spawnOne(Lt(t)),this.nextSequence+=1,this.observeBodyBudget(),this.evictOverflow(),this.revision+=1,this.updateResults.record({kind:"enqueue",count:1},ie)}materializeDueSpawns(){const t=this.revision,e=[],i=[];return this.spawnDue(e,i),0===e.length||(this.observeBodyBudget(i),this.evictOverflow(i),this.syncSimulationState(i),this.revision+=1,this.updateResults.record({kind:"enqueue",count:e.length},this.revision!==t?ie:[])),e}clear(){const t=this.world.snapshot().options;this.world.init({...t,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"},ie)}tick(t){const e=this.revision,i=[],n=[],o=[],r=[],s=[];if(this.paused||!this.visible){const t=this.result(0,i,n,o,r,s,!1);return this.updateResults.record({kind:"tick",count:0},[]),t}const a=Math.max(0,Math.min(t,this.config.maxDeltaSeconds))*this.config.timeScale;this.elapsedSeconds+=a,this.spawnDue(i,s);const c=this.observeBodyBudget(s),d=this.evictOverflow(s);n.push(...d.evicted),o.push(...d.sedimented),this.syncSimulationState(s),this.accumulator+=a;let l=0;for(;this.accumulator>=this.config.fixedDt&&this.config.maxSubsteps>l;){this.world.step(this.config.fixedDt);const t=this.world.events();r.push(...t),this.observeKernelEvents(t,s),this.observeSensorTransitions(s),this.accumulator-=this.config.fixedDt,l+=1}l===this.config.maxSubsteps&&(this.accumulator=Math.min(this.accumulator,this.config.fixedDt)),this.quiescence.refresh(this.world,a,i.length),(l>0||i.length>0||n.length>0||o.length>0||r.length>0)&&(this.revision+=1);const u=this.result(l,i,n,o,r,s,void 0,c);return this.updateResults.record({kind:"tick",count:l},this.revision!==e?i.length||n.length||o.length?ie:ne:[]),u}settle(t=this.config.settleStepLimit){const e=this.revision;this.spawnDue([],[]);const i=this.world.settle(t,this.config.fixedDt);return i>0&&(this.revision+=1),this.syncSimulationState(),this.updateResults.record({kind:"settle",count:i},this.revision!==e?ne:[]),i}settleWithObservations(t=this.config.settleStepLimit){const e=this.revision,i=[],n=[],o=[],r=[],s=[];if(this.paused||!this.visible){const t=this.result(0,i,n,o,r,s,!1);return this.updateResults.record({kind:"settle",count:0},[]),t}this.spawnDue(i,s);const a=this.observeBodyBudget(s),c=this.evictOverflow(s);n.push(...c.evicted),o.push(...c.sedimented),this.syncSimulationState(s);let d=0;for(i.length>0&&this.quiescence.reset();t>d&&!this.atRest();){this.world.step(this.config.fixedDt);const t=this.world.events();r.push(...t),this.observeKernelEvents(t,s),this.observeSensorTransitions(s),d+=1,this.quiescence.refresh(this.world,this.config.fixedDt,0)}(d>0||i.length>0||n.length>0||o.length>0||r.length>0)&&(this.revision+=1);const l=this.result(d,i,n,o,r,s,void 0,a);return this.updateResults.record({kind:"settle",count:d},this.revision!==e?i.length||n.length||o.length?ie:ne:[]),l}readBodies(t=[]){return this.world.readState(t)}readSediment(){return this.sediment.snapshot()}bodyBudgetStatus(){return this.evaluateBodyBudget()}sedimentTotals(){return this.sediment.totals()}sedimentHeightfield(t={}){return Et(this.readSediment(),t)}hitTest(t,e,i=0){return this.bodySpatialIndex.hitTest(this.world,this.revision,this.liveBodyOrder,t,e,i)}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(t){const{timestamp:e,chartType:i,chartId:n,...o}=t,r={...o,timestamp:e??this.elapsedSeconds,chartType:i??this.observation.chartType,chartId:n??this.observation.chartId};return this.emitObservation(r),this.updateResults.record({kind:"update",count:1},["evidence"]),r}getLastUpdateResult(){return this.updateResults.last}getUpdateSnapshot(){return this.updateResults.last}subscribeUpdateResult(t){return this.updateResults.subscribe(t)}version(){return this.revision}setPaused(t){const e=this.paused!==t;this.paused=t,this.syncSimulationState(),this.updateResults.record({kind:"pause"},e?oe:[])}setVisible(t){const e=this.visible!==t;this.visible=t,this.syncSimulationState(),this.updateResults.record({kind:"visibility"},e?oe:[])}remove(t){const e=new Set(t),i=new Set(this.liveBodyOrder),n=new Set(this.queue.map(t=>t.id));this.queue=this.queue.filter(t=>!e.has(t.id)),this.liveBodyOrder=this.liveBodyOrder.filter(t=>!e.has(t)),this.world.remove(t),this.removeActiveSensorPairsForBodies(e);const o=t.filter(t=>i.has(t)||n.has(t));return o.length>0&&(this.revision+=1,this.syncSimulationState()),this.updateResults.record({kind:"remove",keys:o,count:o.length},o.length?ie:[]),o}setConstraint(t){const e=this.world.setConstraint(t);return this.revision+=1,this.updateResults.record({kind:"constraint",keys:[e]},ne),e}removeConstraint(t){this.world.removeConstraint(t),this.revision+=1,this.updateResults.record({kind:"constraint",keys:[t]},ne)}applyImpulse(t,e,i){this.world.applyImpulse(t,e,i),this.revision+=1,this.updateResults.record({kind:"impulse",keys:[t]},ne)}nextRandom(){return this.world.nextRandom()}controls(){return t=this,{applyImpulse:(e,i,n)=>t.applyImpulse(e,i,n),clear:()=>t.clear(),hitTest:(e,i,n)=>t.hitTest(e,i,n),pause:()=>t.setPaused(!0),push:(e,i)=>t.enqueue(e,i),pushMany:(e,i)=>t.enqueue(e,i),bodyBudgetStatus:()=>t.bodyBudgetStatus(),readBodies:e=>t.readBodies(e),readSediment:()=>t.readSediment(),recordObservation:e=>t.recordObservation(e),remove:e=>t.remove(e),restore:e=>t.restore(e),resume:()=>t.setPaused(!1),settle:e=>t.settle(e),settleWithObservations:e=>t.settleWithObservations(e),snapshot:()=>t.snapshot(),sedimentHeightfield:e=>t.sedimentHeightfield(e),sedimentTotals:()=>t.sedimentTotals(),step:e=>t.tick(e)};var t}snapshot(){const t=this.world.snapshot();return{accumulator:this.accumulator,activeSensorPairs:Array.from(this.activeSensorPairs).sort(),bodyBudget:Gt(this.bodyBudget),config:{...this.config,kernel:Ut(t.options)},elapsedSeconds:this.elapsedSeconds,paused:this.paused,queue:this.queue.map(Ht),revision:this.revision,sediment:this.readSediment(),simulationState:this.simulationState,liveBodyOrder:this.liveBodyOrder.slice(),visible:this.visible,world:t}}restore(t){this.config={bodyLimit:t.config.bodyLimit,eviction:t.config.eviction,fixedDt:t.config.fixedDt,maxDeltaSeconds:t.config.maxDeltaSeconds,maxSubsteps:t.config.maxSubsteps,settleStepLimit:t.config.settleStepLimit,timeScale:t.config.timeScale},this.configInput={...t.config,bodyBudget:Gt(t.bodyBudget??{}),kernel:Ut(t.world.options)},this.bodyBudget=Gt(t.bodyBudget??{}),this.bodyBudgetObservationKey="ok",this.quiescence.setKernelOptions(t.world.options),this.quiescence.reset(),this.activeSensorPairs=new Set(t.activeSensorPairs),this.accumulator=t.accumulator,this.elapsedSeconds=t.elapsedSeconds,this.paused=t.paused,this.queue=t.queue.map(Ht).sort(Vt),this.revision=t.revision,this.sediment.restore(t.sediment??[]),this.simulationState=t.simulationState??me(t.paused,t.visible,t.queue.length>0,t.world.bodies.every(t=>t.sleeping)),this.liveBodyOrder=t.liveBodyOrder.slice(),this.visible=t.visible,this.nextSequence=this.queue.reduce((t,e)=>Math.max(t,e.sequence),-1)+1,this.world.restore(t.world),this.updateResults.record({kind:"restore"},ie)}spawnDue(t,e){for(;this.queue.length>0&&this.elapsedSeconds>=this.queue[0].spawnAt;){const i=this.queue.shift();if(!i)return;this.spawnOne(i,e),t.push(i.id)}}spawnOne(t,e){this.liveBodyOrder=this.liveBodyOrder.filter(e=>e!==t.id),this.removeActiveSensorPairsForBodies(new Set([t.id])),this.world.spawn(t),this.liveBodyOrder.push(t.id);for(const e of t.springs??[])this.world.setConstraint({...e,bodyId:t.id});const i=this.world.readState().find(e=>e.id===t.id);this.emitObservation({type:"physics-spawn",timestamp:this.elapsedSeconds,chartType:this.observation.chartType,chartId:this.observation.chartId,bodyId:t.id,datum:i?.datum??t.datum,x:i?.x??t.x,y:i?.y??t.y},e)}result(t,e,i,n,o,r,s,a=this.evaluateBodyBudget()){this.syncSimulationState(r);const c=this.world.allSleeping();return{budget:a,elapsedSeconds:this.elapsedSeconds,evicted:i,events:o,observations:r,queueSize:this.queue.length,revision:this.revision,shouldContinue:s??(this.queue.length>0||!this.atRest()),sleeping:c,sedimented:n,spawned:e,steps:t}}observeKernelEvents(t,e){!function(t,e,i){if(0===e.length)return;const n=new Map(t.readState().map(t=>[t.id,t]));for(const t of e){if("sleep"!==t.type)continue;const e=n.get(t.bodyId);i.emit({type:"physics-settle",timestamp:i.elapsedSeconds,chartType:i.observation.chartType,chartId:i.observation.chartId,bodyId:t.bodyId,datum:e?.datum,x:e?.x,y:e?.y})}}(this.world,t,this.observationContext(e))}observeSensorTransitions(t){this.activeSensorPairs=function(t,e,i){const n=new Set(t.activeSensorPairs().map(t=>`${t.sensorId}\0${t.bodyId}`));if(0===n.size&&0===e.size)return n;const o=new Map(t.readState().map(t=>[t.id,t])),r=(t,e)=>{const{sensorId:n,bodyId:r}=Qt(e),s=i.observation.sensors[n],a=o.get(r);i.emit({type:"enter"===t?s?.enterType??"physics-bin-enter":s?.exitType??"physics-bin-exit",timestamp:i.elapsedSeconds,chartType:i.observation.chartType,chartId:i.observation.chartId,bodyId:r,datum:a?.datum,x:a?.x,y:a?.y,sensorId:n,binId:s?.binId??n})};for(const t of Array.from(n).sort())e.has(t)||r("enter",t);for(const t of Array.from(e).sort())n.has(t)||r("exit",t);return n}(this.world,this.activeSensorPairs,this.observationContext(t))}removeActiveSensorPairsForBodies(t){!function(t,e){for(const i of t)e.has(Qt(i).bodyId)&&t.delete(i)}(this.activeSensorPairs,t)}observationContext(t){return{elapsedSeconds:this.elapsedSeconds,observation:this.observation,emit:e=>this.emitObservation(e,t)}}emitObservation(t,e){e?.push(t),this.observation.onObservation?.(t)}evaluateBodyBudget(){return Ft({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(t){const e=this.evaluateBodyBudget();if("ok"===e.state||!1===this.bodyBudget)return this.bodyBudgetObservationKey="ok",e;const i=`${e.state}:${e.action}`;return i===this.bodyBudgetObservationKey||(this.bodyBudgetObservationKey=i,this.emitObservation({type:"overflow"===e.state?"physics-budget-overflow":"physics-budget-warning",timestamp:this.elapsedSeconds,chartType:this.observation.chartType,chartId:this.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},t)),e}syncSimulationState(t){const e=me(this.paused,this.visible,this.queue.length>0,this.atRest());if(e===this.simulationState)return;const i=this.simulationState;this.simulationState=e,function(t,e,i){i.observation.onSimulationStateChange?.(e,t),"running"!==e&&"settled"!==e||i.emit({type:"running"===e?"sim-active":"sim-idle",timestamp:i.elapsedSeconds,chartType:i.observation.chartType,chartId:i.observation.chartId,simulationState:e,previousSimulationState:t})}(i,e,this.observationContext(t))}evictOverflow(t){const{evicted:e,sedimented:i,liveBodyOrder:n}=function(t,e,i,n,o,r){const s={evicted:[],sedimented:[],liveBodyOrder:o};if(!1===i)return s;const a=Math.max(0,Math.floor(n));if(!Number.isFinite(a))return s;const c=o.length-a;if(0>=c)return s;const d=function(t,e,i){if("sleeping-first"!==e)return i.slice();const n=new Map(t.readState().map(t=>[t.id,t.sleeping])),o=[],r=[];for(const t of i)n.get(t)?o.push(t):r.push(t);return[...o,...r]}(t,i,o),l=d.slice(0,c);if(0===l.length)return s;const u=function(t,e,i,n){const o=new Map(t.readState().map(t=>[t.id,t])),r=[];for(const t of i){const i=o.get(t);if(!i)continue;const s=e.add(i);s&&(r.push(t),n.emit({type:"physics-sediment",timestamp:n.elapsedSeconds,chartType:n.observation.chartType,chartId:n.observation.chartId,bodyId:t,datum:i.datum,x:i.x,y:i.y,binId:s.id,count:s.count,total:s.total}))}return r}(t,e,l,r);t.remove(l);const h=new Set(l);return{evicted:l,sedimented:u,liveBodyOrder:o.filter(t=>!h.has(t))}}(this.world,this.sediment,this.config.eviction,this.config.bodyLimit,this.liveBodyOrder,this.observationContext(t));return e.length>0&&(this.liveBodyOrder=n,this.removeActiveSensorPairsForBodies(new Set(e))),{evicted:e,sedimented:i}}};function ge(t,e){if("function"==typeof e){const i=e(t);return Number.isFinite(i)&&i>0?Number(i):1}const i=t.datum;if(e&&i&&"object"==typeof i){const t=Number(i[e]);if(Number.isFinite(t)&&t>0)return t}const n=Number(i?.work??i?.reviewWork??i?.value);return Number.isFinite(n)&&n>0?n:1}function be(t,e){if("function"==typeof e){const i=e(t);if(null!=i&&(i+"").length>0)return i+""}else if(e){const i=ve(t.datum,e),n=ve(t,e),o=i??n;if(null!=o&&(o+"").length>0)return o+""}return t.id}function xe(t,e){if(0===t.length)return 0;if(1===t.length)return t[0];const i=Math.max(0,Math.min(1,e))*(t.length-1),n=Math.floor(i);return t[n]+(t[Math.ceil(i)]-t[n])*(i-n)}function ve(t,e){if(!e)return;let i=t;for(const t of e.split(".")){if(null==i||"object"!=typeof i)return;i=i[t]}return i}function we(t,e){if(!e)return!0;if("function"==typeof e)return e(t);const i=ve(t,e.property);return!("equals"in e&&!Object.is(i,e.equals)||"notEquals"in e&&Object.is(i,e.notEquals)||e.oneOf&&!e.oneOf.some(t=>Object.is(i,t))||e.notOneOf&&e.notOneOf.some(t=>Object.is(i,t)))}function Ie(t){const e=t.regionId,i=Math.max(0,t.unitsPerSecond),n=t.queueLayout??"lane",o=t.queueSlotSpacing??14,r=t.queueStiffness??.35,s=Number.isFinite(t.maxQueue)?Math.max(0,Math.floor(Number(t.maxQueue))):1/0,a=Math.max(.25,t.metricWindowSeconds??30),c=Math.max(1/60,t.snapshotIntervalSeconds??.25),d=t.releaseImpulse??{x:90,y:0},l=new Map,u=new Map,h=new Map,p=new Map,m=new Map,f=new Map,y=new Map,g=[];let b=0,x=new Map,v=new Map,w=0,I=0,M=0,k=null,S=0,A=0,R=0,P=0,C=0,$=0,j=0,B=0,O=0,N=0,T=0,E=0,q=-1,F=!1;function W(t,i){const n=i(t);return!!n&&n.activeRegionIds.includes(e)}function D(){E+=1}function z(t){return{bodyId:t.bodyId,jobId:t.jobId,visitId:t.visitId,visit:t.visit,regionId:e,work:t.total,queuedAt:t.queuedAt}}function L(i,n,o,r){const s={bodyId:i.id,jobId:n.jobId,visitId:n.visitId,visit:n.visit,remaining:n.work,total:n.work,queuedAt:n.queuedAt,sequence:r};return l.set(n.jobId,s),y.delete(i.id),f.set(i.id,n.jobId),A+=1,R+=n.work,D(),function(i,n,o){const r=z(n);t.onQueued?.(i,r),o.controls.recordObservation({type:"physics-capacity-queued",bodyId:i.id,datum:i.datum,x:i.x,y:i.y,regionId:e,work:n.total,jobId:n.jobId,visitId:n.visitId,visit:n.visit,queuedAt:n.queuedAt,queueDepth:l.size})}(i,s,o),s}function Y(t){if(l.size>=s||0===u.size)return;const e=Array.from(u.values()).sort((t,e)=>t.sequence-e.sequence);for(const i of e){if(l.size>=s)break;const e=m.get(i.jobId);e&&h.has(i.jobId)?(u.delete(i.jobId),y.delete(i.bodyId),L(e,i,t,i.sequence)):u.delete(i.jobId)}}function _(){let t=0;for(const e of l.values())t+=e.remaining;return t}function H(){O=Math.max(O,l.size),N=Math.max(N,_())}function X(){const t=M-a,e=Math.max(0,Math.min(a,M-(k??M)));let n=0,o=0,r=0,s=0,c=0;for(const e of g){if(t>e.end)continue;n+=e.arrivals,o+=e.arrivalWork,r+=e.completions,s+=e.completedWork;const i=e.end-e.start;c+=i>0&&t>e.start?e.processedWork*Math.min(1,Math.max(0,e.end-t)/i):e.processedWork}const d=e>0?o/e:0;return{seconds:e,arrivals:n,arrivalWork:o,completions:r,completedWork:s,processedWork:c,arrivalsPerSecond:e>0?n/e:0,throughputPerSecond:e>0?r/e:0,utilization:e>0&&i>0?Math.max(0,Math.min(1,c/(i*e))):0,pressure:i>0?d/i:0}}return{id:t.id??"capacity-queue:"+e,continuous:!1!==t.continuous,tick:n=>{const o=n.controls.readBodies(),r=new Map,A=new Map;for(const e of o){if(r.set(e.id,e),!W(e.id,n.getRegionState))continue;if(!we(e,t.bodyFilter))continue;const i=be(e,t.jobKey),o=A.get(i)??[];o.push(e),A.set(i,o)}const R=Number.isFinite(n.dt)?Math.max(0,n.dt):0;if(!F){const t=Number.isFinite(n.elapsed)?Math.max(0,n.elapsed):R;M=Math.max(0,t-R),F=!0}const O=M,N=O+R;M=N,k=null==k?O:Math.min(k,O);const E={start:O,end:N,arrivals:0,arrivalWork:0,completions:0,completedWork:0,processedWork:0},_=new Map;for(const[t,e]of A){const i=h.get(t)?.bodyId,n=e.find(t=>t.id===i)??e[0];_.set(t,n),m.set(t,n)}for(const[i,o]of h){if(_.has(i))continue;const s=l.get(i),a=r.get(o.bodyId)??m.get(i);if(s){l.delete(i),f.delete(s.bodyId),j+=1,B+=s.remaining,D();const r={...z(s),abandonedAt:M,remainingWork:s.remaining,queueSeconds:Math.max(0,M-s.queuedAt)};a&&t.onAbandoned?.(a,r),n.controls.recordObservation({type:"physics-capacity-abandoned",bodyId:o.bodyId,datum:a?.datum,x:a?.x,y:a?.y,regionId:e,work:s.total,remainingWork:s.remaining,jobId:i,visitId:s.visitId,visit:s.visit,queuedAt:s.queuedAt,abandonedAt:M,queueSeconds:r.queueSeconds,queueDepth:l.size})}u.delete(i),y.delete(o.bodyId),h.delete(i),m.delete(i)}for(const[i,o]of _){if(h.has(i))continue;const r=(p.get(i)??0)+1;p.set(i,r);const a=ge(o,t.unitAccessor),c={bodyId:o.id,jobId:i,visitId:`${e}:${i}:${r}`,visit:r,regionId:e,work:a,queuedAt:M};h.set(i,c),S+=1,E.arrivals+=1,E.arrivalWork+=a;const d=b++;if(s>l.size)L(o,c,n,d);else{const s={...c,blockedAt:M,sequence:d};u.set(i,s),y.set(o.id,i),$+=1,D(),t.onBlocked?.(o,s),n.controls.recordObservation({type:"physics-capacity-blocked",bodyId:o.id,datum:o.datum,x:o.x,y:o.y,regionId:e,work:a,jobId:i,visitId:c.visitId,visit:r,queuedAt:M,blockedAt:M,queueDepth:l.size,blockedDepth:u.size})}}Y(n),H();const X=Array.from(l.values()).sort((t,e)=>t.sequence-e.sequence);let G=i*R;for(const i of X){if(0>=G)break;const o=Math.min(i.remaining,G);if(i.remaining-=o,G-=o,P+=o,E.processedWork+=o,i.remaining>1e-6)continue;l.delete(i.jobId),f.delete(i.bodyId),I+=1,C+=i.total,E.completions+=1,E.completedWork+=i.total;const s=Math.max(0,M-i.queuedAt);T+=s,D();const a=r.get(i.bodyId);if(!a)continue;n.controls.applyImpulse(i.bodyId,d.x??0,d.y??0);const c={...z(i),completedAt:M,queueSeconds:s};t.onProcessed?.(a,c),n.controls.recordObservation({type:"physics-capacity-processed",bodyId:i.bodyId,datum:a.datum,x:a.x,y:a.y,regionId:e,work:i.total,jobId:i.jobId,visitId:i.visitId,visit:i.visit,queuedAt:i.queuedAt,completedAt:M,queueSeconds:s,queueDepth:l.size})}Y(n),H(),function(){const t=Array.from(l.values()).sort((t,e)=>t.sequence-e.sequence);x=new Map(t.map((t,e)=>[t.bodyId,e]));const e=Array.from(u.values()).sort((t,e)=>t.sequence-e.sequence);v=new Map(e.map((t,e)=>[t.bodyId,e])),w=t.length}(),function(t){(t.end>t.start||t.arrivals>0||t.completions>0||t.processedWork>0)&&g.push(t);const e=M-a;for(;g.length>0&&e>g[0].end;)g.shift()}(E);const V=Math.floor(M/c);V!==q&&(q=V,D())},getSnapshot:()=>{const t=_(),n=function(){let t=0;for(const e of u.values())t+=e.work;return t}(),o=l.size,r=Array.from(l.values()).map(t=>Math.max(0,M-t.queuedAt)).sort((t,e)=>t-e),s=r.reduce((t,e)=>t+e,0);return{regionId:e,queueDepth:o,processedCount:I,unitsPerSecond:i,remainingWork:t,meanRemainingWork:o>0?t/o:0,waitingWork:t+n,blockedDepth:u.size,blockedWork:n,arrivalCount:S,admittedCount:A,admittedWork:R,processedWork:P,completedWork:C,blockedCount:$,abandonedCount:j,abandonedWork:B,peakQueueDepth:O,peakRemainingWork:N,queueAge:{count:r.length,meanSeconds:r.length>0?s/r.length:0,p50Seconds:xe(r,.5),p95Seconds:xe(r,.95),oldestSeconds:r.at(-1)??0},meanCompletedQueueSeconds:I>0?T/I:0,window:X(),simulatedAt:M,metricRevision:E}},bodyForce:t=>{if("none"===n)return null;const i=f.get(t.body.id),s=y.get(t.body.id),a=i?l.get(i):void 0,c=s?u.get(s):void 0;if(!a&&!c)return null;const d=a?x.get(t.body.id):v.get(t.body.id);if(null==d)return null;let h;const p=t.regions;if(p)for(let t=0;p.length>t;t+=1)if(p[t].id===e){const e=p[t].shape;e&&"aabb"===e.type&&(h=e);break}return h?{x:((c?h.x-.44*h.width:h.x-.22*h.width-d*(.15*o))-t.body.x)*r,y:(h.y-(d-((c?u.size:w)-1)/2)*o/Math.max(1,Math.sqrt(c?u.size:w))-t.body.y)*r*.85}:{x:8*-Math.sign(t.body.vx||1),y:0}}}}function Me(t,e){if(!e)return;let i=t;for(const t of e.split(".")){if(null==i||"object"!=typeof i)return;i=i[t]}return i}function ke(t,e){if(!e)return!0;if("function"==typeof e)return e(t);const i=Me(t,e.property);return!("equals"in e&&!Object.is(i,e.equals)||"notEquals"in e&&Object.is(i,e.notEquals)||e.oneOf&&!e.oneOf.some(t=>Object.is(i,t))||e.notOneOf&&e.notOneOf.some(t=>Object.is(i,t)))}function Se(t){const e=t.resources.map(t=>({...t,bodyId:t.bodyId??t.id})),i=new Map(e.map(t=>[t.bodyId,t])),n=new Map,o=new Map,r=t.assignmentForce??.45,s=t.returnForce??.35,a=t.caseAttraction??.08,c=t.assignmentOffset??{x:0,y:0};let d=new Map,l=0,u=0;return{id:t.id??"service-resource-pool",continuous:!0,assign:t=>{const i=n.get(t);if(i)return i;const r=e.find(t=>!o.has(t.id));if(!r)return null;const s={resourceId:r.id,resourceBodyId:r.bodyId,caseBodyId:t,assignedAt:l};return n.set(t,s),o.set(r.id,s),u+=1,s},release:t=>{const e=n.get(t);return!!e&&(n.delete(t),o.delete(e.resourceId),u+=1,!0)},getAssignment:t=>n.get(t),tick:t=>{l=Math.max(l,t.elapsed),d=new Map(t.controls.readBodies().map(t=>[t.id,t]));for(const[t,e]of n)d.has(t)&&d.has(e.resourceBodyId)||(n.delete(t),o.delete(e.resourceId),u+=1)},getSnapshot:()=>({total:e.length,available:e.length-o.size,assigned:o.size,assignments:Array.from(n.values()),simulatedAt:l,metricRevision:u}),bodyForce:t=>{const e=i.get(t.body.id);if(e){const i=o.get(e.id),n=i?d.get(i.caseBodyId):void 0,a=i?r:s;return{x:((n?n.x+(c.x??0):e.home.x)-t.body.x)*a,y:((n?n.y+(c.y??0):e.home.y)-t.body.y)*a}}const l=n.get(t.body.id);if(!l||0>=a)return null;const u=d.get(l.resourceBodyId);return u?{x:(u.x-t.body.x)*a,y:(u.y-t.body.y)*a}:null}}}function Ae(t,e){const i="function"==typeof e.deadlineAccessor?e.deadlineAccessor(t):Me(t.datum,e.deadlineAccessor)??Me(t,e.deadlineAccessor);return Number.isFinite(Number(i))?Math.max(0,Number(i)):0}function Re(t){const e=new Map;let i=0,n=0;function o(i){e.set(i.bodyId,i),n+=1,t.onStateChange?.({...i})}function r(t){const n=e.get(t);return!(!n||null!=n.completedAt||(o({...n,completedAt:i,state:"unhappy"===n.state?"resolved-unhappy":"resolved"}),0))}return{id:t.id??"service-level",continuous:!0,protect:t=>{const n=e.get(t);return!(!n||null!=n.completedAt||"unhappy"===n.state||(o({...n,state:"protected",protectedAt:i}),0))},complete:r,getCase:t=>e.get(t),tick:n=>{i=Math.max(i,n.elapsed);for(const s of n.controls.readBodies()){if(!ke(s,t.bodyFilter))continue;if(!e.has(s.id)){const e=Ae(s,t);o({bodyId:s.id,openedAt:i,deadlineAt:i+e,state:"waiting"})}const a=e.get(s.id);a&&null==a.completedAt&&(t.completionRegionId&&n.getRegionState(s.id)?.activeRegionIds.includes(t.completionRegionId)?r(s.id):"waiting"!==a.state||a.deadlineAt>i||o({...a,state:"unhappy"}))}},getSnapshot:()=>{const t=Array.from(e.values()),o=e=>t.filter(t=>t.state===e).length;return{total:t.length,waiting:o("waiting"),protected:o("protected"),unhappy:o("unhappy"),resolved:o("resolved"),resolvedUnhappy:o("resolved-unhappy"),simulatedAt:i,metricRevision:n}}}}function Pe(t){const e=new Set;let i=0,n=0,o=0,r=!1;return{id:t.id??"dependency-gate:"+t.regionId,continuous:!0,tick:s=>{i=Math.max(i,s.elapsed);const a=r;var c;c=i,r=t.isOpen?t.isOpen(c):null!=t.opensAt&&c>=t.opensAt;const d=s.controls.readBodies(),l=new Map(d.map(t=>[t.id,t]));for(const i of d){const n=s.getRegionState(i.id)?.activeRegionIds.includes(t.regionId);n&&ke(i,t.bodyFilter)&&(r||e.has(i.id)||(e.add(i.id),o+=1,t.onHeld?.(i)))}if(r&&!a){for(const i of e){const e=l.get(i);e&&(s.controls.applyImpulse(i,t.releaseImpulse?.x??86,t.releaseImpulse?.y??0),n+=1,t.onReleased?.(e))}e.clear(),o+=1}for(const t of e)l.has(t)||(e.delete(t),o+=1)},getSnapshot:()=>({regionId:t.regionId,isOpen:r,blocked:e.size,released:n,simulatedAt:i,metricRevision:o}),bodyForce:i=>{if(r||!e.has(i.body.id))return null;const n=i.regions?.find(e=>e.id===t.regionId),o=n?.shape;if(!o||"aabb"!==o.type)return{x:.8*-i.body.vx,y:.8*-i.body.vy};const s=t.holdForce??.4;return{x:(o.x-i.body.x)*s-.45*i.body.vx,y:(o.y-i.body.y)*s-.45*i.body.vy}}}}function Ce(t,e){return t||e?{x:(t?.x??0)+(e?.x??0),y:(t?.y??0)+(e?.y??0)}:null}function $e(t){if(!t?.length)return null;const e=t.slice(),i=e.some(t=>!1!==t.continuous);return{controllers:e,continuous:i,onTick:(t,i,n)=>{const o={result:t,controls:i,dt:n.dt,elapsed:n.elapsed,getRegionState:n.getRegionState};for(const t of e)t.tick(o)},bodyForce:t=>{let i=null;for(const n of e)n.bodyForce&&(i=Ce(i,n.bodyForce(t)));return i}}}function je(t){const e=new Set,i=t.impulse??{x:-60,y:0};return{id:t.id??"portal:"+t.fromRegionId,continuous:!0===t.continuous,tick:n=>{const o=n.controls.readBodies();for(const r of o){const o=n.getRegionState(r.id),s=o?.activeRegionIds.includes(t.fromRegionId);s?e.has(r.id)||(e.add(r.id),n.controls.applyImpulse(r.id,i.x??0,i.y??0),t.onPortal?.(r)):e.delete(r.id)}}}}import*as Be from"react";import{forwardRef as Oe,memo as Ne,useCallback as Te,useEffect as Ee,useImperativeHandle as qe,useId as Fe,useRef as We}from"react";var De={names:["--semiotic-bg","--surface-1","--surface-0"],fallback:"#f8fafc"},ze={names:["--semiotic-border","--surface-3"],fallback:"#334155"},Le={names:["--semiotic-danger","--viz-4"],fallback:"#dc2626"},Ye={names:["--semiotic-focus","--accent","--viz-9"],fallback:"#f97316"},_e={names:["--semiotic-grid","--surface-3"],fallback:"#cbd5e1"},He={names:["--semiotic-primary","--accent","--viz-5"],fallback:"#0ea5e9"},Xe={names:["--semiotic-success","--viz-2"],fallback:"#22c55e"},Ge={names:["--semiotic-text","--text-primary"],fallback:"#0f172a"},Ve={names:["--semiotic-text-secondary","--text-secondary"],fallback:"#475569"},Ue={names:["--semiotic-warning","--viz-9","--viz-3"],fallback:"#f97316"};function Ke(t,e){const i=t.canvas;if("function"!=typeof getComputedStyle||!i)return e.fallback;const n=getComputedStyle(i);for(const i of e.names){const e=n.getPropertyValue(i).trim();if(e)return R(t,e)??e}return e.fallback}function Qe(t,e){const i=Math.max(0,Math.min(1,e)),n=t.trim(),o=n.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);if(o){const[,t,e,n]=o;return Qe(`#${t}${t}${e}${e}${n}${n}`,i)}const r=n.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(r){const[,t,e,n]=r;return`rgba(${parseInt(t,16)}, ${parseInt(e,16)}, ${parseInt(n,16)}, ${i})`}const s=n.match(/^rgb\s*\(\s*([^)]+?)\s*\)$/i);if(s)return`rgba(${s[1]}, ${i})`;const a=n.match(/^rgba\s*\(\s*([^,]+,\s*[^,]+,\s*[^,]+),\s*[^)]+\)$/i);return a?`rgba(${a[1]}, ${i})`:n}function Ze(t){return"number"==typeof t&&Number.isFinite(t)?t:void 0}function Je(t,e){const i="sensor"===t.physics?e.sensorThickness:e.barrierThickness;return Math.max(0,Ze(t.thickness)??Ze(i)??Ze(e.thickness)??4)}var ti=2500;function ei(t){return"function"==typeof t}function ii(t){return void 0===t||!1===t||!ei(t.binAccessor)&&!ei(t.labelAccessor)&&!ei(t.valueAccessor)}function ni(t){if(void 0!==t){if(!1===t)return!1;if(!ii(t))throw new TypeError("Physics worker sediment config only supports string or numeric accessors");return{binAccessor:"string"==typeof t.binAccessor?t.binAccessor:void 0,labelAccessor:"string"==typeof t.labelAccessor?t.labelAccessor:void 0,valueAccessor:"string"==typeof t.valueAccessor||"number"==typeof t.valueAccessor?t.valueAccessor:void 0,retainBodyIds:t.retainBodyIds}}}function oi(t){if(t)return{chartId:t.chartId,chartType:t.chartType,sensors:t.sensors}}function ri(t){return function(t){return!ei(t?.timeAccessor)}(t)}function si(t={}){if(t.engine)throw new TypeError("Physics workers use the built-in kernel adapter");const{engine:e,observation:i,sediment:n,...o}=t;return{...o,observation:oi(i),sediment:ni(n)}}function ai(){if("undefined"!=typeof DOMException)return new DOMException("Physics worker request aborted","AbortError");const t=Error("Physics worker request aborted");return t.name="AbortError",t}var ci=class{constructor(t=function(){const t="string"==typeof import.meta.url&&import.meta.url?new URL("./physicsWorker.js",import.meta.url):n("physicsWorker.js");return new Worker(t,{type:"module",name:"semiotic-physics"})}()){this.nextRequestId=1,this.pending=new Map,this.worker=t,this.worker.onmessage=t=>{const e=t.data,i=this.pending.get(e.requestId);i&&(this.pending.delete(e.requestId),i.cleanup(),e.ok?i.resolve(e.payload):i.reject(function(t){const e=Error(t.error.message);return e.name=t.error.name??"Error",t.error.stack&&(e.stack=t.error.stack),e}(e)))},this.worker.onerror=t=>{this.rejectAll(Error(t.message||"Physics worker failed")),this.worker.terminate()}}request(t,e){if(e?.aborted)return Promise.reject(ai());const i=this.nextRequestId;this.nextRequestId+=1;const n={command:t,requestId:i};return new Promise((t,o)=>{const r=()=>{this.pending.delete(i),e?.removeEventListener("abort",r),o(ai())},s=()=>e?.removeEventListener("abort",r);this.pending.set(i,{cleanup:s,reject:o,resolve:t}),e?.addEventListener("abort",r,{once:!0});try{this.worker.postMessage(n)}catch(t){this.pending.delete(i),s(),o(t)}})}async init(t,e,i,n){if(!ri(i))throw new TypeError("Physics worker spawn pacing only supports string time accessors");const o=await this.request({type:"init",config:si(t),initialSpawns:e,initialSpawnPacing:i},n);if("frame"!==o.type)throw Error("Physics worker returned a non-frame init response");return o.frame}async restore(t,e){const i=await this.request({type:"restore",snapshot:t},e);if("frame"!==i.type)throw Error("Physics worker returned a non-frame restore response");return i.frame}async initFromSnapshot(t,e,i){const n=await this.request({type:"init",config:si(t),snapshot:e},i);if("frame"!==n.type)throw Error("Physics worker returned a non-frame init response");return n.frame}async enqueue(t,e,i){if(!ri(e))throw new TypeError("Physics worker spawn pacing only supports string time accessors");const n=await this.request({type:"enqueue",spawns:t,pacing:e},i);if("frame"!==n.type)throw Error("Physics worker returned a non-frame enqueue response");return n.frame}async tick(t,e){const i=await this.request({type:"tick",deltaSeconds:t},e);if("frame"!==i.type)throw Error("Physics worker returned a non-frame tick response");return i.frame}async settle(t,e){const i=await this.request({type:"settle",maxSteps:t},e);if("frame"!==i.type)throw Error("Physics worker returned a non-frame settle response");return i.frame}async snapshot(t){const e=await this.request({type:"snapshot"},t);if("snapshot"!==e.type)throw Error("Physics worker returned a non-snapshot response");return e.snapshot}async remove(t,e){const i=await this.request({type:"remove",ids:t},e);if("removed"!==i.type)throw Error("Physics worker returned a non-remove response");return{frame:i.frame,removed:i.removed}}terminate(){this.rejectAll(Error("Physics worker terminated")),this.worker.terminate()}rejectAll(t){for(const[e,i]of this.pending)this.pending.delete(e),i.cleanup(),i.reject(t)}};function di(t,e,i){const n=new ye(t);return e?.length&&(n.enqueue(e,i),n.materializeDueSpawns()),n}function li(){return"undefined"!=typeof performance?performance.now():Date.now()}import*as ui from"react-dom/server";function hi(t=[]){return t.map(t=>({id:t.id,label:t.label,count:t.count,...null!=t.secondary?{secondary:t.secondary}:{},...t.secondaryLabel?{secondaryLabel:t.secondaryLabel}:{},...null!=t.observed?{observed:t.observed}:{}}))}var pi={fill:"#4e79a7",stroke:"#172033",strokeWidth:1,opacity:.85};function mi(t){const e=t.datum;if(e&&"object"==typeof e){const t=e.label??e.name??e.id;if(null!=t&&""!==t)return t+""}return t.id}function fi(t,e){const i="function"==typeof e?e(t):e;return{...pi,...i??{}}}function yi(t,e={}){const i=t.settle(e.maxSteps),n=t.readBodies(),o=t.snapshot(),r=function(t,e={}){return t.map(t=>function(t,e={}){const i=function(t){return t.datum&&"object"==typeof t.datum?t.datum:null}(t),n={label:e.getBodyLabel?.(t)??mi(t)},o={style:fi(t,e.bodyStyle),datum:i,accessibleDatum:i,accessibility:n,_transitionKey:t.id};return"aabb"===t.shape.type?{type:"rect",x:t.x-t.shape.width/2,y:t.y-t.shape.height/2,w:t.shape.width,h:t.shape.height,...o}:{type:"point",x:t.x,y:t.y,r:t.shape.radius,pointId:t.id,...o}}(t,e))}(n,e),s=function(t,e={}){const i=e.bodies??function(t){return t.world.bodies.map(t=>({id:t.id,x:t.x,y:t.y,prevX:t.prevX,prevY:t.prevY,vx:t.vx,vy:t.vy,angle:t.angle,mass:t.mass,shape:{...t.shape},sleeping:t.sleeping,datum:t.datum}))}(t),n=i.filter(t=>t.sleeping).length;return{bodyCount:i.length,sleepingCount:n,settled:"settled"===t.simulationState&&0===t.queue.length&&n===i.length,stepsRun:Math.max(0,Math.floor(e.stepsRun??0)),seed:t.world.options.seed,binCounts:hi(e.projectionRows)}}(o,{bodies:n,projectionRows:e.projectionRows,stepsRun:i});return{snapshot:o,bodies:n,sceneNodes:r,evidence:s,stepsRun:i}}import{jsx as gi,jsxs as bi}from"react/jsx-runtime";var xi={top:0,right:0,bottom:0,left:0};function vi(t,e,i){return"function"==typeof t?t({size:e,margin:i}):t}import{useEffect as wi,useRef as Ii}from"react";function Mi(){return"undefined"==typeof document||!document.hidden}function ki(t,e,i){const n=y(t,i.fill)??"#4e79a7",o=i.stroke,r=i.strokeWidth??0,s=i.opacity??1,a=i.fillOpacity??1,c=function(t,e){const i=e.mark;if(i)return i;const n=t.datum,o=n?.__physicsMark??n?.mark;return"circle"===o||"halo"===o||"faceted"===o||"pill"===o||"diamond"===o||"square"===o?o:"circle"===t.shape.type?"circle":"square"}(e,i),d="circle"===e.shape.type?i.r??e.shape.radius:Math.max(e.shape.width,e.shape.height)/2;if(t.save(),t.globalAlpha*=s,t.beginPath(),"pill"===c||"square"===c||"aabb"===e.shape.type){const i="pill"===c?2.4*d:"aabb"===e.shape.type?e.shape.width:1.7*d,n="pill"===c?1.35*d:"aabb"===e.shape.type?e.shape.height:1.7*d,o=e.x-i/2,r=e.y-n/2,s="pill"===c?n/2:Math.min(4,i/4);t.moveTo(o+s,r),t.arcTo(o+i,r,o+i,r+n,s),t.arcTo(o+i,r+n,o,r+n,s),t.arcTo(o,r+n,o,r,s),t.arcTo(o,r,o+i,r,s),t.closePath()}else if("diamond"===c)t.moveTo(e.x,e.y-d),t.lineTo(e.x+d,e.y),t.lineTo(e.x,e.y+d),t.lineTo(e.x-d,e.y),t.closePath();else if("faceted"===c){const i=6;for(let n=0;i>n;n+=1){const o=2*Math.PI*n/i-Math.PI/2,r=e.x+Math.cos(o)*d,s=e.y+Math.sin(o)*d;0===n?t.moveTo(r,s):t.lineTo(r,s)}t.closePath()}else t.arc(e.x,e.y,d,0,2*Math.PI);n&&(t.save(),t.globalAlpha*=a,t.fillStyle=n,t.fill(),t.restore()),"halo"===c&&(t.beginPath(),t.arc(e.x,e.y,1.35*d,0,2*Math.PI),t.strokeStyle=o??n,t.lineWidth=Math.max(1.5,r||1.5),t.globalAlpha*=.55,t.stroke(),t.globalAlpha/=.55),o&&r>0&&(t.strokeStyle=o,t.lineWidth=r,i.strokeDasharray&&t.setLineDash(i.strokeDasharray.split(/[,\s]+/).map(t=>Number(t)).filter(t=>Number.isFinite(t))),t.stroke()),t.restore()}function Si(t){return"circle"===t.shape.type?t.shape.radius:Math.max(t.shape.width,t.shape.height)/2}function Ai(t){return t.sensorId??"stream-region-"+t.id}function Ri(t){const e=Ai(t),i={bodyFilter:t.bodyFilter,friction:t.friction,restitution:t.restitution};if("boundary"===t.collider&&"aabb"===t.shape.type){const n=t.colliderThickness??8,o=t.shape.x-t.shape.width/2,r=t.shape.x+t.shape.width/2,s=t.shape.y-t.shape.height/2,a=t.shape.y+t.shape.height/2;return[{...i,id:e+"-top",shape:{type:"segment",x1:o,y1:s,x2:r,y2:s,thickness:n}},{...i,id:e+"-right",shape:{type:"segment",x1:r,y1:s,x2:r,y2:a,thickness:n}},{...i,id:e+"-bottom",shape:{type:"segment",x1:r,y1:a,x2:o,y2:a,thickness:n}},{...i,id:e+"-left",shape:{type:"segment",x1:o,y1:a,x2:o,y2:s,thickness:n}}]}return t.collider?[{...i,id:e+"-collider",shape:t.shape}]:[]}function Pi(t){if(t)return{activeRegionIds:Array.from(t.activeRegionIds),regionIds:Array.from(t.regionIds),charges:{...t.charges},attributes:{...t.attributes},energy:t.energy}}function Ci(t,e){const i="function"==typeof t?t(e):t;if(!i)return null;const n=Number(i.x??0),o=Number(i.y??0);return Number.isFinite(n)||Number.isFinite(o)?{x:Number.isFinite(n)?n:0,y:Number.isFinite(o)?o:0}:null}function $i(t){if(!1===t.semanticItem)return null;const e=t.shape,i=t.semanticItem??{},n="aabb"===e.type?{id:t.id,label:t.label??t.id,description:t.description,group:t.kind??"region",x:e.x,y:e.y,width:e.width,height:e.height}:{id:t.id,label:t.label??t.id,description:t.description,group:t.kind??"region",x:(e.x1+e.x2)/2,y:(e.y1+e.y2)/2,pathData:`M ${e.x1} ${e.y1} L ${e.x2} ${e.y2}`};return{...n,...i,id:i.id??n.id}}function ji(t){return t.some(t=>null!=t.force||null!=t.damping||null!=t.impulseOnEnter||null!=t.impulseOnExit)}function Bi(t,e){const i="function"==typeof t?t(e):t;if(!i)return null;const n=Number(i.x??0),o=Number(i.y??0);return Number.isFinite(n)||Number.isFinite(o)?{x:Number.isFinite(n)?n:0,y:Number.isFinite(o)?o:0}:null}var Oi=[];function Ni(t){const e=t.store.controls(),i=t.store.snapshot(),n=Math.max(0,t.result.steps*(i.config.fixedDt||1/60)),o=function(t,e,i,n){const o=Number.isFinite(n)?Math.max(0,n):0;if(0>=o||!ji(e))return!1;const r=new Map(e.map(t=>[t.id,t])),s=t.readBodies();let a=!1;for(const e of s){const n=i.get(e.id);if(!n||!n.activeRegionIds.size)continue;const s=Pi(n);if(s)for(const i of n.activeRegionIds){const n=r.get(i);if(!n)continue;const c=Ci(n.force,{body:e,region:n,regionState:s}),d=Number(n.damping??0),l=(c?.x??0)*o-(Number.isFinite(d)?e.vx*d*o:0),u=(c?.y??0)*o-(Number.isFinite(d)?e.vy*d*o:0);(l||u)&&(t.applyImpulse(e.id,l,u),a=!0)}}return a}(e,t.regionEffects,t.regionState,n),r=function(t,e,i,n,o,r){const s=Number.isFinite(r)?Math.max(0,r):0;if(0>=s||!e)return!1;const a=new Map(i.map(t=>[t.id,t])),c=t.readBodies();let d=!1;for(let i=0;c.length>i;i+=1){const r=c[i],l=n.get(r.id),u=Pi(l);let h=Oi;if(l&&l.activeRegionIds.size>0){const t=[];for(const e of l.activeRegionIds){const i=a.get(e);i&&t.push(i)}h=t}const p=Bi(e,{body:r,bodies:c,index:i,regionState:u,regions:h,simulationState:o});if(!p)continue;const m=(p.x??0)*s,f=(p.y??0)*s;(m||f)&&(t.applyImpulse(r.id,m,f),d=!0)}return d}(e,t.bodyForces,t.regionEffects,t.regionState,i.simulationState,n);return t.composed&&t.composed.onTick(t.result,e,{dt:n,elapsed:t.result.elapsedSeconds,getRegionState:e=>Pi(t.regionState.get(e))}),t.onTick?.(t.result,e),{regionEffectsApplied:o,bodyForcesApplied:r,snapshot:i}}function Ti(t,e,i,n,o,r,s,a,c,d){const l=function(t,e){return!!e?.isActive&&(e.predicate?.(t)??!0)}(t,o),u={selected:l,simulationState:e,regionState:r,regions:s},h="function"==typeof i?i(t,u):i,p=s.reduce((e,i)=>i.bodyStyle?{...e,..."function"==typeof i.bodyStyle?i.bodyStyle(t,u):i.bodyStyle}:e,{}),m=l?"function"==typeof n?n(t,u):n:void 0;return{fill:d?.color??a,stroke:d?.stroke??c,strokeWidth:d?.strokeWidth??1,opacity:d?.opacity??.9,...h,...p,...m}}import{useCallback as Ei}from"react";import*as qi from"react";import{jsx as Fi,jsxs as Wi}from"react/jsx-runtime";var Di={border:0,clip:"rect(0 0 0 0)",height:1,margin:-1,overflow:"hidden",padding:0,position:"absolute",whiteSpace:"nowrap",width:1},zi="semiotic-accessible-data-table",Li=zi+" semiotic-accessible-data-table-hidden",Yi=zi+" semiotic-accessible-data-table-visible",_i={position:"absolute",top:0,left:0,right:0,zIndex:"var(--semiotic-data-table-z-index, var(--semiotic-overlay-z-index, 20))",padding:"14px 16px 12px",borderBottom:"1px solid var(--semiotic-data-table-border, var(--semiotic-border, #e0e0e0))",fontFamily:"var(--semiotic-font-family, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif)",fontSize:13,lineHeight:1.5,color:"var(--semiotic-data-table-text, var(--semiotic-text, #333))",background:"var(--semiotic-data-table-bg, var(--semiotic-surface, var(--semiotic-bg, #fff)))",borderRadius:"var(--semiotic-border-radius, 0px) var(--semiotic-border-radius, 0px) 0 0"},Hi={marginBottom:8,paddingRight:28,color:"var(--semiotic-data-table-muted-text, var(--semiotic-text-secondary, #666))",fontSize:12,letterSpacing:"0.01em"},Xi={position:"absolute",top:10,right:10,width:22,height:22,display:"flex",alignItems:"center",justifyContent:"center",border:"1px solid var(--semiotic-data-table-border, var(--semiotic-border, #e0e0e0))",background:"var(--semiotic-data-table-bg, var(--semiotic-surface, var(--semiotic-bg, #fff)))",cursor:"pointer",color:"var(--semiotic-data-table-muted-text, var(--semiotic-text-secondary, #666))",fontSize:13,lineHeight:1,padding:0,borderRadius:"var(--semiotic-border-radius, 4px)"},Gi={width:"100%",borderCollapse:"collapse",fontSize:12,marginTop:4,fontVariantNumeric:"tabular-nums"},Vi={textAlign:"left",padding:"5px 10px",borderBottom:"2px solid var(--semiotic-data-table-border, var(--semiotic-border, #e0e0e0))",fontWeight:600,fontSize:11,textTransform:"uppercase",letterSpacing:"0.04em",color:"var(--semiotic-data-table-muted-text, var(--semiotic-text-secondary, #666))"},Ui={padding:"4px 10px",borderBottom:"1px solid var(--semiotic-data-table-border, var(--semiotic-border, #e0e0e0))"},Ki={textAlign:"left",fontSize:11,color:"var(--semiotic-data-table-muted-text, var(--semiotic-text-secondary, #666))",marginBottom:4,fontStyle:"italic"},Qi={marginTop:8,padding:"4px 10px",fontSize:12,cursor:"pointer",border:"1px solid var(--semiotic-data-table-border, var(--semiotic-border, #e0e0e0))",borderRadius:"var(--semiotic-border-radius, 4px)",background:"var(--semiotic-data-table-bg, var(--semiotic-surface, var(--semiotic-bg, #fff)))",color:"var(--semiotic-data-table-text, var(--semiotic-text, #333))",fontFamily:"inherit"};function Zi(t){return null==t?null:"string"==typeof t||"number"==typeof t||"boolean"==typeof t?t+"":null}function Ji(t){return{__semioticHoverData:!0,body:t,data:t.datum??t,id:t.id,type:"body",x:t.x,y:t.y}}function tn(t){if("circle"===t.shape.type){const e=Math.max(4,2*t.shape.radius);return{height:e,shape:"circle",width:e}}return{height:t.shape.height,shape:"rect",width:t.shape.width}}function en(t){const e=t.datum;if(e&&"object"==typeof e){const t=e.label??e.name??e.id;if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return t+""}return t.id}function nn(t){const e=on(t.datum??t);return e.length?e.map(([t,e])=>`${t}: ${e}`).join(", "):"Physics body "+t.id}function on(t){return t&&"object"==typeof t?Object.entries(t).map(([t,e])=>{if(t.startsWith("_"))return null;const i=Zi(e);return null==i?null:[t,i]}).filter(t=>null!=t).slice(0,8):[]}function rn({hover:t}){const e=on(t.data);return Wi("div",{className:"semiotic-tooltip",style:b,children:[Fi("div",{style:{fontWeight:700,marginBottom:e.length?4:0},children:t.id}),e.map(([t,e])=>Wi("div",{children:[Wi("span",{style:{opacity:.72},children:[t,": "]}),Fi("span",{children:e})]},t))]})}function sn(t){return t.datum&&"object"==typeof t.datum?Object.entries(t.datum).map(([t,e])=>{const i=Zi(e);return null==i?null:`${t}: ${i}`}).filter(t=>null!=t).slice(0,8).join(", "):""}function an(t){const e=[`${t.length} semantic item${1===t.length?"":"s"}.`],i=new Map;for(const e of t)e.group&&i.set(e.group,(i.get(e.group)??0)+1);return i.size&&e.push(Array.from(i).map(([t,e])=>`${t}: ${e}`).join(", ")),e.join(" ")}function cn(t){const{chartTitle:e,items:i,tableId:n}=t,[o,r]=qi.useState(!1),[s,a]=qi.useState(5),c=j(),d=c?.visible??!1,l=o||d,u=qi.useRef(null),h="Data summary for "+(e??"physics chart");qi.useEffect(()=>{l||a(5)},[l]);const p=qi.useCallback(t=>{t.target===t.currentTarget&&(o||d||r(!0))},[o,d]),m=qi.useCallback(t=>{d||u.current?.contains(t.relatedTarget)||r(!1)},[d]);if(!i.length)return Fi("span",{id:n,tabIndex:-1,style:Di});if(!l)return Fi("div",{id:n,className:Li,role:"region","aria-label":h,tabIndex:-1,style:Di,onFocus:p,children:Wi("button",{type:"button",onClick:()=>r(!0),children:["View data summary (",i.length," semantic items)"]})});const f=Math.min(s,i.length),y=i.slice(0,f),g=i.length-f;return Wi("div",{ref:u,id:n,className:Yi,role:"region","aria-label":h,tabIndex:-1,onBlur:m,style:_i,children:[Fi("button",{type:"button",className:"semiotic-accessible-data-table-close","aria-label":"Close data summary",onClick:()=>{d&&c&&c.setVisible(!1),r(!1)},style:Xi,children:"×"}),Fi("div",{className:"semiotic-accessible-data-table-summary",role:"note",style:Hi,children:an(i)}),Wi("table",{className:"semiotic-accessible-data-table-table",role:"table","aria-label":"Semantic items for "+(e??"physics chart"),style:Gi,children:[Fi("caption",{className:"semiotic-accessible-data-table-caption",style:Ki,children:g>0?`First ${f} of ${i.length} semantic items`:`All ${i.length} semantic items`}),Fi("thead",{children:Wi("tr",{children:[Fi("th",{scope:"col",style:Vi,children:"Item"}),Fi("th",{scope:"col",style:Vi,children:"Description"}),Fi("th",{scope:"col",style:Vi,children:"Group"}),Fi("th",{scope:"col",style:Vi,children:"Position"}),Fi("th",{scope:"col",style:Vi,children:"Data"})]})}),Fi("tbody",{children:y.map((t,e)=>Wi("tr",{children:[Fi("th",{scope:"row",style:Ui,children:t.label}),Fi("td",{style:Ui,children:t.description??t.label}),Fi("td",{style:Ui,children:t.group??""}),Wi("td",{style:Ui,children:[Math.round(t.x),", ",Math.round(t.y)]}),Fi("td",{style:Ui,children:sn(t)})]},t.id??`${t.label}-${e}`))})]}),g>0?Wi("button",{type:"button",className:"semiotic-accessible-data-table-show-more",onClick:()=>a(t=>t+25),style:Qi,children:["Show ",Math.min(25,g)," more"," ",1===g?"row":"rows"," (",g," remaining)"]}):null]})}rn.ownsChrome=!0;import{jsx as dn,jsxs as ln}from"react/jsx-runtime";var un=[640,360],hn={top:0,right:0,bottom:0,left:0},pn=new Set(["ArrowRight","ArrowLeft","ArrowUp","ArrowDown","Home","End","PageUp","PageDown"]),mn="StreamPhysicsFrame",fn=Ne(Oe(function(t,e){const{accessibleTable:i=!0,annotations:n,onAnnotationActivate:o,autoPlaceAnnotations:r,background:s,backgroundGraphics:m,bodySemanticItemLimit:f=200,bodySemanticItems:y=!1,bodySemanticUpdateMs:g=200,bodyForces:b,bodyStyle:x,chartId:M,className:S,frameScheduler:A,clock:R,random:P,seed:C,color:$,config:j,controllers:N,continuous:q=!1,description:F,emphasis:W,chartMode:D,enableHover:z=!0,foregroundGraphics:L,hoverRadius:H=16,initialSpawns:X,initialSpawnPacing:G,legend:V,legendClickBehavior:U,legendHighlightedCategory:K,legendHoverBehavior:Q,legendIsolatedCategories:J,legendLayout:tt,legendPosition:it,margin:nt,onClick:ot,onObservation:rt,onRegionEvent:st,onSimulationExecutionChange:at,onBodyHover:ct,onBodyPointerDown:dt,onSemanticItemActivate:lt,onSemanticItemFocus:ut,onTick:ht,opacity:pt,paused:mt=!1,regionEffects:ft=[],responsiveHeight:yt,responsiveWidth:gt,selectedBodyStyle:bt={stroke:"#111827",strokeWidth:2,opacity:1},selection:xt,semanticItems:vt=[],simulationExecution:wt="auto",size:It=un,stroke:Mt,strokeWidth:kt,summary:St,suspendWhenHidden:At=!0,svgAnnotationRules:Rt,title:Pt,tooltipContent:Ct,workerBodyThreshold:$t=ti,renderBody:jt,beforePaint:Bt,afterPaint:Ot}=t,Nt=Be.useMemo(()=>({color:$,stroke:Mt,strokeWidth:kt,opacity:pt}),[$,pt,Mt,kt]),Tt=We(rt);Tt.current=rt;const Et=We(M);Et.current=M;const qt=We(new Map),Ft=We(ft);Ft.current=ft;const Wt=We(b);Wt.current=b;const Dt=We(ht);Dt.current=ht;const zt=Be.useMemo(()=>$e(N),[N]),Lt=We(zt);Lt.current=zt;const Yt=q||!!zt?.continuous,_t=We(Yt);_t.current=Yt;const Ht=Be.useMemo(()=>{if(!b&&!zt?.bodyForce)return b;if(!zt?.bodyForce)return b;if(!b)return zt.bodyForce;const t=zt.bodyForce;return e=>{const i="function"==typeof b?b(e):b,n="function"==typeof t?t(e):t;return i||n?{x:(i?.x??0)+(n?.x??0),y:(i?.y??0)+(n?.y??0)}:null}},[b,zt]);Wt.current=Ht;const Xt=Be.useMemo(()=>new Map(ft.map(t=>[Ai(t),t])),[ft]),Gt=Be.useMemo(()=>new Map(ft.map(t=>[t.id,t])),[ft]),Vt=Be.useMemo(()=>ft.map($i).filter(t=>null!=t),[ft]),[Ut,Kt]=Be.useState([]),Qt=Be.useMemo(()=>Ut.length||Vt.length?[...vt,...Ut,...Vt]:vt,[Ut,Vt,vt]),Zt=Be.useMemo(()=>ji(ft),[ft]),Jt=!!Ht,te=We(null),ee=We(R??li);ee.current=R??li;const ie=Te((t,e,i)=>{const n=te.current;if(!n||!i)return!1;const o=n.readBodies().find(e=>e.id===t),r=Pi(qt.current.get(t));if(!o||!r)return!1;const s=Ci(i,{body:o,region:e,regionState:r});return!(!s||!s.x&&!s.y||(n.applyImpulse(t,s.x??0,s.y??0),0))},[]),ne=Te((t,e,i)=>{if(!i.bodyId)return;const n=Pi(qt.current.get(i.bodyId));if(!n)return;const o={bodyId:i.bodyId,datum:i.datum,observation:i,region:e,regionState:n,type:t};"region-enter"===t?e.onEnter?.(o):e.onExit?.(o),st?.(o)},[st]),oe=Te(t=>{const e=t.sensorId?Xt.get(t.sensorId):void 0;if(!e||!t.bodyId)return;const i=function(t,e){let i=t.get(e);return i||(i={activeRegionIds:new Set,attributes:{},charges:{},energy:0,regionIds:new Set},t.set(e,i)),i}(qt.current,t.bodyId),n=te.current?.readBodies().find(e=>e.id===t.bodyId),o=Pi(i),r=n&&o?{body:n,region:e,regionState:o}:null;if("physics-proximity-enter"===t.type){if(i.activeRegionIds.add(e.id),i.regionIds.add(e.id),i.energy+=e.energyDelta??0,r){!function(t,e,i){const n="function"==typeof t.attributes?t.attributes(e):t.attributes;n&&(i.attributes={...i.attributes,...n})}(e,r,i);const t=function(t,e){return void 0!==t.charge?"function"==typeof t.charge?t.charge(e):t.charge:"charge-gate"===t.kind?1:void 0}(e,r);void 0!==t&&(i.charges[e.id]=t)}ie(t.bodyId,e,e.impulseOnEnter),ne("region-enter",e,t)}else"physics-proximity-exit"===t.type&&(i.activeRegionIds.delete(e.id),ie(t.bodyId,e,e.impulseOnExit),ne("region-exit",e,t))},[ie,ne,Xt]),re=Be.useMemo(()=>{if(!n?.length)return[];const t=n.filter(t=>"barrier"===t.physics||"sensor"===t.physics);return t.length?function(t=[],e={}){const i=e.idPrefix?e.idPrefix+"-":"",n=[];for(const o of t){if("barrier"!==o.physics&&"sensor"!==o.physics)continue;const t=o.axis??e.defaultAxis??"x",r=Je(o,e),s=o.colliderId??`${i}${o.id}`;let a;if("x"===t){const t=Ze(o.x),i=Ze(o.y1)??Ze(e.plotBounds?.y)??Ze(o.y),n=Ze(o.y2)??(e.plotBounds?e.plotBounds.y+e.plotBounds.height:void 0)??Ze(o.y);if(null==t||null==i||null==n)continue;a={type:"segment",x1:t,y1:i,x2:t,y2:n,thickness:r}}else{const t=Ze(o.y),i=Ze(o.x1)??Ze(e.plotBounds?.x)??Ze(o.x),n=Ze(o.x2)??(e.plotBounds?e.plotBounds.x+e.plotBounds.width:void 0)??Ze(o.x);if(null==t||null==i||null==n)continue;a={type:"segment",x1:i,y1:t,x2:n,y2:t,thickness:r}}n.push({id:s,shape:a,sensor:"sensor"===o.physics,..."barrier"!==o.physics||null==o.restitution&&null==e.barrierRestitution?{}:{restitution:Ze(o.restitution)??Ze(e.barrierRestitution)},..."barrier"!==o.physics||null==o.friction&&null==e.barrierFriction?{}:{friction:Ze(o.friction)??Ze(e.barrierFriction)}})}return n}(t,{idPrefix:M?M+"-ann":"physics-ann",plotBounds:{x:0,y:0,width:It?.[0]??un[0],height:It?.[1]??un[1]}}):[]},[n,M,It]),se=Be.useMemo(()=>{const t=void 0===C||void 0!==j?.kernel?.seed?j:{...j,kernel:{...j?.kernel,seed:C}},e=ft.flatMap(t=>[{id:Ai(t),sensor:!0,shape:t.shape,bodyFilter:t.bodyFilter,friction:t.friction,restitution:t.restitution},...Ri(t)]),i=Object.fromEntries(ft.map(t=>[Ai(t),{binId:t.binId??t.id,enterType:"physics-proximity-enter",exitType:"physics-proximity-exit"}])),n=t?.observation,o=ft.length>0;return o||e.length>0||re.length>0||null!=M||n?{...t,colliders:[...t?.colliders??[],...e,...re],observation:{...n,chartId:M??n?.chartId,chartType:n?.chartType??mn,sensors:{...n?.sensors??{},...i},onObservation:t=>{o&&oe(t),n?.onObservation?.(t)}}}:t},[re,M,j,oe,ft,C]);if(!te.current){const t=di(se,X,G);t.setPaused(mt),At&&t.setVisible(Mi()),te.current=t}const ae=We(-1),ce=We(null),de=We(!0),le=T("StreamPhysicsFrame"),ue=We(""),he=Fe().replace(/:/g,""),pe=We(!1),me=We(!1),fe=We(0),ye=We(!1),ge=We(null),be=We(!1),xe=B({sizeProp:It,responsiveWidth:gt,responsiveHeight:yt,userMargin:nt,marginDefault:hn,foregroundGraphics:L,backgroundGraphics:m,frameScheduler:A,clock:R,random:P,seed:C,paused:mt,suspendWhenHidden:At}),{margin:ve,rafRef:we,reducedMotionRef:Ie,renderFnRef:Me,cancelRender:ke,resolvedBackground:Se,resolvedForeground:Ae,responsiveRef:Re,scheduleRender:Pe,size:Ce,frameRuntime:je}=xe,Oe=We(je.now);Oe.current=je.now;const Ne=Y(),ei=_(),[ni,oi]=Be.useState(null),[si,ai]=Be.useState(null),hi=We(null),pi=We(0),mi=We(new Map),fi=he+"-physics-live",Bi=Te((t,e,i=!1)=>{if(!y)return void Kt(t=>t.length?[]:t);const n=Oe.current();if(!i&&g>0&&g>n-pi.current)return;pi.current=n;const o=function(t,e,i,n){if(!i)return[];const o=Math.max(0,Math.floor(n));if(!o)return[];const r=[];for(let n=0;t.length>n&&o>r.length;n+=1){const o=t[n],s="function"==typeof i?i(o,{index:n,simulationState:e}):void 0;if(!1===s)continue;const a=tn(o);r.push({datum:o.datum??o,description:nn(o),group:"body",label:en(o),...a,...s??{},bodyId:s?.bodyId??o.id,id:s?.id??"body:"+o.id,x:s?.x??o.x,y:s?.y??o.y})}return r}(t,e,y,f);Kt(t=>function(t,e){if(t.length!==e.length)return!0;for(let i=0;t.length>i;i+=1){const n=t[i],o=e[i];if(n.id!==o.id||n.label!==o.label||n.description!==o.description||n.group!==o.group||n.bodyId!==o.bodyId||Math.round(n.x)!==Math.round(o.x)||Math.round(n.y)!==Math.round(o.y))return!0}return!1}(t,o)?o:t)},[f,y,g]),Oi=Te(t=>{if(!Qt.length)return;const e=Math.max(0,Math.min(t,Qt.length-1));ae.current=e;const i=Qt[e];if(hi.current=i.bodyId??null,oi(i),ut?.(i),i.bodyId&&te.current){const t=te.current.readBodies().find(t=>t.id===i.bodyId);if(t){const e=Ji(t);ai(e),ct?.(t,e)}}},[Qt,ct,ut]),qi=Te(()=>{ae.current=-1,hi.current=null,oi(null),ut?.(null)},[ut]),Fi=function({onObservationRef:t,chartIdRef:e,wallClockRef:i}){return Ei((n,o)=>{const r=t.current;if(!r)return;const s={timestamp:i.current(),chartType:"StreamPhysicsFrame",chartId:e.current};r("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,t,i])}({onObservationRef:Tt,chartIdRef:Et,wallClockRef:ee}),Wi=Te(()=>{ai(t=>t?(ct?.(null,null),Fi("hover-end"),null):t)},[Fi,ct]),zi=Te(t=>{if(!z||!te.current)return;const e=t.currentTarget.getBoundingClientRect(),i=te.current.hitTest(t.clientX-e.left,t.clientY-e.top,H);if(!i)return void Wi();const n=Ji(i);ai(t=>t&&t.id===n.id&&t.x===n.x&&t.y===n.y?t:(ct?.(i,n),Fi("hover",{datum:i.datum,x:i.x,y:i.y}),n))},[Wi,Fi,z,H,ct]),Li=Te(t=>{qi();const e=te.current,i=t.currentTarget.getBoundingClientRect(),n=t.clientX-i.left,o=t.clientY-i.top,r=e?e.hitTest(n,o,Math.max(16,H)):null;dt?.(r,t),r?(Fi("click",{datum:r.datum,x:r.x,y:r.y}),Fi("activate",{datum:r.datum,inputType:"touch"===t.pointerType?"touch":"pointer"}),ot?.(r.datum??null,{x:r.x,y:r.y,body:r})):(Fi("click-end"),ot?.(null,{x:n,y:o,body:null}),Wi())},[Wi,qi,Fi,H,dt,ot]);Ee(()=>{if(!Qt.length)return void qi();const t=ae.current;if(Qt.length>t){if(t>=0){const e=Qt[t];if(hi.current=e.bodyId??null,oi(t=>null!=t&&t.id===e.id&&Math.round(t.x)===Math.round(e.x)&&Math.round(t.y)===Math.round(e.y)?t:e),e.bodyId&&te.current){const t=te.current.readBodies().find(t=>t.id===e.bodyId);if(t){const e=Ji(t);ai(t=>t?.id===e.id&&Math.round(t.x)===Math.round(e.x)&&Math.round(t.y)===Math.round(e.y)?t:e)}}}}else Oi(Qt.length-1)},[Qt,qi,Oi]),Ee(()=>{z||Wi()},[Wi,z]);const Yi=Te(t=>{if(w(t))return;if(!Qt.length)return;if("Escape"===t.key)return t.preventDefault(),void qi();if(("Enter"===t.key||" "===t.key)&&ae.current>=0){t.preventDefault();const e=Qt[ae.current];return Fi("activate",{datum:e.datum??{id:e.id,label:e.label},inputType:"keyboard"}),void lt?.(e)}if(!pn.has(t.key))return;t.preventDefault();const e=ae.current;if(0>e){Oi(0);const t=Qt[0];return void Fi("focus",{datum:t.datum??{id:t.id,label:t.label},inputType:"keyboard"})}const i=Math.max(1,Math.floor(.1*Qt.length));let n=e;if("Home"===t.key?n=0:"End"===t.key?n=Qt.length-1:"PageDown"===t.key?n=Math.min(Qt.length-1,e+i):"PageUp"===t.key?n=Math.max(0,e-i):"ArrowRight"===t.key||"ArrowDown"===t.key?n=Math.min(Qt.length-1,e+1):"ArrowLeft"!==t.key&&"ArrowUp"!==t.key||(n=Math.max(0,e-1)),Oi(n),n!==e){const t=Qt[n];Fi("focus",{datum:t.datum??{id:t.id,label:t.label},inputType:"keyboard"})}},[qi,Fi,Oi,lt,Qt]),[_i,Hi]=Be.useState([]),Xi=We(0),Gi=!!n?.length&&n.some(t=>null!=t.pointId||null!=t.bodyId||"latest"===t.anchor),{canvasRef:Vi}=O(xe,{hydrated:Ne,wasHydratingFromSSR:ei,storeRef:te,dirtyRef:de,manageFrameRuntime:!1,skipInitialCanvasPaintInvalidation:!0,canvasPaintDependencies:[s,m,Pe]}),Ui=Te(()=>{const t=Vi.current,e=te.current;if(!t||!e)return;const i=le.current.beforeCompute(e.getLastUpdateResult(),!1),n=v(),o=k(t,Ce,ve,n);if(!o)return void le.current.afterCompute(i,!1,!1);const r=function(t){const e=Ke(t,He),i=Ke(t,Le),n=Ke(t,Ue),o=Ke(t,Xe),r=Ke(t,ze),s=Ke(t,De),a=Ke(t,Ge),c=Ke(t,Ve),d=Ke(t,Ye),l=Ke(t,_e);return{annotationBackground:Qe(s,.94),annotationStroke:r,annotationText:a,background:s,border:r,closedWindowFill:Qe(i,.08),closedWindowStroke:Qe(i,.55),danger:i,focus:d,grid:l,gutterFill:Qe(c,.14),lateFill:n,openWindowFill:Qe(e,.07),openWindowStroke:Qe(e,.3),primary:e,selectedFill:n,selectedStroke:d,success:o,text:a,textSecondary:c,warning:n}}(o);o.clearRect(-ve.left,-ve.top,Ce[0],Ce[1]),m||"transparent"===s||(o.fillStyle=s??r.background,o.fillRect(-ve.left,-ve.top,Ce[0],Ce[1]));const a=e.snapshot(),c=e.readBodies();if(Bi(c,a.simulationState),Gi){const t=Oe.current();if(t-Xi.current>=100){Xi.current=t;const e=Z(c);Hi(t=>t.length===e.length&&t.every((t,i)=>t.pointId===e[i].pointId&&Math.round(t.x)===Math.round(e[i].x)&&Math.round(t.y)===Math.round(e[i].y))?t:e)}}Bt&&(o.save(),Bt(o,c),o.restore());for(const t of c){const e=qt.current.get(t.id),i=e?Array.from(e.activeRegionIds).map(t=>Gt.get(t)).filter(t=>null!=t):[],n=Ti(t,a.simulationState,x,bt,xt,Pi(e),i,r.primary,r.text,Nt);jt?(o.save(),jt(o,t,n),o.restore()):ki(o,t,n)}Ot&&(o.save(),Ot(o,c),o.restore()),function(t,e,i){let n=!1;for(const[o,r]of e){const s=Math.min(1,Math.max(0,(i-r.startedAt)/r.durationMs));if(s>=1){e.delete(o);continue}n=!0;const a=1-Math.pow(1-s,3),{body:c}=r,d=r.scale>0?r.scale:1,l=(r.radius+28*a)*d,u=1-s;t.save(),t.globalAlpha*=u,t.strokeStyle=r.color,t.fillStyle=r.color,t.lineWidth=Math.max(.5,(2.4*u+.4)*d),t.beginPath(),t.arc(c.x,c.y,l,0,2*Math.PI),t.stroke(),t.globalAlpha*=.18,t.beginPath(),t.arc(c.x,c.y,.52*l,0,2*Math.PI),t.fill(),t.restore(),t.save(),t.globalAlpha*=u,t.strokeStyle=r.color,t.lineWidth=Math.max(.5,1.8*d);for(let e=0;8>e;e+=1){const i=e*(Math.PI/4)+1.4*s,n=(r.radius+5+12*a)*d,o=(r.radius+12+34*a)*d;t.beginPath(),t.moveTo(c.x+Math.cos(i)*n,c.y+Math.sin(i)*n),t.lineTo(c.x+Math.cos(i)*o,c.y+Math.sin(i)*o),t.stroke()}t.restore()}}(o,mi.current,Oe.current()),le.current.afterCompute(i,!0,!1),de.current=!1},[Vi,le,Ce,ve,m,s,Bi,Gi,Bt,Ot,x,bt,xt,Nt,jt,Gt]),Ki=Te((t,e)=>{const i=te.current,n=`${wt}:${t}:${e??""}`;ue.current!==n&&(ue.current=n,at?.({execution:t,liveBodies:i?.liveBodyCount()??0,queuedBodies:i?.queueSize()??0,reason:e,requested:wt}))},[at,wt]),Qi=Te((t,e=!0)=>{fe.current+=1,pe.current=!1,ye.current=!1,be.current=!1,ge.current?.terminate(),ge.current=null,e&&Ki("sync",t)},[Ki]),Zi=Te(()=>Ne?"undefined"==typeof window||"undefined"==typeof Worker?"worker unavailable":Zt?"runtime region effects require sync":Jt?"body forces require sync":zt?"physics controllers require sync":function(t){return!t||!t.engine&&ii(t.sediment)&&(!(e=t.colliders)||e.every(t=>{const e=t.bodyFilter;return!e||"function"!=typeof e}));var e}(se??{})?ri(G)?me.current?"worker fallback":null:"spawn pacing is not worker-cloneable":"config is not worker-cloneable":"hydrating",[se,zt,Jt,Zt,Ne,G]),on=Te(()=>{const t=te.current,e=Zi();if(!t||e)return{reason:e,useWorker:!1};const i=t.liveBodyCount(),n=t.queueSize(),o=function(t,e,i=0,n=ti){return"sync"!==t&&("worker"===t||e+i>=n)}(wt,i,n,$t);return{reason:o?"worker"===wt?"forced worker":"body threshold":"below threshold",useWorker:o}},[wt,$t,Zi]),sn=Te(t=>{const e=te.current;return e&&t.snapshot?(e.restore(t.snapshot),de.current=!0,e):e},[]),an=Te((t,e=!0)=>{const i=sn(t);if(!i)return;e&&ht?.(t.result,i.controls()),Ui();const n=i.snapshot();!t.result.shouldContinue&&mi.current.size<=0||n.paused||!n.visible||Ie.current||Pe()},[sn,ht,Ui,Ie,Pe]),fn=Te(t=>{me.current=!0,Qi("worker failed: "+((t instanceof Error?t.message:t+"")||"unknown error"))},[Qi]),yn=Te(()=>{const t=te.current;if(!t)return!1;const e=on();if(!e.useWorker)return pe.current||be.current?Qi(e.reason??"sync fallback"):Ki("sync",e.reason??"sync"),!1;if(pe.current||be.current)return!0;const i=ge.current??new ci;ge.current=i,be.current=!0;const n=fe.current+1;return fe.current=n,i.initFromSnapshot(se??{},t.snapshot()).then(t=>{if(fe.current!==n)return;be.current=!1,pe.current=!0,me.current=!1,sn(t),Ki("worker",e.reason??"worker"),Ui();const i=te.current?.snapshot();t.result.shouldContinue&&i&&!i.paused&&i.visible&&!Ie.current&&(ce.current=null,Pe())}).catch(t=>{fe.current===n&&fn(t)}),!0},[sn,se,fn,Ui,Ie,Ki,Pe,Qi,on]),gn=Te(t=>"frame"===t.type||"removed"===t.type?t.frame:null,[]),bn=Te((t,e=!0)=>{const i=ge.current;if(!i||!pe.current)return;const n=fe.current;i.request(t).then(t=>{if(fe.current!==n)return;const i=gn(t);i&&an(i,e)}).catch(fn)},[an,gn,fn]),xn=Te(()=>{const t=te.current;if(!t)return;const e=yn(),i=t.snapshot(),n=Yt||Jt||Zt||!!zt;i.paused||!i.visible||!t.hasPendingWork()&&!n||Ie.current?Me.current():e&&be.current||Pe()},[zt,Yt,Jt,Zt,Ie,Me,Pe,yn]),vn=Te(()=>{ke(),we.current=null;const t=te.current;if(!t)return;if(pe.current&&ge.current){if(ye.current)return;let e=0;if(!Ie.current){const t=Oe.current();e=null!==ce.current?(t-ce.current)/1e3:0,ce.current=t}const i=ge.current,n=fe.current;return ye.current=!0,void(Ie.current?i.settle():i.tick(e)).then(t=>{ye.current=!1,fe.current===n&&an(t)}).catch(i=>{if(ye.current=!1,fe.current!==n)return;fn(i);const o=Ie.current?t.settleWithObservations():t.tick(e);Ni({store:t,result:o,regionEffects:Ft.current,regionState:qt.current,bodyForces:Wt.current,composed:Lt.current,onTick:Dt.current}),Ui()})}let e;if(Ie.current)e=t.settleWithObservations();else{const i=Oe.current(),n=null!==ce.current?(i-ce.current)/1e3:0;ce.current=i,e=t.tick(n)}const i=Lt.current,{regionEffectsApplied:n,bodyForcesApplied:o,snapshot:r}=Ni({store:t,result:e,regionEffects:Ft.current,regionState:qt.current,bodyForces:Wt.current,composed:i,onTick:Dt.current});Ui(),(_t.current||e.shouldContinue||n||o||i||mi.current.size>0)&&!r.paused&&r.visible&&!Ie.current&&Pe()},[an,fn,Ui,ke,Pe,Ie,we]);Me.current=vn,Ee(()=>{me.current=!1,(pe.current||be.current)&&Qi("config changed",!1),te.current?.updateConfig(se??{}),xn()},[se,Qi]),Ee(()=>{me.current=!1,xn()},[Ne,wt,$t]),function({cancelRender:t,frameRuntime:e,lastFrameTimeRef:i,paused:n,postWorkerCommand:o,requestRender:r,storeRef:s,suspendWhenHidden:a}){const c=Ii(o);c.current=o;const d=Ii(r);d.current=r,wi(()=>{const o=s.current;o&&(e.setPaused(n),o.setPaused(n),n&&(i.current=null,t()),c.current({type:"setPaused",paused:n},!1),d.current())},[t,e,n]),wi(()=>{if(!a){const t=s.current;return e.setVisible(!0),void(t&&!t.snapshot().visible&&(t.setVisible(!0),c.current({type:"setVisible",visible:!0},!1),d.current()))}if("undefined"==typeof document)return;const n=()=>{const n=s.current;if(!n)return;const o=Mi();e.setVisible(o),n.setVisible(o),o||(i.current=null,t()),c.current({type:"setVisible",visible:o},!1),d.current()};return n(),document.addEventListener("visibilitychange",n),()=>document.removeEventListener("visibilitychange",n)},[t,e,a])}({cancelRender:ke,frameRuntime:je,lastFrameTimeRef:ce,paused:mt,postWorkerCommand:bn,requestRender:xn,storeRef:te,suspendWhenHidden:At}),Ee(()=>()=>Qi("unmount",!1),[Qi]),Ee(()=>{Ui()},[Ui]),qe(e,()=>({...te.current.controls(),applyImpulse:(t,e,i)=>{te.current.applyImpulse(t,e,i),bn({type:"applyImpulse",id:t,ix:e,iy:i}),xn()},clear:()=>{te.current.clear(),qt.current.clear(),mi.current.clear(),bn({type:"clear"}),xn()},clearRegionState:t=>{t?qt.current.delete(t):qt.current.clear(),xn()},getData:()=>te.current.readBodies(),getRegionState:t=>t?Pi(qt.current.get(t)):function(t){const e={};return t.forEach((t,i)=>{const n=Pi(t);n&&(e[i]=n)}),e}(qt.current),getStore:()=>te.current,pause:()=>{je.setPaused(!0),ce.current=null,ke(),te.current.setPaused(!0),bn({type:"setPaused",paused:!0},!1),xn()},push:(t,e)=>{te.current.enqueue(t,e),ri(e)?bn({type:"enqueue",spawns:[t],pacing:e}):(pe.current||be.current)&&Qi("spawn pacing is not worker-cloneable"),xn()},pushMany:(t,e)=>{te.current.enqueue(t,e),ri(e)?bn({type:"enqueue",spawns:t,pacing:e}):(pe.current||be.current)&&Qi("spawn pacing is not worker-cloneable"),xn()},popBodies:(t,e={})=>{const i=te.current,n=new Map(i.readBodies().map(t=>[t.id,t])),o=i.remove(t),r=Oe.current();for(const t of o){const i=n.get(t);i&&(qt.current.delete(t),mi.current.set(t,{body:i,color:e.color??"#f59e0b",durationMs:Math.max(120,e.durationMs??520),radius:e.radius??Si(i),scale:null!=e.scale&&e.scale>0?e.scale:1,startedAt:r}),hi.current===t&&(hi.current=null,oi(null)),ai(e=>e?.id===t?null:e))}return o.length&&(bn({type:"remove",ids:o}),xn()),o},remove:t=>{const e=te.current.remove(t);for(const e of t)qt.current.delete(e);return bn({type:"remove",ids:t}),xn(),e},restore:t=>{te.current.restore(t),qt.current.clear(),mi.current.clear(),bn({type:"restore",snapshot:t},!1),xn()},resume:()=>{je.setPaused(!1),ce.current=null,te.current.setPaused(!1),bn({type:"setPaused",paused:!1},!1),xn()},settle:t=>{const e=te.current.settle(t);return bn({type:"settle",maxSteps:t}),xn(),e},settleWithObservations:t=>{const e=te.current.settleWithObservations(t);return bn({type:"settle",maxSteps:t}),xn(),e},step:t=>{const e=te.current,i=e.tick(t);return Ni({store:e,result:i,regionEffects:Ft.current,regionState:qt.current,bodyForces:Wt.current,composed:Lt.current,onTick:Dt.current}),bn({type:"tick",deltaSeconds:t}),Ui(),i}}),[ke,je,Ui,bn,xn,Qi]);const wn=I||!Ne&&ei,In=["stream-physics-frame",D?"stream-physics-frame--mode-"+D:null,W?"stream-physics-frame--emphasis-"+W:null,S].filter(Boolean).join(" "),Mn=F??("string"==typeof Pt?Pt:void 0)??"Physics chart",kn=he+"-physics-table",Sn=Math.max(1,Ce[0]-ve.left-ve.right),An=Math.max(1,Ce[1]-ve.top-ve.bottom),Rn=z&&si?Ct?Ct(si):dn(rn,{hover:si}):null,Pn=Rn&&si?dn(d,{x:si.x-ve.left,y:si.y-ve.top,containerWidth:Math.max(1,Ce[0]-ve.left-ve.right),containerHeight:Math.max(1,Ce[1]-ve.top-ve.bottom),margin:ve,className:"stream-physics-tooltip",children:Rn}):null;if(wn){const t=te.current??di(se,X,G),e="string"==typeof Pt?Pt:void 0,{svg:i}=function(t,e={}){const{width:i=640,height:n=360,title:o,description:r,background:s,backgroundGraphics:a,className:c,foregroundGraphics:d,idPrefix:l="physics",margin:u,renderBodySVG:h,...p}=e,m=yi(t,p),f={...xi,...u},y=[i,n],g=vi(a,y,f),b=vi(d,y,f),x=function(t){const e=t.replace(/[^A-Za-z0-9_-]/g,"_");return!e||/^\d/.test(e)?"physics-"+e:e}(l),v=o?x+"-title":void 0,w=r?x+"-desc":void 0,I=[v,w].filter(Boolean).join(" ")||void 0;return{svg:ui.renderToStaticMarkup(bi("svg",{xmlns:"http://www.w3.org/2000/svg",className:c??"stream-physics-frame",width:i,height:n,viewBox:`0 0 ${i} ${n}`,role:"img","aria-labelledby":I,children:[o&&gi("title",{id:v,children:o}),r&&gi("desc",{id:w,children:r}),!a&&s&&"transparent"!==s?gi("rect",{x:0,y:0,width:i,height:n,fill:s}):null,g,gi("g",{id:x+"-data-area",children:m.sceneNodes.map((t,e)=>{const i=m.bodies[e];return(i&&h?h(i,t.style??{},e,x):void 0)??E(t,e,x)})}),b]})),scene:m,evidence:m.evidence}}(t,{width:Ce[0],height:Ce[1],title:e,description:F,background:m||"transparent"===s?void 0:s,backgroundGraphics:Se,className:"stream-physics-frame__svg",foregroundGraphics:Ae,idPrefix:"physics-"+he,margin:ve});return ln("div",{ref:Re,className:In,"data-semiotic-mode":D,role:"img","aria-label":Mn,style:{width:Ce[0],height:Ce[1]},children:[dn(h,{summary:St}),dn("div",{dangerouslySetInnerHTML:{__html:i}})]})}return ln("div",{ref:Re,className:In,"data-semiotic-mode":D,role:"group","aria-label":Mn,"aria-describedby":ni?fi:void 0,tabIndex:0,style:{position:"relative",width:Ce[0],height:Ce[1]},onKeyDown:Yi,children:["production"!==process.env.NODE_ENV&&te.current&&dn(u,{store:te.current,diagnostics:le.current}),i?dn(p,{tableId:kn}):null,i?dn(cn,{chartTitle:"string"==typeof Pt?Pt:Mn,items:Qt,tableId:kn}):null,dn(h,{summary:St}),dn(a,{hoverPoint:si}),dn("div",{id:fi,"aria-live":"polite","aria-atomic":"true",style:Di,children:ni?ni.description??ni.label:""}),ln("div",{role:"img","aria-label":Mn,style:{position:"relative",width:"100%",height:"100%"},children:[dn(c,{size:Ce,margin:ve,children:Se}),dn("canvas",{ref:Vi,width:Ce[0],height:Ce[1],"aria-hidden":"true",style:{position:"absolute",left:0,top:0,display:"block"},onPointerDown:Li,onPointerMove:z?zi:void 0,onPointerLeave:z?Wi:void 0}),Ae,dn(et,{width:Sn,height:An,totalWidth:Ce[0],totalHeight:Ce[1],margin:ve,title:Pt,legend:V,legendPosition:it,legendLayout:tt,legendHoverBehavior:Q,legendClickBehavior:U,legendHighlightedCategory:K,legendIsolatedCategories:J,pointNodes:_i,annotations:n,onAnnotationActivate:o,onObservation:rt,chartId:M,chartType:mn,autoPlaceAnnotations:r,svgAnnotationRules:Rt}),dn(l,{active:null!=ni,hoverPoint:ni?{x:ni.x,y:ni.y}:null,margin:ve,size:Ce,shape:ni?.shape,width:ni?.width,height:ni?.height,pathData:ni?.pathData}),Pn]})]})}));fn.displayName="StreamPhysicsFrame";var yn=fn;import{scaleLinear as gn}from"d3-scale";function bn(t){const[e,i]=t,n=160>e||116>i,o=n?Math.min(12,Math.max(2,.08*e)):32,r=n?Math.min(8,Math.max(2,.12*i)):24,s=n?r:34;return{width:e,height:i,plot:{x:o,y:r,width:Math.max(1,e-2*o),height:Math.max(1,i-r-s)}}}function xn(t){const e=(t??"")+"";if(!e)return"#4e79a7";const i=["#4e79a7","#59a14f","#e15759","#f28e2b","#76b7b2","#edc948","#b07aa1","#ff9da7"];let n=0;for(let t=0;e.length>t;t+=1)n=31*n+e.charCodeAt(t)>>>0;return i[n%i.length]}function vn(t,n="#4e79a7",o){const r=o?.styleRules,s=!!r&&r.length>0,a=s?e(o?.valueAccessor):void 0;return e=>{const o=e.datum,c=o&&t?"function"==typeof t?t(o,0):o[t]:void 0,d={fill:null==c?n:xn(c),stroke:"#111827",strokeWidth:1,opacity:.9};return s&&o&&Object.assign(d,i(o,r,{value:a?a(o):void 0,category:null==c?void 0:c+""})),d}}function wn(t,e,i,n){return{fixedDt:1/120,maxSubsteps:8,colliders:e,observation:{chartType:i},kernel:{seed:t,gravity:{x:0,y:760},cellSize:36,collisionIterations:6,velocityDamping:.995,restitution:.08,friction:.4,sleepSpeed:8,sleepAfter:.6,...n}}}function In(t,e,i){if(!t.length)return[];const n=bn(e),o=n.plot.width/Math.max(1,t.length),r=Math.max(1,...t.map(t=>t.value)),s=.62*n.plot.height,a=n.plot.y+n.plot.height;return t.map((t,e)=>{const c=Math.max(8,t.value/r*s),d=`${i} ${t.label}: ${t.value}${null==t.secondary?"":`, ${t.secondary} secondary`}`;return{id:`${i}-${t.label}`,label:d,description:d,datum:t,x:n.plot.x+(e+.5)*o,y:a-c/2,shape:"rect",width:Math.max(12,.58*o),height:c,group:i}})}function Mn(t,e,i){return"function"==typeof i?i(t,e):t[i]}function kn(t){if(t instanceof Date){const e=t.getTime();return Number.isFinite(e)?e:null}const e="number"==typeof t?t:"string"==typeof t&&t.trim()?Number(t):NaN;return Number.isFinite(e)?e:null}function Sn(t,e,i){return Math.max(e,Math.min(i,t))}function An(t,e){const i=kn(t);return null!=i&&i>0?i:e}function Rn(t){return((t??"unknown")+"").trim().replace(/[^A-Za-z0-9_-]+/g,"_")||"unknown"}function Pn(t){let e=t>>>0;return()=>{e+=1831565813;let t=e;return t=Math.imul(t^t>>>15,1|t),t^=t+Math.imul(t^t>>>7,61|t),((t^t>>>14)>>>0)/4294967296}}function Cn(t){const{data:e,valueAccessor:i,bins:n,ballRadius:o,seed:r,size:s,valueExtent:a}=t,c=bn(s),d=e.map((t,e)=>kn(Mn(t,e,i))).filter(t=>null!=t),l=function(t){if(!t)return;const e=kn(t[0]),i=kn(t[1]);return null!=e&&null!=i?e>i?[i,e]:[e,i]:void 0}(a),u=l?.[0]??(d.length?Math.min(...d):0),h=l?.[1]??(d.length?Math.max(...d):1),p=h===u?1:h-u,m=gn().domain([0,n]).range([c.plot.x,c.plot.x+c.plot.width]),f=Array.from({length:n},()=>0),y=[];e.forEach((t,e)=>{const r=kn(Mn(t,e,i));if(null==r)return;const s=Math.max(0,Math.min(n-1,Math.floor((r-u)/p*n)));f[s]+=1,y.push({id:(t.id??"galton-"+e)+"",x:m(s+.5),y:c.plot.y+o+2,vx:8*(e%5-2),vy:0,mass:1,shape:{type:"circle",radius:o},datum:{...t,value:r,bin:s}})});const g=c.plot.y+c.plot.height;return{config:wn(r,[...Zt({x:c.plot.x,y:c.plot.y,width:c.plot.width,height:c.plot.height},{idPrefix:"galton",wallThickness:20,floorThickness:20}),...Jt({idPrefix:"galton-bin",count:n,domainStart:0,domainStep:1,xScale:m,yTop:c.plot.y-400,yBottom:g,wallThickness:6})],"GaltonBoardChart"),initialSpawns:y,initialSpawnPacing:{pacing:{ratePerSec:55}},projectionRows:f.map((t,e)=>({label:e+1+"",value:t})),metadata:{kind:"galton-board",bins:n,plot:c.plot,valueExtent:[u,h]}}}import{scaleLinear as $n}from"d3-scale";function jn(t){const{count:e,idPrefix:i,wallThickness:n,xScale:o,yBottom:r,yTop:s,yTopForIndex:a}=t;return Array.from({length:e+1},(t,e)=>{const c=Math.min(r-1,a?.(e)??s),d=Math.max(1,r-c);return{id:`${i}-wall-${e}`,shape:{type:"aabb",x:o(e),y:c+d/2,width:n,height:d}}})}function Bn(t){const{data:e,timeAccessor:i,arrivalAccessor:n,windows:o,watermark:r,ballRadius:s,seed:a,size:c,timeExtent:d,timeScale:l=1}=t,u=bn(c),h=e.map((t,e)=>kn(Mn(t,e,i))).filter(t=>null!=t),p=kn(d?.[0]),m=kn(d?.[1]),f=h.length?Math.min(...h):0,y=h.length?Math.max(...h):f+o.size,g=Math.min(p??f,f),b=Math.max(m??y,y),x=Math.floor(g/o.size)*o.size,v=Math.max(1,Math.ceil((b-x+o.size)/o.size)),w=h.length?Math.max(...h):0,I="function"==typeof r?r(w):kn(r?.value)??w-(r?.delay??o.size),M=Math.max(0,Math.min(v,Array.from({length:v},(t,e)=>e).reduce((t,e)=>x+(e+1)*o.size>I?t:t+1,0))),k=function(t,e){const i=Math.max(5*e,Math.min(92,.13*t.plot.width));return{gutter:{x:t.plot.x,y:t.plot.y,width:i,height:t.plot.height},windowPlot:{x:t.plot.x+i,y:t.plot.y,width:Math.max(40,t.plot.width-i),height:t.plot.height},wallTop:t.plot.y+.48*t.plot.height}}(u,s),S=x+v*o.size,A=$n().domain([x,S]).range([k.windowPlot.x,k.windowPlot.x+k.windowPlot.width]),R=Array.from({length:v},()=>({value:0,secondary:0})),P=[];e.forEach((t,e)=>{const r=kn(Mn(t,e,i));if(null==r)return;const a=kn(Mn(t,e,n))??r,c=Math.max(0,Math.min(v-1,Math.floor((r-x)/o.size))),d=I>=x+(c+1)*o.size;R[c].value+=d?0:1,R[c].secondary+=d?1:0,P.push({id:(t.id??"event-"+e)+"",x:Math.max(k.windowPlot.x+s,Math.min(k.windowPlot.x+k.windowPlot.width-s,A(r))),y:u.plot.y+s+2,vx:8*(e%3-1),vy:0,mass:1,friction:.02,spawnAt:a,shape:{type:"circle",radius:s},datum:{...t,eventTime:r,arrivalTime:a,windowIndex:c,late:d}})});const C=u.plot.y+u.plot.height,$=function(t,e){const i=Math.max(0,Math.min(t.windowCount,t.closedWindowCount));if(!i)return[];const n=t.windowStart,o=t.windowStart+t.windowCount*t.windowSize,r=$n().domain([n,o]).range([t.windowPlot.x,t.windowPlot.x+t.windowPlot.width]),s=r(t.windowStart+i*t.windowSize),a=t.windowPlot.x,c=e+Math.max(18,Math.min(.3*t.windowPlot.height,s-a)),d=t=>s===a?e:c+(t-a)/(s-a)*(e-c),l=[];for(let e=0;i>e;e+=1){const i=t.windowStart+e*t.windowSize,n=i+t.windowSize,o=r(i),s=r(n);l.push({id:"eventdrop-lid-"+e,windowIndex:e,x1:o,y1:d(o),x2:s,y2:d(s)})}return l}({closedWindowCount:M,gutter:k.gutter,plot:u.plot,windowCount:v,windowPlot:k.windowPlot,windowSize:o.size,windowStart:x},u.plot.y+.28*u.plot.height);return{config:wn(a,[...Zt({x:u.plot.x,y:u.plot.y,width:u.plot.width,height:u.plot.height},{idPrefix:"eventdrop",wallThickness:20,floorThickness:20}),...jn({idPrefix:"eventdrop-window",count:v,xScale:t=>A(x+t*o.size),yTop:k.wallTop,yTopForIndex:t=>{const e=(t=>{if(0>t||t>M)return null;const e=0===t?$[0]?.y1:$[t-1]?.y2??$[t]?.y1;return"number"==typeof e&&Number.isFinite(e)?e:null})(t);return null==e?k.wallTop:e+1.25*s},yBottom:C,wallThickness:6}),...$.map(t=>({id:t.id,shape:{type:"segment",x1:t.x1,y1:t.y1,x2:t.x2,y2:t.y2,thickness:Math.max(4,.42*s)},friction:.02,restitution:.01}))],"EventDropChart",{friction:.08}),initialSpawns:P,initialSpawnPacing:{pacing:"arrival",timeAccessor:t=>t.datum?.arrivalTime,timeScale:l},projectionRows:R.map((t,e)=>({label:`${x+e*o.size}-${x+(e+1)*o.size}`,value:t.value,secondary:t.secondary})),metadata:{kind:"event-drop",closedWindowCount:M,gutter:k.gutter,lidSegments:$,lateCount:R.reduce((t,e)=>t+e.secondary,0),plot:u.plot,windowPlot:k.windowPlot,watermarkValue:I,windowCount:v,windowSize:o.size,windowStart:x}}}function On(t,e,i){const n=t.width/Math.max(1,e),o=Math.max(2,2*i),r=Math.min(.7*n,Math.max(3.2*o,o+8)),s=Math.max(1,Math.floor(r/o));return{laneWidth:n,tubeWidth:r,ballDiameter:o,perRow:s,centerX:e=>t.x+(e+.5)*n,pileHeight:t=>Math.ceil(Math.max(0,t)/s)*o}}function Nn(t){const{data:e,categoryAccessor:i,valueAccessor:n,unitValue:o,ballRadius:r,seed:s,size:a}=t,c=An(o,1),d=bn(a),l=[],u=new Map,h=new Map,p=[];function m(t){let e=u.get(t);return null==e&&(e=l.length,l.push(t),u.set(t,e)),e}e.forEach((t,e)=>{m((Mn(t,e,i)??"unknown")+"")});const f=Math.max(1,l.length),y=On(d.plot,f,r),g=Math.max(0,y.tubeWidth/2-r-1),b=l.map(()=>[]);e.forEach((t,e)=>{const o=(Mn(t,e,i)??"unknown")+"",s=m(o),a=n?kn(Mn(t,e,n)):1,l=Math.max(0,Math.round((a??0)/c)),u=y.centerX(s);for(let i=0;l>i;i+=1){const n=h.get(o)??0,a=y.perRow>1?((y.perRow>1?n%y.perRow:0)/(y.perRow-1)*2-1)*g:0;h.set(o,n+1),b[s].push({id:`${(t.id??"pile-"+e)+""}-${i}`,x:u+a,y:d.plot.y+r+2,vx:(i%3-1)*r/2,vy:0,mass:1,shape:{type:"circle",radius:r},datum:{...t,category:o,unitIndex:i}})}});const x=b.reduce((t,e)=>Math.max(t,e.length),0);for(let t=0;x>t;t+=1)for(const e of b)e.length>t&&p.push(e[t]);const v=d.plot.y+d.plot.height,w=[...Zt({x:d.plot.x,y:d.plot.y,width:d.plot.width,height:d.plot.height},{idPrefix:"pile",wallThickness:20,floorThickness:20})],I=d.plot.y-400;for(let t=0;f>t;t+=1){const e=y.centerX(t);for(const i of[-1,1])w.push({id:`pile-tube-${t}-${0>i?"l":"r"}`,shape:{type:"aabb",x:e+i*y.tubeWidth/2,y:(I+v)/2,width:6,height:v-I}})}return{config:wn(s,w,"PhysicsPileChart"),initialSpawns:p,initialSpawnPacing:{pacing:{ratePerSec:20}},projectionRows:l.map(t=>({label:t,value:h.get(t)??0}))}}import{scaleLinear as Tn}from"d3-scale";function En(t){const{data:e,xAccessor:i,groupAccessor:n,radiusAccessor:o,pointRadius:r,seed:s,size:a,xExtent:c,collisionIterations:d,settle:l}=t,u=bn(a),h=Pn(s),p=[],m=[],f=new Map;e.forEach((t,e)=>{const s=kn(Mn(t,e,i));if(null==s)return;const a=n?(Mn(t,e,n)??"All")+"":"All",c=o?kn(Mn(t,e,o)):null,d=Sn(null!=c&&c>0?c:r,2,18);!function(t){let e=f.get(t);null==e&&(e=m.length,m.push(t),f.set(t,e))}(a),p.push({datum:t,index:e,value:s,group:a,radius:d})});const y=p.map(t=>t.value),g=c?kn(c[0]):null,b=c?kn(c[1]):null,x=y.length?Math.min(...y):0,v=y.length?Math.max(...y):1;let w=g??x,I=b??v;if(w===I&&(w-=.5,I+=.5),w>I){const t=I;I=w,w=t}const M=Math.max(r,...p.map(t=>t.radius)),k=u.plot.x+M+8,S=u.plot.x+u.plot.width-M-8,A=Tn().domain([w,I]).range([k,S]),R=Math.max(1,m.length),P=Math.min(Math.max(28,3*M),u.plot.height/4),C=u.plot.y+P,$=Math.max(0,u.plot.y+u.plot.height-P-C),j=t=>{const e=f.get(t)??0;return 1===R?u.plot.y+.54*u.plot.height:C+e/(R-1)*$},B=new Map,O=p.map((t,e)=>{B.set(t.group,(B.get(t.group)??0)+1);const i=A(t.value),n=j(t.group),o=(h()-.5)*t.radius*1.6,r=(h()-.5)*t.radius*1.6;return{id:(t.datum.id??"collision-swarm-"+e)+"",x:l?i+o:Sn(i+(e%9-4)*t.radius*2.5,k,S),y:l?n+r:u.plot.y-18-e%12*t.radius,vx:l?0:22*(h()-.5),vy:l?0:24+18*h(),mass:1,shape:{type:"circle",radius:t.radius},datum:{...t.datum,xValue:t.value,group:t.group,radius:t.radius,targetX:i,targetY:n},springs:[{target:{type:"point",x:i,y:n},restLength:0,stiffness:34,damping:5.5}]}});return{config:wn(s,Zt({x:u.plot.x,y:u.plot.y,width:u.plot.width,height:u.plot.height},{idPrefix:"collision-swarm",includeCeiling:!1,wallThickness:20,floorThickness:20}),"CollisionSwarmChart",{gravity:{x:0,y:0},cellSize:Math.max(24,4*M),collisionIterations:Math.max(1,Math.round(d??6)),velocityDamping:.992,restitution:.02,friction:.18,sleepSpeed:3,sleepAfter:.5}),initialSpawns:O,projectionRows:m.map(t=>({label:t,value:B.get(t)??0})),metadata:{kind:"collision-swarm",xExtent:[w,I],xRange:[k,S],groups:m.map(t=>({label:t,y:j(t),count:B.get(t)??0})),plot:u.plot}}}function qn(t){if(Array.isArray(t)&&t.length>=2){const e=kn(t[0]),i=kn(t[1]);return null!=e&&null!=i?{x:e,y:i}:null}if(t&&"object"==typeof t){const e=t,i=kn(e.x),n=kn(e.y);return null!=i&&null!=n?{x:i,y:n}:null}return null}function Fn(t){return Array.isArray(t)?t.map(qn).filter(t=>null!=t):[]}function Wn(t,e,i){return"normalized"===i?{x:e.plot.x+t.x*e.plot.width,y:e.plot.y+t.y*e.plot.height}:{x:Sn(t.x,e.plot.x,e.plot.x+e.plot.width),y:Sn(t.y,e.plot.y,e.plot.y+e.plot.height)}}function Dn(t){let e=0;for(let i=1;t.length>i;i+=1)e+=Math.hypot(t[i].x-t[i-1].x,t[i].y-t[i-1].y);return e}function zn(t,e){if(0===t.length)return{x:0,y:0};if(1===t.length)return{...t[0]};const i=Sn(e,0,1)*Dn(t);let n=0;for(let e=1;t.length>e;e+=1){const o=t[e-1],r=t[e],s=Math.hypot(r.x-o.x,r.y-o.y);if(s>0){if(n+s>=i){const t=(i-n)/s;return{x:o.x+(r.x-o.x)*t,y:o.y+(r.y-o.y)*t}}n+=s}}return{...t[t.length-1]}}function Ln(t,e){const i=zn(t,Math.max(0,e-.02)),n=zn(t,Math.min(1,e+.02)),o=n.x-i.x,r=n.y-i.y,s=Math.hypot(o,r)||1;return{x:o/s,y:r/s}}function Yn(t){const{coordinateMode:e,flowSpeed:i,links:n,maxParticles:o,nodeIdAccessor:r,nodeXAccessor:s,nodeYAccessor:a,nodes:c,particleRadius:d,particleRate:l,pathAccessor:u,pathConstraint:h="path",reducedMotion:p,seed:m,size:f,sourceAccessor:y,targetAccessor:g,throughputAccessor:b}=t,x=bn(f),v=Pn(m),w=new Map,I=new Map,M=[];function k(t){if(t&&"object"==typeof t){const e=t;if("function"==typeof r){const t=r(e,0);if(null!=t)return t+""}if("string"==typeof r&&null!=e[r])return e[r]+"";if(null!=e.id)return e.id+""}return(t??"unknown")+""}c.forEach((t,e)=>{const i=(Mn(t,e,r)??t.id??e)+"",n=kn(Mn(t,e,s)),o=kn(Mn(t,e,a));if(null!=n&&null!=o){const t={x:n,y:o};w.set(i,t),M.push(t)}I.set(i,(t.label??t.name??i)+"")});const S=[];n.forEach((t,e)=>{const i=k(Mn(t,e,y)),n=k(Mn(t,e,g)),o=Math.max(0,kn(Mn(t,e,b))??0),r=Fn(u?Mn(t,e,u):void 0),s=r.length?r:Fn(t.path??t.points??t.route);s.forEach(t=>M.push(t)),S.push({id:(t.id??`physical-flow-${i}-${n}-${e}`)+"",link:t,index:e,source:i,target:n,throughput:o,rawPath:s})});const A=(P=M,"normalized"===(R=e)||"pixels"===R?R:P.length>0&&P.every(t=>!(0>t.x||t.x>1||0>t.y||t.y>1))?"normalized":"pixels");var R,P;const C=new Map;for(const[t,e]of w)C.set(t,Wn(e,x,A));const $=[];for(const t of S){let e=t.rawPath.map(t=>Wn(t,x,A));if(2>e.length){const i=C.get(t.source),n=C.get(t.target);i&&n&&(e=[i,n])}else C.has(t.source)||C.set(t.source,e[0]),C.has(t.target)||C.set(t.target,e[e.length-1]);e.length>=2&&t.throughput>0&&(I.has(t.source)||I.set(t.source,t.source),I.has(t.target)||I.set(t.target,t.target),$.push({...t,path:e,packetCount:0}))}const j=An(l,.12),B=Math.max(1,Math.round(o)),O=$.map(t=>Math.max(1,Math.round(t.throughput*j))),N=O.reduce((t,e)=>t+e,0),T=N>B?B/N:1;$.forEach((t,e)=>{t.packetCount=Math.max(1,Math.floor(O[e]*T))});let E=$.reduce((t,e)=>t+e.packetCount,0);for(;E>B;){const t=$.reduce((t,e,i)=>e.packetCount>1&&(-1===t||e.packetCount>$[t].packetCount)?i:t,-1);if(-1===t)break;$[t].packetCount-=1,E-=1}const q=new Map,F=new Map,W=[],D=An(i,90),z=An(d,4);$.forEach((t,e)=>{q.set(t.target,(q.get(t.target)??0)+t.throughput),F.set(t.source,(F.get(t.source)??0)+t.throughput);const i=Dn(t.path);for(let n=0;t.packetCount>n;n+=1){const o=(n+.5)/t.packetCount,r=p?o:Sn(.12+.84*o+.04*(v()-.5),.04,.98),s=p?r:Math.max(0,r-(.18+.12*v())),a=zn(t.path,s),c=zn(t.path,r),d=Ln(t.path,s),l={x:-d.y,y:d.x},u=(v()-.5)*z*1.5;W.push({id:`${t.id}-packet-${n}`,x:a.x+l.x*u,y:a.y+l.y*u,vx:p?0:d.x*D+10*(v()-.5),vy:p?0:d.y*D+10*(v()-.5),mass:.8,spawnAt:p?0:.04*e+n/32,shape:{type:"circle",radius:z},datum:{...t.link,source:t.source,target:t.target,throughput:t.throughput,packetIndex:n,packetCount:t.packetCount,routeProgress:r,flowPath:t.path,flowPathLength:i,flowRouteId:t.id,flowSpeed:D,sourceLabel:I.get(t.source)??t.source,targetLabel:I.get(t.target)??t.target},springs:"none"!==h&&p?[{target:{type:"point",x:c.x,y:c.y},restLength:.7*z,stiffness:26,damping:4.25}]:void 0})}});const L=Math.max(18,5*z),Y=Array.from(C,([t,e])=>({nodeId:t,label:I.get(t)??t,sensorId:"physical-flow-node-"+Rn(t),point:e})),_=Y.map(t=>({id:t.sensorId,sensor:!0,shape:{type:"aabb",x:t.point.x,y:t.point.y,width:L,height:L}})),H=Object.fromEntries(Y.map(t=>[t.sensorId,{binId:t.label,enterType:"physics-proximity-enter",exitType:"physics-proximity-exit"}])),X=wn(m,[...Zt({x:x.plot.x,y:x.plot.y,width:x.plot.width,height:x.plot.height},{idPrefix:"physical-flow",wallThickness:18,floorThickness:18}),..._],"PhysicalFlowChart",{gravity:{x:0,y:0},cellSize:Math.max(24,7*z),collisionIterations:3,velocityDamping:.994,restitution:.01,friction:.16,sleepSpeed:2.5,sleepAfter:.7});X.bodyLimit=B,X.eviction="oldest",X.observation={...X.observation,sensors:H};const G=Array.from(C,([t,e])=>({id:t,label:I.get(t)??t,x:e.x,y:e.y,sensorId:"physical-flow-node-"+Rn(t),incoming:q.get(t)??0,outgoing:F.get(t)??0})),V=$.map(t=>({id:t.id,source:t.source,target:t.target,sourceLabel:I.get(t.source)??t.source,targetLabel:I.get(t.target)??t.target,throughput:t.throughput,packetCount:t.packetCount,path:t.path}));return{config:X,initialSpawns:W,projectionRows:G.filter(t=>t.incoming>0||t.outgoing>0).map(t=>({label:t.label,value:t.incoming,secondary:t.outgoing})),metadata:{kind:"physical-flow",coordinateMode:A,particleCount:W.length,totalThroughput:$.reduce((t,e)=>t+e.throughput,0),plot:x.plot,nodes:G,links:V}}}function _n(t,e){if("region-enter"!==e.type)return t;const i=e.region.id,n=t[i]??{id:i,label:e.region.label??i,count:0,bodyIds:[]};if(n.bodyIds.includes(e.bodyId))return t;const o=[...n.bodyIds,e.bodyId];return{...t,[i]:{...n,count:o.length,bodyIds:o}}}function Hn(t,e){return(e??Object.keys(t)).map(e=>t[e]).filter(t=>null!=t).map(t=>({label:t.label??t.id,value:t.count}))}function Xn(t,e){const i=e instanceof Set?e:new Set(e);return t.map(t=>{const e=t.bodyIds??[],n=e.filter(t=>!i.has(t)),o=e.length-n.length,r=t.completion?.mode??"allMembersAbsorbed",s=t.completion?.valueByBodyId,a=t=>{const e=s?.[t];return Number.isFinite(e)&&Number(e)>=0?Number(e):1},c=e.reduce((t,e)=>t+a(e),0),d=e.reduce((t,e)=>t+(i.has(e)?a(e):0),0),l=t.completion?.threshold,u="threshold"===r?Number.isFinite(l)&&Number(l)>=0?Number(l):c:void 0;return{id:t.id,label:t.label??t.id,mode:r,complete:e.length>0&&("anyAbsorbed"===r?o>0:"threshold"===r?d>=(u??c):0===n.length),absorbed:o,total:e.length,absorbedValue:d,totalValue:c,threshold:u,missing:n}})}function Gn(t,e,i){return Math.max(e,Math.min(i,t))}function Vn(t,e,i={}){const n=i.random??Math.random,o=t.stages.find(t=>t.id===e)??t.stages[t.stages.length-1],r=Gn(i.along??.5,.05,.95),s=i.jitterX??0,a=i.padY??20,c=o.x0+(o.x1-o.x0)*r+(2*n()-1)*s,d=Math.min(1,o.width/2),l=Gn(c,o.x0+d,o.x1-d),u=t.boundaryY(l,"top")+a,h=t.boundaryY(l,"bottom")-a;return{x:l,y:h>u?u+n()*Math.max(1,h-u):t.midY}}function Un(t){return"bowtie"===t.shape?[{id:"incoming",role:"incoming",points:[[t.left,t.topY],[t.centerLeft,t.pinchTop],[t.centerLeft,t.pinchBottom],[t.left,t.bottomY]]},{id:"center",role:"center",points:[[t.centerLeft,t.pinchTop],[t.centerRight,t.pinchTop],[t.centerRight,t.pinchBottom],[t.centerLeft,t.pinchBottom]]},{id:"outgoing",role:"outgoing",points:[[t.centerRight,t.pinchTop],[t.right,t.topY],[t.right,t.bottomY],[t.centerRight,t.pinchBottom]]}]:[{id:"volume",role:"volume",points:[[t.left,t.topY],[t.right,"funnel"===t.shape?t.pinchTop:t.topY],[t.right,"funnel"===t.shape?t.pinchBottom:t.bottomY],[t.left,t.bottomY]]}]}function Kn(t,e,i){return Math.max(e,Math.min(i,t))}function Qn(t,e,i,n,o,r={}){return{id:t,friction:r.friction,restitution:r.restitution,bodyFilter:r.bodyFilter,shape:{type:"segment",x1:e,y1:i,x2:n,y2:o,thickness:r.thickness??8}}}function Zn(t){const e=t.shape??"lane",i=Math.max(1,Math.round(t.width)),n=Math.max(1,Math.round(t.height)),o=t.padX??46,r=t.padY??72,s=o,a=i-o,c=r,d=n-Math.max(24,Math.round(.45*r)),l=(c+d)/2,u=Math.max(1,d-c),h=Kn(t.pinchRatio??.18,.06,.5),p=Number(t.pinchHeightOffset??0),m=Number.isFinite(p)?p:0,f=Kn(u*h+m,.06*u,.5*u),y=f/2,g=l-y,b=l+y,x=t.idPrefix??"process",v=t.friction??.58,w=t.restitution??.18,I=t.wallThickness??8,M=t.stages;if(!M.length)throw Error("processStageLayout requires at least one stage");const k=Kn(t.centerStageIndex??Math.floor(M.length/2),0,M.length-1),S=function(t){const e=t.reduce((t,e)=>t+(e.share??1),0);return e>0?e:t.length}(M),A=a-s;let R=s;const P=M.map((t,e)=>{const i=R,n=e===M.length-1?a:R+(t.share??1)/S*A;return R=n,{id:t.id,label:t.label,description:t.description,kind:t.kind??"stage",index:e,x0:i,x1:n,x:(i+n)/2,width:n-i,y:l,height:u}}),C=P[k],$=C.x0,j=C.x1,B=(t,i)=>{if("lane"===e)return"top"===i?c:d;if("funnel"===e){const e=Kn((t-s)/Math.max(1,a-s),0,1);return"top"===i?c+(g-c)*e:d+(b-d)*e}if($>=t){const e=Kn((t-s)/Math.max(1,$-s),0,1);return"top"===i?c+(g-c)*e:d+(b-d)*e}if(j>=t)return"top"===i?g:b;const n=Kn((t-j)/Math.max(1,a-j),0,1);return"top"===i?g+(c-g)*n:b+(d-b)*n},O=P.map(t=>{const e=Math.min(B(t.x0,"top"),B(t.x1,"top")),i=Math.max(B(t.x0,"bottom"),B(t.x1,"bottom"));return{...t,y:(e+i)/2,height:Math.max(1,i-e)}}),N={thickness:I,friction:v,restitution:w},T=[];"lane"===e?T.push(Qn(x+"-top",s,c,a,c,N),Qn(x+"-bottom",s,d,a,d,N),Qn(x+"-left",s,c,s,d,{...N,thickness:Math.max(6,I-2)}),Qn(x+"-right",a,c,a,d,{...N,thickness:Math.max(6,I)})):"funnel"===e?T.push(Qn(x+"-top",s,c,a,g,N),Qn(x+"-bottom",s,d,a,b,N),Qn(x+"-left",s,c,s,d,{...N,thickness:Math.max(6,I-2)}),Qn(x+"-right",a,g,a,b,{...N,thickness:Math.max(6,I)})):T.push(Qn(x+"-left-top",s,c,$,g,N),Qn(x+"-left-bottom",s,d,$,b,N),Qn(x+"-center-top",$,g,j,g,N),Qn(x+"-center-bottom",$,b,j,b,N),Qn(x+"-right-top",j,g,a,c,N),Qn(x+"-right-bottom",j,b,a,d,N),Qn(x+"-left",s,c,s,d,{...N,thickness:Math.max(6,I-2)}),Qn(x+"-right",a,c,a,d,{...N,thickness:Math.max(6,I)}));const E=t.membraneDampingScale??.5,q=s,F=Math.max(1,("bowtie"===e?$:a)-q),W=(t.membranes??[]).map(t=>{const e=q+Kn(t.offset,0,1)*F,i=t.width??18+18*t.cost,n=u-16,o=l+.25*(t.wobble??0);return{...t,x:e,y:o,width:i,height:n}}),D=!1===t.includeMembraneRegions?[]:W.map(t=>eo({id:t.id,label:t.label??t.id,description:t.description??(t.label??t.id)+" is a permeable region. It taxes energy and damps velocity while bodies overlap it.",x:t.x,y:t.y,width:t.width,height:t.height,cost:t.cost,dampingScale:t.dampingScale??E,bodyStyle:t.bodyStyle,metadata:t.metadata,semanticItem:t.semanticItem,color:t.color}));return{shape:e,width:i,height:n,padX:o,padY:r,left:s,right:a,topY:c,bottomY:d,midY:l,centerLeft:$,centerRight:j,pinchHeight:f,pinchTop:g,pinchBottom:b,stages:O,membranes:W,colliders:T,regionEffects:D,boundaryY:B}}function Jn(t){return{id:t.id,label:t.label,description:t.description,kind:t.kind,shape:(e=t.x,i=t.y,n=t.width,o=t.height,{type:"aabb",x:e,y:i,width:n,height:o}),bodyFilter:t.bodyFilter,collider:t.collider,colliderThickness:t.colliderThickness,friction:t.friction,restitution:t.restitution,semanticItem:t.semanticItem,metadata:t.metadata,bodyStyle:t.bodyStyle,attributes:t.attributes,onEnter:t.onEnter,onExit:t.onExit};var e,i,n,o}function to(t,e={}){const i=e.idPrefix??"stage",n=Math.max(0,e.insetX??0),o=Math.max(0,e.insetY??1);return t.stages.map(t=>{const r="function"==typeof e.metadata?e.metadata(t):e.metadata??{};return{...Jn({id:i?`${i}:${t.id}`:t.id,label:t.label??t.id,description:t.description,kind:"region",x:t.x,y:t.y,width:Math.max(1,t.width-2*n),height:Math.max(1,t.height-2*o),bodyFilter:e.bodyFilter,semanticItem:e.semanticItem,attributes:{primitive:"processStage",stageId:t.id,stageIndex:t.index},metadata:{...r,primitive:"processStage",stageId:t.id,stageIndex:t.index}})}})}function eo(t){const e=t.dampingScale??.5,i=t.energyScale??1,n=Kn(t.cost,0,2);return{...Jn({...t,kind:t.kind??"membrane",attributes:{primitive:"membrane",membraneCost:n,..."object"==typeof t.attributes&&t.attributes?t.attributes:{}}}),damping:n*e,energyDelta:-n*i}}function io(t){return{...Jn({...t,kind:t.kind??"charge-gate",attributes:{primitive:"chargeGate",..."object"==typeof t.attributes&&t.attributes?t.attributes:{}}}),charge:t.charge??!0,energyDelta:t.energyDelta,impulseOnEnter:t.impulseOnEnter}}function no(t){const e="number"==typeof t.force?{x:t.force,y:0}:t.force??{x:12,y:0};return{...Jn({...t,kind:t.kind??"force-field",attributes:{primitive:"routeSurface",..."object"==typeof t.attributes&&t.attributes?t.attributes:{}}}),force:e,damping:t.damping??.015}}function oo(t){const e=t.pressure??t.occupancy??0,i=t.baseDamping??.08,n=t.dampingPerUnit??.12,o=t.energyPerUnit??0;return{...Jn({...t,kind:t.kind??"membrane",attributes:{primitive:"pressureField",pressure:e,..."object"==typeof t.attributes&&t.attributes?t.attributes:{}}}),damping:i+e*n,energyDelta:o?-e*o:void 0,force:t.force}}function ro(t){const e="number"==typeof t.force?{x:t.force,y:0}:t.force;return{...Jn({...t,kind:t.kind??"force-field",attributes:{primitive:"capacitatedSensor",capacity:t.capacity,unitsPerSecond:t.unitsPerSecond??t.capacity,..."object"==typeof t.attributes&&t.attributes?t.attributes:{}}}),force:e,damping:t.damping,charge:t.charge??t.capacity}}function so(t){return{...Jn({...t,kind:t.kind??"force-field",attributes:{primitive:"portal",targetStage:t.targetStage,..."object"==typeof t.attributes&&t.attributes?t.attributes:{}}}),force:t.force,impulseOnEnter:t.impulseOnEnter,damping:t.damping??.08}}function ao(t){const e="number"==typeof t.force?{x:t.force,y:0}:t.force??{x:24,y:0};return{...Jn({...t,kind:t.kind??"sink",attributes:{primitive:"absorb",..."object"==typeof t.attributes&&t.attributes?t.attributes:{}}}),force:e,damping:t.damping??.02,charge:t.charge??"absorbed"}}function co(t){return{...Jn({...t,kind:t.kind??"force-field",attributes:{primitive:"forceField",..."object"==typeof t.attributes&&t.attributes?t.attributes:{}}}),force:t.force,damping:t.damping,energyDelta:t.energyDelta}}function lo(t){const e=t.x??t.anchor?.x??0,i=t.y??t.anchor?.y??0;return{id:t.id,label:t.label,description:t.description,group:t.group,bodyIds:t.bodyIds,datum:t.datum,state:t.state,x:e,y:i,width:t.width,height:t.height,anchor:t.anchor??{x:e,y:i},completion:t.completion,tether:t.tether,semanticItem:t.semanticItem}}function uo(t){const e=t.idPrefix??"lane",i={thickness:t.thickness??8,friction:t.friction??.5,restitution:t.restitution??.16},n=[Qn(e+"-top",t.left,t.top,t.right,t.top,i),Qn(e+"-bottom",t.left,t.bottom,t.right,t.bottom,i)];return t.openEnds||n.push(Qn(e+"-left",t.left,t.top,t.left,t.bottom,i),Qn(e+"-right",t.right,t.top,t.right,t.bottom,i)),n}function ho(t,e=12){return"number"==typeof t?{x:t,y:0}:t&&"object"==typeof t?{x:Number.isFinite(t.x)?Number(t.x):e,y:Number.isFinite(t.y)?Number(t.y):0}:{x:e,y:0}}function po(t){const e=t.stages;if(!e.length)throw Error("buildProcessFlowPhysics requires at least one stage");const i=t.size,n=bn(i),o=Sn(t.ballRadius??6,2,18),r=t.seed??1,s=Pn(r),a=t.idAccessor,c=t.stageAccessor??"stage",d=t.groupBy,l=t.groupLabelAccessor,u=t.workAccessor,h=t.radiusAccessor,p=t.groupCompletion??(d?"allAbsorbed":"none"),m=t.springStiffness??.28,f=t.springDamping??.72,y=!0===t.settle,g=e.map(t=>({id:t.id,label:t.label??t.id,description:t.description,share:t.share})),b=Zn({width:i[0],height:i[1],shape:"lane",padX:Math.max(28,n.plot.x),padY:Math.max(36,n.plot.y+8),stages:g,idPrefix:"process-flow",includeMembraneRegions:!1,friction:.48,restitution:.14}),x=new Map(b.stages.map((t,e)=>[t.id,e])),v=new Map(b.stages.map(t=>[t.id,t])),w=b.stages[0].id,I=b.stages[0],M=new Set(e.filter(t=>t.absorb).map(t=>t.id)),k=e.map(t=>{const e=v.get(t.id)??I;return function(t,e){const i={id:"process-stage-"+t.id,label:t.label??t.id,description:t.description,x:e.x,y:e.y,width:Math.max(12,.92*e.width),height:Math.max(40,.88*e.height),semanticItem:!1,attributes:{stageId:t.id}};if(t.absorb)return ao({...i,kind:t.kind??"sink",force:ho(t.force,28),damping:t.damping??.04,charge:"absorbed",attributes:{...i.attributes,primitive:"absorb"}});if(t.portal){const e=t.portal.force??t.force??{x:-40,y:0};return so({...i,kind:t.kind??"force-field",force:ho(e,-40),damping:t.damping??.1,targetStage:t.portal.targetStageId,attributes:{...i.attributes,primitive:"portal",targetStage:t.portal.targetStageId}})}if(t.capacity){const e=Math.max(.1,t.capacity.unitsPerSecond);return ro({...i,kind:t.kind??"force-field",capacity:e,unitsPerSecond:e,force:ho(t.force,10+.8*e),damping:t.damping??Math.max(.04,.32-.01*e),attributes:{...i.attributes,unitAccessor:t.capacity.unitAccessor,reviewerCapacity:e}})}if(t.pressure){const e="object"==typeof t.pressure&&t.pressure?t.pressure:{};return oo({...i,kind:t.kind??"membrane",pressure:e.pressure,occupancy:e.occupancy,baseDamping:e.baseDamping??t.damping??.1,dampingPerUnit:e.dampingPerUnit??.1,energyPerUnit:e.energyPerUnit??0,force:ho(t.force,8),attributes:{...i.attributes,primitive:"pressureField"}})}return null!=t.force||null!=t.damping?no({...i,kind:t.kind??"force-field",force:ho(t.force,14),damping:t.damping??.02,attributes:{...i.attributes,primitive:"routeSurface"}}):co({...i,kind:t.kind??"force-field",force:{x:10,y:0},damping:.02,attributes:{...i.attributes,primitive:"forceField"}})}(t,{x:e.x,y:b.midY,width:e.width,height:b.bottomY-b.topY})});k.unshift(no({id:"process-flow-route",label:"process route",description:"Baseline conveyor along the process lane.",x:(b.left+b.right)/2,y:b.midY,width:b.right-b.left,height:b.bottomY-b.topY-12,force:8,damping:.012,semanticItem:!1}));const S=new Map;for(const t of b.stages)S.set(t.id,0);const A=[];t.data.forEach((t,e)=>{const i=(a?Mn(t,e,a)??t.id??"process-flow-"+e:t.id??"process-flow-"+e)+"",n=(Mn(t,e,c)??w)+"",r=x.has(n)?n:w;S.set(r,(S.get(r)??0)+1);const s=d?(Mn(t,e,d)??"")+"":void 0,p=s&&l?(Mn(t,e,l)??s)+"":s,m=u?kn(Mn(t,e,u))??1:1,f=h?kn(Mn(t,e,h)):null,y=Sn(null!=f&&f>0?f:o,2,18);A.push({datum:t,id:i,stageId:r,groupId:s||void 0,groupLabel:p||void 0,work:m,radius:y,index:e})});const R=new Map,P=new Map;for(const t of A){if(!t.groupId)continue;const e=R.get(t.groupId)??[];e.push(t.id),R.set(t.groupId,e),t.groupLabel&&P.set(t.groupId,t.groupLabel)}const C=Sn(t.groupAnchorAlong??.55,.15,.9),$=b.left+(b.right-b.left)*C,j=Array.from(R.keys()),B=j.map((t,i)=>{const n=R.get(t)??[],o=j.length>1?b.topY+28+i/Math.max(1,j.length-1)*(b.bottomY-b.topY-56):b.midY;return lo({id:t,label:P.get(t)??t,bodyIds:n,anchor:{x:$,y:o},x:$,y:o,completion:"allAbsorbed"===p?{mode:"allMembersAbsorbed",targetZone:e.find(t=>t.absorb)?.id??"merged"}:void 0,tether:{stiffness:.06,visible:!0,restLength:18}})}),O=Xn(B,A.filter(t=>M.has(t.stageId)).map(t=>t.id)),N=new Map(B.map(t=>[t.id,t])),T=A.map((t,e)=>{const i=v.get(t.stageId)??I,n=i.x+(s()-.5)*Math.min(24,.2*i.width),o=b.boundaryY(n,"top")+t.radius+10,r=b.boundaryY(n,"bottom")-t.radius-10,a=r>o?o+s()*Math.max(1,r-o):b.midY,c=y?n:b.left+18+e%7*4,d=y?a:b.midY+(s()-.5)*(b.bottomY-b.topY)*.35,l=[{target:{type:"point",x:n,y:a},restLength:.45*t.radius,stiffness:m,damping:f}];if(t.groupId){const e=N.get(t.groupId);e?.anchor&&!M.has(t.stageId)&&l.push({target:{type:"point",x:e.anchor.x,y:e.anchor.y},restLength:e.tether?.restLength??22,stiffness:e.tether?.stiffness??.05,damping:.8})}return{id:t.id,x:c,y:d,vx:y?0:40+40*s(),vy:y?0:20*(s()-.5),mass:1,shape:{type:"circle",radius:t.radius},spawnAt:y?0:.03*e,springs:l,datum:{...t.datum,id:t.id,stage:t.stageId,groupId:t.groupId,groupLabel:t.groupLabel,work:t.work,__processFlow:!0}}}),E={kernel:{seed:r,gravity:{x:t.gravityX??22,y:t.gravityY??0},restitution:.14,friction:.48,velocityDamping:.988,maxVelocity:420,sleepSpeed:8,sleepAfter:.9,collisionIterations:4},colliders:b.colliders,fixedDt:1/60,maxSubsteps:8},q=b.stages.map(t=>({label:t.label??t.id,value:S.get(t.id)??0})),F=e.map(t=>{const e=v.get(t.id)??I;return{id:t.id,label:t.label??t.id,x:e.x,width:e.width,count:S.get(t.id)??0,capacity:t.capacity?.unitsPerSecond,absorb:!0===t.absorb,portalTarget:t.portal?.targetStageId}});return{config:E,initialSpawns:T,initialSpawnPacing:y?void 0:{pacing:"arrival",timeAccessor:"spawnAt",timeScale:1},projectionRows:q,metadata:{kind:"process-flow",plot:n.plot,volume:b,stages:F,groups:B,groupCompletion:O,regionEffects:k}}}import{forwardRef as mo,useCallback as fo,useMemo as yo,useRef as go}from"react";import{useImperativeHandle as bo,useRef as xo}from"react";function vo(t,e){if(!e?.length)return[t];const i=e.filter(e=>{if(e.id===t||e.id.startsWith(t+"-"))return!0;const i=e.datum;return!(!i||"object"!=typeof i||null==i.id)&&i.id+""===t}).map(t=>t.id);return i.length?i:[t]}function wo(t,e,i){if("function"==typeof i)return i(t,e)+"";if("string"==typeof i){const e=t[i];if(null!=e)return e+""}return null!=t&&"object"==typeof t&&"id"in t&&null!=t.id?t.id+"":"physics-row-"+e}function Io(t,e){const i=t?.getData().find(t=>t.id===e),n=i?.datum;if(n&&"object"==typeof n)return n}function Mo(t,e){const{frameRef:i,spawnDatum:n,seedRows:o,idAccessor:r,bodyIdsForSeed:s,seedSpawns:a}=e,c=xo(new Map),d=xo(new Map),l=xo(""),u=o?o.map((t,e)=>wo(t,e,r)).join("\0"):"";if(u!==l.current&&(l.current=u,o))for(let t=0;o.length>t;t+=1){const e=o[t],i=wo(e,t,r);c.current.set(i,e),d.current.set(i,s?.(e,i,t)??vo(i,a))}bo(t,()=>{const t=c.current,e=d.current;function o(t,e){const i=n(t,e);return{datumId:i.datumId||wo(t,e,r),spawns:i.spawns.map(t=>({...t,spawnAt:void 0}))}}function s(n){const o=[];for(const{datum:i,result:r}of n)t.set(r.datumId,i),e.set(r.datumId,r.spawns.map(t=>t.id)),o.push(...r.spawns);if(!o.length)return;const r=i.current;r?(r.pushMany(o),r.step(0)):"production"!==process.env.NODE_ENV&&console.warn("[semiotic/physics] push() called before the physics frame mounted (loading/empty early-return). Omit data for push mode and ensure the chart is mounted.")}function a(n){const o=t.get(n);if(o)return o;const r=e.get(n)??[n];for(const o of r){const r=Io(i.current,o);if(r)return t.set(n,r),e.has(n)||e.set(n,[o]),r}}return{push:e=>{s([{datum:e,result:o(e,t.size)}])},pushMany:e=>{const i=t.size;s(e.map((t,e)=>({datum:t,result:o(t,i+e)})))},remove:n=>{const o=Array.isArray(n)?n:[n],r=[],s=[];for(const i of o){const n=a(i);n&&r.push(n),t.delete(i),s.push(...e.get(i)??[i]),e.delete(i)}return s.length&&i.current?.remove(s),r},update:(n,r)=>{const c=Array.isArray(n)?n:[n],d=[];for(const n of c){const c=a(n);if(!c)continue;d.push(c);const l=e.get(n)??[n];i.current?.remove(l),t.delete(n),e.delete(n);const u=r(c);s([{datum:u,result:o(u,t.size)}])}return d},clear:()=>{t.clear(),e.clear(),l.current="",i.current?.clear()},getData:()=>{const e=i.current;if(!e)return Array.from(t.values());const n=e.getData().map(t=>t.datum).filter(t=>!!t&&"object"==typeof t);return n.length?n:Array.from(t.values())},getScales:()=>null,getCustomLayout:()=>i.current?.snapshot()??null,popBodies:(t,e)=>i.current?.popBodies(t,e)??[]}},[i,r,n])}import{useCallback as ko,useEffect as So,useMemo as Ao,useRef as Ro,useState as Po}from"react";import{Fragment as Co,jsx as $o,jsxs as jo}from"react/jsx-runtime";var Bo=new Set(["sample","mechanical"]);function Oo(t,e,i,n){const[o,r]=Po(0),s=Ro(null),a=Ro(!1),c=function(t){return"number"==typeof t&&Number.isFinite(t)&&t>=0?t:null}(e),d=Ro(c),l=Ro(!!i),u=Ro(n);d.current=c,l.current=!!i,u.current=n;const h=ko(()=>{null!=s.current&&(clearTimeout(s.current),s.current=null)},[]),p=ko(()=>{h();const t=d.current;null!=t&&!l.current&&a.current&&(s.current=setTimeout(()=>{s.current=null,a.current=!1,u.current?.(),r(t=>t+1)},t))},[h]);So(()=>{null==c||i?h():a.current&&p()},[h,c,i,p]),So(()=>h,[h]);const m=t?.observation?.onSimulationStateChange,f=ko((t,e)=>{if(m?.(t,e),"running"===t)return a.current=!1,void h();"settled"===t&&"running"===e&&(a.current=!0,p())},[h,m,p]);return{config:Ao(()=>null==c?t:{...t,observation:{...t?.observation,onSimulationStateChange:f}},[t,c,f]),rerunKey:o}}function No(t,e,i){const n=i?.hasSimulationMode?function(t){const e=t=>"string"==typeof t&&Bo.has(t);return t.simulationMode?{chartMode:e(t.mode)?void 0:t.mode,simulationMode:t.simulationMode}:e(t.mode)?{chartMode:void 0,simulationMode:t.mode}:{chartMode:t.mode,simulationMode:"sample"}}({mode:t.mode,simulationMode:t.simulationMode}):{chartMode:"sample"===t.mode||"mechanical"===t.mode?void 0:t.mode,simulationMode:"sample"},o=$(n.chartMode,{width:t.width,height:t.height,enableHover:t.enableHover,title:t.title,description:t.description,summary:t.summary,accessibleTable:t.accessibleTable,mobileInteraction:t.mobileInteraction,mobileSemantics:t.mobileSemantics,responsiveRules:t.responsiveRules},{width:e[0],height:e[1]}),r=t.size?.[0],s=t.size?.[1],a=e[0],c=e[1],d=Ao(()=>{return t=[a,c],(null!=r&&null!=s?[r,s]:void 0)??[o.width??t[0],o.height??t[1]];var t},[c,a,o.height,o.width,s,r]),l=o.compactMode?"sparkline"===n.chartMode?{top:2,right:2,bottom:2,left:2}:{top:8,right:8,bottom:8,left:8}:{top:0,right:0,bottom:0,left:0};const u=t.showProjection??!o.compactMode,h=t.showChrome??!o.compactMode,p=Fo(t.tooltip,void 0),m=void 0!==p.enableHover?p.enableHover:o.enableHover,f=o.compactMode?o.title:o.title??t.title,y=[t.className,n.chartMode&&"primary"!==n.chartMode?"semiotic-physics--"+n.chartMode:null].filter(Boolean).join(" ")||void 0;return{chartMode:n.chartMode,simulationMode:n.simulationMode,resolved:o,chartSize:d,margin:l,showProjection:u,showChrome:h,enableHover:m,title:f,description:o.description??t.description,summary:o.summary??t.summary,accessibleTable:o.accessibleTable??t.accessibleTable,className:y,compactMode:o.compactMode,mobileInteraction:o.mobileInteraction,mobileSemantics:o.mobileSemantics}}function To(t){const[e,i]=t.size;return L(t.loading,e,i,t.loadingContent)||z(t.data,e,i,t.emptyContent)}function Eo(t,e,i){return $o(D,{componentName:t,width:e[0],height:e[1],children:i})}function qo(t,e){return t?e?i=>jo(Co,{children:["function"==typeof t?t(i):t,"function"==typeof e?e(i):e]}):t:e}function Fo(t,e){return!1===t?{enableHover:!1}:{enableHover:e?.enableHover,tooltipContent:M(t)||e?.tooltipContent}}function Wo(t,e,i,n){return{accessibleTable:n?.accessibleTable??t.accessibleTable??e?.accessibleTable,annotations:t.annotations??e?.annotations,autoPlaceAnnotations:t.autoPlaceAnnotations??e?.autoPlaceAnnotations,background:t.background??e?.background,chartId:t.chartId??e?.chartId,chartMode:n?.chartMode??e?.chartMode,className:n?.className??t.className??e?.className,color:t.color??e?.color,description:n?.description??t.description??e?.description,emphasis:t.emphasis??e?.emphasis,enableHover:n?.enableHover??e?.enableHover,hoverRadius:t.hoverRadius??e?.hoverRadius,legend:t.legend??e?.legend,legendLayout:t.legendLayout??e?.legendLayout,legendPosition:t.legendPosition??e?.legendPosition,margin:n?.margin??e?.margin,onClick:null!=t.onClick?(e,i)=>{e&&t.onClick?.(e,{x:i.x,y:i.y})}:e?.onClick,onObservation:t.onObservation??e?.onObservation,onAnnotationActivate:e?.onAnnotationActivate,opacity:t.opacity??e?.opacity,semanticItems:e?.semanticItems??i,stroke:t.stroke??e?.stroke,strokeWidth:t.strokeWidth??e?.strokeWidth,summary:n?.summary??t.summary??e?.summary,svgAnnotationRules:t.svgAnnotationRules??e?.svgAnnotationRules,title:n?.title??t.title??e?.title}}import{Fragment as Do,jsx as zo,jsxs as Lo}from"react/jsx-runtime";var Yo=mo(function(t,e){const{data:i,valueAccessor:n="value",styleRules:o,bins:r=21,ballRadius:s,colorBy:a,branchProbability:c=.5,emptyContent:d,frameProps:l,loading:u,loadingContent:h,mechanicalCount:p,paused:m,pegRows:f,referenceLines:y,rerunMS:g,responsiveHeight:b,responsiveWidth:x,seed:v=1,valueExtent:w}=t,I=No(t,[700,420],{hasSimulationMode:!0}),{chartSize:M,simulationMode:k,showProjection:S,className:A,title:R,chartMode:P,margin:C,enableHover:$,description:j,summary:B,accessibleTable:O}=I,N=s??("sparkline"===P?1.5:"context"===P?4:6),T=go(null),E=Math.max(1,Math.round(f??r-1)),q=yo(()=>"mechanical"===k?[0,E]:function(t){if(!t)return;const e=Number(t[0]),i=Number(t[1]);return Number.isFinite(e)&&Number.isFinite(i)?e>i?[i,e]:[e,i]:void 0}(w),[E,k,w]),F=yo(()=>"mechanical"===k?function(t){const e=Math.max(2,Math.round(t.bins)),i=Math.max(1,Math.round(t.pegRows??e-1)),n=Math.max(1,Math.round(t.count??Math.max(64,4*e))),o=Sn(Number.isFinite(t.branchProbability)?t.branchProbability??.5:.5,0,1),r=Pn(t.seed??1),s=t.idPrefix??"mechanical";return Array.from({length:n},(t,e)=>{let n=0;for(let t=0;i>t;t+=1)r()<o&&(n+=1);const a=i/2;return{id:`${s}-${e}`,value:n,mechanical:!0,pegRows:i,branchProbability:o,pathRights:n,side:a>n?"left":n>a?"right":"center"}})}({bins:r,branchProbability:c,count:p,pegRows:E,seed:v}):i??[],[r,c,i,p,E,v,k]),W=yo(()=>Cn({data:F,valueAccessor:n,bins:r,ballRadius:N,seed:v,size:M,valueExtent:q}),[r,F,M,N,q,v,n]),D=Oo(W.config,g,m);Mo(e,{frameRef:T,spawnDatum:fo((t,e)=>{const i=Cn({data:[t],valueAccessor:n,bins:r,ballRadius:N,seed:v+e+1,size:M,valueExtent:q}).initialSpawns[0]??{id:(t.id??"galton-push-"+e)+"",x:bn(M).plot.x,y:bn(M).plot.y,mass:1,shape:{type:"circle",radius:N},datum:t};return{datumId:(t.id??i.id)+"",spawns:[i]}},[r,M,N,q,v,n]),seedRows:F,seedSpawns:W.initialSpawns});const z="mechanical"===k&&null==a?"side":a,L=yo(()=>vn(z,"#4e79a7",{styleRules:o,valueAccessor:n}),[z,o,n]),Y=yo(()=>In(W.projectionRows,M,"bin"),[M,W.projectionRows]),_=To({data:"mechanical"===k?F:i,emptyContent:d,loading:u,loadingContent:h,size:M});if(_)return _;const H=function(t,e,i,n,o){const r=Array.isArray(o)?o:o?[o]:[];if(!1!==i||0!==r.length)return({size:o})=>{const s=[Number(o[0])||700,Number(o[1])||420],a=bn(s),c=Math.max(2,Math.round(e)),d=a.plot.width/c,l=a.plot.y+a.plot.height,u=Math.max(1,...t.map(t=>t.value)),h=!1!==i,[p,m]=n?.valueExtent??[0,c],f=m===p?1:m-p,y=t.map((t,e)=>{const i=l-t.value/u*a.plot.height*.9;return`${0===e?"M":"L"} ${(a.plot.x+(e+.5)*d).toFixed(1)} ${i.toFixed(1)}`}).join(" ");return Lo("svg",{"aria-hidden":"true","data-testid":"galton-board-structure-overlay",width:s[0],height:s[1],viewBox:`0 0 ${s[0]} ${s[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[h?Lo(Do,{children:[Array.from({length:c+1},(t,e)=>{const i=a.plot.x+e*d;return zo("line",{"data-testid":"galton-board-bin-wall",x1:i,x2:i,y1:a.plot.y,y2:l,stroke:"var(--semiotic-border, #d1d5db)",strokeOpacity:.28,strokeWidth:1},"bin-wall-"+e)}),zo("line",{x1:a.plot.x,x2:a.plot.x+a.plot.width,y1:l,y2:l,stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:1.5}),zo("path",{d:y,fill:"none",stroke:"var(--semiotic-accent, #4e79a7)",strokeOpacity:.7,strokeWidth:2,strokeLinejoin:"round"}),t.map((t,e)=>t.value>0?zo("text",{x:a.plot.x+(e+.5)*d,y:Math.max(a.plot.y+10,l-t.value/u*a.plot.height*.9-6),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:t.value},`${t.label}-${e}`):null)]}):null,r.map((t,e)=>{const i=Number(t.value);if(!Number.isFinite(i))return null;const n=a.plot.x+Math.max(0,Math.min(1,(i-p)/f))*a.plot.width,o=t.color??"var(--semiotic-warning, #f28e2b)",r="bottom"===t.labelPosition?Math.min(s[1]-8,l+16):a.plot.y+16;return Lo("g",{className:t.className,"data-testid":"galton-board-reference-line",children:[zo("line",{x1:n,x2:n,y1:a.plot.y+8,y2:l-4,stroke:o,strokeDasharray:t.strokeDasharray??"6 5",strokeWidth:t.strokeWidth??2}),null==t.label?null:zo("text",{x:Math.min(a.plot.x+a.plot.width-4,n+6),y:r,fill:o,fontSize:10,fontWeight:700,children:t.label})]},`galton-reference-${e}-${i}`)})]})}}(W.projectionRows,r,S,W.metadata,y),X=Fo(t.tooltip,l),G=Wo(t,l,Y,{chartMode:P,className:A,title:R,description:j,summary:B,accessibleTable:O,enableHover:$,margin:C});return Eo("GaltonBoardChart",M,zo(yn,{...l,...X,...G,ref:T,config:D.config,foregroundGraphics:qo(H,l?.foregroundGraphics),initialSpawns:W.initialSpawns,initialSpawnPacing:W.initialSpawnPacing,paused:m,responsiveHeight:b,responsiveWidth:x,size:M,bodyStyle:L},D.rerunKey))});import{forwardRef as _o,useCallback as Ho,useMemo as Xo,useRef as Go}from"react";import{jsx as Vo,jsxs as Uo}from"react/jsx-runtime";var Ko=_o(function(t,e){const{arrivalAccessor:i="arrivalTime",ballRadius:n=7,colorBy:o,styleRules:r,data:s,emptyContent:a,frameProps:c,loading:d,loadingContent:l,paused:u,responsiveHeight:h,responsiveWidth:p,seed:m=1,timeAccessor:f="time",timeExtent:y,timeScale:g=1,watermark:b,windows:x={size:10}}=t,v=No(t,[760,360]),{chartSize:w,showProjection:I,className:M,title:k,chartMode:S,margin:A,enableHover:R,description:P,summary:C,accessibleTable:$}=v,j=Go(null),B=Xo(()=>s??[],[s]),O=Xo(()=>Bn({data:B,timeAccessor:f,arrivalAccessor:i,windows:x,watermark:b,ballRadius:n,seed:m,size:w,timeExtent:y,timeScale:g}),[i,n,w,B,m,f,y,g,b,x]),N=O.metadata;Mo(e,{frameRef:j,spawnDatum:Ho((t,e)=>{const o=N?function(t,e,i,n){const o=kn(Mn(t,e,n.timeAccessor));if(null==o)return null;const r=kn(Mn(t,e,n.arrivalAccessor))??o,{windowPlot:s,windowStart:a,windowCount:c,windowSize:d,watermarkValue:l}=i,u=a+c*d,h=$n().domain([a,u]).range([s.x,s.x+s.width]),p=Math.max(0,Math.min(c-1,Math.floor((o-a)/d))),m=l>=a+(p+1)*d,{ballRadius:f}=n;return{id:(t.id??"event-push-"+e)+"",x:Math.max(s.x+f,Math.min(s.x+s.width-f,h(o))),y:s.y+f+2,vx:8*(e%3-1),vy:0,mass:1,friction:.02,shape:{type:"circle",radius:f},datum:{...t,eventTime:o,arrivalTime:r,windowIndex:p,late:m}}}(t,e,N,{timeAccessor:f,arrivalAccessor:i,ballRadius:n}):null,r=o??{id:(t.id??"event-push-"+e)+"",x:bn(w).plot.x,y:bn(w).plot.y,mass:1,shape:{type:"circle",radius:n},datum:t};return{datumId:(t.id??r.id)+"",spawns:[r]}},[i,n,w,N,f]),seedRows:B,seedSpawns:O.initialSpawns});const T=Xo(()=>vn(o,"#4e79a7",{styleRules:r,valueAccessor:f}),[o,r,f]),E=Xo(()=>function(t,e,i){if(!e)return In(t,i,"window");const n=e.windowPlot.width/Math.max(1,t.length),o=Math.max(1,...t.map(t=>t.value+(t.secondary??0))),r=.62*e.windowPlot.height,s=e.windowPlot.y+e.windowPlot.height;return t.map((t,i)=>{const a=Math.max(8,(t.value+(t.secondary??0))/o*r),c=`window ${t.label}: ${t.value} on time${t.secondary?`, ${t.secondary} late`:""}`;return{id:"window-"+t.label,label:c,description:c,datum:t,x:e.windowPlot.x+(i+.5)*n,y:s-a/2,shape:"rect",width:Math.max(12,.58*n),height:a,group:"window"}})}(O.projectionRows,N,w),[w,O.projectionRows,N]),q=To({data:s,emptyContent:a,loading:d,loadingContent:l,size:w});if(q)return q;const F=function(t,e,i){if(!1!==i&&e)return({size:i})=>{const n=[Number(i[0])||760,Number(i[1])||360],o=bn(n),r=Math.max(1,e.windowCount),s=e.plot??o.plot,a=e.gutter??{x:s.x,y:s.y,width:0,height:s.height},c=e.windowPlot??s,d=c.width/r,l=s.y+s.height,u=s.y+.48*s.height,h=e.lidSegments[0]?.y1??u,p=e.windowStart,m=e.windowStart+r*e.windowSize,f=c.x+Math.max(0,Math.min(1,m===p?0:(e.watermarkValue-p)/(m-p)))*c.width;return Uo("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:[Vo("rect",{x:s.x,y:s.y,width:s.width,height:s.height,fill:"none",stroke:"var(--semiotic-border, #d1d5db)",strokeOpacity:.7,strokeWidth:1}),a.width>0?Uo("g",{children:[Vo("rect",{x:a.x,y:h,width:a.width,height:l-h,fill:"var(--semiotic-negative, #e15759)",fillOpacity:.07,stroke:"var(--semiotic-border, #d1d5db)",strokeOpacity:.55,strokeWidth:1}),Vo("text",{x:a.x+a.width/2,y:h-8,textAnchor:"middle",fill:"var(--semiotic-negative, #e15759)",fontSize:10,fontWeight:700,children:"gutter"})]}):null,Array.from({length:r},(i,o)=>{const r=t[o],s=c.x+o*d,a=e.closedWindowCount>o,h=r?.secondary??0;return Uo("g",{children:[Vo("rect",{x:s,y:u,width:d,height:l-u,fill:a?"var(--semiotic-negative, #e15759)":"var(--semiotic-accent, #4e79a7)",fillOpacity:a?.08:.06,stroke:"var(--semiotic-border, #d1d5db)",strokeOpacity:.68,strokeWidth:1}),a?e.lidSegments.filter(t=>t.windowIndex===o).map(t=>Vo("line",{x1:t.x1,x2:t.x2,y1:t.y1,y2:t.y2,stroke:"var(--semiotic-negative, #e15759)",strokeOpacity:.78,strokeWidth:2,strokeLinecap:"round"},t.id)):null,Uo("text",{x:s+d/2,y:u-8,textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:[r?.value??0,h?` / ${h} late`:""]}),Vo("text",{x:s+d/2,y:Math.min(n[1]-8,l+16),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:r?.label??""})]},"window-"+o)}),e.lidSegments.filter(t=>null==t.windowIndex).map(t=>Vo("line",{x1:t.x1,x2:t.x2,y1:t.y1,y2:t.y2,stroke:"var(--semiotic-negative, #e15759)",strokeOpacity:.62,strokeWidth:2,strokeLinecap:"round"},t.id)),Vo("line",{x1:s.x,x2:s.x+s.width,y1:l,y2:l,stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:1.5}),Vo("line",{"data-testid":"event-drop-watermark",x1:f,x2:f,y1:s.y+8,y2:l,stroke:"var(--semiotic-warning, #f28e2b)",strokeDasharray:"5 4",strokeWidth:2}),Uo("text",{x:Math.min(s.x+s.width-4,f+6),y:s.y+16,fill:"var(--semiotic-warning, #f28e2b)",fontSize:10,fontWeight:700,children:["watermark ",Math.round(100*e.watermarkValue)/100]}),e.lateCount>0?Uo("text",{x:a.x+a.width/2,y:s.y+32,textAnchor:"middle",fill:"var(--semiotic-negative, #e15759)",fontSize:10,fontWeight:700,children:[e.lateCount," late"]}):null]})}}(O.projectionRows,O.metadata,I),W=Fo(t.tooltip,c),D=Wo(t,c,E,{chartMode:S,className:M,title:k,description:P,summary:C,accessibleTable:$,enableHover:R,margin:A});return Eo("EventDropChart",w,Vo(yn,{...c,...W,...D,ref:j,config:O.config,foregroundGraphics:qo(F,c?.foregroundGraphics),initialSpawns:O.initialSpawns,initialSpawnPacing:O.initialSpawnPacing,paused:u,responsiveHeight:h,responsiveWidth:p,size:w,bodyStyle:T}))});import{forwardRef as Qo,useCallback as Zo,useMemo as Jo,useRef as tr}from"react";import{jsx as er,jsxs as ir}from"react/jsx-runtime";var nr=Qo(function(t,e){const{ballRadius:i=8,categoryAccessor:n="category",colorBy:o,data:r,emptyContent:s,frameProps:a,loading:c,loadingContent:d,mechanicalCategories:l,mechanicalCount:u,paused:h,responsiveHeight:p,responsiveWidth:m,seed:f=1,unitValue:y=1,valueAccessor:g,styleRules:b}=t,x=No(t,[700,380],{hasSimulationMode:!0}),{chartSize:v,simulationMode:w,showProjection:I,className:M,title:k,chartMode:S,margin:A,enableHover:R,description:P,summary:C,accessibleTable:$}=x,j=tr(null),B="mechanical"===w&&null==g?"value":g,O=Jo(()=>"mechanical"===w?function(t={}){const e=(t.categories?.length?t.categories:["Intake","Review","Build","Ship"]).map(t=>(t+"").trim()).filter(Boolean),i=e.length?e:["Intake"],n=Math.max(i.length,Math.round(t.count??Math.max(48,12*i.length))),o=An(t.unitValue,1),r=Pn(t.seed??1),s=t.idPrefix??"mechanical-pile",a=i.map(()=>.65+.9*r()),c=a.reduce((t,e)=>t+e,0)||1,d=n-i.length,l=a.map(t=>t/c*d),u=l.map(t=>1+Math.floor(t));let h=n-u.reduce((t,e)=>t+e,0);const p=l.map((t,e)=>({index:e,fraction:t-Math.floor(t)})).sort((t,e)=>e.fraction-t.fraction);for(let t=0;h>0;t=(t+1)%p.length)u[p[t].index]+=1,h-=1;return i.map((t,e)=>({id:`${s}-${e}`,category:t,value:u[e]*o,mechanical:!0,unitCount:u[e],unitValue:o,share:u[e]/n}))}({categories:l,count:u,seed:f,unitValue:y}):r??[],[r,l,u,f,w,y]),N=Jo(()=>Nn({data:O,categoryAccessor:n,valueAccessor:B,unitValue:y,ballRadius:i,seed:f,size:v}),[i,n,v,O,B,f,y]);Mo(e,{frameRef:j,spawnDatum:Zo((t,e)=>{const o=Nn({data:[t],categoryAccessor:n,valueAccessor:B,unitValue:y,ballRadius:i,seed:f+e+1,size:v}),r={id:(t.id??"pile-push-"+e)+"",x:bn(v).plot.x,y:bn(v).plot.y,mass:1,shape:{type:"circle",radius:i},datum:t},s=o.initialSpawns.length?o.initialSpawns:[r];return{datumId:(t.id??s[0].id)+"",spawns:s}},[i,n,v,B,f,y]),seedRows:O,seedSpawns:N.initialSpawns});const T="mechanical"===w&&null==o?"category":o,E=Jo(()=>vn(T,"#4e79a7",{styleRules:b,valueAccessor:g}),[T,b,g]),q=Jo(()=>In(N.projectionRows,v,"category"),[v,N.projectionRows]),F=To({data:"mechanical"===w?O:r,emptyContent:s,loading:c,loadingContent:d,size:v});if(F)return F;const W=function(t,e,i){if(!1!==i&&0!==t.length)return({size:i})=>{const n=[Number(i[0])||700,Number(i[1])||380],o=bn(n),r=On(o.plot,t.length,e),s=o.plot.y+o.plot.height;return ir("svg",{"aria-hidden":"true","data-testid":"physics-pile-projection-overlay",width:n[0],height:n[1],viewBox:`0 0 ${n[0]} ${n[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[er("line",{x1:o.plot.x,x2:o.plot.x+o.plot.width,y1:s,y2:s,stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:1}),t.map((t,e)=>{const i=Math.min(o.plot.height,r.pileHeight(t.value)),a=r.tubeWidth,c=r.centerX(e),d=s-i;return ir("g",{children:[er("rect",{x:c-a/2,y:d,width:a,height:i,rx:3,fill:"var(--semiotic-accent, #4e79a7)",fillOpacity:.08,stroke:"var(--semiotic-accent, #4e79a7)",strokeOpacity:.42,strokeWidth:1,strokeDasharray:"4 3"}),er("text",{x:c,y:Math.max(o.plot.y+12,d-6),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:11,fontWeight:700,children:t.value}),er("text",{x:c,y:Math.min(n[1]-8,s+16),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:t.label})]},`${t.label}-${e}`)})]})}}(N.projectionRows,i,I),D=Fo(t.tooltip,a),z=Wo(t,a,q,{chartMode:S,className:M,title:k,description:P,summary:C,accessibleTable:$,enableHover:R,margin:A});return Eo("PhysicsPileChart",v,er(yn,{...a,...D,...z,ref:j,config:N.config,foregroundGraphics:qo(W,a?.foregroundGraphics),initialSpawns:N.initialSpawns,initialSpawnPacing:N.initialSpawnPacing,paused:h,responsiveHeight:p,responsiveWidth:m,size:v,bodyStyle:E}))});import{forwardRef as or,useCallback as rr,useMemo as sr,useRef as ar}from"react";import{jsx as cr,jsxs as dr}from"react/jsx-runtime";function lr(t){return t.toLocaleString(void 0,Math.abs(t)>=1e3||.01>Math.abs(t)?{maximumFractionDigits:0}:{maximumFractionDigits:2})}var ur=or(function(t,e){const{colorBy:i,styleRules:n,collisionIterations:o,data:r,emptyContent:s,frameProps:a,groupAccessor:c,loading:d,loadingContent:l,paused:u,pointRadius:h,radiusAccessor:p,rerunMS:m,responsiveHeight:f,responsiveWidth:y,seed:g=1,settle:b,xAccessor:x="x",xExtent:v}=t,w=No(t,[700,360]),{chartSize:I,showProjection:M,className:k,title:S,chartMode:A,margin:R,enableHover:P,description:C,summary:$,accessibleTable:j}=w,B=h??("sparkline"===A?2:"context"===A?4:5),O=ar(null),N=sr(()=>r??[],[r]),T=sr(()=>En({data:N,xAccessor:x,groupAccessor:c,radiusAccessor:p,pointRadius:B,seed:g,size:I,xExtent:v,collisionIterations:o,settle:b}),[N,I,o,c,B,p,g,b,x,v]),E=Oo(T.config,m,u);Mo(e,{frameRef:O,spawnDatum:rr((t,e)=>{const i=En({data:[t],xAccessor:x,groupAccessor:c,radiusAccessor:p,pointRadius:B,seed:g+e+1,size:I,xExtent:v,collisionIterations:o,settle:b}).initialSpawns[0]??{id:(t.id??"collision-swarm-push-"+e)+"",x:bn(I).plot.x,y:bn(I).plot.y,mass:1,shape:{type:"circle",radius:B},datum:t};return{datumId:(t.id??i.id)+"",spawns:[i]}},[I,o,c,B,p,g,b,x,v]),seedRows:N,seedSpawns:T.initialSpawns});const q=i??c,F=sr(()=>vn(q,"#4e79a7",{styleRules:n,valueAccessor:x}),[q,n,x]),W=To({data:r,emptyContent:s,loading:d,loadingContent:l,size:I});if(W)return W;const D=function(t,e){if(!1!==e&&t)return({size:e})=>{const i=[Number(e[0])||700,Number(e[1])||360],n=bn(i),o=n.plot.y+n.plot.height,[r,s]=t.xExtent,a=r+(s-r)/2,c=[{label:lr(r),x:t.xRange[0]},{label:lr(a),x:t.xRange[0]+(t.xRange[1]-t.xRange[0])/2},{label:lr(s),x:t.xRange[1]}];return dr("svg",{"aria-hidden":"true","data-testid":"collision-swarm-projection-overlay",width:i[0],height:i[1],viewBox:`0 0 ${i[0]} ${i[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[t.groups.map(t=>dr("g",{children:[cr("line",{x1:n.plot.x,x2:n.plot.x+n.plot.width,y1:t.y,y2:t.y,stroke:"var(--semiotic-border, #d1d5db)",strokeDasharray:"3 5",strokeWidth:1}),cr("text",{x:n.plot.x+4,y:t.y-7,fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:t.label}),dr("text",{x:n.plot.x+n.plot.width-4,y:t.y-7,textAnchor:"end",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:["n=",t.count]})]},t.label)),cr("line",{x1:t.xRange[0],x2:t.xRange[1],y1:o,y2:o,stroke:"var(--semiotic-text-secondary, #555)",strokeWidth:1}),c.map(t=>dr("g",{children:[cr("line",{x1:t.x,x2:t.x,y1:o,y2:o+5,stroke:"var(--semiotic-text-secondary, #555)",strokeWidth:1}),cr("text",{x:t.x,y:Math.min(i[1]-8,o+18),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:t.label})]},`${t.label}-${t.x}`))]})}}(T.metadata,M),z=function(t){if(!t)return[];const e=Math.max(24,t.xRange[1]-t.xRange[0]),i=t.xRange[0]+e/2;return t.groups.map(t=>{const n=`${t.label} lane: ${t.count} points`;return{id:"collision-swarm-"+t.label,label:n,description:n,datum:t,x:i,y:t.y,shape:"rect",width:e,height:28,group:"lane"}})}(T.metadata),L=Fo(t.tooltip,a),Y=Wo(t,a,z,{chartMode:A,className:k,title:S,description:C,summary:$,accessibleTable:j,enableHover:P,margin:R});return Eo("CollisionSwarmChart",I,cr(yn,{...a,...L,...Y,ref:O,config:E.config,foregroundGraphics:qo(D,a?.foregroundGraphics),initialSpawns:T.initialSpawns,paused:u,responsiveHeight:f,responsiveWidth:y,size:I,bodyStyle:F},E.rerunKey))}),hr=1e-9;function pr(t,e){return e>t?-1:t>e?1:0}function mr(t){return{...t}}function fr(t){return t.map(t=>({...t,sourceIds:t.sourceIds?[...t.sourceIds]:void 0,productIds:t.productIds?[...t.productIds]:void 0,relationIds:t.relationIds?[...t.relationIds]:void 0,outletIds:t.outletIds?[...t.outletIds]:void 0}))}function yr(t){const e=Object.fromEntries(Object.entries(t.components).map(([t,e])=>[t,{...e,initialMetrics:mr(e.initialMetrics),metrics:mr(e.metrics),productIds:[...e.productIds],history:fr(e.history)}])),i=Object.fromEntries(Object.entries(t.products).map(([t,e])=>[t,{...e,metrics:mr(e.metrics),sourceIds:[...e.sourceIds],history:fr(e.history)}])),n=Object.fromEntries(Object.entries(t.relations).map(([t,e])=>[t,{...e,sourceIds:[...e.sourceIds],metrics:e.metrics?mr(e.metrics):void 0}]));return{...t,eventsApplied:[...t.eventsApplied],components:e,products:i,relations:n,input:{amount:t.input.amount,metrics:mr(t.input.metrics)},metrics:mr(t.metrics),loss:{amount:t.loss.amount,metrics:mr(t.loss.metrics)},history:fr(t.history)}}function gr(t,e,i,n,o){return{severity:t,code:e,message:i,path:n,ids:o?[...o]:void 0}}function br(t){const e=new Set,i=new Set;for(const n of t)e.has(n)&&i.add(n),e.add(n);return[...i].sort(pr)}function xr(t,e){return t?Object.entries(t).flatMap(([t,i])=>Number.isFinite(i)?[]:[gr("error","invalid-metric",`Metric "${t}" must be a finite number.`,`${e}.${t}`)]):[]}function vr(t,e){for(const[i,n]of Object.entries(e))t[i]=Number(t[i]??0)+n}function wr(t,e,i="selector"){const n=[],o=Object.values(t.components),r=new Set(o.map(t=>t.id)),s=(e.ids??[]).filter(t=>!r.has(t));if(s.length&&n.push(gr("error","unknown-component",`Selector references unknown component id${1===s.length?"":"s"}: ${s.join(", ")}.`,i+".ids",s)),void 0===e.count||Number.isInteger(e.count)&&e.count>=0||n.push(gr("error","invalid-selector-count","Selector count must be a non-negative integer.",i+".count")),n.some(t=>"error"===t.severity))return{ids:[],diagnostics:n};const a=e.ids?new Set(e.ids):null,c=e.categories?new Set(e.categories):null,d=e.statuses?new Set(e.statuses):null,l=e.outletIds?new Set(e.outletIds):null;let u=o.filter(t=>!a||a.has(t.id)).filter(t=>!c||c.has(t.category)).filter(t=>!d||d.has(t.status)).filter(t=>!l||void 0!==t.outletId&&l.has(t.outletId)).map(t=>t.id).sort(pr);return void 0!==e.count&&(u=u.slice(0,e.count)),u.length||n.push(gr("warning","empty-selector","Selector matched no source components.",i)),{ids:u,diagnostics:n}}function Ir(t,e,i={}){return{eventId:t.event.id,effectType:e.type,phaseId:t.context.phaseId,authoredAt:t.context.authoredAt,appliedAt:t.context.appliedAt,label:t.event.label,summary:t.event.summary,...i}}function Mr(t,e){const i={...e,eventId:t.event.id};t.materializations.push(i),t.observations.push({...i,phaseId:t.context.phaseId,authoredAt:t.context.authoredAt,appliedAt:t.context.appliedAt})}function kr(t,e,i){return!(void 0!==e&&!t.outletIds.has(e)&&(t.diagnostics.push(gr("error","unknown-outlet",`Unknown outlet "${e}".`,i,[e])),1))}function Sr(t,e,i){const n=br(e);e.length||t.diagnostics.push(gr("error","empty-source-list","A product requires at least one source component.",i)),n.length&&t.diagnostics.push(gr("error","duplicate-source",`Source ids may appear only once: ${n.join(", ")}.`,i,n));const o=e.filter(e=>!t.state.components[e]);o.length&&t.diagnostics.push(gr("error","unknown-component",`Unknown source component id${1===o.length?"":"s"}: ${o.join(", ")}.`,i,o));const r=e.filter(e=>(t.state.components[e]?.productIds.length??0)>0);r.length&&t.diagnostics.push(gr("error","source-already-assigned",`Source component${1===r.length?" is":"s are"} already assigned: ${r.join(", ")}.`,i,r));const s=e.filter(e=>"consumed"===t.state.components[e]?.status&&!r.includes(e));return s.length&&t.diagnostics.push(gr("error","source-unavailable",`Consumed source component${1===s.length?" is":"s are"} unavailable: ${s.join(", ")}.`,i,s)),t.diagnostics.some(t=>"error"===t.severity)?null:e.map(e=>t.state.components[e])}function Ar(t,e,i,n,o){const r=n?.amount??0;(!Number.isFinite(r)||0>r||r>e+hr)&&t.diagnostics.push(gr("error","invalid-loss","Loss amount must be finite, non-negative, and no greater than its sources.",o+".amount")),t.diagnostics.push(...xr(n?.metrics,o+".metrics"));for(const[e,r]of Object.entries(n?.metrics??{}))(0>r||r>Number(i[e]??0)+hr)&&t.diagnostics.push(gr("error","invalid-metric-loss",`Metric loss "${e}" must be non-negative and no greater than its sources.`,`${o}.metrics.${e}`));return!t.diagnostics.some(t=>"error"===t.severity)}function Rr(t,e,i,n,o,r,s){return{id:t.id,label:t.label??t.id,description:t.description,category:t.category??"product",color:t.color,order:t.order,declaredAmount:t.amount,amount:r&&void 0!==t.amount?t.amount:i,metrics:r&&t.metrics?{...n,...t.metrics}:n,status:r?"complete":"forming",sourceIds:[...e],outletId:r?t.outletId??(o.outletIds.has("product")?"product":void 0):void 0,createdByEventId:o.event.id,createdAt:o.context.appliedAt,completedByEventId:r?o.event.id:void 0,completedAt:r?o.context.appliedAt:void 0,history:[s]}}function Pr(t,e,i,n){void 0!==e.amount&&Math.abs(e.amount-i)>hr&&t.diagnostics.push(gr("warning","declared-product-amount-mismatch",`Product "${e.id}" declares ${e.amount}, while its sources yield ${i}.`,n,[e.id]))}function Cr(t,e,i){const n=`events.${t.event.id}.effects.${i}`,o=t.state;if("set-state"===e.type){["queued","active","transformed","retained","ejected","failed","recovered"].includes(e.state)||t.diagnostics.push(gr("error","invalid-component-state",`set-state cannot assign "${e.state+""}".`,n+".state")),t.diagnostics.push(...xr(e.metricsDelta,n+".metricsDelta")),kr(t,e.outletId,n+".outletId");const i=wr(o,e.select,n+".select");t.diagnostics.push(...i.diagnostics);const r=i.ids.filter(t=>o.components[t].productIds.length);if(r.length&&t.diagnostics.push(gr("error","source-already-assigned",`Assigned source components cannot be retargeted: ${r.join(", ")}.`,n+".select",r)),t.diagnostics.some(t=>"error"===t.severity))return;const s=Ir(t,e,{sourceIds:i.ids,outletIds:e.outletId?[e.outletId]:void 0});for(const t of i.ids){const i=o.components[t];i.status=e.state,i.outletId=e.outletId,i.reason=e.reason,e.metricsDelta&&vr(i.metrics,e.metricsDelta),i.history.push(s)}return o.history.push(s),void(i.ids.length&&Mr(t,{type:"retarget-component",sourceIds:i.ids,outletIds:e.outletId?[e.outletId]:void 0}))}if("set-relation"===e.type){const{relation:i}=e;i.id&&!o.relations[i.id]||t.diagnostics.push(gr("error","duplicate-relation",`Relation id "${i.id}" is missing or already active.`,n+".relation.id",[i.id]));const r=function(t,e,i){const n=br(e),o=e.filter(e=>!t.state.components[e]);return 2>e.length&&t.diagnostics.push(gr("error","insufficient-relation-sources","A relation requires at least two source components.",i)),n.length&&t.diagnostics.push(gr("error","duplicate-source",`Relation source ids must be unique: ${n.join(", ")}.`,i,n)),o.length&&t.diagnostics.push(gr("error","unknown-component",`Relation references unknown source component${1===o.length?"":"s"}: ${o.join(", ")}.`,i,o)),t.diagnostics.some(t=>"error"===t.severity)?null:e.map(e=>t.state.components[e])}(t,i.sourceIds,n+".relation.sourceIds");if(t.diagnostics.push(...xr(i.metrics,n+".relation.metrics")),!r||t.diagnostics.some(t=>"error"===t.severity))return;o.relations[i.id]={...i,sourceIds:[...i.sourceIds],metrics:i.metrics?{...i.metrics}:void 0,status:"active",createdByEventId:t.event.id,createdAt:t.context.appliedAt};const s=Ir(t,e,{sourceIds:[...i.sourceIds],relationIds:[i.id]});return o.history.push(s),void Mr(t,{type:"activate-relation",sourceIds:[...i.sourceIds],relationIds:[i.id]})}if("resolve-relation"===e.type){const i=br(e.relationIds),r=e.relationIds.filter(t=>!o.relations[t]),s=e.relationIds.filter(t=>"resolved"===o.relations[t]?.status);if(i.length&&t.diagnostics.push(gr("error","duplicate-relation","Relation ids must be unique.",n+".relationIds",i)),r.length&&t.diagnostics.push(gr("error","unknown-relation",`Unknown relation: ${r.join(", ")}.`,n+".relationIds",r)),s.length&&t.diagnostics.push(gr("error","resolved-relation",`Relation is already resolved: ${s.join(", ")}.`,n+".relationIds",s)),t.diagnostics.some(t=>"error"===t.severity))return;for(const i of e.relationIds){const n=o.relations[i];n.status="resolved",n.resolution=e.resolution,n.resolvedByEventId=t.event.id,n.resolvedAt=t.context.appliedAt,n.reason=e.reason}const a=Ir(t,e,{relationIds:[...e.relationIds]});return o.history.push(a),void Mr(t,{type:"resolve-relation",relationIds:[...e.relationIds]})}if("combine"===e.type||"contribute"===e.type){const i=t.productDefinitions.get(e.productId);i||t.diagnostics.push(gr("error","unknown-product",`Product "${e.productId}" has no declared mold.`,n+".productId",[e.productId]));const r=o.products[e.productId];"combine"===e.type&&r&&t.diagnostics.push(gr("error","duplicate-product",`Product "${e.productId}" has already been formed.`,n+".productId",[e.productId])),"contribute"!==e.type||r&&"forming"===r.status||t.diagnostics.push(gr("error","product-not-forming",`Contributions require an existing forming product "${e.productId}".`,n+".productId",[e.productId]));const s=Sr(t,e.sourceIds,n+".sourceIds"),a="contribute"===e.type&&r?[...r.sourceIds,...e.sourceIds]:e.sourceIds,c=function(t,e,i,n){if(!e?.length)return[];const o=br(e),r=e.filter(e=>!t.state.relations[e]),s=e.filter(e=>"resolved"===t.state.relations[e]?.status),a=new Set(i),c=e.filter(e=>(t.state.relations[e]?.sourceIds??[]).some(t=>!a.has(t)));return o.length&&t.diagnostics.push(gr("error","duplicate-relation","Basis relations must be unique.",n,o)),r.length&&t.diagnostics.push(gr("error","unknown-relation",`Unknown basis relation: ${r.join(", ")}.`,n,r)),s.length&&t.diagnostics.push(gr("error","resolved-relation",`Basis relation is already resolved: ${s.join(", ")}.`,n,s)),c.length&&t.diagnostics.push(gr("error","relation-source-mismatch",`Basis relation includes a source outside this product: ${c.join(", ")}.`,n,c)),t.diagnostics.some(t=>"error"===t.severity)?null:e.map(e=>t.state.relations[e])}(t,e.basisRelationIds,a,n+".basisRelationIds");if(!s||!c||!i||t.diagnostics.some(t=>"error"===t.severity))return;const d=s.reduce((t,e)=>t+e.amount,0),l=function(t){const e={};for(const i of t)vr(e,i.metrics);return e}(s);if(!Ar(t,d,l,e.loss,n+".loss"))return;const u=d-(e.loss?.amount??0);!function(t,e,i){t.state.loss.amount+=i?.amount??0;for(const[n,o]of Object.entries(i?.metrics??{}))e[n]=Number(e[n]??0)-o,t.state.loss.metrics[n]=Number(t.state.loss.metrics[n]??0)+o}(t,l,e.loss);const h="combine"===e.type&&!1!==e.complete,p=Ir(t,e,{sourceIds:[...e.sourceIds],productIds:[e.productId],relationIds:e.basisRelationIds?[...e.basisRelationIds]:void 0});let m;if("combine"===e.type){if(h&&Pr(t,i,u,n+".productId"),m=Rr(i,e.sourceIds,u,l,t,h,p),h&&!kr(t,m.outletId,n+".productId"))return;o.products[e.productId]=m}else m=r,m.sourceIds.push(...e.sourceIds),m.amount+=u,vr(m.metrics,l),m.history.push(p);for(const t of s)t.productIds=[e.productId],t.status="consumed",t.outletId=void 0,t.history.push(p);return o.history.push(p),function(t,e){if(e.length){for(const i of e)i.status="resolved",i.resolution="combined",i.resolvedByEventId=t.event.id,i.resolvedAt=t.context.appliedAt;Mr(t,{type:"resolve-relation",relationIds:e.map(t=>t.id)})}}(t,c),Mr(t,{type:"combine"===e.type?"form-product":"update-product",sourceIds:[...e.sourceIds],productIds:[e.productId],relationIds:e.basisRelationIds?[...e.basisRelationIds]:void 0,outletIds:m.outletId?[m.outletId]:void 0}),void(h&&Mr(t,{type:"complete-product",sourceIds:[...m.sourceIds],productIds:[m.id],outletIds:m.outletId?[m.outletId]:void 0}))}if("complete-product"===e.type){const i=o.products[e.productId];return i?void function(t,e,i,n,o,r){const s=t.productDefinitions.get(e.id),a=i??s?.outletId??(t.outletIds.has("product")?"product":void 0);if(!kr(t,a,r+".outletId"))return;if("complete"===e.status)return void t.diagnostics.push(gr("error","product-already-complete",`Product "${e.id}" is already complete.`,r,[e.id]));s&&(Pr(t,s,e.amount,r+".productId"),void 0!==s.amount&&(e.amount=s.amount),s.metrics&&(e.metrics={...e.metrics,...s.metrics})),e.status="complete",e.outletId=a,e.reason=n,e.completedByEventId=t.event.id,e.completedAt=t.context.appliedAt;const c=Ir(t,o,{sourceIds:[...e.sourceIds],productIds:[e.id],outletIds:a?[a]:void 0});e.history.push(c),t.state.history.push(c),Mr(t,{type:"complete-product",sourceIds:[...e.sourceIds],productIds:[e.id],outletIds:a?[a]:void 0})}(t,i,e.outletId,e.reason,e,n):void t.diagnostics.push(gr("error","unknown-product-state",`Product "${e.productId}" has not been formed.`,n+".productId",[e.productId]))}if("split"===e.type){const i=Sr(t,[e.sourceId],n+".sourceId");e.products.length||t.diagnostics.push(gr("error","empty-split","A split requires at least one product allocation.",n+".products"));const r=e.products.map(t=>t.productId),s=br(r);s.length&&t.diagnostics.push(gr("error","duplicate-product","Split product ids must be unique.",n+".products",s));const a=r.map(e=>t.productDefinitions.get(e)),c=r.filter((t,e)=>!a[e]),d=r.filter(t=>o.products[t]);c.length&&t.diagnostics.push(gr("error","unknown-product",`Split references undeclared product molds: ${c.join(", ")}.`,n+".products",c)),d.length&&t.diagnostics.push(gr("error","duplicate-product",`Split products already exist: ${d.join(", ")}.`,n+".products",d));for(const[i,o]of e.products.entries())void 0===o.amount||Number.isFinite(o.amount)&&o.amount>=0||t.diagnostics.push(gr("error","invalid-product-amount","Split allocation amounts must be finite and non-negative.",`${n}.products.${i}.amount`)),t.diagnostics.push(...xr(o.metrics,`${n}.products.${i}.metrics`));if(!i?.length||t.diagnostics.some(t=>"error"===t.severity))return;const l=i[0];if(!Ar(t,l.amount,l.metrics,e.loss,n+".loss"))return;const u=l.amount-(e.loss?.amount??0),h=e.products.map((t,e)=>t.amount??a[e]?.amount),p=h.filter(t=>void 0!==t).length;if(0!==p&&p!==h.length)return void t.diagnostics.push(gr("error","partial-split-allocation","Either every split product must declare an amount or none may do so.",n+".products"));const m=p?h:e.products.map(()=>u/e.products.length),f=m.reduce((t,e)=>t+e,0);if(Math.abs(f-u)>hr)return void t.diagnostics.push(gr("error","split-amount-mismatch",`Split allocations total ${f}, but ${u} remains after loss.`,n+".products"));const y={...l.metrics};for(const[t,i]of Object.entries(e.loss?.metrics??{}))y[t]=Number(y[t]??0)-i;const g=Ir(t,e,{sourceIds:[l.id],productIds:r});if(e.products.forEach((i,r)=>{const s=a[r],c=u>hr?m[r]/u:1/e.products.length,d=Object.fromEntries(Object.entries(y).map(([t,e])=>[t,e*c])),h=i.metrics??s.metrics??d,p=Rr({...s,amount:m[r],metrics:h},[l.id],m[r],{...h},t,!0,g);kr(t,p.outletId,`${n}.products.${r}.productId`)&&(o.products[p.id]=p)}),t.diagnostics.some(t=>"error"===t.severity))return;l.productIds=r,l.status="consumed",l.outletId=void 0,l.history.push(g),o.loss.amount+=e.loss?.amount??0;for(const[t,i]of Object.entries(e.loss?.metrics??{}))o.loss.metrics[t]=Number(o.loss.metrics[t]??0)+i;o.history.push(g),Mr(t,{type:"split-source",sourceIds:[l.id],productIds:r});for(const e of r)Mr(t,{type:"complete-product",sourceIds:[l.id],productIds:[e],outletIds:o.products[e].outletId?[o.products[e].outletId]:void 0});return}if("eject"===e.type){kr(t,e.outletId,n+".outletId");const i=wr(o,e.select,n+".select");t.diagnostics.push(...i.diagnostics);const r=i.ids.filter(t=>o.components[t].productIds.length);if(r.length&&t.diagnostics.push(gr("error","source-already-assigned",`Assigned source components cannot be ejected: ${r.join(", ")}.`,n+".select",r)),t.diagnostics.some(t=>"error"===t.severity))return;const s=Ir(t,e,{sourceIds:i.ids,outletIds:[e.outletId]});for(const t of i.ids){const i=o.components[t];i.status=e.state??"ejected",i.outletId=e.outletId,i.reason=e.reason,i.history.push(s)}return o.history.push(s),void(i.ids.length&&Mr(t,{type:"retarget-component",sourceIds:i.ids,outletIds:[e.outletId]}))}if("set-metric"===e.type){if(t.diagnostics.push(...xr(e.metricsDelta,n+".metricsDelta")),t.diagnostics.some(t=>"error"===t.severity))return;let i,r;if("run"===e.target)vr(o.metrics,e.metricsDelta);else if("components"in e.target){const r=wr(o,e.target.components,n+".target.components");if(t.diagnostics.push(...r.diagnostics),t.diagnostics.some(t=>"error"===t.severity))return;i=r.ids;for(const t of r.ids)vr(o.components[t].metrics,e.metricsDelta)}else{r=[...e.target.productIds];const i=br(r),s=r.filter(t=>!o.products[t]);if(i.length&&t.diagnostics.push(gr("error","duplicate-product","Metric target product ids must be unique.",n+".target.productIds",i)),s.length&&t.diagnostics.push(gr("error","unknown-product-state",`Metric target product has not formed: ${s.join(", ")}.`,n+".target.productIds",s)),t.diagnostics.some(t=>"error"===t.severity))return;for(const t of r)vr(o.products[t].metrics,e.metricsDelta)}return void o.history.push(Ir(t,e,{sourceIds:i,productIds:r}))}e.outcome.trim()?(o.outcome=e.outcome,o.summary=e.summary,o.history.push(Ir(t,e)),t.observations.push({type:"crucible-outcome",eventId:t.event.id,phaseId:t.context.phaseId,authoredAt:t.context.authoredAt,appliedAt:t.context.appliedAt,outcome:e.outcome})):t.diagnostics.push(gr("error","invalid-outcome","Outcome must be a non-empty string.",n+".outcome"))}function $r(t,e,i){if(t.eventsApplied.includes(e.id))return{applied:!1,state:t,materializations:[],observations:[],diagnostics:[gr("warning","duplicate-event-application",`Event "${e.id}" has already been applied.`,"events."+e.id,[e.id])]};const n=yr(t),o={state:n,event:e,context:i,productDefinitions:new Map(i.products.map(t=>[t.id,t])),outletIds:new Set(i.outlets.map(t=>t.id)),diagnostics:[],materializations:[],observations:[]};for(const[i,n]of e.effects.entries())if(Cr(o,n,i),o.diagnostics.some(t=>"error"===t.severity))return{applied:!1,state:t,materializations:[],observations:[],diagnostics:o.diagnostics};return n.elapsed=Math.max(n.elapsed,i.appliedAt),n.phaseId=i.phaseId,n.eventsApplied.push(e.id),o.observations.unshift({type:"crucible-event",eventId:e.id,phaseId:i.phaseId,authoredAt:i.authoredAt,appliedAt:i.appliedAt}),{applied:!0,state:n,materializations:o.materializations,observations:o.observations,diagnostics:o.diagnostics}}function jr(t,e={}){const i=e.groupBy??"outlet",n=new Map,o=t=>{const e=function(t,e){return"product"===e?"product"===t.kind?t.id:"unassigned":"outlet"===e?t.outletId??"unassigned":"category"===e?t.category:t.status}({...t,status:t.status??"active"},i),o=n.get(e);if(o)return o.count+=1,o.amount+=t.amount,void vr(o.metrics,t.metrics);n.set(e,{key:e,label:"product"===i&&"product"===t.kind?t.label:e,count:1,amount:t.amount,metrics:{...t.metrics},status:"status"===i?t.status:void 0,outletId:"outlet"===i?t.outletId:void 0,category:"category"===i?t.category:void 0,productId:"product"===i&&"product"===t.kind?t.id:void 0})};for(const e of Object.values(t.components))e.productIds.length||"consumed"===e.status||o({kind:"component",id:e.id,label:e.label,status:e.status,outletId:e.outletId,category:e.category,amount:e.amount,metrics:e.metrics});for(const e of Object.values(t.products))o({kind:"product",id:e.id,label:e.label,status:e.status,outletId:e.outletId,category:e.category,amount:e.amount,metrics:e.metrics});const r=new Map((e.order??[]).map((t,e)=>[t,e]));return[...n.values()].sort((t,e)=>(r.get(t.key)??Number.MAX_SAFE_INTEGER)-(r.get(e.key)??Number.MAX_SAFE_INTEGER)||pr(t.key,e.key))}var Br=jr;function Or(t,e={}){const i=e.field??"amount",n=t=>"amount"===i?t.amount:Number(t.metrics[i]??0),o="amount"===i?t.input.amount:Number(t.input.metrics[i]??0),r=Object.values(t.products).reduce((t,e)=>t+n(e),0),s=Object.values(t.components).filter(t=>!t.productIds.length&&"consumed"!==t.status).reduce((t,e)=>t+n(e),0),a="amount"===i?t.loss.amount:Number(t.loss.metrics[i]??0),c=r+s+a,d=c-o;return{field:i,input:o,products:r,unassigned:s,loss:a,output:c,delta:d,conserved:Math.max(0,e.tolerance??1e-6)>=Math.abs(d)}}function Nr(t,e={}){return{history:fr(t.history),projection:jr(t,e.projection),conservation:Or(t,e.conservation)}}var Tr=900,Er=520,qr=[900,520],Fr=[{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}],Wr=new Set(["queued","active","transformed","consumed","retained","ejected","failed","recovered"]),Dr=1e-9;function zr(t,e){return e>t?-1:t>e?1:0}function Lr(t,e,i,n,o){return{severity:t,code:e,message:i,path:n,ids:o?[...o]:void 0}}function Yr(t){const e=new Set,i=new Set;for(const n of t)e.has(n)&&i.add(n),e.add(n);return[...i].sort(zr)}function _r(t){const e="number"==typeof t?t:Number(t);return Number.isFinite(e)?e:null}function Hr(t,e,i,n,o,r){if(!i)return n;try{return("function"==typeof i?i(t,e):t[i])??n}catch(t){return o.push(Lr("error","accessor-error",`Accessor threw: ${t instanceof Error?t.message:t+""}.`,r)),n}}function Xr(t,e,i){if(!t||"object"!=typeof t||Array.isArray(t))return null!=t&&e.push(Lr("error","invalid-metrics","Metrics must be a numeric object.",i)),{};const n={};for(const[o,r]of Object.entries(t)){const t=_r(r);null!=t?n[o]=t:e.push(Lr("error","invalid-metric",`Metric "${o}" must be finite.`,`${i}.${o}`))}return n}function Gr(t){const e=[],i={},n=[];let o=0;const r={};t.data.forEach((s,a)=>{const c=(s.id??"component-"+a)+"",d=((Hr(s,a,t.idAccessor,c,e,`data.${a}.id`)??c)+"").trim();if(!d)return void e.push(Lr("error","invalid-component-id","Component ids may not be empty.",`data.${a}.id`));n.push(d);const l=_r(Hr(s,a,t.amountAccessor,1,e,`data.${a}.amount`)),u=null==l||0>l?0:l;(null==l||0>l)&&e.push(Lr("error","invalid-component-amount","Component amount must be finite and non-negative.",`data.${a}.amount`,[d]));const h=Xr(Hr(s,a,t.metricsAccessor,{},e,`data.${a}.metrics`),e,`data.${a}.metrics`),p=Hr(s,a,t.initialStateAccessor,"active",e,`data.${a}.status`),m=Wr.has(p)?p:"active";Wr.has(p)||e.push(Lr("error","invalid-component-status",`Unknown component status "${p+""}".`,`data.${a}.status`,[d]));const f=Hr(s,a,t.labelAccessor,(s.label??s.name??d)+"",e,`data.${a}.label`)+"",y=Hr(s,a,t.categoryAccessor,"component",e,`data.${a}.category`)+"";i[d]||(i[d]={id:d,label:f,category:y,datum:s,status:m,initialAmount:u,amount:u,initialMetrics:{...h},metrics:{...h},productIds:[],history:[]},o+=u,function(t,e){for(const[i,n]of Object.entries(e))t[i]=Number(t[i]??0)+n}(r,h))});const s=Yr(n);s.length&&e.push(Lr("error","duplicate-component-id",`Component ids must be unique: ${s.join(", ")}.`,"data",s));const a=Xr(t.metrics??{},e,"metrics");return{state:{elapsed:0,phaseElapsed:0,phaseId:t.phases[0]?.id??"",phaseIndex:t.phases.length?0:-1,playing:!1,complete:0===t.phases.length,outcome:"in_process",eventsApplied:[],components:i,products:{},relations:{},input:{amount:o,metrics:r},metrics:a,loss:{amount:0,metrics:{}},history:[]},diagnostics:e}}function Vr(t){return t.map((t,e)=>({outlet:t,index:e})).sort((t,e)=>(t.outlet.order??t.index)-(e.outlet.order??e.index)||t.index-e.index).map(({outlet:t})=>({...t}))}function Ur(t=qr,e=Fr){const i=Math.max(1,_r(t[0])??900),n=Math.max(1,_r(t[1])??520),o=360>i||260>n,r=o?Math.max(4,.035*Math.min(i,n)):20,s=o?Math.max(10,.075*n):34,a={x:r,y:r,width:Math.max(1,i-2*r),height:s},c=o?Math.max(16,.14*n):Math.min(78,.16*n),d={x:r,y:n-r-c,width:Math.max(1,i-2*r),height:c},l=o?Math.max(12,.08*i):Math.min(150,.17*i),u=a.y+a.height+(o?12:38),h=d.y-(o?10:34),p={x:l,y:u,width:Math.max(24,i-2*l),height:Math.max(24,h-u)},m=Math.max(18,Math.min(.32*p.width,o?84:180)),f={x:p.x+(p.width-m)/2,y:p.y-(o?10:24),width:m,height:o?12:28},y=Vr(e),g={left:y.filter(t=>"left"===(t.side??"bottom")),right:y.filter(t=>"right"===t.side),bottom:y.filter(t=>"bottom"===(t.side??"bottom"))},b=[],x=(t,e)=>{const n=Math.max(8,l-1.5*r),s=p.height/Math.max(1,e.length);e.forEach((e,a)=>{b.push({...e,side:t,x:"left"===t?r:i-r-n,y:p.y+a*s,width:n,height:Math.max(8,s-(o?2:8))})})};x("left",g.left),x("right",g.right);const v=p.width/Math.max(1,g.bottom.length);return g.bottom.forEach((t,e)=>{b.push({...t,side:"bottom",x:p.x+e*v,y:p.y+p.height+(o?2:7),width:Math.max(8,v-(o?2:8)),height:Math.max(8,d.y-p.y-p.height-(o?4:12))})}),b.sort((t,e)=>y.findIndex(e=>e.id===t.id)-y.findIndex(t=>t.id===e.id)),{width:i,height:n,phaseRail:a,chamber:p,mouth:f,projection:d,outlets:b}}function Kr(t){const{id:e,orientation:i,fixed:n,start:o,end:r,openings:s,thickness:a,friction:c,restitution:d}=t,l=function(t,e,i){const n=i.map(([i,n])=>[Math.max(t,Math.min(i,n)),Math.min(e,Math.max(i,n))]).filter(([t,e])=>e>t+Dr).sort((t,e)=>t[0]-e[0]||t[1]-e[1]),o=[];let r=t;for(const[t,e]of n)t>r+Dr&&o.push([r,t]),r=Math.max(r,e);return e>r+Dr&&o.push([r,e]),o}(o,r,s);return l.map(([t,o],r)=>({id:1===l.length?e:`${e}:${r}`,friction:c,restitution:d,shape:"horizontal"===i?{type:"segment",x1:t,y1:n,x2:o,y2:n,thickness:a}:{type:"segment",x1:n,y1:t,x2:n,y2:o,thickness:a}}))}function Qr(t){const{chamber:e,mouth:i}=t,n=Math.max(2,Math.min(10,.018*Math.min(t.width,t.height))),o=Math.max(e.x,i.x),r=Math.min(e.x+e.width,i.x+i.width),s={left:t.outlets.filter(t=>"left"===t.side),right:t.outlets.filter(t=>"right"===t.side),bottom:t.outlets.filter(t=>"bottom"===t.side)},a=[{id:"crucible:wall:top-left",friction:.42,restitution:.1,shape:{type:"segment",x1:e.x,y1:e.y,x2:o,y2:e.y,thickness:n}},{id:"crucible:wall:top-right",friction:.42,restitution:.1,shape:{type:"segment",x1:r,y1:e.y,x2:e.x+e.width,y2:e.y,thickness:n}}];a.push(...Kr({id:"crucible:wall:left",orientation:"vertical",fixed:e.x,start:e.y,end:e.y+e.height,openings:s.left.map(t=>[t.y,t.y+t.height]),thickness:n,friction:.46,restitution:.12}),...Kr({id:"crucible:wall:right",orientation:"vertical",fixed:e.x+e.width,start:e.y,end:e.y+e.height,openings:s.right.map(t=>[t.y,t.y+t.height]),thickness:n,friction:.46,restitution:.12}),...Kr({id:"crucible:wall:bottom",orientation:"horizontal",fixed:e.y+e.height,start:e.x,end:e.x+e.width,openings:s.bottom.map(t=>[t.x,t.x+t.width]),thickness:n,friction:.5,restitution:.08}));for(const e of t.outlets)a.push({id:"crucible:outlet:"+encodeURIComponent(e.id),sensor:!0,shape:{type:"aabb",x:e.x+e.width/2,y:e.y+e.height/2,width:e.width,height:e.height}});return a}function Zr(t){let e=2166136261;for(let i=0;t.length>i;i+=1)e^=t.charCodeAt(i),e=Math.imul(e,16777619);return e>>>0}function Jr(t){return"number"==typeof t&&Number.isFinite(t)?t>>>0:"string"==typeof t?Zr(t):1}function ts(t,e){return{fixedDt:1/120,maxSubsteps:8,settleStepLimit:7200,colliders:e.map(t=>({...t,shape:{...t.shape}})),observation:{chartType:"crucible"},kernel:{seed:Jr(t),gravity:{x:0,y:0},cellSize:42,collisionIterations:6,velocityDamping:.992,restitution:.12,friction:.42,sleepSpeed:4,sleepAfter:.5,maxVelocity:620}}}function es(t){return"crucible:component:"+encodeURIComponent(t)}function is(t){return"crucible:product:"+encodeURIComponent(t)}function ns(t,e){return`crucible:bond:${encodeURIComponent(t)}:${encodeURIComponent(e)}`}function os(t,e,i,n){if(void 0!==i&&Number.isFinite(i)&&i>0)return i;const o=Math.min(...e,t),r=Math.max(...e,t);return r-o>Dr?n[0]+(n[1]-n[0])*Math.sqrt(Math.max(0,t-o)/(r-o)):(n[0]+n[1])/2}function rs(t,e){const i=Math.max(.25,Math.min(1,e.width/900,e.height/520)),n=t?.[0]??7*i,o=t?.[1]??18*i,r=Math.max(1,Math.min(n,o));return[r,Math.max(r,Math.max(n,o))]}function ss(t,e,i={}){const n=Object.values(t.components).sort((t,e)=>zr(t.id,e.id)),o=n.map(t=>t.amount),r=rs(i.radiusRange,e),s=function(t){let e=t>>>0;return()=>{e+=1831565813;let t=e;return t=Math.imul(t^t>>>15,1|t),t^=t+Math.imul(t^t>>>7,61|t),((t^t>>>14)>>>0)/4294967296}}(Jr(i.seed)),a=e.mouth.x+e.mouth.width/2,c=e.chamber.y+Math.max(18,.18*e.chamber.height),d=Math.max(4,.28*e.chamber.width),l=Math.max(4,.12*e.chamber.height);return n.map((t,e)=>{const u=e/Math.max(1,n.length)*Math.PI*2+.18*(s()-.5),h=os(t.amount,o,i.bodyRadius,r),p={__crucible:!0,kind:"component",semanticId:t.id,sourceDatum:t.datum};return{id:es(t.id),x:a+Math.cos(u)*d*(.45+.45*s()),y:c+Math.sin(u)*l*(.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 as(t,e){if(!t)return[];const i=Math.min(t,Math.max(1,Math.ceil(Math.sqrt(t*Math.max(.5,e.width/Math.max(1,e.height)))))),n=Math.max(1,Math.ceil(t/i));return Array.from({length:t},(t,o)=>({x:e.x+e.width/i*(o%i+.5),y:e.y+(Math.floor(o/i)+.5)*(e.height/n)}))}function cs(t){return t.outletId?t.outletId:"failed"===t.status?"failed":"recovered"===t.status?"recovered":"retained"===t.status?"retained":"ejected"===t.status?"residue":void 0}function ds(t,e){return t.outlets.find(t=>t.id===e)||{x:t.chamber.x+.18*t.chamber.width,y:t.chamber.y+.2*t.chamber.height,width:.64*t.chamber.width,height:.6*t.chamber.height}}function ls(t,e,i={}){const n=Object.values(t.products).sort((t,e)=>zr(t.id,e.id)),o=Object.values(t.components).sort((t,e)=>zr(t.id,e.id)),r=[...o.map(t=>t.amount),...n.map(t=>t.amount)],s=rs(i.radiusRange,e),a=function(t,e){const i=new Map;for(const e of t){const t=e.outletId??"__chamber__",n=i.get(t)??[];n.push(e),i.set(t,n)}const n=new Map;for(const[t,o]of i){o.sort((t,e)=>(t.order??Number.MAX_SAFE_INTEGER)-(e.order??Number.MAX_SAFE_INTEGER)||zr(t.id,e.id));const i=as(o.length,ds(e,"__chamber__"===t?void 0:t));o.forEach((t,e)=>n.set(t.id,i[e]))}return n}(n,e),c=n.map(t=>{const n=a.get(t.id)??{x:e.chamber.x+e.chamber.width/2,y:e.chamber.y+e.chamber.height/2},o=1.28*os(t.amount,r,i.bodyRadius,s),c={__crucible:!0,kind:"product",semanticId:t.id,product:t};return{id:is(t.id),x:n.x,y:n.y,mass:Math.max(.25,o*o*.018),bodyCollisions:!1,shape:{type:"circle",radius:o},datum:c}}),d=new Map;for(const t of o.filter(t=>!t.productIds.length)){const e=cs(t)??"__chamber__",i=d.get(e)??[];i.push(t),d.set(e,i)}const l=new Map;for(const[t,i]of d){const n=as(i.length,ds(e,"__chamber__"===t?void 0:t));i.forEach((t,e)=>l.set(t.id,n[e]))}return[...o.map(t=>{let n=l.get(t.id);if(t.productIds.length){const i=t.productIds.map(t=>a.get(t)).filter(t=>!!t);if(i.length){n={x:i.reduce((t,e)=>t+e.x,0)/i.length,y:i.reduce((t,e)=>t+e.y,0)/i.length};const o=Zr(t.id)/4294967295*Math.PI*2,r=Math.min(20,Math.max(4,.012*e.width));n={x:n.x+Math.cos(o)*r,y:n.y+Math.sin(o)*r}}}n??(n={x:e.chamber.x+e.chamber.width/2,y:e.chamber.y+e.chamber.height/2});const o=os(t.amount,r,i.bodyRadius,s),c={__crucible:!0,kind:"component",semanticId:t.id,sourceDatum:t.datum};return{id:es(t.id),x:n.x,y:n.y,mass:Math.max(.25,o*o*.015),shape:{type:"circle",radius:o},datum:c}}),...c]}var us=ls;function hs(t){return Array.isArray(t)?t.map(hs):t&&"object"==typeof t?Object.fromEntries(Object.entries(t).filter(([,t])=>void 0!==t&&"function"!=typeof t).sort(([t],[e])=>zr(t,e)).map(([t,e])=>[t,hs(e)])):t}function ps(t){return JSON.stringify(hs(t))}function ms(t,e){const i=_r(e)??0,n=Math.max(0,Math.min(t.duration,i));if(!t.phases.length)return{elapsed:n,phaseId:"",phaseIndex:-1,phaseElapsed:0,complete:!0};const o=n>=t.duration-Dr,r=o?t.phases[t.phases.length-1]:t.phases.find(t=>n>=t.start&&t.end>n)??t.phases[0];return{elapsed:n,phaseId:r.id,phaseIndex:r.index,phaseElapsed:o?r.duration:Math.max(0,n-r.start),complete:o}}function fs(t,e){if(void 0===e)return t.duration;if("number"==typeof e)return Math.max(0,Math.min(t.duration,_r(e)??0));const i=t.phases.find(t=>t.id===e.phaseId);if(!i)return t.duration;const n=Math.max(0,Math.min(1,_r(e.progress??0)??0));return i.start+i.duration*n}function ys(t,e=t.duration){const i=ms(t,e);let n=yr(t.initialState);const o=[],r=[],s=[];for(const e of t.events){if(e.authoredAt>i.elapsed+Dr)break;const a=$r(n,e,{phaseId:e.phaseId,authoredAt:e.authoredAt,appliedAt:e.authoredAt,products:t.products,outlets:t.outlets});o.push(...a.diagnostics),r.push(...a.materializations),s.push(...a.observations),a.applied&&(n=a.state)}return n.elapsed=i.elapsed,n.phaseId=i.phaseId,n.phaseIndex=i.phaseIndex,n.phaseElapsed=i.phaseElapsed,n.complete=i.complete,i.complete&&"in_process"===n.outcome&&(n.outcome="complete"),n.playing=!1,{state:n,diagnostics:o,materializations:r,observations:s}}function gs(t){const e=function(t){const e=[];t.length||e.push(Lr("error","empty-phase-program","CrucibleChart requires at least one phase.","phases"));const i=Yr(t.map(t=>t.id));i.length&&e.push(Lr("error","duplicate-phase-id",`Phase ids must be unique: ${i.join(", ")}.`,"phases",i));let n=0;return{phases:t.map((t,i)=>{const o=_r(t.duration),r=null!=o&&o>0?o:0;t.id.trim()||e.push(Lr("error","invalid-phase-id","Phase ids may not be empty.",`phases.${i}.id`)),null!=o&&o>0||e.push(Lr("error","invalid-phase-duration","Phase duration must be finite and greater than zero.",`phases.${i}.duration`,[t.id])),void 0===t.intensity||Number.isFinite(t.intensity)||e.push(Lr("error","invalid-phase-intensity","Phase intensity must be finite.",`phases.${i}.intensity`,[t.id]));const s={...t,duration:r,intensity:void 0===t.intensity?.5:Number.isFinite(t.intensity)?Math.max(0,Math.min(1,t.intensity)):.5,motion:t.motion??"hold",index:i,start:n,end:n+r};return n=s.end,s}),diagnostics:e}}(t.phases),i=e.phases.at(-1)?.end??0,n=Vr(t.outlets??Fr),o=(t.products??[]).map(t=>({...t,metrics:t.metrics?{...t.metrics}:void 0})),r=function(t,e,i){const n=[],o=Yr(t.map(t=>t.id));o.length&&n.push(Lr("error","duplicate-event-id",`Event ids must be unique: ${o.join(", ")}.`,"events",o));const r=[];return t.forEach((t,o)=>{let s,a,c;if(t.id.trim()||n.push(Lr("error","invalid-event-id","Event ids may not be empty.",`events.${o}.id`)),"time"in t.at&&void 0!==t.at.time){const r=_r(t.at.time);if(null==r||0>r||r>i+Dr)return void n.push(Lr("error","event-time-out-of-range",`Event time must fall between 0 and ${i}.`,`events.${o}.at.time`,[t.id]));s=Math.max(0,Math.min(i,r));const d=function(t,e,i){const n=t.find(t=>Dr>=Math.abs(t.start-i));if(n)return{phase:n,boundaryRank:1};const o=t.find(t=>i>=t.start&&t.end>i);return o?{phase:o,boundaryRank:0}:Dr>=Math.abs(i-e)&&t.length?{phase:t[t.length-1],boundaryRank:0}:{phase:void 0,boundaryRank:1}}(e,i,s);a=d.phase,c=d.boundaryRank}else{if(a=e.find(e=>e.id===t.at.phaseId),!a)return void n.push(Lr("error","unknown-event-phase",`Event references unknown phase "${t.at.phaseId}".`,`events.${o}.at.phaseId`,[t.id,t.at.phaseId]));const i=t.at.progress??0;if(!Number.isFinite(i)||0>i||i>1)return void n.push(Lr("error","event-progress-out-of-range","Event phase progress must be between 0 and 1.",`events.${o}.at.progress`,[t.id]));s=a.start+a.duration*i,c=0===i?1:0}a?r.push({...t,index:o,authoredAt:s,phaseId:a.id,phaseIndex:a.index,boundaryRank:c}):n.push(Lr("error","event-without-phase","Event could not be assigned to a phase.",`events.${o}.at`,[t.id]))}),r.sort((t,e)=>t.authoredAt-e.authoredAt||t.boundaryRank-e.boundaryRank||t.index-e.index),{events:r,diagnostics:n}}(t.events??[],e.phases,i),s=Gr(t),a=Ur(t.size??qr,n),c=Qr(a),d=function(t,e){const i=[],n=new Set(e.map(t=>t.id)),o=Yr(e.map(t=>t.id)),r=Yr(t.map(t=>t.id));return o.length&&i.push(Lr("error","duplicate-outlet-id",`Outlet ids must be unique: ${o.join(", ")}.`,"outlets",o)),r.length&&i.push(Lr("error","duplicate-product-id",`Product ids must be unique: ${r.join(", ")}.`,"products",r)),e.forEach((t,e)=>{t.id.trim()||i.push(Lr("error","invalid-outlet-id","Outlet ids may not be empty.",`outlets.${e}.id`)),void 0===t.order||Number.isFinite(t.order)||i.push(Lr("error","invalid-outlet-order","Outlet order must be finite.",`outlets.${e}.order`,[t.id]))}),t.forEach((t,e)=>{t.id.trim()||i.push(Lr("error","invalid-product-id","Product ids may not be empty.",`products.${e}.id`)),void 0===t.amount||Number.isFinite(t.amount)&&t.amount>=0||i.push(Lr("error","invalid-product-amount","Declared product amount must be finite and non-negative.",`products.${e}.amount`,[t.id])),void 0===t.outletId||n.has(t.outletId)||i.push(Lr("error","unknown-outlet",`Product "${t.id}" references unknown outlet "${t.outletId}".`,`products.${e}.outletId`,[t.outletId])),Xr(t.metrics??{},i,`products.${e}.metrics`)}),i}(o,n),l=ps({seed:t.seed??1,components:Object.values(s.state.components).sort((t,e)=>zr(t.id,e.id)).map(t=>({id:t.id,label:t.label,category:t.category,amount:t.amount,metrics:t.metrics,status:t.status})),phases:e.phases.map(({id:t,duration:e,label:i,description:n,intensity:o,motion:r,color:s,metrics:a})=>({id:t,duration:e,label:i,description:n,intensity:o,motion:r,color:s,metrics:a})),products:o,outlets:n,events:r.events.map(({id:t,label:e,description:i,summary:n,authoredAt:o,phaseId:r,boundaryRank:s,effects:a})=>({id:t,label:e,description:i,summary:n,authoredAt:o,phaseId:r,boundaryRank:s,effects:a}))}),u=ss(s.state,a,{seed:t.seed,bodyRadius:t.bodyRadius,radiusRange:t.radiusRange}),h=[...e.diagnostics,...r.diagnostics,...s.diagnostics,...d],p={phases:e.phases,events:r.events,products:o,outlets:n,duration:i,initialState:s.state,terminalState:s.state,layout:a,colliders:c,config:ts(t.seed,c),initialSpawns:u,terminalSpawns:[],semanticKey:l,diagnostics:h},m=ys(p),f=Object.values(m.state.products).filter(t=>"forming"===t.status).map(t=>t.id),y=f.length?[Lr("warning","forming-product-at-end",`Products remain forming at the end of the tape: ${f.join(", ")}.`,"events",f)]:[];return p.terminalState=m.state,p.terminalSpawns=us(m.state,a,{seed:t.seed,bodyRadius:t.bodyRadius,radiusRange:t.radiusRange}),p.diagnostics=[...h,...m.diagnostics,...y],p}function bs(t,e,i){return{id:t.id??e,at:{...t.at},effects:i,...void 0===t.label?null:{label:t.label},...void 0===t.description?null:{description:t.description},...void 0===t.summary?null:{summary:t.summary}}}function xs(t){if(t)return{...t,...t.metrics?{metrics:{...t.metrics}}:null}}function vs(t){const{productId:e,form:i,contributions:n=[],complete:o}=t,r=t.idPrefix??e,s=xs(i.loss),a=[bs(i,r+"-form",[{type:"combine",sourceIds:[...i.sourceIds],productId:e,...i.basisRelationIds?{basisRelationIds:[...i.basisRelationIds]}:null,...s?{loss:s}:null,complete:!1}])];return n.forEach((t,i)=>{const n=xs(t.loss);a.push(bs(t,`${r}-contribute-${i+1}`,[{type:"contribute",sourceIds:[...t.sourceIds],productId:e,...t.basisRelationIds?{basisRelationIds:[...t.basisRelationIds]}:null,...n?{loss:n}:null}]))}),a.push(bs(o,r+"-complete",[{type:"complete-product",productId:e,...void 0===o.outletId?null:{outletId:o.outletId},...void 0===o.reason?null:{reason:o.reason}}])),a}import{forwardRef as ws,useCallback as Is,useEffect as Ms,useImperativeHandle as ks,useMemo as Ss,useRef as As,useState as Rs}from"react";function Ps(t,e){return t.playing=e&&!t.complete,t}function Cs(t,e,i=!1){const n=ys(t,e);return{...n,state:Ps(n.state,i)}}function $s(t,e,i,n=e.playing){const o=Cs(t,i,n),r=new Set(e.eventsApplied);return{...o,observations:o.observations.filter(t=>!r.has(t.eventId)),materializations:o.materializations.filter(t=>!r.has(t.eventId))}}function js(t,e,i={}){return ls(e,t.layout,i)}function Bs(t,e){return function(t){let e=2166136261;for(let i=0;t.length>i;i+=1)e^=t.charCodeAt(i),e=Math.imul(e,16777619);return e>>>0}(`${e}:${t}`)/4294967295}function Os(t,e){return t.phases[e.phaseIndex]??t.phases.find(t=>t.id===e.phaseId)}function Ns(t,e,i={}){return new Map(js(t,e,i).flatMap(t=>{const e=t.datum;return e?.__crucible?[[`${e.kind}:${e.semanticId}`,{x:t.x,y:t.y}]]:[]}))}function Ts(t,e){const i=Object.values(t.terminalState.products).map(t=>t.id).sort(),n=Math.max(0,i.indexOf(e))/Math.max(1,i.length)*Math.PI*2-Math.PI/2,o=Math.min(58,.19*t.layout.chamber.width),r=Math.min(38,.16*t.layout.chamber.height);return{x:t.layout.chamber.x+t.layout.chamber.width/2+Math.cos(n)*o,y:t.layout.chamber.y+.52*t.layout.chamber.height+Math.sin(n)*r}}import*as Es from"react";import{jsx as qs,jsxs as Fs}from"react/jsx-runtime";function Ws(t,e,i){if("string"!=typeof e)return i;if("function"!=typeof getComputedStyle||!t.canvas)return e||i;const n=e.startsWith("var(")?e.match(/var\((--[^,\s)]+)/)?.[1]:e.startsWith("--")?e:null;return n?getComputedStyle(t.canvas).getPropertyValue(n).trim()||i:e||i}function Ds(t){return Number.isFinite(t)?1e3>Math.abs(t)?Number.isInteger(t)?t+"":t.toFixed(2).replace(/\.00$/,"").replace(/(\.\d)0$/,"$1"):t.toLocaleString():"0"}function zs(t){const e=t.productIds.length?` Contributes to ${t.productIds.join(", ")}.`:t.outletId?` Routed to ${t.outletId}.`:"",i=t.reason?` ${t.reason}.`:"";return`${Ds(t.amount)} amount; ${t.status}.${e}${i}`}function Ls(t){const e=t.outletId?` Routed to ${t.outletId}.`:"";return`${t.status} product with ${t.sourceIds.length} source${1===t.sourceIds.length?"":"s"} and ${Ds(t.amount)} amount.${e}`}function Ys(t,e,i){const n=e.datum;if(!n?.__crucible)return;const o="circle"===e.shape.type?e.shape.radius:8,r=Ws(t,i.fill,"product"===n.kind?"#b8792d":"#356b63"),s=Ws(t,i.stroke,"#26323a");if(t.save(),t.translate(e.x,e.y),t.globalAlpha="number"==typeof i.opacity?i.opacity:.96,t.fillStyle=r,t.strokeStyle=s,t.lineWidth="number"==typeof i.strokeWidth?i.strokeWidth:1.25,"product"===n.kind){t.shadowColor=r,t.shadowBlur=10,t.beginPath();for(let e=0;6>e;e+=1){const i=-Math.PI/2+e/6*Math.PI*2,n=Math.cos(i)*o,r=Math.sin(i)*o;0===e?t.moveTo(n,r):t.lineTo(n,r)}t.closePath(),t.fill(),t.shadowBlur=0,t.stroke(),t.beginPath(),t.arc(0,0,Math.max(2,.36*o),0,2*Math.PI),t.strokeStyle=Ws(t,"var(--semiotic-background, #fffaf0)","#fffaf0"),t.globalAlpha*=.72,t.stroke()}else t.beginPath(),t.arc(0,0,o,0,2*Math.PI),t.fill(),t.stroke(),t.beginPath(),t.arc(.25*-o,.28*-o,Math.max(1,.18*o),0,2*Math.PI),t.fillStyle="rgba(255,255,255,0.34)",t.fill();t.restore()}import{Fragment as _s,jsx as Hs,jsxs as Xs}from"react/jsx-runtime";var Gs="var(--semiotic-text, #26323a)",Vs="var(--semiotic-text-secondary, #6c7377)",Us="var(--semiotic-accent, #b8792d)",Ks="var(--semiotic-negative, #9f3d35)",Qs="var(--semiotic-positive, #356b63)";function Zs(t){const{x:e,y:i,width:n,height:o}=t.chamber,r=Math.min(.14*n,48),s=i+o;return[`M ${e} ${i}`,`L ${e+r} ${s-.16*o}`,`Q ${e+n/2} ${s+.1*o} ${e+n-r} ${s-.16*o}`,`L ${e+n} ${i}`].join(" ")}function Js({layout:t,phases:e,state:i,compact:n=!1}){const o=Math.max(1,e.reduce((t,e)=>t+Math.max(0,e.duration),0));return Xs("svg",{"aria-hidden":"true","data-testid":"crucible-chrome",viewBox:`0 0 ${t.width} ${t.height}`,style:{inset:0,pointerEvents:"none",position:"absolute"},children:[Xs("defs",{children:[Xs("linearGradient",{id:"semiotic-crucible-heat",x1:"0",x2:"0",y1:"0",y2:"1",children:[Hs("stop",{offset:"0",stopColor:Us,stopOpacity:"0.03"}),Hs("stop",{offset:"0.66",stopColor:Us,stopOpacity:"0.1"}),Hs("stop",{offset:"1",stopColor:Ks,stopOpacity:"0.18"})]}),Hs("pattern",{id:"semiotic-crucible-hatch",width:"7",height:"7",patternUnits:"userSpaceOnUse",patternTransform:"rotate(20)",children:Hs("line",{x1:"0",x2:"0",y1:"0",y2:"7",stroke:Gs,strokeOpacity:"0.08",strokeWidth:"1"})})]}),Hs("rect",{x:t.chamber.x,y:t.chamber.y,width:t.chamber.width,height:t.chamber.height,rx:2,fill:"url(#semiotic-crucible-heat)",stroke:Gs,strokeOpacity:"0.52",strokeWidth:n?1:2.2}),Hs("path",{d:Zs(t),fill:"url(#semiotic-crucible-hatch)",stroke:"none"}),Hs("line",{x1:t.mouth.x,x2:t.mouth.x+t.mouth.width,y1:t.mouth.y,y2:t.mouth.y,stroke:Gs,strokeLinecap:"round",strokeOpacity:"0.72",strokeWidth:n?2:5}),n?null:Hs("g",{"data-testid":"crucible-phase-rail",children:e.map((n,r)=>{const s=e.slice(0,r).reduce((t,e)=>t+Math.max(0,e.duration),0),a=t.phaseRail.x+s/o*t.phaseRail.width,c=Math.max(0,n.duration)/o*t.phaseRail.width,d=n.id===i.phaseId,l=i.phaseIndex>r||i.complete;return Xs("g",{children:[Hs("rect",{x:a,y:t.phaseRail.y,width:Math.max(1,c-2),height:t.phaseRail.height,rx:2,fill:d?n.color??Us:l?Qs:Gs,fillOpacity:d?.68:l?.28:.09}),46>c?null:Hs("text",{x:a+c/2,y:t.phaseRail.y+t.phaseRail.height+13,fill:d?Gs:Vs,fontFamily:"system-ui, sans-serif",fontSize:8.5,fontWeight:d?800:650,letterSpacing:"0.04em",textAnchor:"middle",children:(n.label??n.id).toUpperCase()})]},n.id)})}),t.outlets.map(t=>Xs("g",{children:[Hs("rect",{x:t.x,y:t.y,width:t.width,height:t.height,rx:3,fill:t.color??("left"===t.side?Ks:Qs),fillOpacity:"0.1",stroke:t.color??("left"===t.side?Ks:Qs),strokeDasharray:"3 3",strokeOpacity:"0.62"}),n?null:Hs("text",{x:t.x+t.width/2,y:t.y+Math.min(13,t.height/2+3),fill:Vs,fontFamily:"system-ui, sans-serif",fontSize:8,fontWeight:750,letterSpacing:"0.05em",textAnchor:"middle",children:(t.label??t.id).toUpperCase()})]},t.id))]})}function ta(t,e){return"count"===e?t.count:"amount"===e?t.amount:Number(t.metrics[e]??0)}function ea({rows:t,layout:e,projection:i,amountLabel:n}){if(!t.length)return null;const o=i.measure??"count",r=t.map(t=>Math.max(0,ta(t,o))),s=Math.max(1,...r),a=e.projection.width/Math.max(1,t.length),c=e.projection.height>48?21:4,d=Math.max(5,e.projection.height-c-5);return Hs("svg",{"aria-hidden":"true","data-testid":"crucible-projection-overlay",viewBox:`0 0 ${e.width} ${e.height}`,style:{inset:0,pointerEvents:"none",position:"absolute"},children:t.map((t,i)=>{const l=r[i],u=Math.max(l>0?2:0,l/s*d),h=e.projection.x+i*a+.18*a;return Xs("g",{children:[Hs("rect",{x:h,y:e.projection.y+d-u,width:Math.max(3,.64*a),height:u,rx:2,fill:"failed"===t.status||"ejected"===t.status?Ks:"complete"===t.status?Us:Qs,fillOpacity:"0.68"}),c>4&&a>=34?Xs(_s,{children:[Hs("text",{x:h+.32*a,y:e.projection.y+d+10,fill:Vs,fontFamily:"system-ui, sans-serif",fontSize:7.5,fontWeight:700,textAnchor:"middle",children:t.label.length>13?t.label.slice(0,12)+"…":t.label}),Xs("text",{x:h+.32*a,y:e.projection.y+d+19,fill:Gs,fontFamily:"system-ui, sans-serif",fontSize:8,fontWeight:850,textAnchor:"middle",children:[Ds(l),"amount"===o&&n?" "+n:""]})]}):null]},t.key)})})}function ia({controls:t,duration:e,elapsed:i,phaseLabel:n,playing:o,complete:r,playbackRate:s,disabled:a,onPlayPause:c,onReset:d,onStepPhase:l,onPlaybackRateChange:u}){const h=e>0?Math.min(1,Math.max(0,i/e)):1;return Xs("div",{"aria-label":"Crucible replay controls",className:"semiotic-crucible-controls",style:{alignItems:"center",color:Gs,display:"flex",flexWrap:"wrap",fontFamily:"system-ui, sans-serif",fontSize:11,gap:6,marginBottom:7},children:[t.playPause?Hs("button",{type:"button",disabled:a,onClick:c,"aria-pressed":o,children:o?"Pause":r?"Replay":"Play"}):null,t.stepPhase?Hs("button",{type:"button",disabled:a,onClick:l,children:"Next phase"}):null,t.reset?Hs("button",{type:"button",disabled:a,onClick:d,children:"Reset"}):null,t.timeline?Xs("div",{style:{alignItems:"center",display:"flex",flex:"1 1 150px",gap:7,minWidth:130},children:[Hs("span",{style:{fontWeight:750,whiteSpace:"nowrap"},children:n}),Hs("span",{"aria-hidden":"true",style:{background:"rgba(38,50,58,0.14)",borderRadius:2,flex:1,height:4,overflow:"hidden"},children:Hs("span",{style:{background:Us,display:"block",height:"100%",transform:`scaleX(${h})`,transformOrigin:"left center"}})}),Xs("span",{style:{color:Vs,fontVariantNumeric:"tabular-nums"},children:[i.toFixed(1),"s"]})]}):null,t.speed?Xs("label",{style:{alignItems:"center",display:"flex",gap:4},children:["Speed",Xs("select",{disabled:a,value:s,onChange:t=>u(Number(t.currentTarget.value)),children:[Hs("option",{value:.25,children:"¼×"}),Hs("option",{value:.5,children:"½×"}),Hs("option",{value:1,children:"1×"}),Hs("option",{value:2,children:"2×"})]})]}):null]})}function na(t,e,i,n){const o="function"==typeof n?n(e,i):n,r=e.datum;return{fill:t,stroke:"product"===r?.kind?"var(--semiotic-background, #fffaf0)":Gs,strokeWidth:"product"===r?.kind?1.8:1.1,opacity:.96,...o}}import{jsx as oa,jsxs as ra}from"react/jsx-runtime";import{createElement as sa}from"react";var aa=["#356b63","#a34b43","#c08b38","#3e5f83","#785b7c","#6e7740","#8f5c3a","#41717b"];function ca(t){let e=2166136261;for(let i=0;t.length>i;i+=1)e^=t.charCodeAt(i),e=Math.imul(e,16777619);return e>>>0}function da(t){return"number"==typeof t&&Number.isFinite(t)?t:ca((t??"crucible")+"")}function la(t){const e=Number(t);return Number.isFinite(e)&&e>0?Math.max(.05,Math.min(8,e)):1}function ua(t,e,i){return"category"===e?t.category:"status"===e?t.status:"outlet"===e?t.outletId??"in chamber":"product"===e?t.productIds[0]??"unalloyed":function(t,e,i){return(("function"==typeof t?t(e,i):e[t])??"unassigned")+""}(e,t.datum,i)}function ha(t){return aa[ca(t)%aa.length]}function pa(t,e){const i=Object.keys(t.components).length,n=Object.keys(t.products).length,o=Object.values(t.products).reduce((t,e)=>t+e.amount,0),r=e?" "+e:" amount",s=t.outcome?` Outcome: ${t.outcome}.`:"";return`${i} source component${1===i?"":"s"}; ${n} product${1===n?"":"s"}; ${o.toLocaleString()}${r} in products.${s}`}var ma=ws(function(t,e){const{amountAccessor:i,amountLabel:n,bodyRadius:o,categoryAccessor:r,colorBy:s="category",conservation:a,controls:c,data:d,emptyContent:l,events:u,frameProps:h={},idAccessor:p,initialStateAccessor:m,initialSpawnPacing:f,labelAccessor:y,loading:g,loadingContent:b,metrics:v,metricsAccessor:w,onClick:I,onConservation:M,onCrucibleObservation:k,onDiagnostic:S,onStateChange:A,outlets:R,paused:P,phases:C,playback:$="replay",playbackRate:j=1,products:B,projection:O,radiusRange:T,rerunMS:E,responsiveHeight:q,responsiveWidth:F,seed:W,showBonds:D=!0,snapshotAt:z}=t,L=As(null),Y=As(P);Y.current=P;const X=H(),G=_(),V=No(t,qr),{chartMode:U,chartSize:K,showChrome:Q,showProjection:Z,className:J,title:tt,description:et,summary:it,accessibleTable:nt,enableHover:ot,margin:rt}=V,[st,at]=N(K,F,!1),ct=F?Math.max(1,at[0]):K[0],dt=K[1],lt=Ss(()=>[ct,dt],[dt,ct]),ut=Ss(()=>x(d??[]),[d]),ht=Ss(()=>gs({data:ut,phases:C,products:B,outlets:R,events:u,idAccessor:p,labelAccessor:y,categoryAccessor:r,amountAccessor:i,metricsAccessor:w,initialStateAccessor:m,metrics:v,size:lt,seed:W,bodyRadius:o,radiusRange:T}),[i,o,r,u,p,m,y,v,w,R,C,B,T,lt,ut,W]),pt=Object.values(ht.initialState.components).map((t,e)=>ua(t,s,e)).join("\0"),mt=`${ht.semanticKey}:${lt[0]}x${lt[1]}:${(o??"auto")+""}:${T?.join(",")??"auto"}:${pt}`,ft=As(ht),yt=As(mt);yt.current!==mt&&(yt.current=mt,ft.current=ht);const gt=ft.current,bt="snapshot"===$||X||G,xt=bt?function(t,e){return fs(t,e)}(gt,z):0,vt=!bt,wt=Ss(()=>Cs(gt,xt,vt&&!P),[yt.current,xt,vt]),[It,Mt]=Rs(wt),kt=As(It),[St,At]=Rs(vt),Rt=As(St),[Pt,Ct]=Rs(0),[$t,jt]=Rs(()=>la(j)),Bt=As(Ns(gt,wt.state,{seed:W,bodyRadius:o,radiusRange:T})),Ot=As(""),Nt=As(A),Tt=As(k),Et=As(S),qt=As(M);Nt.current=A,Tt.current=k,Et.current=S,qt.current=M;const Ft=As({seed:W,bodyRadius:o,radiusRange:T});Ft.current={seed:W,bodyRadius:o,radiusRange:T};const Wt=Is((t,e=!1)=>{if(kt.current=t,Bt.current=Ns(ft.current,t.state,Ft.current),Mt(t),e)for(const e of t.observations)Tt.current?.(e)},[]);Ms(()=>{jt(la(j))},[j]),Ms(()=>{const t=!bt,e=Cs(gt,bt?xt:0,t&&!Y.current);Rt.current=t,At(t),Wt(e)},[Wt,gt,xt,bt,mt]),Ms(()=>{const t=kt.current,e=Rt.current&&!P&&!t.state.complete;if(t.state.playing===e)return;const i={...t,state:yr(t.state)};i.state.playing=e,Wt(i)},[Wt,P]),Ms(()=>{for(const t of gt.diagnostics)Et.current?.(t)},[mt,gt.diagnostics]),Ms(()=>{if(Nt.current?.(It.state),a){const t=!0===a?{}:a;qt.current?.(Or(It.state,t))}},[a,It.state]);const Dt=Is(()=>{Ot.current="";const t=!bt,e=Cs(ft.current,0,t&&!P);Rt.current=t,At(t),Wt(e)},[Wt,P,bt]),zt=Ss(()=>({...gt.config,...h.config,fixedDt:h.config?.fixedDt??gt.config.fixedDt,maxSubsteps:h.config?.maxSubsteps??gt.config.maxSubsteps,settleStepLimit:h.config?.settleStepLimit??gt.config.settleStepLimit,timeScale:$t,colliders:[...gt.config.colliders??[],...h.config?.colliders??[]],kernel:{...gt.config.kernel,...h.config?.kernel,gravity:h.config?.kernel?.gravity??gt.config.kernel?.gravity??{x:0,y:0}},observation:{...gt.config.observation,...h.config?.observation,chartType:"CrucibleChart"}}),[h.config,$t,gt.config]),Lt=bt||!!P||!St&&!It.state.complete,Yt=Oo(zt,E,Lt,Dt),_t=Is(()=>{if("number"!=typeof E||!Number.isFinite(E)||0>E)return;const t=`${mt}:${Pt}:${Yt.rerunKey}`;Ot.current!==t&&(Ot.current=t,Yt.config?.observation?.onSimulationStateChange?.("settled","running"))},[Yt.config,Yt.rerunKey,E,Pt,mt]),Ht=Is(()=>{const t=Cs(ft.current,0,!1);Rt.current=!1,At(!1),Wt(t),Ct(t=>t+1)},[Wt]),Xt=Is(()=>{const t=ft.current,e=$s(t,kt.current.state,t.duration,!1);Rt.current=!1,At(!1),Wt(e,!0);const i=js(t,e.state,Ft.current),n=L.current;n&&(n.clear(),n.pushMany(i),n.step(0),n.settle()),_t()},[Wt,_t]),Gt=Is(()=>{Rt.current=!1,At(!1);const t={...kt.current,state:yr(kt.current.state)};t.state.playing=!1,Wt(t)},[Wt]),Vt=Is(()=>{if(Ot.current="",bt){const t=Cs(ft.current,xt,!1);return Rt.current=!1,At(!1),Wt(t),void Ct(t=>t+1)}const t=Cs(ft.current,0,!P);Rt.current=!0,At(!0),Wt(t),Ct(t=>t+1)},[Wt,P,xt,bt]),Ut=Is(()=>{if(bt)return void Vt();if(kt.current.state.complete)return void Vt();Rt.current=!0,At(!0);const t={...kt.current,state:yr(kt.current.state)};t.state.playing=!P,Wt(t)},[Wt,P,Vt,bt]),Kt=Is(()=>{const t=ft.current,e=function(t,e){const i=t.phases.find(t=>t.end>e+1e-7);return i?.end??t.duration}(t,kt.current.state.elapsed),i=$s(t,kt.current.state,e,!1);Rt.current=!1,At(!1),Wt(i,!0);const n=L.current;n&&(n.clear(),n.pushMany(js(t,i.state,Ft.current)),n.step(0))},[Wt]);ks(e,()=>({play:Ut,pause:Gt,reset:Ht,replay:Vt,stepPhase:Kt,settle:Xt,getCrucibleState:()=>yr(kt.current.state)}),[Gt,Ut,Vt,Ht,Xt,Kt]);const Qt=Is((t,e)=>{if(h.onTick?.(t,e),bt||P||!Rt.current)return;const i=kt.current.state,n=Math.min(ft.current.duration,t.elapsedSeconds);if(i.elapsed+.045>=n&&ft.current.duration>n)return;const o=$s(ft.current,i,n,ft.current.duration>n),r=o.state.eventsApplied.length!==i.eventsApplied.length;if(r&&function(t,e){const i=new Set(t.readBodies().map(t=>t.id)),n=e.filter(t=>!i.has(t.id));n.length&&t.pushMany([...n]),n.map(t=>t.id)}(e,js(ft.current,o.state,Ft.current)),o.state.complete){Rt.current=!1,At(!1);const t=js(ft.current,o.state,Ft.current);e.clear(),e.pushMany(t),e.step(0),e.settle()}Wt(o,r),o.state.complete&&_t()},[Wt,h,P,_t,bt]),Zt=Is(({body:t})=>function(t){const e=function(t){const{body:e,plan:i,state:n,targets:o}=t,r=e.datum;if(!r?.__crucible)return null;let s=o.get(`${r.kind}:${r.semanticId}`);if(!s)return null;const a=Os(i,n),c=Math.max(0,Math.min(2,Number(a?.intensity??.5))),d=a?.motion??"hold",l=n.elapsed;if("product"===r.kind){const t=n.products[r.semanticId];"forming"===t?.status&&(s=Ts(i,t.id))}else{const t=n.components[r.semanticId],e=t?.productIds.map(t=>n.products[t]).find(t=>"forming"===t?.status);if(e){const n=Ts(i,e.id),o=Bs(t.id,17)*Math.PI*2,r=Math.max(5,Math.min(18,.026*i.layout.width));s={x:n.x+Math.cos(o)*r,y:n.y+Math.sin(o)*r}}}const u=r.semanticId,h=Bs(u,23)*Math.PI*2;if(!n.complete&&!(i.layout.chamber.x>s.x||s.x>i.layout.chamber.x+i.layout.chamber.width||i.layout.chamber.y>s.y||s.y>i.layout.chamber.y+i.layout.chamber.height))if("mix"===d){const t=Math.min(34,.1*i.layout.chamber.width)*c,e=Math.min(24,.09*i.layout.chamber.height)*c;s={x:s.x+Math.cos(l*(1.4+Bs(u,29))+h)*t,y:s.y+Math.sin(l*(1.8+Bs(u,31))+h)*e}}else if("press"===d){const t=i.layout.chamber.x+i.layout.chamber.width/2,e=i.layout.chamber.y+.56*i.layout.chamber.height;s={x:t+(s.x-t)*Math.max(.3,1-.32*c),y:e+(s.y-e)*Math.max(.35,1-.26*c)}}else if("separate"===d){const t=.5>Bs(u,41)?-1:1;s={x:s.x+t*Math.min(28,.075*i.layout.chamber.width)*c,y:s.y}}else if("bind"===d){const t=i.layout.chamber.x+i.layout.chamber.width/2,e=i.layout.chamber.y+.5*i.layout.chamber.height;s={x:t+.72*(s.x-t),y:e+.72*(s.y-e)}}else"charge"===d?s={x:s.x,y:s.y+4*Math.sin(2*l+h)*c}:"quench"===d&&(s={x:s.x+2*Math.sin(h)*c,y:s.y});return s}(t);if(!e)return null;const{body:i,state:n}=t,o=e.x-i.x,r=e.y-i.y,s=Math.hypot(o,r),a=Math.hypot(i.vx,i.vy);if(n.complete&&.7>s&&.45>a)return null;const c=!n.complete&&"pour"===Os(t.plan,n)?.motion,d=n.complete?.68:c?.72:.5,l=n.complete?.22:c?.18:.14,u=n.complete?42:c?72:56;return{x:Math.max(-u,Math.min(u,o*d-i.vx*l)),y:Math.max(-u,Math.min(u,r*d-i.vy*l))}}({body:t,plan:ft.current,state:kt.current.state,targets:Bt.current}),[]),Jt=Ss(()=>new Map(Object.keys(gt.initialState.components).map((t,e)=>[t,e])),[gt.initialState.components]),te=Is(e=>{if(t.color)return t.color;const i=e.datum;if(!i?.__crucible)return"var(--semiotic-accent, #b8792d)";if("product"===i.kind){const t=kt.current.state.products[i.semanticId];return t?.color??ha(t?.id??i.semanticId)}const n=kt.current.state.components[i.semanticId];return n?ha(ua(n,s,Jt.get(n.id)??0)):"var(--semiotic-accent, #356b63)"},[s,Jt,t.color]),ee=Is((e,i)=>({...na(te(e),e,i,h.bodyStyle),...void 0!==t.stroke?{stroke:t.stroke}:null,...void 0!==t.strokeWidth?{strokeWidth:t.strokeWidth}:null,...void 0!==t.opacity?{opacity:t.opacity}:null}),[te,h.bodyStyle,t.opacity,t.stroke,t.strokeWidth]),ie=Is((t,e)=>("function"==typeof h.bodySemanticItems?h.bodySemanticItems(t,e):void 0)??function(t,e){const i=t.datum;if(!i?.__crucible)return!1;if("component"===i.kind){const t=e.components[i.semanticId];return!!t&&{id:"crucible-component-"+t.id,label:t.label,description:zs(t),group:"source component · "+t.status,datum:t}}const n=e.products[i.semanticId];return!!n&&{id:"crucible-product-"+n.id,label:n.label,description:Ls(n),group:"derived product · "+n.status,datum:n}}(t,kt.current.state),[h]),ne=Is(t=>{if(!I||!t||"object"!=typeof t)return;if(!t.__crucible)return;const e=kt.current.state,i="component"===t.kind?e.components[t.semanticId]:e.products[t.semanticId];i&&I(i)},[I]),oe=Is((t,e)=>{h.beforePaint?.(t,e),D&&function(t,e,i){const n=new Map;for(const t of e){const e=t.datum;e?.__crucible&&n.set(`${e.kind}:${e.semanticId}`,t)}t.save(),t.lineCap="round";for(const e of Object.values(i.relations)){if("active"!==e.status)continue;const i=e.sourceIds.map(t=>n.get("component:"+t)).filter(t=>!!t);2>i.length||(t.strokeStyle="rejected"===e.category?"#9f3d35":"#b8792d",t.globalAlpha=.4,t.lineWidth=Math.max(.8,1.3*Number(e.strength??1)),t.setLineDash([3,4]),t.beginPath(),i.forEach((e,i)=>{0===i?t.moveTo(e.x,e.y):t.lineTo(e.x,e.y)}),t.stroke())}t.setLineDash([]);for(const e of Object.values(i.products)){const i=n.get("product:"+e.id);if(i)for(const o of e.sourceIds){const r=n.get("component:"+o);r&&(t.strokeStyle=e.color??"#b8792d",t.globalAlpha="complete"===e.status?.5:.28,t.lineWidth="complete"===e.status?1.6:1,t.beginPath(),t.moveTo(r.x,r.y),t.lineTo(i.x,i.y),t.stroke())}}t.restore()}(t,e,kt.current.state)},[h,D]),re=Ss(()=>O??{groupBy:"outlet",measure:"count"},[O]),se=Ss(()=>jr(It.state,re),[re,It.state]),ae=Ss(()=>Z?function(t,e,i,n){if(!t.length)return[];const o=i.measure??"count",r=e.projection.width/Math.max(1,t.length);return t.map((t,i)=>{const s=ta(t,o),a="amount"===o&&n?`${Ds(s)} ${n}`:`${Ds(s)} ${o}`;return{id:"crucible-projection-"+t.key,label:`${t.label}: ${a}`,description:`${t.count} source component${1===t.count?"":"s"}; ${Ds(t.amount)} amount.`,datum:t,group:"settled composition",x:e.projection.x+(i+.5)*r,y:e.projection.y+e.projection.height/2,shape:"rect",width:Math.max(12,.62*r),height:Math.max(8,e.projection.height-8)}})}(se,gt.layout,re,n):[],[n,gt.layout,re,se,Z]),ce=Fo(t.tooltip,h),de=Wo({...t,onClick:void 0},h,ae,{chartMode:U,className:J,title:tt??"Crucible",description:et??"A bounded inventory is transformed by an authored phase and event tape; physics explains the motion but does not determine the outcome.",summary:it??pa(It.state,n),accessibleTable:nt,enableHover:ot,margin:rt}),le=qo(Q?oa(Js,{layout:gt.layout,phases:gt.phases,state:It.state,compact:V.compactMode||360>lt[0]||260>lt[1]}):void 0,h.backgroundGraphics),ue=qo(Z?oa(ea,{rows:se,layout:gt.layout,projection:re,amountLabel:n}):void 0,h.foregroundGraphics),he=Is(t=>function(t,e){const i=t.data;if(!i?.__crucible)return null;const n="component"===i.kind?e.components[i.semanticId]:e.products[i.semanticId];if(!n)return null;const o="product"===i.kind;return Xs("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:[Hs("strong",{children:n.label}),Hs("div",{style:{opacity:.78,fontSize:11,letterSpacing:"0.06em",textTransform:"uppercase"},children:o?"Product · "+n.status:"Source · "+n.status}),Hs("div",{style:{marginTop:4},children:o?Ls(n):zs(n)})]})}(t,kt.current.state),[]),pe=bt?js(gt,It.state,Ft.current):gt.initialSpawns,me=function(t){return t?!0===t?{playPause:!0,reset:!0,stepPhase:!0,timeline:!0,speed:!0}:{playPause:t.playPause??!0,reset:t.reset??!0,stepPhase:t.stepPhase??!0,timeline:t.timeline??!0,speed:t.speed??!1}:{playPause:!1,reset:!1,stepPhase:!1,timeline:!1,speed:!1}}(c),fe=Object.values(me).some(Boolean),ye=gt.phases[It.state.phaseIndex],ge=To({data:d,emptyContent:l,loading:g,loadingContent:b,size:lt});if(ge)return ge;const be=gt.diagnostics.filter(t=>"error"===t.severity);return be.length?ra("div",{className:J,role:"alert",style:{maxWidth:"100%",width:lt[0]},children:[oa("strong",{children:"CrucibleChart could not compile this treatment tape."}),oa("ul",{children:be.map((t,e)=>oa("li",{children:t.message},`${t.code}-${e}`))})]}):Eo("CrucibleChart",lt,ra("div",{ref:st,className:"semiotic-crucible-chart",style:{maxWidth:"100%",overflow:"hidden",position:"relative",width:F?"100%":lt[0]},children:[fe?oa(ia,{controls:me,duration:gt.duration,elapsed:It.state.elapsed,phaseLabel:ye?.label??ye?.id??"Complete",playing:St&&!P,complete:It.state.complete,playbackRate:$t,disabled:bt,onPlayPause:St?Gt:Ut,onReset:Ht,onStepPhase:Kt,onPlaybackRateChange:jt}):null,sa(yn,{...h,...ce,...de,key:`${mt}:${Pt}:${Yt.rerunKey}:${bt?xt:"replay"}`,ref:L,accessibleTable:t.accessibleTable??h.accessibleTable,backgroundGraphics:le,bodyForces:Zt,bodySemanticItems:ie,bodyStyle:ee,beforePaint:oe,config:Yt.config,continuous:!bt&&St&&!P&&!It.state.complete,enableHover:ce.enableHover??ot,foregroundGraphics:ue,hoverRadius:t.hoverRadius??h.hoverRadius??18,initialSpawns:pe,initialSpawnPacing:f,onClick:I?ne:de.onClick,onTick:Qt,paused:Lt,renderBody:h.renderBody??Ys,responsiveHeight:q,responsiveWidth:!1,seed:da(W),size:lt,tooltipContent:ce.tooltipContent??he})]}))});function fa(t,e={}){const i=e.id??"physics-process-boundary",n={bodyFilter:e.bodyFilter,friction:e.friction,restitution:e.restitution};if("segment"===t.type)return[{...n,id:i,shape:t}];const o=e.thickness??8,r=t.x-t.width/2,s=t.x+t.width/2,a=t.y-t.height/2,c=t.y+t.height/2;return[{...n,id:i+"-top",shape:{type:"segment",x1:r,y1:a,x2:s,y2:a,thickness:o}},{...n,id:i+"-right",shape:{type:"segment",x1:s,y1:a,x2:s,y2:c,thickness:o}},{...n,id:i+"-bottom",shape:{type:"segment",x1:s,y1:c,x2:r,y2:c,thickness:o}},{...n,id:i+"-left",shape:{type:"segment",x1:r,y1:c,x2:r,y2:a,thickness:o}}]}function ya(t){if(!1===t.semanticItem)return null;const e=t.semanticItem??{},i=t.shape,n="aabb"===i.type?{id:t.id,label:t.label??t.id,description:t.description,group:t.kind??"region",x:i.x,y:i.y,width:i.width,height:i.height}:{id:t.id,label:t.label??t.id,description:t.description,group:t.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{...n,...e,id:e.id??n.id}}function ga(t){return t.map(t=>({id:t.id,label:t.label??t.id,description:t.description,group:t.kind??"stage",x:t.x??0,y:t.y??0,width:t.width,height:t.height}))}function ba(t){return t.flatMap(t=>{if(!1===t.semanticItem)return[];const e=t.semanticItem??{},i={id:t.id,label:t.label??t.id,description:t.description,datum:t.datum,group:t.group??t.state??"body group",x:t.x??0,y:t.y??0,width:t.width,height:t.height};return[{...i,...e,id:e.id??i.id}]})}function xa(t){return t?Array.isArray(t)?[...t]:Object.entries(t).flatMap(([t,e])=>Array.from({length:Math.max(0,Math.round(Number(e)||0))},()=>t)):[]}function va(t,e){return e?Array.isArray(e)?[...e]:e.ids?[...e.ids]:e.candidates?e.candidates.filter(e=>t.includes(e)).slice(0,e.count??1):[]:[]}function wa(t,e){return va(t.activePositiveIds,e.popPositive)}function Ia(t){const e=Number(t.budget),i=Number.isFinite(e)?Math.max(0,e):0,n=t.properties instanceof Map?t.properties:new Map(t.properties.map(t=>[t.id,t])),o=t.candidates?new Set(t.candidates):null,r=t.attachedIds.map((t,e)=>{const i=n.get(t),o=Number(i?.work??1),r=Number(i?.priority??e);return{id:t,index:e,priority:Number.isFinite(r)?r:e,work:Number.isFinite(o)&&o>0?o:1}}).filter(t=>!o||o.has(t.id)).sort((t,e)=>t.priority-e.priority||t.index-e.index),s=[],a=[];let c=0;for(const t of r)c+t.work>i+Number.EPSILON?a.push(t.id):(s.push(t.id),c+=t.work);return{ids:s,used:c,budget:i,remaining:Math.max(0,i-c),skippedIds:a}}function Ma(t,e){if(!e.from||!e.to||e.from===e.to)return{};const i=Math.max(0,Math.floor(Number(e.count??1)||0)),n=t.negativeIds.filter(t=>t===e.from).length,o=Math.min(i,n);return o?{addNegative:{[e.to]:o},popNegative:{ids:Array.from({length:o},()=>e.from)}}:{}}function ka(t,e){const i=va(t.negativeIds,e.popNegative);if(!i.length)return[];const n=new Map;for(const t of i)n.set(t,(n.get(t)??0)+1);const o=[];return t.negativeIds.forEach((t,e)=>{const i=n.get(t)??0;i>0&&(o.push({propertyId:t,index:e}),n.set(t,i-1))}),o}function Sa(t,e,i){if(e.when&&!e.when(i))return t;let n={...t};const o=wa(n,e);o.length&&(n={...n,activePositiveIds:n.activePositiveIds.filter(t=>!o.includes(t)),poppedPositiveIds:Array.from(new Set([...n.poppedPositiveIds,...o]))});const r=ka(n,e);if(r.length){const t=new Set(r.map(t=>t.index));n={...n,negativeIds:n.negativeIds.filter((e,i)=>!t.has(i)),poppedNegativeIds:[...n.poppedNegativeIds,...r.map(t=>t.propertyId)]}}const s=xa(e.addPositive);s.length&&(n={...n,activePositiveIds:Array.from(new Set([...n.activePositiveIds,...s])),missingPositiveIds:n.missingPositiveIds.filter(t=>!s.includes(t))});const a=xa(e.addNegative);if(a.length&&(n={...n,negativeIds:[...n.negativeIds,...a]}),e.delayDelta&&(n={...n,delay:n.delay+e.delayDelta}),e.metricsDelta){const t={...n.metrics};for(const[i,n]of Object.entries(e.metricsDelta))t[i]=Number(t[i]??0)+n;n={...n,metrics:t}}return e.viabilityDelta&&(n={...n,viability:n.viability+e.viabilityDelta}),e.stage&&(n={...n,stage:e.stage}),e.outcome&&(n={...n,outcome:e.outcome}),n}function Aa(t,e){return{id:t.id,label:t.label??t.id,summary:t.summary??e.find(t=>t.summary)?.summary,time:t.time}}function Ra(t,e){return t.eventsApplied.includes(e.id)?t:{...t,eventsApplied:[...t.eventsApplied,e.id],eventHistory:[...t.eventHistory??[],e],lastEvent:e,stage:e.label??t.stage}}ma.displayName="CrucibleChart";import{forwardRef as Pa,useCallback as Ca,useEffect as $a,useImperativeHandle as ja,useMemo as Ba,useRef as Oa,useState as Na}from"react";var Ta="gauntlet-core",Ea="gauntlet-positive",qa="gauntlet-negative";function Fa(t){const e=Ha(t);return[{id:"gauntlet-left",restitution:.12,friction:.42,shape:{type:"segment",x1:e.left,y1:e.top,x2:e.left,y2:t.floorY,thickness:e.thickness}},{id:"gauntlet-ceiling",restitution:.12,friction:.42,shape:{type:"segment",x1:e.left,y1:e.top,x2:t.width-e.rightInset,y2:e.top,thickness:e.thickness}},{id:"gauntlet-floor",restitution:.12,friction:.42,shape:{type:"segment",x1:e.left,y1:t.floorY,x2:t.width-e.rightInset,y2:t.floorY,thickness:e.thickness}},{id:"gauntlet-right",restitution:.12,friction:.42,shape:{type:"segment",x1:t.width-e.rightInset,y1:e.top,x2:t.width-e.rightInset,y2:t.floorY,thickness:e.thickness}}]}function Wa(t,e,i,n){return i?"function"==typeof i?i(t,e):t[i]??n:n}function Da(t){return t?.label??t?.id??"property"}function za(t){return`gauntlet:${t}:core`}function La(t,e){return`gauntlet:${t}:positive:${e}`}function Ya(t,e,i){return`gauntlet:${t}:negative:${e}:${i}`}var _a={left:28,top:76,rightInset:30,thickness:8};function Ha(t){const e=t.height??t.floorY+36;if(t.width>=220&&e>=160)return _a;const i=Math.max(1,Math.min(t.width,e)),n=Math.max(2,.04*t.width);return{left:n,top:Math.max(2,.08*e),rightInset:n,thickness:Math.max(1,Math.min(4,.04*i))}}function Xa(t){return Math.max(.12,Math.min(1,t.width/500,(t.height??t.floorY+36)/260))}function Ga(t,e,i,n){const o=Ha(n),r=Math.max(2,i+2),s=o.top+o.thickness/2+r,a=n.floorY-r,c=(t,e,i)=>e>i?(e+i)/2:Math.max(e,Math.min(i,t));return{x:c(t,o.left+o.thickness/2+r,n.width-o.rightInset-o.thickness/2-r),y:c(e,s,a)}}function Va(t){return{graveyardX:t.graveyardX,graveyardY:t.graveyardY,routeY:t.routeY,socketX:t.socketX,socketY:t.routeY-4,startX:t.startX,startY:t.routeY}}function Ua(t,e,i,n){const o=Va(i),r=n?.(t,e,i)??{};return{...o,...r,startY:r.startY??r.routeY??o.startY,socketY:r.socketY??r.routeY??o.socketY,graveyardY:r.graveyardY??o.graveyardY}}function Ka(t,e,i=1){const n=[...t].sort((t,e)=>t.localeCompare(e)),o=Math.max(0,n.indexOf(e));return{angle:.82*-Math.PI+(n.length>1?o/(n.length-1):.5)*Math.PI*.64,index:o,radius:(48+o%2*6)*i}}function Qa(t,e,i){const n=t.activePositiveIds.reduce((t,i)=>t+(e.get(i)?.value??1),0),o=t.missingPositiveIds.length+t.poppedPositiveIds.length,r=t.negativeIds.reduce((t,e)=>t+(i.get(e)?.load??1),0);return Math.max(0,Math.min(100,75+3*n-8*r-1.2*t.delay-5*o))}function Za(t,e,i,n,o){const r=Wa(t,e,i.idAccessor,null!=t.id?t.id+"":"project-"+e)+"",s=n.map(t=>t.id),a=[...Wa(t,e,i.positiveAccessor,s)],c=[...Wa(t,e,i.negativeAccessor,[])].filter(t=>o.has(t));return{id:r,activePositiveIds:a,datum:t,delay:0,eventsApplied:[],eventHistory:[],killed:!1,metrics:{...Wa(t,e,i.metricsAccessor,{})},missingPositiveIds:s.filter(t=>!a.includes(t)),negativeIds:c,outcome:"in_process",poppedPositiveIds:[],poppedNegativeIds:[],startedAt:Math.max(0,Number(Wa(t,e,i.startTimeAccessor,0))||0),stage:"project filed",viability:Wa(t,e,i.initialViability,100)}}function Ja(t,e,i,n,o,r,s){const a=Xa(i),c=Math.max(3,28*a),d=n.startX,l=n.startY+(n.startY===i.routeY?38*e*a:0),u=s?.(t,e,i,n)??{},h=u.x??d,p=u.y??l,m={__gauntlet:!0,kind:Ta,projectId:t.id,sourceDatum:t.datum},f=[{...u,id:za(t.id),x:h,y:p,vx:u.vx??42,vy:u.vy??0,mass:u.mass??7,bodyCollisions:u.bodyCollisions??!0,shape:u.shape??{type:"circle",radius:c},spawnAt:u.spawnAt??t.startedAt,datum:m}],y=Ga(h,p,u.shape&&"radius"in u.shape&&Number(u.shape.radius)||c,i);f[0].x=y.x,f[0].y=y.y;for(const e of t.activePositiveIds){const n=o.get(e);if(!n)continue;const r=Ka(t.activePositiveIds,e,a),s=n.radius??Math.max(2,10*a),c=Ga(y.x+Math.cos(r.angle)*r.radius,y.y+Math.sin(r.angle)*r.radius,s,i);f.push({id:La(t.id,e),x:c.x,y:c.y,vx:18*Math.cos(r.angle),vy:18*Math.sin(r.angle),mass:n.mass??.75,bodyCollisions:!1,shape:{type:"circle",radius:s},spawnAt:u.spawnAt??t.startedAt,datum:{__gauntlet:!0,kind:Ea,projectId:t.id,property:n,sourceDatum:t.datum},springs:!1===n.spring?[]:[{target:{type:"body",bodyId:za(t.id)},stiffness:.56,damping:.9,restLength:Math.max(6,(52+r.index%2*4)*a),...n.spring??{}}]})}return t.negativeIds.forEach((e,n)=>{const o=r.get(e);o&&f.push(tc(t,o,n,y.x,y.y,i,u.spawnAt??t.startedAt))}),f}function tc(t,e,i,n,o,r,s){const a=Xa(r),c=e.radius??Math.max(2,7.2*a),d=Ga(n+(i%4*12-12)*a,o+(54+12*Math.floor(i/4))*a,c,r);return{id:Ya(t.id,e.id,i),x:d.x,y:d.y,vx:10,vy:6,mass:e.mass??.72,bodyCollisions:!1,shape:{type:"circle",radius:c},spawnAt:s,datum:{__gauntlet:!0,kind:qa,projectId:t.id,property:e,sourceDatum:t.datum},springs:!1===e.spring?[]:[{target:{type:"body",bodyId:za(t.id)},stiffness:.62,damping:.92,restLength:Math.max(6,(52+i%4*3)*a),...e.spring??{}}]}}function ec(t,e){const i=t.datum;return!(!i?.__gauntlet||i.projectId!==e||i.kind!==qa)}function ic(t){const e=t.id.slice(t.id.lastIndexOf(":")+1),i=Number(e);return Number.isFinite(i)?i:-1}function nc(t,e){return 2>Math.hypot(t.vx,t.vy)&&4>Math.hypot(e.x,e.y)?null:e}import{Fragment as oc,jsx as rc,jsxs as sc}from"react/jsx-runtime";function ac(t){const e=t.data;return e?.__gauntlet?sc("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:[rc("strong",{children:e.kind===Ta?"string"==typeof e.sourceDatum?.label?e.sourceDatum.label:e.projectId:Da(e.property)}),rc("div",{children:e.kind===Ea?"Positive property":e.kind===qa?"Negative property":"Project core"})]}):null}function cc(t,e,i){const n=e.datum;if(!n?.__gauntlet)return;const o="circle"===e.shape.type?e.shape.radius:8;if(t.save(),t.translate(e.x,e.y),n.kind===Ta)t.fillStyle=dc(t,i.fill,"#0f766e"),t.strokeStyle=dc(t,i.stroke,"#f8fafc"),t.lineWidth=2.4,t.beginPath(),t.arc(0,0,o,0,2*Math.PI),t.fill(),t.stroke();else{const e=n.property;t.fillStyle=dc(t,i.fill??e?.color,"#38bdf8"),t.strokeStyle=dc(t,i.stroke,"#0f172a"),t.lineWidth=1.1,t.beginPath(),n.kind===qa?t.rect(-o,-o,2*o,2*o):t.arc(0,0,o,0,2*Math.PI),t.fill(),t.stroke(),t.fillStyle=dc(t,"var(--semiotic-background, #07111f)","#07111f"),t.font=`900 ${n.kind===qa?9:8}px system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,t.textAlign="center",t.textBaseline="middle",t.fillText(e?.short??e?.id?.slice(0,1).toUpperCase()??"?",0,.5)}t.restore()}function dc(t,e,i){if("string"!=typeof e)return i;if("function"!=typeof getComputedStyle||!t.canvas)return e||i;const n=e.startsWith("var(")?e.match(/var\((--[^,\s)]+)/)?.[1]:e.startsWith("--")?e:null;return n?getComputedStyle(t.canvas).getPropertyValue(n).trim()||i:e||i}function lc({layout:t,compact:e,showLabels:i}){const n=e?Math.round(.14*t.height):Math.max(80,t.routeY-180),o=e?Math.max(6,Math.round(.72*t.height)):Math.min(360,t.height-170);return rc(oc,{children:t.gates.map(r=>sc("g",{children:[rc("rect",{x:r.x-r.width/2,y:n,width:r.width,height:o,rx:e?2:12,fill:r.color??"var(--semiotic-accent, #38bdf8)",fillOpacity:.1,stroke:r.color??"var(--semiotic-accent, #38bdf8)",strokeDasharray:"5 5",strokeOpacity:.7}),i?rc("text",{x:r.x,y:Math.max(64,t.routeY-196),fill:"var(--semiotic-text-secondary, #64748b)",fontSize:10,fontWeight:800,textAnchor:"middle",children:r.label??r.id}):null]},r.id))})}function uc({layout:t,states:e,compact:i=!1}){return i?rc("svg",{"aria-hidden":"true",viewBox:`0 0 ${t.width} ${t.height}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:rc(lc,{layout:t,compact:!0,showLabels:!1})}):sc("svg",{"aria-hidden":"true",viewBox:`0 0 ${t.width} ${t.height}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[rc("path",{d:`M ${t.startX-42} ${t.routeY} C ${.24*t.width} ${t.routeY-70}, ${.42*t.width} ${t.routeY+78}, ${.58*t.width} ${t.routeY} S ${.78*t.width} ${t.routeY-82}, ${t.socketX+36} ${t.routeY}`,fill:"none",stroke:"var(--semiotic-accent, #38bdf8)",strokeDasharray:"18 12",strokeLinecap:"round",strokeOpacity:.45,strokeWidth:7}),rc("line",{x1:Math.round(.06*t.width),x2:Math.round(.94*t.width),y1:t.crashY,y2:t.crashY,stroke:"var(--semiotic-negative, #ef4444)",strokeDasharray:"3 7",strokeOpacity:.64}),rc("text",{x:Math.round(.07*t.width),y:t.crashY-8,fill:"var(--semiotic-negative, #ef4444)",fontSize:9,fontWeight:800,children:"CRASH LINE"}),rc(lc,{layout:t,compact:!1,showLabels:!0}),sc("g",{children:[rc("rect",{x:t.socketX-52,y:t.routeY-56,width:104,height:112,rx:13,fill:"var(--semiotic-positive, #22c55e)",fillOpacity:.12,stroke:"var(--semiotic-positive, #22c55e)",strokeWidth:1.5}),rc("text",{x:t.socketX,y:t.routeY-72,fill:"var(--semiotic-text-secondary, #64748b)",fontSize:10,fontWeight:800,textAnchor:"middle",children:"SOCKET"})]}),sc("g",{children:[rc("rect",{x:t.graveyardX-82,y:t.graveyardY-34,width:164,height:58,rx:11,fill:"var(--semiotic-negative, #ef4444)",fillOpacity:.16,stroke:"var(--semiotic-negative, #ef4444)",strokeOpacity:.7}),rc("text",{x:t.graveyardX,y:t.graveyardY-8,fill:"var(--semiotic-negative, #ef4444)",fontSize:10,fontWeight:800,textAnchor:"middle",children:"GRAVEYARD"}),rc("text",{x:t.graveyardX,y:t.graveyardY+12,fill:"var(--semiotic-text-secondary, #64748b)",fontSize:9,fontWeight:700,textAnchor:"middle",children:e.some(t=>t.killed)?"lift shut off":"too heavy or too small"})]})]})}function hc(t){const e=t.datum;return!!e?.__gauntlet&&(e.kind===Ta?{label:e.projectId+" project core",group:"project",description:"Project core carrying positive and negative properties."}:{label:`${Da(e.property)} ${e.kind===Ea?"positive":"negative"} property`,group:e.kind===Ea?"positive property":"negative property",description:`${Da(e.property)} attached to ${e.projectId}.`})}function pc({states:t,layout:e}){const i=function(t){return t.map(t=>({label:t.id,value:Math.max(0,Number(t.viability)||0),outcome:t.outcome||t.stage||"in-process"}))}(t);if(!i.length)return null;const n=Math.max(1,...i.map(t=>t.value)),o=Math.max(40,(e.width-80)/i.length);return sc("svg",{"aria-hidden":"true","data-testid":"gauntlet-projection-overlay",width:e.width,height:e.height,viewBox:`0 0 ${e.width} ${e.height}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[rc("text",{x:36,y:18,fill:"var(--semiotic-text-secondary, #64748b)",fontSize:9,fontWeight:800,children:"SETTLED · viability / outcome"}),i.map((t,e)=>{const i=40+e*o,r=Math.max(2,t.value/n*28),s=/kill|crash|block|grave/i.test(t.outcome);return sc("g",{children:[rc("rect",{x:i+.18*o,y:28-r+22,width:Math.max(10,.45*o),height:r,rx:2,fill:s?"var(--semiotic-danger, #ef4444)":"var(--semiotic-success, #16a34a)",fillOpacity:.35,stroke:s?"var(--semiotic-danger, #ef4444)":"var(--semiotic-success, #16a34a)",strokeOpacity:.55,strokeWidth:1}),rc("text",{x:i+.4*o,y:62,textAnchor:"middle",fill:"var(--semiotic-text-secondary, #64748b)",fontSize:9,fontWeight:700,children:t.label})]},t.label)})]})}import{jsx as mc}from"react/jsx-runtime";import{createElement as fc}from"react";var yc=[],gc=Pa(function(t,e){const{bodyGroups:i,coreBody:n,coreForceMode:o="route",crashDetection:r=!0,crashOffset:s=30,data:a,emptyContent:c,events:d,frameProps:l={},gates:u,initialSpawnPacing:h,loading:p,loadingContent:m,negativeProperties:f,onCapacityChange:y,onClick:g,onStateChange:b,outcome:v,paused:w,positiveProperties:I=yc,projectPlacement:M,rerunMS:k,responsiveHeight:S,responsiveWidth:A,showTethers:R=!0,terminalBehavior:P="outcome",viability:C}=t,$=Oa(null),j=Ba(()=>({idAccessor:t.idAccessor,initialViability:t.initialViability,metricsAccessor:t.metricsAccessor,negativeAccessor:t.negativeAccessor,positiveAccessor:t.positiveAccessor,startTimeAccessor:t.startTimeAccessor}),[t.idAccessor,t.initialViability,t.metricsAccessor,t.negativeAccessor,t.positiveAccessor,t.startTimeAccessor]),B=No(t,[900,520]),{chartSize:O,showProjection:N,showChrome:T,className:E,title:q,chartMode:F,margin:W,enableHover:D,description:z,summary:L,accessibleTable:Y}=B,_=To({data:a,emptyContent:c,loading:p,loadingContent:m,size:O}),H=Ba(()=>x(a??[]),[a]),X=Ba(()=>H.map((t,e)=>Wa(t,e,j.idAccessor,null!=t.id?t.id+"":"project-"+e)+"").join("|"),[H,j.idAccessor]),G=Ba(()=>new Map(I.map(t=>[t.id,t])),[I]),V=Ba(()=>new Map(f.map(t=>[t.id,t])),[f]),U=Ba(()=>function(t,e,i){const[n,o]=t,r=220>n||160>o,s=Math.round(.48*o),a=r?o-Math.max(3,Math.min(12,.1*o)):o-36,c=(e??[]).filter(t=>!1!==t.enabled),d=Math.max(1,c.length),l=.22*n,u=d>1?(.78*n-l)/(d-1):0,h=r?Math.max(Math.round(.12*n),.08*n+6):Math.max(Math.round(.14*n),110);return{crashY:a-(r?Math.min(i,Math.max(3,.22*o)):i),floorY:a,gates:c.map((t,e)=>({...t,id:t.id,x:t.x??Math.round(l+e*u),width:t.width??Math.max(r?8:54,Math.round(.07*n))})),graveyardX:Math.round(n*(r?.72:.84)),graveyardY:a-4,height:o,routeY:s,socketX:Math.round(n*(r?.82:.92)),startX:h,width:n}}(O,u,s),[O,s,u]),K=Ba(()=>new Map(U.gates.map(t=>[t.id,t])),[U.gates]),Q=Ba(()=>U.gates.map(t=>({kind:"force-field",damping:.035,force:{x:12,y:0},semanticItem:!1,...t.regionEffect,id:"gauntlet-gate-"+t.id,label:t.label??t.id,description:t.description,bodyFilter:t.capacity?{property:"datum.kind",equals:Ta}:t.regionEffect?.bodyFilter,shape:{type:"aabb",x:t.x,y:U.routeY,width:t.capacity?t.capacity.sensorWidth??Math.max(220>U.width?12:96,t.width*(220>U.width?2:6)):Math.max(t.width,220>U.width?10:54),height:Math.max(4,Math.min(360,U.height-(160>U.height?8:170)))}})),[U.gates,U.height,U.routeY,U.width]),[Z,J]=Na(()=>H.map((t,e)=>{const i=Za(t,e,j,I,V);return{...i,viability:C?.(i,{negativeProperties:V,positiveProperties:G})??Qa(i,G,V)}})),tt=Oa(Z),et=Oa(0),it=Oa(new Map),nt=Oa([]),ot=Oa(y);ot.current=y;const rt=Oa(H);rt.current=H;const st=Oa(b);st.current=b;const at=Oa({negativeById:V,positiveById:G,positiveProperties:I,stateAccessors:j,viability:C});at.current={negativeById:V,positiveById:G,positiveProperties:I,stateAccessors:j,viability:C};const ct=Ca((t,e,i=0)=>{const n=at.current,o=Za(t,e,n.stateAccessors,n.positiveProperties,n.negativeById);return n.stateAccessors.startTimeAccessor||(o.startedAt=Math.max(0,i)),{...o,viability:n.viability?.(o,{negativeProperties:n.negativeById,positiveProperties:n.positiveById})??Qa(o,n.positiveById,n.negativeById)}},[]),dt=Ca(()=>{it.current.clear(),nt.current=[],et.current=0;const t=rt.current.map((t,e)=>ct(t,e));tt.current=t,J(t)},[ct]),lt=Oo(Ba(()=>({fixedDt:1/60,maxSubsteps:8,kernel:{gravity:{x:0,y:0},restitution:.16,friction:.44,velocityDamping:.982,maxVelocity:520,sleepAfter:.8,sleepSpeed:7,...l.config?.kernel??{}},colliders:[...Fa(U),...l.config?.colliders??[]]}),[l.config?.colliders,l.config?.kernel,U]),k,w,dt),ut=Ba(()=>function(t){const{dataKey:e,gates:i,statesRef:n,processedGateVisitsRef:o}=t;return i.flatMap(t=>t.capacity&&t.capacity.unitsPerSecond>0?[Ie({id:`gauntlet-capacity-${e}-${t.id}`,regionId:"gauntlet-gate-"+t.id,unitsPerSecond:t.capacity.unitsPerSecond,bodyFilter:{property:"datum.kind",equals:Ta},maxQueue:t.capacity.maxQueue,queueLayout:t.capacity.queueLayout,queueSlotSpacing:t.capacity.queueSlotSpacing,queueStiffness:t.capacity.queueStiffness??24,releaseImpulse:{x:36,y:0},unitAccessor:e=>{const i=e.datum,o=i?.sourceDatum,r=t.capacity?.unitAccessor,s=n.current.find(t=>t.id===i?.projectId);let a;"function"==typeof r?a=s?r(s):void 0:r&&(a=o?.[r]);const c=Number(a??o?.reviewWork??o?.work??s?.metrics.reviewWork??o?.points);return Number.isFinite(c)&&c>0?c:1},onProcessed:e=>{const i=e.datum;if(!i?.projectId)return;const n=`${i.projectId}:${t.id}`;o.current.set(n,(o.current.get(n)??0)+1)}})]:[])}({dataKey:`${X}:${lt.rerunKey}`,gates:U.gates,statesRef:tt,processedGateVisitsRef:it}),[X,U.gates,lt.rerunKey]),ht=Ba(()=>[...ut,...l.controllers??[]],[ut,l.controllers]);$a(()=>{it.current.clear(),nt.current=[],et.current=0;const t=rt.current.map((t,e)=>ct(t,e));tt.current=t,J(t)},[ct,X]),$a(()=>{tt.current=Z,st.current?.(Z)},[Z]);const pt=Ca(t=>[...("function"==typeof d?d(t,U):d)??[]].sort((t,e)=>t.time-e.time),[d,U]),mt=Ca((t,e,i)=>{if(!e.gateId||!K.get(e.gateId)?.capacity)return!0;const n=Number(e.gateVisit),o=Number.isFinite(n)&&n>0?Math.floor(n):i.filter(t=>t.gateId===e.gateId).findIndex(t=>t.id===e.id)+1;return o>0&&(it.current.get(`${t.id}:${e.gateId}`)??0)>=o},[K]),ft=Ca(()=>{if(!ut.length)return;const t=ut.flatMap(t=>{const e=t.getSnapshot?.();return e?[e]:[]});var e,i;(e=nt.current).length===(i=t).length&&e.every((t,e)=>{const n=i[e];return!!n&&t.regionId===n.regionId&&t.queueDepth===n.queueDepth&&t.blockedDepth===n.blockedDepth&&t.processedCount===n.processedCount&&t.metricRevision===n.metricRevision})||(nt.current=t,ot.current?.(t))},[ut]),yt=Ba(()=>Z.flatMap((t,e)=>{const i=Ua(t,e,U,M);return Ja(t,e,U,i,G,V,n)}),[n,U,V,G,M,Z]),gt=Ca((t,e)=>{let i=!1;const n=tt.current.map(n=>{if(n.id!==t)return n;const o=e(n);return i=i||o!==n,o});i&&(tt.current=n,J(n))},[]);ja(e,()=>function(t){const{statesRef:e,setStates:i,elapsedRef:n,frameRef:o,layout:r,projectPlacement:s,positiveById:a,negativeById:c,coreBody:d,createState:l}=t;return{push:t=>{const u=l(t,e.current.length,n.current),h=Ua(u,e.current.length,r,s),p=Ja(u,e.current.length,r,h,a,c,d),m=[...e.current,u];e.current=m,i(m),o.current?.pushMany(p),o.current?.step(0)},pushMany:t=>{const u=[...e.current],h=[],p=n.current;t.forEach(t=>{const e=l(t,u.length,p),i=Ua(e,u.length,r,s);h.push(...Ja(e,u.length,r,i,a,c,d)),u.push(e)}),e.current=u,i(u),h.length&&o.current?.pushMany(h),o.current?.step(0)},remove:t=>{const n=Array.isArray(t)?t:[t],r=[],s=[];for(const t of n){const i=e.current.find(e=>e.id===t);i&&(r.push(i.datum),s.push(za(i.id),...i.activePositiveIds.map(t=>La(i.id,t))),i.negativeIds.forEach((t,e)=>{s.push(Ya(i.id,t,e))}))}return e.current=e.current.filter(t=>!n.includes(t.id)),i(e.current),o.current?.remove(s),r},update:(t,u)=>{const h=Array.isArray(t)?t:[t],p=[];for(const t of h){const i=e.current.find(e=>e.id===t);if(!i)continue;const h=e.current.findIndex(e=>e.id===t);p.push(i.datum);const m=u(i.datum),f=l(m,0>h?e.current.length:h,i.startedAt??n.current),y=Ua(f,0>h?e.current.length:h,r,s);o.current?.remove([za(i.id),...i.activePositiveIds.map(t=>La(i.id,t)),...i.negativeIds.map((t,e)=>Ya(i.id,t,e))]),o.current?.pushMany(Ja(f,0>h?e.current.length:h,r,y,a,c,d)),e.current=e.current.map(e=>e.id===t?f:e)}return i(e.current),p},clear:()=>{e.current=[],i([]),o.current?.clear()},getData:()=>e.current.map(t=>t.datum),getScales:()=>null,getCustomLayout:()=>o.current?.snapshot()??null,popBodies:(t,e)=>o.current?.popBodies(t,e)??[]}}({statesRef:tt,setStates:J,elapsedRef:et,frameRef:$,layout:U,projectPlacement:M,positiveById:G,negativeById:V,coreBody:n,createState:ct}),[n,ct,U,V,G,M]);const bt="sparkline"===F?.22:"mobile"===F?.55:1,xt=Ca((t,e,i)=>{!function(t){const{project:e,effect:i,controls:n,layout:o,positiveById:r,negativeById:s,coreBody:a,popBodies:c,popScale:d}=t,l=n.readBodies().find(t=>t.id===za(e.id)),u=n.readBodies(),h=l?.x??o.startX,p=l?.y??o.routeY,m=function(t,e){let i=-1;for(const n of e)ec(n,t.id)&&(i=Math.max(i,ic(n)));return Math.max(t.negativeIds.length,i+1)}(e,u),f=xa(i.addNegative).flatMap((t,i)=>{const n=s.get(t);return n?[tc(e,n,m+i,h,p,o)]:[]}),y=xa(i.addPositive).flatMap(t=>{if(!r.get(t)||e.activePositiveIds.includes(t))return[];const i={...Va(o),routeY:p,socketY:p,startX:h,startY:p};return Ja({...e,activePositiveIds:[t],negativeIds:[]},0,o,i,r,s,a).filter(t=>t.id.includes(":positive:"))});(f.length||y.length)&&n.pushMany([...f,...y]);const g=wa(e,i);for(const t of g){const i=r.get(t);c([La(e.id,t)],{color:i?.popColor??i?.color,durationMs:900,radius:(i?.radius??10)+3,scale:d})}const b=ka(e,i),x=function(t,e,i){const n=e.filter(e=>ec(e,t.id)).sort((t,e)=>ic(t)-ic(e)||t.id.localeCompare(e.id)),o=new Set;return i.map(e=>{const i=n.find(t=>!o.has(t.id)&&t.datum.property?.id===e.propertyId);return i?(o.add(i.id),i.id):Ya(t.id,e.propertyId,e.index)})}(e,u,b);b.forEach((t,e)=>{const i=s.get(t.propertyId);c([x[e]],{color:i?.popColor??i?.color,durationMs:900,radius:(i?.radius??7)+3,scale:d})})}({project:t,effect:e,controls:i,layout:U,positiveById:G,negativeById:V,coreBody:n,popBodies:(t,e)=>$.current?.popBodies(t,e),popScale:bt})},[n,U,V,G,bt]),vt=Ca(({body:t,bodies:e})=>function(t){const{body:e,bodies:i,layout:n,states:o,projectPlacement:r,positiveById:s,negativeById:a,projectEvents:c,gateById:d,coreForceMode:l,terminalBehavior:u,elapsed:h}=t,p=e.datum;if(!p?.__gauntlet)return null;const m=o.findIndex(t=>t.id===p.projectId),f=0>m?void 0:o[m];if(!f)return null;const y=Ua(f,m,n,r),g=i.find(t=>t.id===za(f.id)),b=Xa(n),x=f.negativeIds.reduce((t,e)=>t+(a.get(e)?.load??1),0),v=f.killed?0:58*Math.max(.25,b);if(p.kind!==Ta){if(!g)return null;let t;const o=p.property;if(o?.target){const r=i.filter(t=>{const e=t.datum;return e?.__gauntlet&&e.projectId===f.id&&e.kind===p.kind}).sort((t,e)=>(t.id+"").localeCompare(e.id+"")),s=Math.max(0,r.findIndex(t=>t.id===e.id));t=o.target({body:e,bodies:i,core:g,index:s,layout:n,placement:y,project:f})??{x:g.x,y:g.y}}else if(p.kind===Ea&&p.property){const e=Ka(f.activePositiveIds,p.property.id,b);t={x:g.x+Math.cos(e.angle)*e.radius,y:g.y+Math.sin(e.angle)*e.radius-2}}else{const n=i.filter(t=>t.datum?.kind===qa&&t.datum.projectId===f.id).sort((t,e)=>(t.id+"").localeCompare(e.id+"")),o=Math.max(0,n.findIndex(t=>t.id===e.id)),r=Math.floor(o/4);t={x:g.x+18*(o%4-(Math.min(4,n.length-4*r)-1)/2)*b,y:g.y+(54+13*r)*b}}const r="circle"===e.shape.type?e.shape.radius:8;t=Ga(t.x,t.y,r,n);const s=Ga(e.x,e.y,r,n);if(Math.abs(s.x-e.x)>.5||Math.abs(s.y-e.y)>.5)return{x:48*(s.x-e.x)-6*e.vx,y:48*(s.y-e.y)-6*e.vy};const a=p.kind!==Ea||f.killed?0:3.2*(o?.buoyancy??o?.value??1),c=p.kind===qa?{x:.22*(o?.pull?.x??-8),y:.22*(o?.pull?.y??22)}:{x:0,y:0};return nc(e,{x:28*(t.x-e.x)-3*(e.vx-g.vx)+c.x+.01*v,y:28*(t.y-e.y)-3*(e.vy-g.vy)+c.y-a})}if(f.killed)return nc(e,{x:44*((f.crashX??f.metrics.lastX??e.x)-e.x)-9*e.vx,y:(160+12*x)*b-1.6*e.vy});const w=c(f),I=function(t,e,i,n,o,r,s){const a=Xa(i);if(e.killed)return{x:e.metrics.lastX??n.graveyardX,y:n.graveyardY};const c=o[o.length-1];if(!c)return{x:n.socketX,y:n.routeY};const d=o.find(i=>t>=i.time&&!e.eventsApplied.includes(i.id)&&!(!i.gateId||!r.get(i.gateId)?.capacity)),l=d?Math.min(t,d.time):t,u="built"===e.outcome||"built_diminished"===e.outcome;if(l>c.time+.85){if("hold-last"===s){const t=c.gateId?r.get(c.gateId):void 0;return{x:c.routeX??t?.x??n.socketX,y:c.routeY??n.routeY}}return u?{x:n.socketX,y:n.socketY}:{x:n.graveyardX,y:n.graveyardY-14}}const h=.85*e.delay+12*e.negativeIds.length+8*(e.poppedPositiveIds.length+e.missingPositiveIds.length),p=[{time:0,x:n.startX,y:n.startY},...o.map(t=>{const e=t.gateId?r.get(t.gateId):void 0;return{time:t.time,x:t.routeX??e?.x??n.startX,y:t.routeY??n.routeY+.28*Math.min(180,h)*a}})].sort((t,e)=>t.time-e.time);let m=p[0],f=p[p.length-1];for(let t=1;p.length>t;t+=1){if(p[t].time>=l){f=p[t];break}m=p[t]}const y=Math.max(0,Math.min(1,(l-m.time)/Math.max(.1,f.time-m.time))),g=y*y*(3-2*y);return{x:m.x+(f.x-m.x)*g,y:m.y+(f.y-m.y)*g+7*Math.sin(2.6*l)*a}}(Math.max(0,h-(f.startedAt??0)),f,n,y,w,d,u),M=f.activePositiveIds.reduce((t,e)=>t+(s.get(e)?.buoyancy??s.get(e)?.value??1),0);return nc(e,"net"===l?{x:15*(I.x-e.x)-1.8*e.vx+.18*v,y:1.25*(y.routeY-e.y)-1.4*e.vy+32*(x-M)}:{x:15*(I.x-e.x)-1.8*e.vx+.18*v,y:15*(I.y-e.y)-1.8*e.vy+13*x-2.2*M})}({body:t,bodies:e,layout:U,states:tt.current,projectPlacement:M,positiveById:G,negativeById:V,projectEvents:pt,gateById:K,coreForceMode:o,terminalBehavior:P,elapsed:et.current}),[o,K,U,V,G,pt,M,P]),wt=Ca((t,e)=>{!function(t,e,i){const{frameProps:n,elapsedRef:o,statesRef:r,crashDetection:s,layout:a,projectEvents:c,gateById:d,capacityEventReady:l,addBodiesForEffect:u,updateProjectState:h,viability:p,positiveById:m,negativeById:f,outcome:y,reportCapacity:g}=i;n.onTick?.(t,e),o.current=t.elapsedSeconds??e.snapshot().elapsedSeconds,g();for(const t of r.current){const i=e.readBodies().find(e=>e.id===za(t.id));if(!i)continue;if(s&&!t.killed&&i.y+("circle"===i.shape.type?i.shape.radius:28)>=a.crashY){e.readBodies().forEach(i=>{const n=i.datum;n?.__gauntlet&&n.projectId===t.id&&e.applyImpulse(i.id,-i.vx*i.mass,0)}),h(t.id,t=>{const e={appliedAt:Math.max(0,o.current-(t.startedAt??0)),id:"gauntlet-crash-line",label:"Crash Line",summary:"The project hit the crash threshold; lift and forward motion shut off.",time:Math.max(0,o.current-(t.startedAt??0))};return{...t,crashX:i.x,eventHistory:[...t.eventHistory??[],e],killed:!0,lastEvent:e,metrics:{...t.metrics,lastX:i.x},outcome:"bad_design_crash",stage:"Crash Line",viability:Math.min(0,t.viability)}});continue}if(t.killed)continue;const n=Math.max(0,o.current-(t.startedAt??0)),r=c(t),g=r.filter(e=>n>=e.time&&!t.eventsApplied.includes(e.id)&&l(t,e,r));let b=t;for(const i of g){const o=i.gateId?d.get(i.gateId):void 0,r=i.effects??[];for(const t of r){const n={event:i,gate:o,negativeProperties:f,positiveProperties:m,project:b};t.when&&!t.when(n)||(u(b,t,e),b=Sa(b,t,n))}const s={...Aa(i,r),appliedAt:n};b=Ra(b,s),h(t.id,t=>{let e=Ra(t,s);if(e===t)return t;for(const t of r)e=Sa(e,t,{event:i,gate:o,negativeProperties:f,positiveProperties:m,project:e});const n=p?.(e,{negativeProperties:f,positiveProperties:m})??Qa(e,m,f);return e={...e,viability:n},i.final&&(e={...e,outcome:i.outcome??y?.(e,{layout:a,negativeProperties:f,positiveProperties:m})??(e.viability>20?"built":"approved_not_built")}),e})}}}(t,e,{frameProps:l,elapsedRef:et,statesRef:tt,crashDetection:r,layout:U,projectEvents:pt,gateById:K,capacityEventReady:mt,addBodiesForEffect:xt,updateProjectState:gt,viability:C,positiveById:G,negativeById:V,outcome:v,reportCapacity:ft})},[xt,mt,r,l,K,U,V,v,G,pt,ft,gt,C]),It=Ca((t,e)=>{const i="function"==typeof l.bodyStyle?l.bodyStyle(t,e):l.bodyStyle,n=t.datum;return n?.__gauntlet?{fill:n.kind===Ta?"var(--semiotic-accent, #0f766e)":n.property?.color??"var(--semiotic-accent, #38bdf8)",stroke:n.kind===Ta?"#f8fafc":"#0f172a",opacity:.96,...i}:i??{}},[l]),Mt=Ba(()=>"function"==typeof i?i(Z,U):i??[],[i,U,Z]),kt=Ba(()=>ba(Mt),[Mt]),St=Ba(()=>N?function(t,e){if(!t.length)return[];const i=Math.max(40,(e.width-80)/t.length);return t.map((t,e)=>{const n=`${t.id}: viability ${Math.round(t.viability)}, ${t.outcome||t.stage}`;return{id:"gauntlet-projection-"+t.id,label:n,description:n,datum:t,x:40+(e+.5)*i,y:28,shape:"rect",width:Math.max(16,.55*i),height:22,group:"settled projection"}})}(Z,U):[],[U,N,Z]),At=Ba(()=>[...St,...kt],[kt,St]),Rt=Ca((t,e)=>{l.onBodyPointerDown?.(t,e)},[l]),Pt=Ca((t,e)=>{g&&(t&&"object"==typeof t&&t.__gauntlet?g(t.sourceDatum,{x:e.x,y:e.y}):t&&g(t,{x:e.x,y:e.y}))},[g]),Ct=Ca((t,e)=>{l.beforePaint?.(t,e),R&&function(t,e){const i=new Map(e.filter(t=>t.datum?.kind===Ta).map(t=>[t.datum.projectId,t]));t.save(),t.lineWidth=1.1,t.setLineDash([3,4]);for(const n of e){const e=n.datum;if(!e?.__gauntlet||e.kind===Ta)continue;const o=i.get(e.projectId);o&&(t.globalAlpha=e.kind===qa?.24:.36,t.strokeStyle=e.kind===qa?"#d94a45":"#7a8794",t.beginPath(),t.moveTo(o.x,o.y),t.lineTo(n.x,n.y),t.stroke())}t.restore()}(t,e)},[l,R]),$t=Ba(()=>[...Q,...l.regionEffects??[]],[l.regionEffects,Q]);if(_)return _;const jt=Fo(t.tooltip,l),Bt=Wo(t,l,At,{chartMode:F,className:E,title:q,description:z,summary:L,accessibleTable:Y,enableHover:D,margin:W}),Ot=N?mc(pc,{states:Z,layout:U}):void 0,Nt=qo(T?mc(uc,{layout:U,states:Z,compact:B.resolved.compactMode}):void 0,l.backgroundGraphics),Tt=qo(Ot,l.foregroundGraphics),Et=l.renderBody??cc,qt=jt.tooltipContent??ac;return Eo("GauntletChart",O,fc(yn,{...l,...jt,...Bt,key:`${O[0]}x${O[1]}:${X}:${lt.rerunKey}`,ref:$,accessibleTable:t.accessibleTable??l.accessibleTable,backgroundGraphics:Nt,bodyForces:vt,bodySemanticItems:l.bodySemanticItems??hc,bodyStyle:It,beforePaint:Ct,onClick:g?Pt:Bt.onClick,config:lt.config,controllers:ht,enableHover:jt.enableHover??!0,foregroundGraphics:Tt,hoverRadius:t.hoverRadius??l.hoverRadius??18,initialSpawns:yt,initialSpawnPacing:h,onBodyPointerDown:Rt,onTick:wt,paused:w,regionEffects:$t,renderBody:Et,responsiveHeight:S,responsiveWidth:A,size:O,tooltipContent:qt}))});gc.displayName="GauntletChart";var bc=gc;import{forwardRef as xc,useCallback as vc,useMemo as wc,useRef as Ic}from"react";import{jsx as Mc,jsxs as kc}from"react/jsx-runtime";function Sc(t){return t.toLocaleString(void 0,1e3>Math.abs(t)?{maximumFractionDigits:1}:{maximumFractionDigits:0})}function Ac(t){return t.map((t,e)=>`${0===e?"M":"L"} ${t.x} ${t.y}`).join(" ")}function Rc(t){if(!t||"object"!=typeof t)return null;const e=t,i=Number(e.x),n=Number(e.y);return Number.isFinite(i)&&Number.isFinite(n)?{x:i,y:n}:null}function Pc(t){if(!t||"object"!=typeof t)return[];const e=t.flowPath;return Array.isArray(e)?e.map(Rc).filter(t=>null!=t):[]}function Cc(t,e){if(2>e.length)return null;let i=0;const n=[];for(let t=1;e.length>t;t+=1){const o=Math.hypot(e[t].x-e[t-1].x,e[t].y-e[t-1].y);n.push(o),i+=o}if(0>=i)return null;let o=null,r=0;for(let s=1;e.length>s;s+=1){const a=e[s-1],c=e[s],d=n[s-1];if(0>=d)continue;const l=c.x-a.x,u=c.y-a.y,h=Math.max(0,Math.min(1,((t.x-a.x)*l+(t.y-a.y)*u)/(d*d))),p={x:a.x+l*h,y:a.y+u*h},m={distance:Math.hypot(t.x-p.x,t.y-p.y),point:p,progress:(r+h*d)/i,tangent:{x:l/d,y:u/d},totalLength:i};o&&m.distance>=o.distance||(o=m),r+=d}return o}function $c(t,e,i){if(0===t.length)return{x:0,y:0};if(1===t.length||0>=i)return{...t[0]};let n=0;const o=Math.max(0,Math.min(1,e))*i;for(let e=1;t.length>e;e+=1){const i=t[e-1],r=t[e],s=Math.hypot(r.x-i.x,r.y-i.y);if(s>0){if(n+s>=o){const t=(o-n)/s;return{x:i.x+(r.x-i.x)*t,y:i.y+(r.y-i.y)*t}}n+=s}}return{...t[t.length-1]}}function jc(t){return"circle"===t.shape.type?t.shape.radius:Math.max(t.shape.width,t.shape.height)/2}function Bc(t,e,i){const n=Math.hypot(t,e);if(i>=n||0>=n)return[t,e];const o=i/n;return[t*o,e*o]}function Oc(t,e,i){const n=Cc({...t,x:e[0].x,y:e[0].y},e),o=n?.tangent??{x:e[1].x-e[0].x,y:e[1].y-e[0].y},r=Math.hypot(o.x,o.y)||1,s=o.x/r,a=o.y/r,c=jc(t),d=function(t,e){let i=0;for(let e=0;t.length>e;e+=1)i=31*i+t.charCodeAt(e)>>>0;return(i%1e3/1e3-.5)*e*1.4}(t.id,c);return{id:t.id,x:e[0].x+-a*d,y:e[0].y+s*d,vx:s*i,vy:a*i,mass:t.mass,shape:t.shape,datum:{...t.datum&&"object"==typeof t.datum?t.datum:{},routeProgress:0}}}var Nc=xc(function(t,e){const{chartId:i,colorBy:n,coordinateMode:o="auto",data:r,edges:s,emptyContent:a,flowSpeed:c=90,frameProps:d,links:l,loading:u,loadingContent:h,maxParticles:p=180,nodeIdAccessor:m="id",nodeXAccessor:f="x",nodeYAccessor:y="y",nodes:g,onObservation:b,particleRadius:x=4,particleRate:v=.16,pathAccessor:w="path",pathConstraint:I="path",paused:M,reducedMotion:k=!1,responsiveHeight:S,responsiveWidth:A,seed:R=1,showNodeLabels:P=!0,showSensors:C=!1,showStaticFlow:$=!0,sourceAccessor:j="source",styleRules:B,targetAccessor:O="target",throughputAccessor:N="value"}=t,T=No(t,[760,420]),{chartSize:E,className:q,title:F,chartMode:W,margin:D,enableHover:z,description:L,summary:Y,accessibleTable:_}=T,H=Ic(null),X=wc(()=>g??[],[g]),G=wc(()=>l??s??r??[],[r,s,l]),V=wc(()=>Yn({nodes:X,links:G,nodeIdAccessor:m,nodeXAccessor:f,nodeYAccessor:y,sourceAccessor:j,targetAccessor:O,throughputAccessor:N,pathAccessor:w,coordinateMode:o,particleRate:v,maxParticles:p,particleRadius:x,flowSpeed:c,pathConstraint:I,reducedMotion:k,seed:R,size:E}),[G,X,E,o,c,p,m,f,y,x,v,w,I,k,R,j,O,N]);Mo(e,{frameRef:H,spawnDatum:vc((t,e)=>{const i=Yn({nodes:X,links:[t],nodeIdAccessor:m,nodeXAccessor:f,nodeYAccessor:y,sourceAccessor:j,targetAccessor:O,throughputAccessor:N,pathAccessor:w,coordinateMode:o,particleRate:v,maxParticles:p,particleRadius:x,flowSpeed:c,pathConstraint:I,reducedMotion:k,seed:R+e+1,size:E}),n={id:(t.id??"physical-flow-push-"+e)+"",x:bn(E).plot.x,y:bn(E).plot.y,mass:1,shape:{type:"circle",radius:x},datum:t},r=i.initialSpawns.length?i.initialSpawns:[n];return{datumId:(t.id??r[0].id)+"",spawns:r}},[X,E,o,c,p,m,f,y,x,v,w,I,k,R,j,O,N]),seedRows:G,seedSpawns:V.initialSpawns});const U=n??"source",K=wc(()=>vn(U,"#2563eb",{styleRules:B,valueAccessor:N}),[U,B,N]),Q=wc(()=>function(t,e,i){return{...t,observation:{...t.observation,chartId:e??t.observation?.chartId??"physical-flow",chartType:"PhysicalFlowChart",onObservation:i??t.observation?.onObservation}}}(V.config,i,b),[i,V.config,b]),Z=Ic(d?.onTick);Z.current=d?.onTick;const J=vc((t,e)=>{k||"none"===I||function(t,e){const i=t.readBodies(),n=[],o=[];for(const r of i){const i=Pc(r.datum);if(2>i.length)continue;const s=Cc(r,i);if(!s)continue;const a=r.datum,c=Number(a?.flowSpeed),d=Number.isFinite(c)&&c>0?c:e;if(s.progress>=.985||s.distance>Math.max(90,14*jc(r))){n.push(r.id),o.push(Oc(r,i,d));continue}const l=$c(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-r.vx)*r.mass*.16+(l.x-r.x)*r.mass*.045+(s.point.x-r.x)*r.mass*.08,p=(u.y*d-r.vy)*r.mass*.16+(l.y-r.y)*r.mass*.045+(s.point.y-r.y)*r.mass*.08,[m,f]=Bc(h,p,r.mass*d*.35);t.applyImpulse(r.id,m,f)}n.length&&t.remove(n),o.length&&t.pushMany(o)}(e,c),Z.current?.(t,e)},[c,I,k]),tt=To({data:null==l&&null==s&&null==r?void 0:G,emptyContent:a,loading:u,loadingContent:h,size:E});if(tt)return tt;const et=function(t,e){const{showNodeLabels:i,showSensors:n,showStaticFlow:o}=e;if(t&&(o||n))return({size:e})=>{const r=[Number(e[0])||760,Number(e[1])||420],s=Math.max(1,...t.links.map(t=>t.throughput)),a=new Set(t.nodes.map(t=>t.sensorId));return kc("svg",{"aria-hidden":"true","data-testid":"physical-flow-static-flow-overlay",width:r[0],height:r[1],viewBox:`0 0 ${r[0]} ${r[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[o?t.links.map(t=>{const e=3+t.throughput/s*16,i=t.path[Math.floor(t.path.length/2)];return kc("g",{children:[Mc("path",{d:Ac(t.path),fill:"none",stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:e+5,strokeLinecap:"round",strokeLinejoin:"round",opacity:.26}),Mc("path",{d:Ac(t.path),fill:"none",stroke:"var(--semiotic-accent, #4e79a7)",strokeWidth:e,strokeLinecap:"round",strokeLinejoin:"round",opacity:.16}),i?Mc("text",{x:i.x,y:i.y-e/2-5,textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:Sc(t.throughput)}):null]},t.id)}):null,t.nodes.map(t=>kc("g",{children:[n&&a.has(t.sensorId)?Mc("rect",{"data-testid":"physical-flow-sensor-overlay",x:t.x-12,y:t.y-12,width:24,height:24,rx:4,fill:"none",stroke:"var(--semiotic-warning, #f59e0b)",strokeDasharray:"3 3",strokeWidth:1.5,opacity:.88}):null,o?Mc("circle",{cx:t.x,cy:t.y,r:6,fill:"var(--semiotic-bg, #fff)",stroke:"var(--semiotic-text-secondary, #555)",strokeWidth:1.2}):null,i?Mc("text",{x:t.x,y:t.y-14,textAnchor:"middle",fill:"var(--semiotic-text-primary, #111827)",fontSize:11,fontWeight:800,children:t.label}):null]},t.id))]})}}(V.metadata,{showNodeLabels:P,showSensors:C,showStaticFlow:$}),it=(nt=V.metadata)?nt.links.map(t=>{const e=t.path[Math.floor(t.path.length/2)]??t.path[0],i=`${t.sourceLabel} to ${t.targetLabel}: ${Sc(t.throughput)} throughput, ${t.packetCount} packets`;return{id:t.id,label:i,description:i,datum:t,x:e?.x??0,y:e?.y??0,shape:"path",pathData:Ac(t.path),group:"flow"}}):[];var nt;const ot=Fo(t.tooltip,d),rt=Wo(t,d,it,{chartMode:W,className:q,title:F,description:L,summary:Y,accessibleTable:_,enableHover:z,margin:D});return Eo("PhysicalFlowChart",E,Mc(yn,{...d,...ot,...rt,ref:H,config:Q,continuous:!k&&"none"!==I,foregroundGraphics:qo(et,d?.foregroundGraphics),initialSpawns:V.initialSpawns,onTick:J,paused:M||k,responsiveHeight:S,responsiveWidth:A,simulationExecution:"none"===I?d?.simulationExecution:"sync",size:E,bodyStyle:K,workerBodyThreshold:d?.workerBodyThreshold??1/0}))});Nc.displayName="PhysicalFlowChart";import{Fragment as Tc,jsx as Ec,jsxs as qc}from"react/jsx-runtime";var Fc={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 Wc(t,e,i){return Math.max(e,Math.min(i,t))}function Dc(t){return 6.2*t.length}function zc(t,e){const i=t.trim();if(e>=i.length)return i;if(1>=e)return i.slice(0,1);const n=i.split(/\s+/).filter(Boolean).map(t=>t[0]).join("").toUpperCase();return n.length>1&&e>=n.length?n:e>3?i.slice(0,Math.max(1,e-2))+"..":i.slice(0,e).toUpperCase()}function Lc(t,e,i="auto"){const n=Math.max(1,Math.floor(e/6.2)),o="compact"===i?zc(t,n):"full"===i?t:Dc(t)>e?zc(t,n):t;return{text:o,textLength:Dc(o)>e?Math.max(4,e):void 0}}function Yc(t,e={}){const{showFlowSpine:i=!0,showStageCounts:n=!0,showCapacityBadges:o=!0,showGroupSockets:r=!0,stageLabelMode:s="auto",outlineStages:a=!1,testId:c="process-flow-chrome"}=e,{width:d,height:l,left:u,right:h,topY:p,bottomY:m,midY:f,stages:y,groups:g=[]}=t,b=m-p;return qc("svg",{"aria-hidden":"true","data-testid":c,"data-outline-stages":a?"true":void 0,width:d,height:l,viewBox:`0 0 ${d} ${l}`,style:{position:"absolute",inset:0,pointerEvents:"none"},className:["semiotic-process-chrome",a?"semiotic-process-chrome--outline-stages":null].filter(Boolean).join(" "),children:[Ec("defs",{children:qc("linearGradient",{id:"semiotic-process-floor",x1:"0",x2:"0",y1:"0",y2:"1",children:[Ec("stop",{offset:"0%",stopColor:"var(--semiotic-process-floor, var(--semiotic-bg, #0f172a))",stopOpacity:"0.2"}),Ec("stop",{offset:"100%",stopColor:"var(--semiotic-process-lane, var(--semiotic-surface, #1e293b))",stopOpacity:"0.55"})]})}),Ec("rect",{x:0,y:0,width:d,height:l,fill:"url(#semiotic-process-floor)"}),Ec("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?Ec("line",{x1:u+8,x2:h-8,y1:f,y2:f,stroke:"var(--semiotic-process-border, var(--semiotic-border, #475569))",strokeWidth:2,strokeDasharray:"6 8",opacity:.55}):null,y.map((t,e)=>{const i=function(t){return t.absorb?"absorb":t.portalTarget?"portal":null!=t.capacity?"capacity":"flow"}(t),r=Fc[i],c=Math.max(12,t.width-8),d=Wc(c-8,22,88),u=Lc(t.label,Math.max(8,d-10),s),h="none"!==s&&c-8>=22,g=function(t){if(null!=t.capacity){const e=null!=t.queueDepth?" · q "+t.queueDepth:"";return t.capacityLabel?`${t.capacityLabel}${e}`:`cap ${Number.isInteger(t.capacity)?t.capacity+"":t.capacity.toFixed(1)}${e}`}return t.absorb?"absorb":t.portalTarget?"portal":"flow"}(t),x=Lc(g,Math.max(16,c-10),"auto"),v=o&&!1!==t.showBadge&&c>=32,w=null!=t.count?`n=${t.count}${null!=t.processed?" done "+t.processed:""}`:"",I=Lc(w,Math.max(16,c-8),"auto"),M=Math.max(30,p-15),k=M-13;return qc("g",{"data-stage":t.id,"data-role":i,children:[Ec("rect",{className:"semiotic-process-chrome__stage-bay",x:t.x0+4,y:p+6,width:c,height:b-12,rx:10,fill:a?"none":r.fill,stroke:r.stroke,strokeWidth:a?1.85:"flow"===i?1:1.6}),y.length-1>e?Ec("polygon",{points:`${t.x1-2},${f-7} ${t.x1+8},${f} ${t.x1-2},${f+7}`,fill:r.accent,opacity:.85}):null,h?qc(Tc,{children:[Ec("rect",{className:"semiotic-process-chrome__stage-label-bg",x:t.x-d/2,y:k,width:d,height:18,rx:9,fill:"var(--semiotic-bg, #0f172a)",fillOpacity:.75,stroke:r.stroke}),qc("text",{x:t.x,y:M,textAnchor:"middle",fill:r.accent,fontSize:10,fontWeight:800,className:"semiotic-process-chrome__stage-label",textLength:u.textLength,lengthAdjust:u.textLength?"spacingAndGlyphs":void 0,children:[Ec("title",{children:t.label}),u.text]})]}):null,v?qc("text",{x:t.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:[Ec("title",{children:g}),x.text]}):null,n&&null!=t.count?qc("text",{x:t.x,y:Math.min(l-8,m+16),textAnchor:"middle",fill:"var(--semiotic-process-text, var(--semiotic-text, #e2e8f0))",fontSize:11,fontWeight:800,textLength:I.textLength,lengthAdjust:I.textLength?"spacingAndGlyphs":void 0,children:[Ec("title",{children:w}),I.text]}):null]},t.id)}),r?g.map((t,e)=>{const i=t.total??0,n=t.absorbed??0,o=t.complete??(i>0&&n>=i),r=!o&&i>0&&n/i>=.75,s=o?"rgba(52, 211, 153, 0.35)":r?"rgba(251, 191, 36, 0.28)":"rgba(15, 23, 42, 0.75)",a=o?"#34d399":r?"#fbbf24":"var(--semiotic-border, #64748b)",c=i>0?`${n}/${i}${o?" shipped":r?" almost":""}`:"feature "+(e+1),d=Wc(Math.max(54,Dc(t.label)+18,Dc(c)+16),54,104),l=Lc(t.label,d-12,"auto"),u=Lc(c,d-12,"auto");return qc("g",{"data-group":t.id,children:[Ec("rect",{x:t.x-d/2,y:t.y-22,width:d,height:44,rx:10,fill:s,stroke:a,strokeWidth:1.5}),qc("text",{x:t.x,y:t.y-4,textAnchor:"middle",fill:"var(--semiotic-process-text, var(--semiotic-text, #f8fafc))",fontSize:10,fontWeight:800,textLength:l.textLength,lengthAdjust:l.textLength?"spacingAndGlyphs":void 0,children:[Ec("title",{children:t.label}),l.text]}),qc("text",{x:t.x,y:t.y+12,textAnchor:"middle",fill:a,fontSize:9,fontWeight:700,textLength:u.textLength,lengthAdjust:u.textLength?"spacingAndGlyphs":void 0,children:[Ec("title",{children:c}),u.text]})]},t.id)}):null]})}import{forwardRef as _c,useCallback as Hc,useEffect as Xc,useMemo as Gc,useRef as Vc,useState as Uc}from"react";import{jsx as Kc}from"react/jsx-runtime";var Qc=_c(function(t,e){const{ballRadius:i=6,chromeOptions:n,colorBy:o,data:r,emptyContent:s,frameProps:a={},groupAnchorAlong:c,groupBy:d,groupCompletion:l,groupLabelAccessor:u,gravityX:h,gravityY:p,idAccessor:m,initialSpawnPacing:f,liveCapacity:y=!0,onCapacityChange:g,selection:b,bodyLimit:v,bodyMark:w,loading:I,loadingContent:M,paused:k,radiusAccessor:S,responsiveHeight:A,responsiveWidth:R,route:P="horizontal",seed:C=1,settle:$,springDamping:j,springStiffness:B,stageAccessor:O="stage",stages:N,workAccessor:T}=t,E=No(t,[900,420]),{chartSize:q,showProjection:F,showChrome:W,className:D,title:z,chartMode:L,margin:Y,enableHover:_,description:H,summary:X,accessibleTable:G}=E,V=Vc(null),U=Gc(()=>x(r??[]),[r]),K=Gc(()=>({data:U,stages:N,size:q,idAccessor:m,stageAccessor:O,groupBy:d,groupLabelAccessor:u,workAccessor:T,radiusAccessor:S,ballRadius:i,seed:C,route:P,groupCompletion:l,groupAnchorAlong:c,springStiffness:B,springDamping:j,gravityX:h,gravityY:p,settle:$}),[i,q,h,p,c,d,l,u,m,S,P,U,C,$,j,B,O,N,T]),Q=Gc(()=>po(K),[K]),Z=Q.metadata;Mo(e,{frameRef:V,spawnDatum:Hc((t,e)=>{const n=po({...K,data:[t],seed:C+e+1,settle:!0}).initialSpawns[0]??{id:(t.id??"process-flow-push-"+e)+"",x:bn(q).plot.x,y:bn(q).plot.y,mass:1,shape:{type:"circle",radius:i},datum:t};return{datumId:(t.id??n.id)+"",spawns:[n]}},[i,K,q,C]),seedRows:U,seedSpawns:Q.initialSpawns});const J=Gc(()=>vn(o),[o]),tt=Gc(()=>{if(!y)return a.controllers;const t=[...N.filter(t=>t.capacity&&t.capacity.unitsPerSecond>0).map(t=>{const e=t.capacity.unitsPerSecond;return Ie({id:"process-capacity-"+t.id,regionId:"process-stage-"+t.id,unitsPerSecond:e,unitAccessor:t.capacity.unitAccessor??(T?"string"==typeof T?T:t=>{const e=t.datum;if(!e)return 1;try{return Number(T(e,0))||1}catch{return 1}}:"work"),releaseImpulse:{x:70+Math.min(40,2*e),y:0},queueLayout:"lane",continuous:!0})}),...a.controllers??[]];return t.length?t:void 0},[a.controllers,y,N,T]),[et,it]=Uc({}),nt=Vc(tt);nt.current=tt;const ot=Vc(a.onTick);ot.current=a.onTick;const rt=!1!==W||null!=g;Xc(()=>{if(!g)return;const t=Object.values(et);t.length&&g(t)},[et,g]);const st=Hc((t,e)=>{if(ot.current?.(t,e),!rt)return;const i=nt.current;if(!i?.length)return;const n={};for(const t of i){const e=t.getSnapshot?.();e&&"string"==typeof e.regionId&&(n[e.regionId]=e)}it(t=>function(t,e){const i=Object.keys(t),n=Object.keys(e);if(i.length!==n.length)return!1;for(const n of i){const i=t[n],o=e[n];if(!o)return!1;if(i.queueDepth!==o.queueDepth||i.blockedDepth!==o.blockedDepth||i.processedCount!==o.processedCount||i.unitsPerSecond!==o.unitsPerSecond||i.regionId!==o.regionId||i.metricRevision!==o.metricRevision)return!1}return!0}(t,n)?t:n)},[rt]),at=Gc(()=>{const t=J,e=a.bodyStyle;return w||e?(i,n)=>{const o="function"==typeof e?e(i,n):e;return{..."function"==typeof t?t(i):t,...o,mark:o?.mark??i.datum?.__physicsMark??i.datum?.mark??w}}:t},[w,J,a.bodyStyle]),ct=To({data:r,emptyContent:s,loading:I,loadingContent:M,size:q});if(ct)return ct;if(!N?.length)return Eo("ProcessFlowChart",q,Kc("div",{role:"status",style:{width:q[0],height:q[1],display:"grid",placeItems:"center",color:"var(--semiotic-text-secondary, #64748b)"},children:"ProcessFlowChart requires a non-empty stages array."}));const dt=function(t,e,i={},n){if(!1===e||!t)return;const{volume:o,stages:r,groups:s,groupCompletion:a}=t,c=new Map(o.stages.map(t=>[t.id,t])),d=new Map(a.map(t=>[t.id,t]));return({size:t})=>{const e=Number(t[0])||o.width,a=Number(t[1])||o.height,l=r.map(t=>{const e=c.get(t.id),n=i["process-stage-"+t.id];return{id:t.id,label:t.label,x0:e?.x0??t.x-t.width/2,x1:(e?.x0??t.x-t.width/2)+(e?.width??t.width),x:t.x,width:e?.width??t.width,count:t.count,capacity:t.capacity,absorb:t.absorb,portalTarget:t.portalTarget,queueDepth:n?.queueDepth,processed:n?.processedCount}}),u=s.map(t=>{const e=d.get(t.id);return{id:t.id,label:t.label??t.id,x:t.anchor?.x??t.x??0,y:t.anchor?.y??t.y??0,absorbed:e?.absorbed,total:e?.total,complete:e?.complete}});return Yc({width:e,height:a,left:o.left,right:o.right,topY:o.topY,bottomY:o.bottomY,midY:o.midY,stages:l,groups:u},{showCapacityBadges:!0,showGroupSockets:!0,...n})}}(Z,W,et,n),lt=function(t,e,i){if(!1===i||!e||0===t.length)return;const n=new Map(e.volume.stages.map(t=>[t.id,t]));return({size:i})=>{const o=[Number(i[0])||e.volume.width,Number(i[1])||e.volume.height],r=bn(o),s=Math.max(1,...t.map(t=>t.value)),a=Math.min(48,.18*r.plot.height),c=r.plot.y+6;return Kc("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:e.stages.map((e,i)=>{const o=t[i];if(!o)return null;const r=n.get(e.id);if(!r)return null;const d=Math.max(2,o.value/s*a),l=Math.max(8,.35*r.width);return Kc("rect",{x:r.x-l/2,y:c,width:l,height:d,rx:2,fill:"var(--semiotic-primary, #4e79a7)",fillOpacity:.18,stroke:"var(--semiotic-primary, #4e79a7)",strokeOpacity:.45,strokeWidth:1},e.id)})})}}(Q.projectionRows,Z,F),ut=[...In(Q.projectionRows,q,"stage"),...ba(Z?.groups??[])],ht=Fo(t.tooltip,a),pt=Wo(t,a,ut,{chartMode:L,className:D,title:z,description:H,summary:X,accessibleTable:G,enableHover:_,margin:Y}),mt=[...Z?.regionEffects??[],...a.regionEffects??[]];return Eo("ProcessFlowChart",q,Kc(yn,{...a,...ht,...pt,ref:V,controllers:tt,regionEffects:mt,selection:b??a.selection,backgroundGraphics:qo(dt,a.backgroundGraphics),foregroundGraphics:qo(lt,a.foregroundGraphics),initialSpawns:Q.initialSpawns,initialSpawnPacing:f??Q.initialSpawnPacing,onTick:st,paused:k,responsiveHeight:A,responsiveWidth:R,size:q,bodyStyle:at,config:{...Q.config,...null!=v?{bodyLimit:v,eviction:"oldest"}:{},...a.config}}))});Qc.displayName="ProcessFlowChart";import{forwardRef as Zc,useCallback as Jc,useMemo as td,useRef as ed}from"react";import{scaleLinear as id}from"d3-scale";function nd(t,e){const i=e.config??{},n=(e.sensors??[]).map(t=>({...t,sensor:!0})),o=[...e.colliders??[],...n],r=[...t.colliders??[],...i.colliders??[],...o];return{...t,...i,observation:{...t.observation,...i.observation},...r.length>0&&{colliders:r}}}function od(t){const e=function(t,e,i){const n=t?.observation;return{...t,observation:{...n,chartId:e??n?.chartId??"physics-custom",chartType:n?.chartType??"PhysicsCustomChart",onObservation:i??n?.onObservation}}}(t.config,t.chartId,t.onObservation),i=r(t.colorScheme,t.themeCategorical,P),n=bn(t.size),s={data:t.data,scales:{x:id().domain(t.xExtent??[0,1]).range([n.plot.x,n.plot.x+n.plot.width]),y:id().domain(t.yExtent??[0,1]).range([n.plot.y+n.plot.height,n.plot.y])},dimensions:n,theme:{semantic:t.semantic,categorical:[...i]},resolveColor:o(i,t.colorScheme),config:t.layoutConfig??{},world:new ye(e)},a=t.skipLayout?{}:t.layout(s)??{},c=function(t,e){if(!e?.length)return t;const i=new Map;for(const t of e){const{bodyId:e,...n}=t,o=i.get(e)??[];o.push(n),i.set(e,o)}return t.map(t=>{const e=i.get(t.id);return e?.length?{...t,springs:[...t.springs??[],...e]}:t})}([...a.initialSpawns??a.bodies??[]],a.constraints);return{config:nd(e,a),context:s,initialSpawnPacing:a.initialSpawnPacing,initialSpawns:c,result:a}}import{jsx as rd}from"react/jsx-runtime";var sd=Zc(function(t,e){const{chartId:i,color:n,colorBy:o,colorScheme:r,config:s,controllers:a,data:c,emptyContent:d,frameProps:l={},layout:u,layoutConfig:h,loading:p,loadingContent:m,onObservation:f,opacity:y,paused:g,spawnDatum:b,stroke:v,strokeWidth:w,title:I,xExtent:M,yExtent:k}=t,S=No(t,[700,380]),{chartSize:A,className:R,title:P,chartMode:C,margin:$,enableHover:j,description:B,summary:O,accessibleTable:N}=S,T=ed(null),E=ed(null),D=ed(""),z=To({data:c,emptyContent:d,loading:p,loadingContent:m,size:A}),L=null!=z,Y=td(()=>x(c??[]),[c]),_=W(t=>t.theme),H=td(()=>F(_)??{},[_]),X=_?.colors?.categorical??q.colors.categorical,G=td(()=>[A[0],A[1],Y.length,Y.map((t,e)=>(t.id??e)+"").join("|"),M?.join(",")??"",k?.join(",")??""].join("::"),[A,Y,M,k]),V=td(()=>od({chartId:i,colorScheme:r,config:s,data:Y,layout:u,layoutConfig:h,onObservation:f,semantic:H,skipLayout:L,size:A,themeCategorical:X,xExtent:M,yExtent:k}),[i,A,r,s,u,h,f,Y,H,L,X,M,k]);D.current===G&&null!=E.current||(D.current=G,E.current=V.initialSpawns);const U=E.current,K=td(()=>{const t=[...V.result.controllers??[],...a??[],...l.controllers??[]];return t.length?t:void 0},[l.controllers,a,V.result.controllers]),Q=td(()=>{const t=[...V.result.regionEffects??[],...l.regionEffects??[]];return t.length?t:void 0},[l.regionEffects,V.result.regionEffects]),Z=Jc(t=>{const e=t.datum,i=e&&o?function(t,e,i){return"function"==typeof i?i(t,0):t[i]}(e,0,o)+"":t.id;return{fill:n??V.context.resolveColor(i,e),stroke:v??"#111827",strokeWidth:w??1,opacity:y??.9}},[n,o,y,V.context,v,w]);Mo(e,{frameRef:T,spawnDatum:Jc((t,e)=>{const n=t;if(b)return function(t,e,i){return Array.isArray(i)?{datumId:(t.id??i[0]?.id??"physics-custom-"+e)+"",spawns:i}:"spawns"in i?i:{datumId:(t.id??i.id??"physics-custom-"+e)+"",spawns:[i]}}(t,e,b(n,e,V.context));const o=od({chartId:i,colorScheme:r,config:s,data:[n],layout:u,layoutConfig:h,onObservation:f,semantic:H,size:A,themeCategorical:X,xExtent:M,yExtent:k}),a=o.initialSpawns.length?o.initialSpawns:[{id:(t.id??"physics-custom-"+e)+"",x:o.context.dimensions.plot.x+o.context.dimensions.plot.width/2,y:o.context.dimensions.plot.y+12,mass:1,shape:{type:"circle",radius:5},datum:t}];return{datumId:(t.id??a[0].id)+"",spawns:a}},[i,A,r,s,b,u,h,f,V.context,H,X,M,k]),seedRows:Y,seedSpawns:U});const J=Jc((t,e)=>{l.onBodyPointerDown?.(t,e)},[l]);if(z)return z;const tt=Fo(t.tooltip,l),et=Wo(t,l,V.result.semanticItems,{chartMode:C,className:R,title:P??I,description:B,summary:O,accessibleTable:N,enableHover:j,margin:$});return Eo("PhysicsCustomChart",A,rd(yn,{...l,...tt,...et,ref:T,backgroundGraphics:qo(l.backgroundGraphics,V.result.backgroundOverlays),bodyForces:V.result.bodyForces??l.bodyForces,bodyStyle:V.result.bodyStyle??l.bodyStyle??Z,config:V.config,controllers:K,foregroundGraphics:qo(l.foregroundGraphics,V.result.overlays),initialSpawnPacing:V.initialSpawnPacing,initialSpawns:U,onBodyPointerDown:J,paused:g,regionEffects:Q,responsiveHeight:t.responsiveHeight,responsiveWidth:t.responsiveWidth,selectedBodyStyle:V.result.selectedBodyStyle??l.selectedBodyStyle,size:A}))});sd.displayName="PhysicsCustomChart";export{Z as bodiesToAnnotationAnchors,J as buildPhysicsAnnotationContext,tt as normalizePhysicsAnnotations,et as PhysicsSVGOverlay,kt as BuiltInPhysicsEngineAdapter,St as createDefaultPhysicsEngineAdapter,Tt as PhysicsSedimentAccumulator,Et as sedimentHeightfield,Ft as evaluatePhysicsBodyBudget,Zt as collidersFromPlotBounds,Jt as collidersFromXScaleBins,ye as PhysicsPipelineStore,Ie as createCapacityQueueController,Se as createServiceResourcePoolController,Re as createServiceLevelController,Pe as createDependencyGateController,$e as composePhysicsControllers,je as createPortalController,fn as StreamPhysicsFrame,yn as StreamPhysicsFrame_default,Cn as buildGaltonBoardPhysics,Bn as buildEventDropPhysics,Nn as buildPhysicsPile,En as buildCollisionSwarmPhysics,Yn as buildPhysicalFlowPhysics,_n as aggregateRegionCounts,Hn as regionCountsToProjectionRows,Xn as groupCompletionRows,Vn as stageTargetInVolume,Un as processVolumePolygons,Zn as processStageLayout,to as processStageRegions,eo as membraneRegion,io as chargeGateRegion,no as routeSurfaceRegion,oo as pressureFieldRegion,ro as capacitatedRegion,so as portalRegion,ao as absorbRegion,co as forceFieldRegion,lo as bodyGroupSpec,uo as processLaneWalls,po as buildProcessFlowPhysics,Yo as GaltonBoardChart,Ko as EventDropChart,nr as PhysicsPileChart,ur as CollisionSwarmChart,yr as cloneCrucibleState,wr as resolveCrucibleSelector,$r as applyCrucibleEvent,jr as buildCrucibleProjection,Br as crucibleProjectionRows,Or as evaluateCrucibleConservation,Nr as buildCrucibleEvidence,Tr as DEFAULT_CRUCIBLE_WIDTH,Er as DEFAULT_CRUCIBLE_HEIGHT,qr as DEFAULT_CRUCIBLE_SIZE,Fr as DEFAULT_CRUCIBLE_OUTLETS,Gr as createInitialCrucibleState,Ur as buildCrucibleLayout,Qr as crucibleBoundaryColliders,ts as buildCruciblePhysicsConfig,es as crucibleComponentBodyId,is as crucibleProductBodyId,ns as crucibleBondId,ss as buildCrucibleInitialSpawns,ls as buildCrucibleStateSpawns,us as buildCrucibleTerminalSpawns,ps as crucibleSemanticKey,ms as resolveCrucibleTime,fs as resolveCrucibleSnapshotAt,ys as replayCruciblePlan,gs as compileCruciblePlan,vs as buildCrucibleProductEvents,ma as CrucibleChart,fa as physicsProcessBoundaryColliders,ya as physicsProcessRegionSemanticItem,ga as physicsProcessStageSemanticItems,ba as physicsProcessGroupSemanticItems,Ia as planGauntletPropertyWork,Ma as replaceGauntletNegative,gc as GauntletChart,bc as GuantletChart,Nc as PhysicalFlowChart,Yc as processChrome,Qc as ProcessFlowChart,sd as PhysicsCustomChart};
|