semiotic 3.8.1 → 3.8.3
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 +3 -1
- package/README.md +54 -52
- package/ai/behaviorContracts.cjs +9 -0
- package/ai/dist/mcp-server.js +142 -13
- package/ai/schema.json +616 -42
- package/ai/surface-manifest.json +1 -1
- package/ai/system-prompt.md +5 -2
- package/dist/chunk-OrdinalBrushOverlay-PXHQYDB2.module.min.js +2 -0
- package/dist/chunk-XYBrushOverlay-ECZJJLAJ.module.min.js +1 -0
- package/dist/chunk-XYBrushOverlay-EP2SV3UI.module.min.js +2 -0
- package/dist/chunk-chunk-255KDHW5.module.min.js +1 -0
- package/dist/chunk-chunk-2CCFBTQC.module.min.js +2 -0
- package/dist/chunk-chunk-2CXCXRB4.module.min.js +1 -0
- package/dist/chunk-chunk-2JGJ5GUG.module.min.js +2 -0
- package/dist/chunk-chunk-2RXP3FS3.module.min.js +1 -0
- package/dist/chunk-chunk-2WVCH4PL.module.min.js +1 -0
- package/dist/chunk-chunk-4TMZXLCR.module.min.js +1 -0
- package/dist/chunk-chunk-5APBQXZA.module.min.js +1 -0
- package/dist/chunk-chunk-5RKXZQ2P.module.min.js +1 -0
- package/dist/chunk-chunk-5UKL5W76.module.min.js +2 -0
- package/dist/chunk-chunk-6HSGDMTA.module.min.js +2 -0
- package/dist/chunk-chunk-7FW6EGLP.module.min.js +2 -0
- package/dist/chunk-chunk-7OEOSCBP.module.min.js +1 -0
- package/dist/chunk-chunk-A63CTACR.module.min.js +2 -0
- package/dist/chunk-chunk-ANYDWOZF.module.min.js +1 -0
- package/dist/chunk-chunk-AZJUDQRM.module.min.js +2 -0
- package/dist/chunk-chunk-B6V35LMY.module.min.js +2 -0
- package/dist/chunk-chunk-BOSVL645.module.min.js +2 -0
- package/dist/chunk-chunk-CA3YDW6F.module.min.js +1 -0
- package/dist/chunk-chunk-CP3EN6KZ.module.min.js +1 -0
- package/dist/chunk-chunk-DSNGDNJY.module.min.js +1 -0
- package/dist/chunk-chunk-EMO5NUGE.module.min.js +2 -0
- package/dist/chunk-chunk-F25UA5HT.module.min.js +1 -0
- package/dist/chunk-chunk-FRIO6MCV.module.min.js +1 -0
- package/dist/chunk-chunk-FYY2ACNJ.module.min.js +2 -0
- package/dist/chunk-chunk-G7WFWHAD.module.min.js +2 -0
- package/dist/chunk-chunk-GMQ5AYTD.module.min.js +1 -0
- package/dist/chunk-chunk-GWSWSPXN.module.min.js +1 -0
- package/dist/chunk-chunk-I6C3KR5H.module.min.js +2 -0
- package/dist/chunk-chunk-IP2UE74X.module.min.js +1 -0
- package/dist/chunk-chunk-J3ELI22J.module.min.js +1 -0
- package/dist/chunk-chunk-J3QOW4OE.module.min.js +0 -0
- package/dist/chunk-chunk-J3XWETBJ.module.min.js +2 -0
- package/dist/chunk-chunk-J5RL6GXU.module.min.js +2 -0
- package/dist/chunk-chunk-JCG72SGW.module.min.js +2 -0
- package/dist/{semiotic-ai-chunk-OG7BQUUW.module.min.js → chunk-chunk-JJ2OOIET.module.min.js} +0 -1
- package/dist/chunk-chunk-JNCHKRIR.module.min.js +2 -0
- package/dist/chunk-chunk-KTWEBFMX.module.min.js +2 -0
- package/dist/chunk-chunk-L3H6DQCR.module.min.js +2 -0
- package/dist/chunk-chunk-M337NY6L.module.min.js +1 -0
- package/dist/chunk-chunk-M7VYYHCE.module.min.js +2 -0
- package/dist/chunk-chunk-MC35ILYP.module.min.js +2 -0
- package/dist/chunk-chunk-N72SWNBV.module.min.js +1 -0
- package/dist/chunk-chunk-OBQRFTIL.module.min.js +2 -0
- package/dist/chunk-chunk-OQTLSTGI.module.min.js +2 -0
- package/dist/chunk-chunk-Q2YADC2V.module.min.js +2 -0
- package/dist/chunk-chunk-QRIBHZYW.module.min.js +1 -0
- package/dist/chunk-chunk-QSQVBIJA.module.min.js +1 -0
- package/dist/chunk-chunk-RCF52Z42.module.min.js +2 -0
- package/dist/chunk-chunk-ROP4HI7H.module.min.js +2 -0
- package/dist/chunk-chunk-RZH7VZYS.module.min.js +2 -0
- package/dist/chunk-chunk-SA3D43RA.module.min.js +2 -0
- package/dist/chunk-chunk-SANERMIZ.module.min.js +2 -0
- package/dist/chunk-chunk-SIRIJ3DY.module.min.js +1 -0
- package/dist/chunk-chunk-SV4XAZ3Q.module.min.js +1 -0
- package/dist/chunk-chunk-U66USBWU.module.min.js +1 -0
- package/dist/chunk-chunk-UHSZEB74.module.min.js +1 -0
- package/dist/chunk-chunk-VVCA3DB7.module.min.js +1 -0
- package/dist/chunk-chunk-WCX6U47H.module.min.js +2 -0
- package/dist/chunk-chunk-XEVJDUTH.module.min.js +1 -0
- package/dist/chunk-chunk-XQYVEKEJ.module.min.js +2 -0
- package/dist/chunk-chunk-Y6AXCRVO.module.min.js +1 -0
- package/dist/chunk-chunk-YCQYG6J5.module.min.js +2 -0
- package/dist/chunk-chunk-YHNZCPOZ.module.min.js +2 -0
- package/dist/chunk-chunk-YWZB3KPI.module.min.js +2 -0
- package/dist/chunk-chunk-ZCNBUZPL.module.min.js +2 -0
- package/dist/chunk-statisticalOverlays-6MVAK5RW.module.min.js +2 -0
- package/dist/components/charts/custom/XYCustomChart.d.ts +3 -0
- package/dist/components/charts/physics/PhysicalFlowChart.d.ts +7 -0
- package/dist/components/charts/realtime/RealtimeHistogram.d.ts +5 -6
- package/dist/components/charts/realtime/temporalHistogramConfig.d.ts +11 -0
- package/dist/components/charts/shared/areaSeriesData.d.ts +15 -0
- package/dist/components/charts/shared/auditAccessibilityText.d.ts +13 -0
- package/dist/components/charts/shared/chartMode.d.ts +67 -0
- package/dist/components/charts/shared/colorUtils.d.ts +8 -0
- package/dist/components/charts/shared/geoStyleDefaults.d.ts +3 -0
- package/dist/components/charts/shared/hooks.d.ts +13 -80
- package/dist/components/charts/shared/useChartSetup.d.ts +3 -0
- package/dist/components/charts/shared/useCustomChartSetup.d.ts +3 -0
- package/dist/components/charts/shared/useXYLineStyle.d.ts +3 -2
- package/dist/components/charts/shared/xyLineStyle.d.ts +21 -0
- package/dist/components/charts/xy/LineChart.d.ts +3 -0
- package/dist/components/legendLayout.d.ts +31 -0
- package/dist/components/server/serverChartConfigShared.d.ts +29 -0
- package/dist/components/server/serverChartConfigs.d.ts +2 -13
- package/dist/components/server/serverChartConfigsXY.d.ts +3 -0
- package/dist/components/server/serverGaugeOverlay.d.ts +28 -0
- package/dist/components/server/staticLegend.d.ts +7 -1
- package/dist/components/server/staticSVGChrome.d.ts +60 -2
- package/dist/components/stream/GeoPipelineStore.d.ts +2 -0
- package/dist/components/stream/GeoSVGOverlay.d.ts +2 -0
- package/dist/components/stream/OrdinalBrushOverlay.d.ts +1 -2
- package/dist/components/stream/OrdinalBrushOverlayLazy.d.ts +9 -0
- package/dist/components/stream/SceneToSVG.d.ts +8 -6
- package/dist/components/stream/SceneToSVGGeo.d.ts +10 -0
- package/dist/components/stream/SceneToSVGNetwork.d.ts +12 -0
- package/dist/components/stream/XYBrushOverlayLazy.d.ts +17 -0
- package/dist/components/stream/canvasBackground.d.ts +7 -0
- package/dist/components/stream/networkTypes.d.ts +2 -4
- package/dist/components/stream/renderBackend.d.ts +14 -0
- package/dist/components/stream/sceneToSVGShared.d.ts +51 -0
- package/dist/components/types/legendTypes.d.ts +16 -3
- package/dist/controls.min.js +1 -1
- package/dist/controls.module.min.js +1 -1
- 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-matter.min.js +1 -1
- package/dist/physics-matter.module.min.js +1 -1
- package/dist/physics-rapier.min.js +1 -1
- package/dist/physics-rapier.module.min.js +1 -1
- package/dist/physics.min.js +1 -1
- package/dist/physics.module.min.js +1 -1
- package/dist/realtime.min.js +1 -1
- package/dist/realtime.module.min.js +1 -1
- package/dist/rough.min.js +1 -1
- package/dist/rough.module.min.js +1 -1
- package/dist/semiotic-ai-core.min.js +1 -1
- package/dist/semiotic-ai-core.module.min.js +1 -1
- package/dist/semiotic-ai.min.js +1 -1
- package/dist/semiotic-ai.module.min.js +1 -1
- package/dist/semiotic-data.min.js +1 -1
- package/dist/semiotic-data.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-realtime-core.min.js +1 -1
- package/dist/semiotic-realtime-core.module.min.js +1 -1
- package/dist/semiotic-realtime-react.min.js +1 -1
- package/dist/semiotic-realtime-react.module.min.js +1 -1
- package/dist/semiotic-recipes-core.min.js +1 -1
- package/dist/semiotic-recipes-core.module.min.js +1 -1
- package/dist/semiotic-recipes-react.min.js +1 -1
- package/dist/semiotic-recipes-react.module.min.js +1 -1
- package/dist/semiotic-recipes.min.js +1 -1
- package/dist/semiotic-recipes.module.min.js +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-themes-core.min.js +1 -1
- package/dist/semiotic-themes-core.module.min.js +1 -1
- package/dist/semiotic-themes-react.min.js +1 -1
- package/dist/semiotic-themes-react.module.min.js +1 -1
- package/dist/semiotic-themes.min.js +1 -1
- package/dist/semiotic-themes.module.min.js +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-react.min.js +1 -1
- package/dist/semiotic-utils-react.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-value.min.js +1 -1
- package/dist/semiotic-value.module.min.js +1 -1
- 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 +4 -4
- package/dist/semiotic-ai-statisticalOverlays-CY4WKR4A.module.min.js +0 -2
- package/dist/semiotic-chunk-3FSVZ46U.module.min.js +0 -2
- package/dist/semiotic-statisticalOverlays-UOMSFKVJ.module.min.js +0 -2
- package/dist/xy-chunk-IWD6IB6V.module.min.js +0 -2
- package/dist/xy-statisticalOverlays-7RWG6LJT.module.min.js +0 -2
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import{mulberry32 as e}from"./chunk-chunk-SIRIJ3DY.module.min.js";import{makeRuleValueResolver as t,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-SANERMIZ.module.min.js";import{ANNOTATION_DISCLOSURE_REVEAL_CSS as s,AriaLiveTooltip as a,CanvasFrameBackground as c,FlippingTooltip as l,FocusRing as d,SceneRevisionDiagnosticsObserver as u,ScreenReaderSummary as h,SkipToTableLink as p,UpdateResultTracker as m,annotationLayout as y,coerceCanvasFill as f,createDefaultAnnotationRules as g,defaultTooltipStyle as b,filterSparseArray as x,getDevicePixelRatio as v,isInteractiveKeyboardTarget as w,isServerEnvironment as k,normalizeTooltip as M,prepareCanvas as S,renderAnnotationPass as I,renderLegendFromConfig as A,resolveCSSColor as P,schemeCategory10 as C,useAnnotationActivationOptions as R,useChartMode as B,useDataSummary as j,useFrame as T,useFrameCanvasHost as N,useSceneRevisionDiagnostics as O,xySceneNodeToSVG as E}from"./chunk-chunk-6HSGDMTA.module.min.js";import{LIGHT_THEME as $,resolveThemeSemanticColors as q,useThemeSelector as W}from"./chunk-chunk-WCX6U47H.module.min.js";import{SafeRender as F,renderEmptyState as D,renderLoadingState as z,useHydration as Y,useWasHydratingFromSSR as L}from"./chunk-chunk-ZCNBUZPL.module.min.js";import*as H from"react";import{scaleLinear as X}from"d3-scale";import{Fragment as _,jsx as G,jsxs as V}from"react/jsx-runtime";function U(e){return"circle"===e.shape.type?e.shape.radius:Math.max(e.shape.width,e.shape.height)/2}function K(e){return e.map(e=>({pointId:e.id,x:e.x,y:e.y,r:Math.max(1,U(e))}))}function Q(e){const{width:t,height:i,pointNodes:n=[],data:o}=e;return{scales:{x:X().domain([0,Math.max(1,t)]).range([0,Math.max(1,t)]),y:X().domain([0,Math.max(1,i)]).range([0,Math.max(1,i)])},width:t,height:i,frameType:"network",pointNodes:n,data:o,xAccessor:"x",yAccessor:"y"}}function Z(e){return e?.length?e.map(e=>null!=e.pointId||null==e.bodyId?e:{...e,pointId:e.bodyId+""}):e}function J(e){const{width:t,height:i,totalWidth:n,totalHeight:o,margin:r,title:a,legend:c,legendHoverBehavior:l,legendClickBehavior:d,legendHighlightedCategory:u,legendIsolatedCategories:h,legendPosition:p="right",legendLayout:m,pointNodes:f=[],annotations:b,onAnnotationActivate:x,onObservation:v,chartId:w,chartType:k,autoPlaceAnnotations:M,svgAnnotationRules:S,children:P}=e,C=R({onAnnotationActivate:x,onObservation:v,chartId:w,chartType:k}),B=H.useMemo(()=>Z(b),[b]),j=H.useMemo(()=>Q({width:t,height:i,pointNodes:f}),[i,f,t]),T=H.useMemo(()=>B&&M?y({annotations:B,context:j,..."object"==typeof M?M:{}}):B,[j,M,B]),N=H.useMemo(()=>g("network",C),[C]),O=T?I(T,N,S,j):null,E=!0===T?.some(e=>"widget"===e.type&&!0===e._annotationDeferred);return V(_,{children:[E?G("style",{children:s},"physics-annotation-disclosure-style"):null,V("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:[V("g",{transform:`translate(${r.left},${r.top})`,children:[O,P]}),a&&"string"==typeof a?G("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?G("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:l,legendClickBehavior:d,legendHighlightedCategory:u,legendIsolatedCategories:h}):null]})]})}var ee={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},te=1e-9,ie=.005;function ne(e){return"circle"===e.type?{type:"circle",radius:e.radius}:{type:"aabb",width:e.width,height:e.height}}function oe(e){return"aabb"===e.type?{type:"aabb",x:e.x,y:e.y,width:e.width,height:e.height}:{type:"segment",x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2,thickness:e.thickness}}function re(e,t,i){return Math.max(t,Math.min(i,e))}function se(e){return 0>e?-1:1}function ae(e){if("circle"===e.shape.type){const t=e.shape.radius;return{minX:e.x-t,minY:e.y-t,maxX:e.x+t,maxY:e.y+t}}const t=e.shape.width/2,i=e.shape.height/2;return{minX:e.x-t,minY:e.y-i,maxX:e.x+t,maxY:e.y+i}}function ce(e){const t=e.shape;if("aabb"===t.type){const e=t.width/2,i=t.height/2;return{minX:t.x-e,minY:t.y-i,maxX:t.x+e,maxY:t.y+i}}const i=(t.thickness??0)/2;return{minX:Math.min(t.x1,t.x2)-i,minY:Math.min(t.y1,t.y2)-i,maxX:Math.max(t.x1,t.x2)+i,maxY:Math.max(t.y1,t.y2)+i}}function le(e,t){return!(e.minX>t.maxX||t.minX>e.maxX||e.minY>t.maxY||t.minY>e.maxY)}function de(e,t,i,n,o,r,s,a){const c=o-e,l=(i+s)/2-Math.abs(c);if(0>=l)return null;const d=r-t,u=(n+a)/2-Math.abs(d);return u>0?u>l?{nx:se(c),ny:0,penetration:l}:{nx:0,ny:se(d),penetration:u}:null}function ue(e,t,i,n,o,r,s){const a=r/2,c=s/2;let l=e-re(e,n-a,n+a),d=t-re(t,o-c,o+c);const u=l*l+d*d;if(u>i*i)return null;if(te>=u){const r=Math.abs(e-(n-a)),s=Math.abs(e-(n+a)),u=Math.abs(t-(o-c)),h=Math.abs(t-(o+c)),p=Math.min(r,s,u,h);return p===r?(l=-1,d=0,{nx:l,ny:d,penetration:i+r}):p===s?(l=1,d=0,{nx:l,ny:d,penetration:i+s}):p===u?(l=0,d=-1,{nx:l,ny:d,penetration:i+u}):(l=0,d=1,{nx:l,ny:d,penetration:i+h})}const h=Math.sqrt(u);return{nx:l/h,ny:d/h,penetration:i-h}}function he(e,t){if("circle"===e.shape.type&&"circle"===t.shape.type)return function(e,t,i,n,o,r){const s=n-e,a=o-t,c=i+r,l=s*s+a*a;if(l>=c*c)return null;if(te>=l)return{nx:1,ny:0,penetration:c};const d=Math.sqrt(l);return{nx:s/d,ny:a/d,penetration:c-d}}(e.x,e.y,e.shape.radius,t.x,t.y,t.shape.radius);if("aabb"===e.shape.type&&"aabb"===t.shape.type)return de(e.x,e.y,e.shape.width,e.shape.height,t.x,t.y,t.shape.width,t.shape.height);if("circle"===e.shape.type&&"aabb"===t.shape.type){const i=ue(e.x,e.y,e.shape.radius,t.x,t.y,t.shape.width,t.shape.height);return i?{nx:-i.nx,ny:-i.ny,penetration:i.penetration}:null}return"aabb"===e.shape.type&&"circle"===t.shape.type?ue(t.x,t.y,t.shape.radius,e.x,e.y,e.shape.width,e.shape.height):null}function pe(e,t){const i=t.shape;return"aabb"===i.type?"circle"===e.shape.type?ue(e.x,e.y,e.shape.radius,i.x,i.y,i.width,i.height):de(i.x,i.y,i.width,i.height,e.x,e.y,e.shape.width,e.shape.height):function(e,t,i,n,o,r,s,a=0){const c=r-n,l=s-o,d=c*c+l*l,u=d>te?re(((e-n)*c+(t-o)*l)/d,0,1):0,h=i+a/2,p=e-(n+c*u),m=t-(o+l*u),y=p*p+m*m;if(y>=h*h)return null;if(te>=y){const e=Math.sqrt(d);return e>te?{nx:-l/e,ny:c/e,penetration:h}:{nx:1,ny:0,penetration:h}}const f=Math.sqrt(y);return{nx:p/f,ny:m/f,penetration:h-f}}(e.x,e.y,"circle"===e.shape.type?e.shape.radius:Math.sqrt(e.shape.width*e.shape.width+e.shape.height*e.shape.height)/2,i.x1,i.y1,i.x2,i.y2,i.thickness??0)}function me(e,t){return`${e}\0${t}`}function ye(e){const t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}function fe(e){return{id:e.id,x:e.x,y:e.y,prevX:e.prevX,prevY:e.prevY,vx:e.vx,vy:e.vy,angle:e.angle,mass:e.mass,bodyCollisions:e.bodyCollisions,shape:ne(e.shape),sleeping:e.sleeping,datum:e.datum,index:e.index,sleepTime:e.sleepTime,restitution:e.restitution,friction:e.friction}}function ge(e){return e&&"function"!=typeof e?{property:e.property,equals:e.equals,notEquals:e.notEquals,oneOf:e.oneOf?.slice(),notOneOf:e.notOneOf?.slice()}:e}function be(e){return{id:e.id,shape:oe(e.shape),sensor:e.sensor,restitution:e.restitution,friction:e.friction,bodyFilter:ge(e.bodyFilter),index:e.index}}function xe(e,t){return!!t?.some(t=>Object.is(e,t))}function ve(e,t){const i=e.bodyFilter;if(!i)return!0;if("function"==typeof i)return i(t);const n=function(e,t){if(!t)return;let i=e;for(const e of t.split(".")){if(null==i||"object"!=typeof i)return;i=i[e]}return i}(t,i.property);return!("equals"in i&&!Object.is(n,i.equals)||"notEquals"in i&&Object.is(n,i.notEquals)||i.oneOf&&!xe(n,i.oneOf)||i.notOneOf&&xe(n,i.notOneOf))}var we=class{constructor(t={}){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={...ee,...t},this.random=e(this.options.seed)}init(t={}){this.options={...ee,...t},this.random=e(this.options.seed),this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors.clear(),this.lastEvents=[],this.nextBodyIndex=0,this.nextColliderIndex=0,this.nextSpringIndex=0}spawn(e){const t={id:e.id,x:e.x,y:e.y,prevX:e.x,prevY:e.y,vx:e.vx??0,vy:e.vy??0,angle:e.angle??0,mass:Math.max(te,e.mass??1),bodyCollisions:e.bodyCollisions??!0,shape:ne(e.shape),sleeping:!1,datum:e.datum,restitution:e.restitution,friction:e.friction,index:this.nextBodyIndex,sleepTime:0};this.nextBodyIndex+=1,this.bodies.set(e.id,t)}remove(e){for(const t of e){this.bodies.delete(t);for(const e of Array.from(this.activeSensors))ye(e).bodyId===t&&this.activeSensors.delete(e)}}setColliders(e){this.colliders.clear(),this.activeSensors.clear(),this.nextColliderIndex=0;for(const t of e)this.colliders.set(t.id,{...t,shape:oe(t.shape),bodyFilter:ge(t.bodyFilter),index:this.nextColliderIndex}),this.nextColliderIndex+=1}setConstraint(e){const t=e.id??"spring-"+this.nextSpringIndex;return this.springs.set(t,{id:t,bodyId:e.bodyId,target:e.target,restLength:e.restLength??0,stiffness:e.stiffness??40,damping:e.damping??3}),this.nextSpringIndex+=1,t}removeConstraint(e){this.springs.delete(e)}applyImpulse(e,t,i){const n=this.bodies.get(e);n&&(n.vx+=t/n.mass,n.vy+=i/n.mass,this.wake(n))}step(e=this.options.fixedDt){const t=Math.max(0,e);if(this.lastEvents=[],0===t)return;const i=this.sortedBodies();for(const e of i)e.prevX=e.x,e.prevY=e.y;this.applySprings(t);const n=this.options.maxVelocity;for(const e of i)if(!e.sleeping){if(e.vx+=this.options.gravity.x*t,e.vy+=this.options.gravity.y*t,e.vx*=this.options.velocityDamping,e.vy*=this.options.velocityDamping,n>0){const t=Math.sqrt(e.vx*e.vx+e.vy*e.vy);if(t>n){const i=n/t;e.vx*=i,e.vy*=i}}e.x+=e.vx*t,e.y+=e.vy*t}this.supportedThisStep.clear();const o=this.bodyPairKeys(i),r=this.sortedColliders().filter(e=>!e.sensor);for(let e=0;this.options.collisionIterations>e;e+=1)this.resolveBodyPairs(i,o,0===e),this.resolveColliders(i,r,0===e);this.updateSensors(i),this.updateSleeping(i,t)}settle(e=1200,t=this.options.fixedDt){let i=0;for(;e>i&&!this.allSleeping();)this.step(t),i+=1;return i}readState(e=[]){e.length=0;for(const t of this.sortedBodies())e.push({id:t.id,x:t.x,y:t.y,prevX:t.prevX,prevY:t.prevY,vx:t.vx,vy:t.vy,angle:t.angle,mass:t.mass,shape:ne(t.shape),sleeping:t.sleeping,datum:t.datum});return e}events(){return this.lastEvents.slice()}activeSensorPairs(){return Array.from(this.activeSensors).sort().map(ye)}allSleeping(){for(const e of this.bodies.values())if(!e.sleeping)return!1;return!0}snapshot(){return{options:{...this.options,gravity:{...this.options.gravity}},bodies:this.sortedBodies().map(fe),colliders:this.sortedColliders().map(be),springs:Array.from(this.springs.values()).map(e=>({...e,target:{...e.target}})),activeSensors:Array.from(this.activeSensors).sort()}}restore(t){this.options={...t.options,gravity:{...t.options.gravity}},this.random=e(this.options.seed),this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors=new Set(t.activeSensors),this.lastEvents=[],this.nextBodyIndex=0;for(const e of t.bodies){const t=fe(e);this.bodies.set(t.id,t),this.nextBodyIndex=Math.max(this.nextBodyIndex,t.index+1)}this.nextColliderIndex=0;for(const e of t.colliders){const t=be(e);this.colliders.set(t.id,t),this.nextColliderIndex=Math.max(this.nextColliderIndex,t.index+1)}this.nextSpringIndex=0;for(const e of t.springs){this.springs.set(e.id,{...e,target:{...e.target}});const t=/^spring-(\d+)$/.exec(e.id);t&&(this.nextSpringIndex=Math.max(this.nextSpringIndex,Number(t[1])+1))}}dispose(){this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors.clear(),this.lastEvents=[]}sortedBodies(){return Array.from(this.bodies.values()).sort((e,t)=>e.index-t.index)}sortedColliders(){return Array.from(this.colliders.values()).sort((e,t)=>e.index-t.index)}applySprings(e){for(const t of Array.from(this.springs.values()).sort((e,t)=>e.id.localeCompare(t.id))){const i=this.bodies.get(t.bodyId);if(!i||i.sleeping)continue;const n="point"===t.target.type?t.target:this.bodies.get(t.target.bodyId);if(!n)continue;const o=n.x-i.x,r=n.y-i.y,s=Math.sqrt(o*o+r*r);if(te>=s)continue;const a=o/s,c=r/s,l=(s-t.restLength)*t.stiffness+((("vx"in n?n.vx:0)-i.vx)*a+(("vy"in n?n.vy:0)-i.vy)*c)*t.damping;i.vx+=l*a*e/i.mass,i.vy+=l*c*e/i.mass}}resolveBodyPairs(e,t,i){for(const n of t){const[t,o]=n.split(":").map(Number),r=e[t],s=e[o];if(!r||!s)continue;const a=he(r,s);a&&(this.resolveDynamicCollision(r,s,a),i&&this.lastEvents.push({type:"contact",bodyId:r.id,otherId:s.id,sensor:!1}))}}bodyPairKeys(e){const t=Math.max(1,this.options.cellSize),i=new Map;for(let n=0;e.length>n;n+=1){if(!1===e[n].bodyCollisions)continue;const o=ae(e[n]),r=Math.floor(o.minX/t),s=Math.floor(o.maxX/t),a=Math.floor(o.minY/t),c=Math.floor(o.maxY/t);for(let e=r;s>=e;e+=1)for(let t=a;c>=t;t+=1){const o=`${e}:${t}`,r=i.get(o);r?r.push(n):i.set(o,[n])}}const n=new Set;for(const t of Array.from(i.keys()).sort()){const o=i.get(t)??[];o.sort((e,t)=>e-t);for(let t=0;o.length>t;t+=1)for(let i=t+1;o.length>i;i+=1){const r=o[t],s=o[i];!1!==e[r].bodyCollisions&&!1!==e[s].bodyCollisions&&le(ae(e[r]),ae(e[s]))&&n.add(`${r}:${s}`)}}return Array.from(n).sort((e,t)=>{const[i,n]=e.split(":").map(Number),[o,r]=t.split(":").map(Number);return i===o?n-r:i-o})}resolveDynamicCollision(e,t,i){e.sleeping&&this.supportedThisStep.add(t.id),t.sleeping&&this.supportedThisStep.add(e.id);const n=e.sleeping?0:1/e.mass,o=t.sleeping?0:1/t.mass,r=n+o;if(te>=r)return;const s=Math.max(0,i.penetration-ie)/r;e.x-=i.nx*s*n,e.y-=i.ny*s*n,t.x+=i.nx*s*o,t.y+=i.ny*s*o;const a=(t.vx-e.vx)*i.nx+(t.vy-e.vy)*i.ny;if(a>0)return;const c=Math.abs(a),l=-(1+Math.min(e.restitution??this.options.restitution,t.restitution??this.options.restitution))*a/r,d=l*i.nx,u=l*i.ny;e.vx-=d*n,e.vy-=u*n,t.vx+=d*o,t.vy+=u*o,this.applyFriction(e,t,i,l,n,o),c>this.options.contactWakeSpeed&&(this.wake(e),this.wake(t))}applyFriction(e,t,i,n,o,r){const s=-i.ny,a=i.nx,c=(t.vx-e.vx)*s+(t.vy-e.vy)*a,l=o+r;if(te>=Math.abs(c)||te>=l)return;const d=Math.max(0,Math.min(1,Math.max(e.friction??this.options.friction,t.friction??this.options.friction))),u=re(-c/l,-n*d,n*d),h=u*s,p=u*a;e.vx-=h*o,e.vy-=p*o,t.vx+=h*r,t.vy+=p*r}resolveColliders(e,t,i){for(const n of e)for(const e of t){if(!ve(e,n))continue;if(!le(ae(n),ce(e)))continue;const t=pe(n,e);t&&(this.resolveStaticCollision(n,e,t),this.supportedThisStep.add(n.id),i&&this.lastEvents.push({type:"contact",bodyId:n.id,otherId:e.id,sensor:!1}))}}resolveStaticCollision(e,t,i){e.x+=i.nx*Math.max(0,i.penetration-ie),e.y+=i.ny*Math.max(0,i.penetration-ie);const n=e.vx*i.nx+e.vy*i.ny;if(0>n){const o=Math.min(e.restitution??this.options.restitution,t.restitution??this.options.restitution);e.vx-=(1+o)*n*i.nx,e.vy-=(1+o)*n*i.ny;const r=-i.ny,s=i.nx,a=e.vx*r+e.vy*s,c=Math.max(0,Math.min(1,Math.max(e.friction??this.options.friction,t.friction??this.options.friction)));e.vx-=a*r*c,e.vy-=a*s*c}}updateSensors(e){const t=new Set,i=this.sortedColliders().filter(e=>e.sensor);for(const n of e){const e=ae(n);for(const o of i){if(!ve(o,n))continue;if(!le(e,ce(o)))continue;if(!pe(n,o))continue;const i=me(o.id,n.id);t.add(i),this.activeSensors.has(i)||this.lastEvents.push({type:"sensor-enter",bodyId:n.id,sensorId:o.id})}}for(const e of Array.from(this.activeSensors).sort()){if(t.has(e))continue;const{sensorId:i,bodyId:n}=ye(e);this.lastEvents.push({type:"sensor-exit",bodyId:n,sensorId:i})}this.activeSensors=t}updateSleeping(e,t){const i=Math.hypot(this.options.gravity.x,this.options.gravity.y)>1;for(const n of e)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*t||i&&!this.supportedThisStep.has(n.id)?n.sleeping?this.wake(n):n.sleepTime=0:(n.sleepTime+=t,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(e){e.sleeping&&this.lastEvents.push({type:"wake",bodyId:e.id}),e.sleeping=!1,e.sleepTime=0}nextRandom(){return this.random()}},ke=class{constructor(e={}){this.id="builtin",this.capabilities={...(new we).capabilities,engine:"builtin"},this.world=new we(e)}init(e={}){this.world.init(e)}spawn(e){this.world.spawn(e)}remove(e){this.world.remove(e)}setColliders(e){this.world.setColliders(e)}setConstraint(e){return this.world.setConstraint(e)}removeConstraint(e){this.world.removeConstraint(e)}applyImpulse(e,t,i){this.world.applyImpulse(e,t,i)}step(e){this.world.step(e)}settle(e,t){return this.world.settle(e,t)}readState(e){return this.world.readState(e)}events(){return this.world.events()}activeSensorPairs(){return this.world.activeSensorPairs()}allSleeping(){return this.world.allSleeping()}snapshot(){return this.world.snapshot()}restore(e){this.world.restore(e)}nextRandom(){return this.world.nextRandom()}dispose(){this.world.dispose()}};function Me(e={}){return new ke(e)}function Se(e,t={}){return e?"function"==typeof e?e(t):(e.init(t),e):Me(t)}var Ie=["binId","targetBin","category","windowIndex","lane","group"];function Ae(e,t){if(!Number.isFinite(t))return;e.count+=1,e.total+=t,e.min=Math.min(e.min,t),e.max=Math.max(e.max,t);const i=t-e.mean;e.mean+=i/e.count,e.m2+=i*(t-e.mean)}function Pe(e){return{count:e.count,total:e.total,mean:e.count>0?e.mean:0,min:e.count>0?e.min:0,max:e.count>0?e.max:0,variance:e.count>1?e.m2/(e.count-1):0}}function Ce(e){return{count:e.count,total:e.total,mean:e.mean,m2:e.variance*Math.max(0,e.count-1),min:e.count>0?e.min:1/0,max:e.count>0?e.max:-1/0}}function Re(e,t){if(null!=e[t])return e[t];const i=e.datum;return i&&"object"==typeof i?i[t]:void 0}function Be(e,t,i){return"function"==typeof e?e(t,i):"string"==typeof e?Re(t,e):void 0}function je(e){if(null==e)return;const t=e+"";return t.trim()?t:void 0}function Te(e){const t=Pe(e.value);return{id:e.id,label:e.label,count:t.count,total:t.total,bodyIds:e.bodyIds.slice(),lastBodyId:e.lastBodyId,lastDatum:e.lastDatum,x:Pe(e.x),y:Pe(e.y),value:t}}var Ne=class{constructor(e=!1){this.bins=new Map,this.nextIndex=0,this.config=e}updateConfig(e){void 0!==e&&(this.config=e,!1===e&&this.clear())}isEnabled(){return!1!==this.config}add(e){if(!1===this.config)return null;const t=this.nextIndex;this.nextIndex+=1;const i=je(Be(this.config.binAccessor,e,t))??function(e){for(const t of Ie){const i=je(Re(e,t));if(i)return i}return"sediment"}(e),n=je(Be(this.config.labelAccessor,e,t))??i,o=function(e,t,i){if("number"==typeof e)return e;const n="function"==typeof e?e(t,i):"string"==typeof e?Re(t,e):1,o="number"==typeof n?n:Number(n);return Number.isFinite(o)?o:1}(this.config.valueAccessor,e,t),r=Math.max(0,Math.floor(this.config.retainBodyIds??12));let s=this.bins.get(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=e.id,s.lastDatum=e.datum,Ae(s.x,e.x),Ae(s.y,e.y),Ae(s.value,o),r>0&&(s.bodyIds.push(e.id),s.bodyIds.length>r&&(s.bodyIds=s.bodyIds.slice(s.bodyIds.length-r))),Te(s)}clear(){this.bins.clear(),this.nextIndex=0}snapshot(){return Array.from(this.bins.values()).map(Te)}restore(e=[]){this.bins.clear();for(const t of e)this.bins.set(t.id,{id:t.id,label:t.label,bodyIds:t.bodyIds.slice(),lastBodyId:t.lastBodyId,lastDatum:t.lastDatum,x:Ce(t.x),y:Ce(t.y),value:Ce(t.value)});this.nextIndex=e.reduce((e,t)=>e+t.count,0)}totals(){const e=this.snapshot();return{bins:e.length,count:e.reduce((e,t)=>e+t.count,0),total:e.reduce((e,t)=>e+t.total,0)}}};function Oe(e,t={}){const{baselineY:i=0,binWidth:n=24,gap:o=2,maxHeight:r=80,value:s="count",x:a}=t,c=Math.max(1,...e.map(e=>e[s]));return e.map((e,t)=>{const l=Math.max(0,e[s]/c*r),d=a?.(e,t)??t*(n+o);return{binId:e.id,label:e.label,index:t,count:e.count,total:e.total,x:d,y:i-l,width:n,height:l,meanX:e.x.mean,meanY:e.y.mean}})}function Ee(e){const t=Number(e);if(Number.isFinite(t)&&t>0)return Math.floor(t)}function $e(e){const t=Math.max(0,Math.floor(e.liveBodies)),i=Math.max(0,Math.floor(e.queuedBodies??0)),n=t+i,o=Ee(e.bodyLimit),r=Ee(e.engineMaxBodiesHint),s=function(e,t,i){if(!1===i)return;const n=Ee(i?.warnAt);return null!=n?n:null!=e?Math.max(1,Math.floor(.8*e)):null!=t?Math.max(1,Math.floor(.8*t)):void 0}(o,r,e.options),a=null==o?0:Math.max(0,t-o),c=a>0?"overflow":null==s||s>n?"ok":"warning";return{action:"overflow"!==c?"continue":e.sedimentEnabled?"sediment":e.evictionEnabled?"evict":"retain",bodyLimit:o,engineMaxBodiesHint:r,liveBodies:t,overflow:a,projectedBodies:n,queuedBodies:i,state:c,warnAt:s}}var qe={bodyLimit:1/0,eviction:"oldest",fixedDt:1/120,maxDeltaSeconds:.1,maxSubsteps:8,settleStepLimit:1200,timeScale:1},We={chartId:"physics",chartType:"physics",sensors:{},onObservation:void 0,onSimulationStateChange:void 0};function Fe(e={},t=We){return{chartId:e.chartId??t.chartId,chartType:e.chartType??t.chartType,sensors:e.sensors??t.sensors,onObservation:e.onObservation??t.onObservation,onSimulationStateChange:e.onSimulationStateChange??t.onSimulationStateChange}}function De(e){return{...e,shape:{...e.shape},datum:e.datum,springs:e.springs?.map(e=>({...e,target:{...e.target}}))}}function ze(e){if(e instanceof Date){const t=e.getTime();return Number.isFinite(t)?t:void 0}const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:void 0}function Ye(e,t){if(null!=e[t])return e[t];const i=e.datum;return i&&"object"==typeof i?i[t]:void 0}function Le(e){return{...De(e),sequence:e.sequence,spawnAt:e.spawnAt}}function He(e){return e.map(e=>({...e,shape:{...e.shape},bodyFilter:e.bodyFilter&&"function"!=typeof e.bodyFilter?{...e.bodyFilter,oneOf:e.bodyFilter.oneOf?.slice(),notOneOf:e.bodyFilter.notOneOf?.slice()}:e.bodyFilter}))}function Xe(e){return!1!==e&&{...e}}function _e(e,t){return e.spawnAt===t.spawnAt?e.sequence-t.sequence:e.spawnAt-t.spawnAt}function Ge(e){return{...e,gravity:{...e.gravity}}}function Ve(e,t,i,n){if("circle"===e.shape.type){const o=e.x-t,r=e.y-i,s=e.shape.radius+n,a=o*o+r*r;return a>s*s?null:a}const o=Math.max(Math.abs(t-e.x)-e.shape.width/2,0),r=Math.max(Math.abs(i-e.y)-e.shape.height/2,0),s=o*o+r*r;return s>n*n?null:s}function Ue(e){const t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}function Ke(e,t={}){const{idPrefix:i="plot",includeFloor:n=!0,includeCeiling:o=!1,includeLeftWall:r=!0,includeRightWall:s=!0,wallThickness:a=20,floorThickness:c=a}=t,l=[],d=e.x+e.width/2,u=e.y+e.height/2;return n&&l.push({id:i+"-floor",shape:{type:"aabb",x:d,y:e.y+e.height+c/2,width:e.width+2*a,height:c}}),o&&l.push({id:i+"-ceiling",shape:{type:"aabb",x:d,y:e.y-c/2,width:e.width+2*a,height:c}}),r&&l.push({id:i+"-left-wall",shape:{type:"aabb",x:e.x-a/2,y:u,width:a,height:e.height+2*c}}),s&&l.push({id:i+"-right-wall",shape:{type:"aabb",x:e.x+e.width+a/2,y:u,width:a,height:e.height+2*c}}),l}function Qe(e){const{idPrefix:t="bin",count:i,domainStart:n,domainStep:o,xScale:r,yTop:s,yBottom:a,wallThickness:c=4,includeBoundaryWalls:l=!0,includeInteriorWalls:d=!0,closedBefore:u,lidY:h=s,lidThickness:p=Math.max(2,c)}=e,m=[],y=s+(a-s)/2,f=Math.abs(a-s),g=l?i:i-1;if(d||l)for(let e=l?0:1;g>=e;e+=1){if(!d&&e>0&&i>e)continue;const s=r(n+e*o);m.push({id:`${t}-wall-${e}`,shape:{type:"aabb",x:s,y:y,width:c,height:f}})}if(null!=u)for(let e=0;i>e;e+=1){const i=n+e*o,s=i+o;if(s>=u)continue;const a=r(i),l=r(s);m.push({id:`${t}-lid-${e}`,shape:{type:"segment",x1:Math.min(a,l)+c/2,y1:h,x2:Math.max(a,l)-c/2,y2:h,thickness:p}})}return m}import{quadtree as Ze}from"d3-quadtree";var Je=class{constructor(){this.maxSearchRadius=0,this.revision=-1,this.tree=null}hitTest(e,t,i,n,o,r=0){const s=this.ensure(e,t);if(!s)return null;let a=null,c=1/0;const l=Math.max(0,r)+this.maxSearchRadius,d=n-l,u=n+l,h=o-l,p=o+l;return s.visit((e,t,s,l,m)=>{if(d>l||t>u||h>m||s>p)return!0;if(e.length)return!1;let y=e;for(;y;){const e=y.data;if(e){const t=Ve(e,n,o,Math.max(0,r));null!=t&&(c>t||t===c&&i.indexOf(e.id)>i.indexOf(a?.id??""))&&(a=e,c=t)}y=y.next}return!1}),a}ensure(e,t){if(this.tree&&this.revision===t)return this.tree;const i=e.readState();return 0===i.length?(this.tree=null,this.maxSearchRadius=0,this.revision=t,null):(this.maxSearchRadius=i.reduce((e,t)=>Math.max(e,function(e){return"circle"===e.shape.type?e.shape.radius:Math.hypot(e.shape.width,e.shape.height)/2}(t)),0),this.tree=Ze().x(e=>e.x).y(e=>e.y).addAll(i),this.revision=t,this.tree)}},et=["data","scene-geometry","data-paint","accessibility","evidence"],tt=["scene-geometry","data-paint","accessibility","evidence"],it=["overlay","accessibility","evidence"],nt=(e,t)=>({retainedData:e,invalidations:t}),ot=["layout","scene-geometry","data-paint","overlay","accessibility","evidence"],rt=["scene-geometry","data-paint","accessibility","evidence"],st=[],at={engine:nt("rebuild",["scene-geometry","data-paint","accessibility","evidence"]),kernel:nt("preserve",rt),colliders:nt("preserve",rt),sediment:nt("preserve",rt),bodyBudget:nt("preserve",ot),bodyLimit:nt("preserve",ot),eviction:nt("preserve",ot),fixedDt:nt("preserve",st),maxDeltaSeconds:nt("preserve",st),maxSubsteps:nt("preserve",st),settleStepLimit:nt("preserve",st),timeScale:nt("preserve",st),observation:nt("preserve",st)},ct=nt("preserve",ot);function lt(e){let t="preserve";const i=new Set;for(const n of e){const e=at[n]??ct;"rebuild"===e.retainedData&&(t="rebuild");for(const t of e.invalidations)i.add(t)}return{retainedData:t,invalidations:i}}var dt=["seed","fixedDt","cellSize","collisionIterations","velocityDamping","sleepSpeed","sleepAfter","restitution","friction","maxVelocity","contactWakeSpeed"];function ut(e,t){return e===t||!(!e||!t)&&e.gravity?.x===t.gravity?.x&&e.gravity?.y===t.gravity?.y&&dt.every(i=>e[i]===t[i])}function ht(e,t,i,n){return e||!t?"paused":i||!n?"running":"settled"}var pt=class{constructor(e={}){this.activeSensorPairs=new Set,this.accumulator=0,this.bodyBudgetObservationKey="ok",this.bodySpatialIndex=new Je,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;const{bodyBudget:t,colliders:i,engine:n,kernel:o,observation:r,sediment:s,...a}=e;this.config={...qe,...a},this.configInput={...e},this.bodyBudget=t??{},this.engineInput=n,this.observation=Fe(r),this.sediment=new Ne(s??!1),this.world=Se(n,{fixedDt:this.config.fixedDt,...o}),i&&this.world.setColliders(He(i))}updateConfig(e){const t=function(e,t){return Object.keys(e).filter(i=>"kernel"===i?!ut(e.kernel,t.kernel):e[i]!==t[i])}(e,this.configInput),{colliders:i,bodyBudget:n,engine:o,kernel:r,observation:s,sediment:a,...c}=e;if(this.config={...this.config,...c},void 0!==n&&(this.bodyBudget=n,!1===n&&(this.bodyBudgetObservationKey="ok")),o&&o!==this.engineInput){const e=this.world.snapshot();this.world.dispose(),this.engineInput=o,this.world=Se(o,e.options),this.world.restore(e),this.revision+=1}if(r&&!ut(r,this.configInput.kernel)){const e=this.world.snapshot(),t={...e.options,...r,gravity:{...e.options.gravity,...r.gravity}};this.world.restore({...e,options:t}),this.revision+=1}s&&(this.observation=Fe(s,this.observation)),this.sediment.updateConfig(a),i&&(this.world.setColliders(He(i)),this.revision+=1),this.configInput={...this.configInput,...e};const l=lt(t);this.updateResults.record({kind:"config",keys:t},l.invalidations)}updateConfigWithResult(e){return this.updateConfig(e),this.updateResults.last}setColliders(e){this.world.setColliders(He(e)),this.revision+=1,this.updateResults.record({kind:"config",keys:["colliders"]},lt(["colliders"]).invalidations)}enqueue(e,t){const i=Array.isArray(e)?e:[e],n=t?function(e,t={}){const i=ze(t.startAt)??0,n=t.pacing??"immediate";if("arrival"===n){const n=e.map((e,i)=>function(e,t,i){return"function"==typeof i?ze(i(e,t)):"string"==typeof i?ze(Ye(e,i)):ze(e.spawnAt)??ze(Ye(e,"arrivalTime"))??ze(Ye(e,"timestamp"))??ze(Ye(e,"time"))??ze(Ye(e,"eventTime"))}(e,i,t.timeAccessor)),o=n.filter(e=>null!=e),r=o.length>0?Math.min(...o):0,s=ze(t.timeScale)??1,a=s>0?s:1;return e.map((e,t)=>{const o=n[t],s=null==o?0:Math.max(0,o-r);return{...De(e),spawnAt:i+s/a}})}if("object"==typeof n){const t=ze(n.ratePerSec);if(t&&t>0)return e.map((e,n)=>({...De(e),spawnAt:i+n/t}))}return e.map(e=>({...De(e),spawnAt:i}))}(i,{...t,startAt:t.startAt??this.elapsedSeconds}):i;for(const e of n)this.queue.push({...De(e),sequence:this.nextSequence,spawnAt:e.spawnAt??this.elapsedSeconds}),this.nextSequence+=1;this.queue.sort(_e),n.length>0&&(this.revision+=1),this.updateResults.record({kind:"enqueue",count:n.length},n.length?et:[])}enqueueWithResult(e,t){return this.enqueue(e,t),this.updateResults.last}spawnNow(e){this.spawnOne(De(e)),this.nextSequence+=1,this.observeBodyBudget(),this.evictOverflow(),this.revision+=1,this.updateResults.record({kind:"enqueue",count:1},et)}clear(){const e=this.world.snapshot().options;this.world.init({...e,fixedDt:this.config.fixedDt}),this.activeSensorPairs.clear(),this.liveBodyOrder=[],this.queue=[],this.accumulator=0,this.elapsedSeconds=0,this.nextSequence=0,this.sediment.clear(),this.bodyBudgetObservationKey="ok",this.revision+=1,this.syncSimulationState(),this.updateResults.record({kind:"clear"},et)}tick(e){const t=this.revision,i=[],n=[],o=[],r=[],s=[];if(this.paused||!this.visible){const e=this.result(0,i,n,o,r,s,!1);return this.updateResults.record({kind:"tick",count:0},[]),e}const a=Math.max(0,Math.min(e,this.config.maxDeltaSeconds))*this.config.timeScale;this.elapsedSeconds+=a,this.spawnDue(i,s);const c=this.observeBodyBudget(s),l=this.evictOverflow(s);n.push(...l.evicted),o.push(...l.sedimented),this.syncSimulationState(s),this.accumulator+=a;let d=0;for(;this.accumulator>=this.config.fixedDt&&this.config.maxSubsteps>d;){this.world.step(this.config.fixedDt);const e=this.world.events();r.push(...e),this.observeKernelEvents(e,s),this.observeSensorTransitions(s),this.accumulator-=this.config.fixedDt,d+=1}d===this.config.maxSubsteps&&(this.accumulator=Math.min(this.accumulator,this.config.fixedDt)),(d>0||i.length>0||n.length>0||o.length>0||r.length>0)&&(this.revision+=1);const u=this.result(d,i,n,o,r,s,void 0,c);return this.updateResults.record({kind:"tick",count:d},this.revision!==t?i.length||n.length||o.length?et:tt:[]),u}settle(e=this.config.settleStepLimit){const t=this.revision;this.spawnDue([],[]);const i=this.world.settle(e,this.config.fixedDt);return i>0&&(this.revision+=1),this.syncSimulationState(),this.updateResults.record({kind:"settle",count:i},this.revision!==t?tt:[]),i}settleWithObservations(e=this.config.settleStepLimit){const t=this.revision,i=[],n=[],o=[],r=[],s=[];if(this.paused||!this.visible){const e=this.result(0,i,n,o,r,s,!1);return this.updateResults.record({kind:"settle",count:0},[]),e}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 l=0;for(;e>l&&!this.world.allSleeping();){this.world.step(this.config.fixedDt);const e=this.world.events();r.push(...e),this.observeKernelEvents(e,s),this.observeSensorTransitions(s),l+=1}(l>0||i.length>0||n.length>0||o.length>0||r.length>0)&&(this.revision+=1);const d=this.result(l,i,n,o,r,s,void 0,a);return this.updateResults.record({kind:"settle",count:l},this.revision!==t?i.length||n.length||o.length?et:tt:[]),d}readBodies(e=[]){return this.world.readState(e)}readSediment(){return this.sediment.snapshot()}bodyBudgetStatus(){return this.evaluateBodyBudget()}sedimentTotals(){return this.sediment.totals()}sedimentHeightfield(e={}){return Oe(this.readSediment(),e)}hitTest(e,t,i=0){return this.bodySpatialIndex.hitTest(this.world,this.revision,this.liveBodyOrder,e,t,i)}events(){return this.world.events()}allSleeping(){return this.world.allSleeping()}hasPendingWork(){return this.queue.length>0||!this.world.allSleeping()}queueSize(){return this.queue.length}liveBodyCount(){return this.liveBodyOrder.length}elapsed(){return this.elapsedSeconds}recordObservation(e){const{timestamp:t,chartType:i,chartId:n,...o}=e,r={...o,timestamp:t??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(e){return this.updateResults.subscribe(e)}version(){return this.revision}setPaused(e){const t=this.paused!==e;this.paused=e,this.syncSimulationState(),this.updateResults.record({kind:"pause"},t?it:[])}setVisible(e){const t=this.visible!==e;this.visible=e,this.syncSimulationState(),this.updateResults.record({kind:"visibility"},t?it:[])}remove(e){const t=new Set(e),i=new Set(this.liveBodyOrder),n=new Set(this.queue.map(e=>e.id));this.queue=this.queue.filter(e=>!t.has(e.id)),this.liveBodyOrder=this.liveBodyOrder.filter(e=>!t.has(e)),this.world.remove(e),this.removeActiveSensorPairsForBodies(t);const o=e.filter(e=>i.has(e)||n.has(e));return o.length>0&&(this.revision+=1,this.syncSimulationState()),this.updateResults.record({kind:"remove",keys:o,count:o.length},o.length?et:[]),o}setConstraint(e){const t=this.world.setConstraint(e);return this.revision+=1,this.updateResults.record({kind:"constraint",keys:[t]},tt),t}removeConstraint(e){this.world.removeConstraint(e),this.revision+=1,this.updateResults.record({kind:"constraint",keys:[e]},tt)}applyImpulse(e,t,i){this.world.applyImpulse(e,t,i),this.revision+=1,this.updateResults.record({kind:"impulse",keys:[e]},tt)}nextRandom(){return this.world.nextRandom()}controls(){return e=this,{applyImpulse:(t,i,n)=>e.applyImpulse(t,i,n),clear:()=>e.clear(),hitTest:(t,i,n)=>e.hitTest(t,i,n),pause:()=>e.setPaused(!0),push:(t,i)=>e.enqueue(t,i),pushMany:(t,i)=>e.enqueue(t,i),bodyBudgetStatus:()=>e.bodyBudgetStatus(),readBodies:t=>e.readBodies(t),readSediment:()=>e.readSediment(),recordObservation:t=>e.recordObservation(t),remove:t=>e.remove(t),restore:t=>e.restore(t),resume:()=>e.setPaused(!1),settle:t=>e.settle(t),settleWithObservations:t=>e.settleWithObservations(t),snapshot:()=>e.snapshot(),sedimentHeightfield:t=>e.sedimentHeightfield(t),sedimentTotals:()=>e.sedimentTotals(),step:t=>e.tick(t)};var e}snapshot(){const e=this.world.snapshot();return{accumulator:this.accumulator,activeSensorPairs:Array.from(this.activeSensorPairs).sort(),bodyBudget:Xe(this.bodyBudget),config:{...this.config,kernel:Ge(e.options)},elapsedSeconds:this.elapsedSeconds,paused:this.paused,queue:this.queue.map(Le),revision:this.revision,sediment:this.readSediment(),simulationState:this.simulationState,liveBodyOrder:this.liveBodyOrder.slice(),visible:this.visible,world:e}}restore(e){this.config={bodyLimit:e.config.bodyLimit,eviction:e.config.eviction,fixedDt:e.config.fixedDt,maxDeltaSeconds:e.config.maxDeltaSeconds,maxSubsteps:e.config.maxSubsteps,settleStepLimit:e.config.settleStepLimit,timeScale:e.config.timeScale},this.configInput={...e.config,bodyBudget:Xe(e.bodyBudget??{}),kernel:Ge(e.world.options)},this.bodyBudget=Xe(e.bodyBudget??{}),this.bodyBudgetObservationKey="ok",this.activeSensorPairs=new Set(e.activeSensorPairs),this.accumulator=e.accumulator,this.elapsedSeconds=e.elapsedSeconds,this.paused=e.paused,this.queue=e.queue.map(Le).sort(_e),this.revision=e.revision,this.sediment.restore(e.sediment??[]),this.simulationState=e.simulationState??ht(e.paused,e.visible,e.queue.length>0,e.world.bodies.every(e=>e.sleeping)),this.liveBodyOrder=e.liveBodyOrder.slice(),this.visible=e.visible,this.nextSequence=this.queue.reduce((e,t)=>Math.max(e,t.sequence),-1)+1,this.world.restore(e.world),this.updateResults.record({kind:"restore"},et)}spawnDue(e,t){for(;this.queue.length>0&&this.elapsedSeconds>=this.queue[0].spawnAt;){const i=this.queue.shift();if(!i)return;this.spawnOne(i,t),e.push(i.id)}}spawnOne(e,t){this.liveBodyOrder=this.liveBodyOrder.filter(t=>t!==e.id),this.removeActiveSensorPairsForBodies(new Set([e.id])),this.world.spawn(e),this.liveBodyOrder.push(e.id);for(const t of e.springs??[])this.world.setConstraint({...t,bodyId:e.id});const i=this.world.readState().find(t=>t.id===e.id);this.emitObservation({type:"physics-spawn",timestamp:this.elapsedSeconds,chartType:this.observation.chartType,chartId:this.observation.chartId,bodyId:e.id,datum:i?.datum??e.datum,x:i?.x??e.x,y:i?.y??e.y},t)}result(e,t,i,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||!c),sleeping:c,sedimented:n,spawned:t,steps:e}}observeKernelEvents(e,t){!function(e,t,i){if(0===t.length)return;const n=new Map(e.readState().map(e=>[e.id,e]));for(const e of t){if("sleep"!==e.type)continue;const t=n.get(e.bodyId);i.emit({type:"physics-settle",timestamp:i.elapsedSeconds,chartType:i.observation.chartType,chartId:i.observation.chartId,bodyId:e.bodyId,datum:t?.datum,x:t?.x,y:t?.y})}}(this.world,e,this.observationContext(t))}observeSensorTransitions(e){this.activeSensorPairs=function(e,t,i){const n=new Set(e.activeSensorPairs().map(e=>`${e.sensorId}\0${e.bodyId}`));if(0===n.size&&0===t.size)return n;const o=new Map(e.readState().map(e=>[e.id,e])),r=(e,t)=>{const{sensorId:n,bodyId:r}=Ue(t),s=i.observation.sensors[n],a=o.get(r);i.emit({type:"enter"===e?s?.enterType??"physics-bin-enter":s?.exitType??"physics-bin-exit",timestamp:i.elapsedSeconds,chartType:i.observation.chartType,chartId:i.observation.chartId,bodyId:r,datum:a?.datum,x:a?.x,y:a?.y,sensorId:n,binId:s?.binId??n})};for(const e of Array.from(n).sort())t.has(e)||r("enter",e);for(const e of Array.from(t).sort())n.has(e)||r("exit",e);return n}(this.world,this.activeSensorPairs,this.observationContext(e))}removeActiveSensorPairsForBodies(e){!function(e,t){for(const i of e)t.has(Ue(i).bodyId)&&e.delete(i)}(this.activeSensorPairs,e)}observationContext(e){return{elapsedSeconds:this.elapsedSeconds,observation:this.observation,emit:t=>this.emitObservation(t,e)}}emitObservation(e,t){t?.push(e),this.observation.onObservation?.(e)}evaluateBodyBudget(){return $e({bodyLimit:this.config.bodyLimit,engineMaxBodiesHint:this.world.capabilities.maxBodiesHint,evictionEnabled:!1!==this.config.eviction,liveBodies:this.liveBodyOrder.length,queuedBodies:this.queue.length,sedimentEnabled:this.sediment.isEnabled(),options:this.bodyBudget})}observeBodyBudget(e){const t=this.evaluateBodyBudget();if("ok"===t.state||!1===this.bodyBudget)return this.bodyBudgetObservationKey="ok",t;const i=`${t.state}:${t.action}`;return i===this.bodyBudgetObservationKey||(this.bodyBudgetObservationKey=i,this.emitObservation({type:"overflow"===t.state?"physics-budget-overflow":"physics-budget-warning",timestamp:this.elapsedSeconds,chartType:this.observation.chartType,chartId:this.observation.chartId,budgetAction:t.action,bodyLimit:t.bodyLimit,engineMaxBodiesHint:t.engineMaxBodiesHint,liveBodies:t.liveBodies,overflow:t.overflow,projectedBodies:t.projectedBodies,queuedBodies:t.queuedBodies,warnAt:t.warnAt},e)),t}syncSimulationState(e){const t=ht(this.paused,this.visible,this.queue.length>0,this.world.allSleeping());if(t===this.simulationState)return;const i=this.simulationState;this.simulationState=t,function(e,t,i){i.observation.onSimulationStateChange?.(t,e),"running"!==t&&"settled"!==t||i.emit({type:"running"===t?"sim-active":"sim-idle",timestamp:i.elapsedSeconds,chartType:i.observation.chartType,chartId:i.observation.chartId,simulationState:t,previousSimulationState:e})}(i,t,this.observationContext(e))}evictOverflow(e){if(!1===this.config.eviction)return{evicted:[],sedimented:[]};const t=Math.max(0,Math.floor(this.config.bodyLimit));if(!Number.isFinite(t))return{evicted:[],sedimented:[]};const i=this.liveBodyOrder.length-t;if(0>=i)return{evicted:[],sedimented:[]};const n=("sleeping-first"===this.config.eviction?this.sleepingFirstEvictionOrder():this.liveBodyOrder.slice()).slice(0,i);if(0===n.length)return{evicted:[],sedimented:[]};const o=this.absorbSediment(n,e);this.world.remove(n);const r=new Set(n);return this.liveBodyOrder=this.liveBodyOrder.filter(e=>!r.has(e)),this.removeActiveSensorPairsForBodies(r),{evicted:n,sedimented:o}}absorbSediment(e,t){const i=new Map(this.world.readState().map(e=>[e.id,e])),n=[];for(const o of e){const e=i.get(o);if(!e)continue;const r=this.sediment.add(e);r&&(n.push(o),this.emitObservation({type:"physics-sediment",timestamp:this.elapsedSeconds,chartType:this.observation.chartType,chartId:this.observation.chartId,bodyId:o,datum:e.datum,x:e.x,y:e.y,binId:r.id,count:r.count,total:r.total},t))}return n}sleepingFirstEvictionOrder(){const e=new Map(this.world.readState().map(e=>[e.id,e.sleeping])),t=[],i=[];for(const n of this.liveBodyOrder)e.get(n)?t.push(n):i.push(n);return[...t,...i]}};function mt(e,t){if("function"==typeof t){const i=t(e);return Number.isFinite(i)&&i>0?Number(i):1}const i=e.datum;if(t&&i&&"object"==typeof i){const e=Number(i[t]);if(Number.isFinite(e)&&e>0)return e}const n=Number(i?.work??i?.reviewWork??i?.value);return Number.isFinite(n)&&n>0?n:1}function yt(e,t){if("function"==typeof t){const i=t(e);if(null!=i&&(i+"").length>0)return i+""}else if(t){const i=gt(e.datum,t),n=gt(e,t),o=i??n;if(null!=o&&(o+"").length>0)return o+""}return e.id}function ft(e,t){if(0===e.length)return 0;if(1===e.length)return e[0];const i=Math.max(0,Math.min(1,t))*(e.length-1),n=Math.floor(i);return e[n]+(e[Math.ceil(i)]-e[n])*(i-n)}function gt(e,t){if(!t)return;let i=e;for(const e of t.split(".")){if(null==i||"object"!=typeof i)return;i=i[e]}return i}function bt(e,t){if(!t)return!0;if("function"==typeof t)return t(e);const i=gt(e,t.property);return!("equals"in t&&!Object.is(i,t.equals)||"notEquals"in t&&Object.is(i,t.notEquals)||t.oneOf&&!t.oneOf.some(e=>Object.is(i,e))||t.notOneOf&&t.notOneOf.some(e=>Object.is(i,e)))}function xt(e){const t=e.regionId,i=Math.max(0,e.unitsPerSecond),n=e.queueLayout??"lane",o=e.queueSlotSpacing??14,r=e.queueStiffness??.35,s=Number.isFinite(e.maxQueue)?Math.max(0,Math.floor(Number(e.maxQueue))):1/0,a=Math.max(.25,e.metricWindowSeconds??30),c=Math.max(1/60,e.snapshotIntervalSeconds??.25),l=e.releaseImpulse??{x:90,y:0},d=new Map,u=new Map,h=new Map,p=new Map,m=new Map,y=new Map,f=new Map,g=[];let b=0,x=new Map,v=new Map,w=0,k=0,M=0,S=null,I=0,A=0,P=0,C=0,R=0,B=0,j=0,T=0,N=0,O=0,E=0,$=0,q=-1,W=!1;function F(e,i){const n=i(e);return!!n&&n.activeRegionIds.includes(t)}function D(){$+=1}function z(e){return{bodyId:e.bodyId,jobId:e.jobId,visitId:e.visitId,visit:e.visit,regionId:t,work:e.total,queuedAt:e.queuedAt}}function Y(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 d.set(n.jobId,s),f.delete(i.id),y.set(i.id,n.jobId),A+=1,P+=n.work,D(),function(i,n,o){const r=z(n);e.onQueued?.(i,r),o.controls.recordObservation({type:"physics-capacity-queued",bodyId:i.id,datum:i.datum,x:i.x,y:i.y,regionId:t,work:n.total,jobId:n.jobId,visitId:n.visitId,visit:n.visit,queuedAt:n.queuedAt,queueDepth:d.size})}(i,s,o),s}function L(e){if(d.size>=s||0===u.size)return;const t=Array.from(u.values()).sort((e,t)=>e.sequence-t.sequence);for(const i of t){if(d.size>=s)break;const t=m.get(i.jobId);t&&h.has(i.jobId)?(u.delete(i.jobId),f.delete(i.bodyId),Y(t,i,e,i.sequence)):u.delete(i.jobId)}}function H(){let e=0;for(const t of d.values())e+=t.remaining;return e}function X(){N=Math.max(N,d.size),O=Math.max(O,H())}function _(){const e=M-a,t=Math.max(0,Math.min(a,M-(S??M)));let n=0,o=0,r=0,s=0,c=0;for(const t of g){if(e>t.end)continue;n+=t.arrivals,o+=t.arrivalWork,r+=t.completions,s+=t.completedWork;const i=t.end-t.start;c+=i>0&&e>t.start?t.processedWork*Math.min(1,Math.max(0,t.end-e)/i):t.processedWork}const l=t>0?o/t:0;return{seconds:t,arrivals:n,arrivalWork:o,completions:r,completedWork:s,processedWork:c,arrivalsPerSecond:t>0?n/t:0,throughputPerSecond:t>0?r/t:0,utilization:t>0&&i>0?Math.max(0,Math.min(1,c/(i*t))):0,pressure:i>0?l/i:0}}return{id:e.id??"capacity-queue:"+t,continuous:!1!==e.continuous,tick:n=>{const o=n.controls.readBodies(),r=new Map,A=new Map;for(const t of o){if(r.set(t.id,t),!F(t.id,n.getRegionState))continue;if(!bt(t,e.bodyFilter))continue;const i=yt(t,e.jobKey),o=A.get(i)??[];o.push(t),A.set(i,o)}const P=Number.isFinite(n.dt)?Math.max(0,n.dt):0;if(!W){const e=Number.isFinite(n.elapsed)?Math.max(0,n.elapsed):P;M=Math.max(0,e-P),W=!0}const N=M,O=N+P;M=O,S=null==S?N:Math.min(S,N);const $={start:N,end:O,arrivals:0,arrivalWork:0,completions:0,completedWork:0,processedWork:0},H=new Map;for(const[e,t]of A){const i=h.get(e)?.bodyId,n=t.find(e=>e.id===i)??t[0];H.set(e,n),m.set(e,n)}for(const[i,o]of h){if(H.has(i))continue;const s=d.get(i),a=r.get(o.bodyId)??m.get(i);if(s){d.delete(i),y.delete(s.bodyId),j+=1,T+=s.remaining,D();const r={...z(s),abandonedAt:M,remainingWork:s.remaining,queueSeconds:Math.max(0,M-s.queuedAt)};a&&e.onAbandoned?.(a,r),n.controls.recordObservation({type:"physics-capacity-abandoned",bodyId:o.bodyId,datum:a?.datum,x:a?.x,y:a?.y,regionId:t,work:s.total,remainingWork:s.remaining,jobId:i,visitId:s.visitId,visit:s.visit,queuedAt:s.queuedAt,abandonedAt:M,queueSeconds:r.queueSeconds,queueDepth:d.size})}u.delete(i),f.delete(o.bodyId),h.delete(i),m.delete(i)}for(const[i,o]of H){if(h.has(i))continue;const r=(p.get(i)??0)+1;p.set(i,r);const a=mt(o,e.unitAccessor),c={bodyId:o.id,jobId:i,visitId:`${t}:${i}:${r}`,visit:r,regionId:t,work:a,queuedAt:M};h.set(i,c),I+=1,$.arrivals+=1,$.arrivalWork+=a;const l=b++;if(s>d.size)Y(o,c,n,l);else{const s={...c,blockedAt:M,sequence:l};u.set(i,s),f.set(o.id,i),B+=1,D(),e.onBlocked?.(o,s),n.controls.recordObservation({type:"physics-capacity-blocked",bodyId:o.id,datum:o.datum,x:o.x,y:o.y,regionId:t,work:a,jobId:i,visitId:c.visitId,visit:r,queuedAt:M,blockedAt:M,queueDepth:d.size,blockedDepth:u.size})}}L(n),X();const _=Array.from(d.values()).sort((e,t)=>e.sequence-t.sequence);let G=i*P;for(const i of _){if(0>=G)break;const o=Math.min(i.remaining,G);if(i.remaining-=o,G-=o,C+=o,$.processedWork+=o,i.remaining>1e-6)continue;d.delete(i.jobId),y.delete(i.bodyId),k+=1,R+=i.total,$.completions+=1,$.completedWork+=i.total;const s=Math.max(0,M-i.queuedAt);E+=s,D();const a=r.get(i.bodyId);if(!a)continue;n.controls.applyImpulse(i.bodyId,l.x??0,l.y??0);const c={...z(i),completedAt:M,queueSeconds:s};e.onProcessed?.(a,c),n.controls.recordObservation({type:"physics-capacity-processed",bodyId:i.bodyId,datum:a.datum,x:a.x,y:a.y,regionId:t,work:i.total,jobId:i.jobId,visitId:i.visitId,visit:i.visit,queuedAt:i.queuedAt,completedAt:M,queueSeconds:s,queueDepth:d.size})}L(n),X(),function(){const e=Array.from(d.values()).sort((e,t)=>e.sequence-t.sequence);x=new Map(e.map((e,t)=>[e.bodyId,t]));const t=Array.from(u.values()).sort((e,t)=>e.sequence-t.sequence);v=new Map(t.map((e,t)=>[e.bodyId,t])),w=e.length}(),function(e){(e.end>e.start||e.arrivals>0||e.completions>0||e.processedWork>0)&&g.push(e);const t=M-a;for(;g.length>0&&t>g[0].end;)g.shift()}($);const V=Math.floor(M/c);V!==q&&(q=V,D())},getSnapshot:()=>{const e=H(),n=function(){let e=0;for(const t of u.values())e+=t.work;return e}(),o=d.size,r=Array.from(d.values()).map(e=>Math.max(0,M-e.queuedAt)).sort((e,t)=>e-t),s=r.reduce((e,t)=>e+t,0);return{regionId:t,queueDepth:o,processedCount:k,unitsPerSecond:i,remainingWork:e,meanRemainingWork:o>0?e/o:0,waitingWork:e+n,blockedDepth:u.size,blockedWork:n,arrivalCount:I,admittedCount:A,admittedWork:P,processedWork:C,completedWork:R,blockedCount:B,abandonedCount:j,abandonedWork:T,peakQueueDepth:N,peakRemainingWork:O,queueAge:{count:r.length,meanSeconds:r.length>0?s/r.length:0,p50Seconds:ft(r,.5),p95Seconds:ft(r,.95),oldestSeconds:r.at(-1)??0},meanCompletedQueueSeconds:k>0?E/k:0,window:_(),simulatedAt:M,metricRevision:$}},bodyForce:e=>{if("none"===n)return null;const i=y.get(e.body.id),s=f.get(e.body.id),a=i?d.get(i):void 0,c=s?u.get(s):void 0;if(!a&&!c)return null;const l=a?x.get(e.body.id):v.get(e.body.id);if(null==l)return null;let h;const p=e.regions;if(p)for(let e=0;p.length>e;e+=1)if(p[e].id===t){const t=p[e].shape;t&&"aabb"===t.type&&(h=t);break}return h?{x:((c?h.x-.44*h.width:h.x-.22*h.width-l*(.15*o))-e.body.x)*r,y:(h.y-(l-((c?u.size:w)-1)/2)*o/Math.max(1,Math.sqrt(c?u.size:w))-e.body.y)*r*.85}:{x:8*-Math.sign(e.body.vx||1),y:0}}}}function vt(e,t){if(!t)return;let i=e;for(const e of t.split(".")){if(null==i||"object"!=typeof i)return;i=i[e]}return i}function wt(e,t){if(!t)return!0;if("function"==typeof t)return t(e);const i=vt(e,t.property);return!("equals"in t&&!Object.is(i,t.equals)||"notEquals"in t&&Object.is(i,t.notEquals)||t.oneOf&&!t.oneOf.some(e=>Object.is(i,e))||t.notOneOf&&t.notOneOf.some(e=>Object.is(i,e)))}function kt(e){const t=e.resources.map(e=>({...e,bodyId:e.bodyId??e.id})),i=new Map(t.map(e=>[e.bodyId,e])),n=new Map,o=new Map,r=e.assignmentForce??.45,s=e.returnForce??.35,a=e.caseAttraction??.08,c=e.assignmentOffset??{x:0,y:0};let l=new Map,d=0,u=0;return{id:e.id??"service-resource-pool",continuous:!0,assign:e=>{const i=n.get(e);if(i)return i;const r=t.find(e=>!o.has(e.id));if(!r)return null;const s={resourceId:r.id,resourceBodyId:r.bodyId,caseBodyId:e,assignedAt:d};return n.set(e,s),o.set(r.id,s),u+=1,s},release:e=>{const t=n.get(e);return!!t&&(n.delete(e),o.delete(t.resourceId),u+=1,!0)},getAssignment:e=>n.get(e),tick:e=>{d=Math.max(d,e.elapsed),l=new Map(e.controls.readBodies().map(e=>[e.id,e]));for(const[e,t]of n)l.has(e)&&l.has(t.resourceBodyId)||(n.delete(e),o.delete(t.resourceId),u+=1)},getSnapshot:()=>({total:t.length,available:t.length-o.size,assigned:o.size,assignments:Array.from(n.values()),simulatedAt:d,metricRevision:u}),bodyForce:e=>{const t=i.get(e.body.id);if(t){const i=o.get(t.id),n=i?l.get(i.caseBodyId):void 0,a=i?r:s;return{x:((n?n.x+(c.x??0):t.home.x)-e.body.x)*a,y:((n?n.y+(c.y??0):t.home.y)-e.body.y)*a}}const d=n.get(e.body.id);if(!d||0>=a)return null;const u=l.get(d.resourceBodyId);return u?{x:(u.x-e.body.x)*a,y:(u.y-e.body.y)*a}:null}}}function Mt(e,t){const i="function"==typeof t.deadlineAccessor?t.deadlineAccessor(e):vt(e.datum,t.deadlineAccessor)??vt(e,t.deadlineAccessor);return Number.isFinite(Number(i))?Math.max(0,Number(i)):0}function St(e){const t=new Map;let i=0,n=0;function o(i){t.set(i.bodyId,i),n+=1,e.onStateChange?.({...i})}function r(e){const n=t.get(e);return!(!n||null!=n.completedAt||(o({...n,completedAt:i,state:"unhappy"===n.state?"resolved-unhappy":"resolved"}),0))}return{id:e.id??"service-level",continuous:!0,protect:e=>{const n=t.get(e);return!(!n||null!=n.completedAt||"unhappy"===n.state||(o({...n,state:"protected",protectedAt:i}),0))},complete:r,getCase:e=>t.get(e),tick:n=>{i=Math.max(i,n.elapsed);for(const s of n.controls.readBodies()){if(!wt(s,e.bodyFilter))continue;if(!t.has(s.id)){const t=Mt(s,e);o({bodyId:s.id,openedAt:i,deadlineAt:i+t,state:"waiting"})}const a=t.get(s.id);a&&null==a.completedAt&&(e.completionRegionId&&n.getRegionState(s.id)?.activeRegionIds.includes(e.completionRegionId)?r(s.id):"waiting"!==a.state||a.deadlineAt>i||o({...a,state:"unhappy"}))}},getSnapshot:()=>{const e=Array.from(t.values()),o=t=>e.filter(e=>e.state===t).length;return{total:e.length,waiting:o("waiting"),protected:o("protected"),unhappy:o("unhappy"),resolved:o("resolved"),resolvedUnhappy:o("resolved-unhappy"),simulatedAt:i,metricRevision:n}}}}function It(e){const t=new Set;let i=0,n=0,o=0,r=!1;return{id:e.id??"dependency-gate:"+e.regionId,continuous:!0,tick:s=>{i=Math.max(i,s.elapsed);const a=r;var c;c=i,r=e.isOpen?e.isOpen(c):null!=e.opensAt&&c>=e.opensAt;const l=s.controls.readBodies(),d=new Map(l.map(e=>[e.id,e]));for(const i of l){const n=s.getRegionState(i.id)?.activeRegionIds.includes(e.regionId);n&&wt(i,e.bodyFilter)&&(r||t.has(i.id)||(t.add(i.id),o+=1,e.onHeld?.(i)))}if(r&&!a){for(const i of t){const t=d.get(i);t&&(s.controls.applyImpulse(i,e.releaseImpulse?.x??86,e.releaseImpulse?.y??0),n+=1,e.onReleased?.(t))}t.clear(),o+=1}for(const e of t)d.has(e)||(t.delete(e),o+=1)},getSnapshot:()=>({regionId:e.regionId,isOpen:r,blocked:t.size,released:n,simulatedAt:i,metricRevision:o}),bodyForce:i=>{if(r||!t.has(i.body.id))return null;const n=i.regions?.find(t=>t.id===e.regionId),o=n?.shape;if(!o||"aabb"!==o.type)return{x:.8*-i.body.vx,y:.8*-i.body.vy};const s=e.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 At(e,t){return e||t?{x:(e?.x??0)+(t?.x??0),y:(e?.y??0)+(t?.y??0)}:null}function Pt(e){if(!e?.length)return null;const t=e.slice(),i=t.some(e=>!1!==e.continuous);return{controllers:t,continuous:i,onTick:(e,i,n)=>{const o={result:e,controls:i,dt:n.dt,elapsed:n.elapsed,getRegionState:n.getRegionState};for(const e of t)e.tick(o)},bodyForce:e=>{let i=null;for(const n of t)n.bodyForce&&(i=At(i,n.bodyForce(e)));return i}}}function Ct(e){const t=new Set,i=e.impulse??{x:-60,y:0};return{id:e.id??"portal:"+e.fromRegionId,continuous:!0===e.continuous,tick:n=>{const o=n.controls.readBodies();for(const r of o){const o=n.getRegionState(r.id),s=o?.activeRegionIds.includes(e.fromRegionId);s?t.has(r.id)||(t.add(r.id),n.controls.applyImpulse(r.id,i.x??0,i.y??0),e.onPortal?.(r)):t.delete(r.id)}}}}import*as Rt from"react";import{forwardRef as Bt,memo as jt,useCallback as Tt,useEffect as Nt,useImperativeHandle as Ot,useId as Et,useRef as $t}from"react";var qt={names:["--semiotic-bg","--surface-1","--surface-0"],fallback:"#f8fafc"},Wt={names:["--semiotic-border","--surface-3"],fallback:"#334155"},Ft={names:["--semiotic-danger","--viz-4"],fallback:"#dc2626"},Dt={names:["--semiotic-focus","--accent","--viz-9"],fallback:"#f97316"},zt={names:["--semiotic-grid","--surface-3"],fallback:"#cbd5e1"},Yt={names:["--semiotic-primary","--accent","--viz-5"],fallback:"#0ea5e9"},Lt={names:["--semiotic-success","--viz-2"],fallback:"#22c55e"},Ht={names:["--semiotic-text","--text-primary"],fallback:"#0f172a"},Xt={names:["--semiotic-text-secondary","--text-secondary"],fallback:"#475569"},_t={names:["--semiotic-warning","--viz-9","--viz-3"],fallback:"#f97316"};function Gt(e,t){const i=e.canvas;if("function"!=typeof getComputedStyle||!i)return t.fallback;const n=getComputedStyle(i);for(const i of t.names){const t=n.getPropertyValue(i).trim();if(t)return P(e,t)??t}return t.fallback}function Vt(e,t){const i=Math.max(0,Math.min(1,t)),n=e.trim(),o=n.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);if(o){const[,e,t,n]=o;return Vt(`#${e}${e}${t}${t}${n}${n}`,i)}const r=n.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(r){const[,e,t,n]=r;return`rgba(${parseInt(e,16)}, ${parseInt(t,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 Ut(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function Kt(e,t){const i="sensor"===e.physics?t.sensorThickness:t.barrierThickness;return Math.max(0,Ut(e.thickness)??Ut(i)??Ut(t.thickness)??4)}var Qt=2500;function Zt(e){return"function"==typeof e}function Jt(e){return void 0===e||!1===e||!Zt(e.binAccessor)&&!Zt(e.labelAccessor)&&!Zt(e.valueAccessor)}function ei(e){if(void 0!==e){if(!1===e)return!1;if(!Jt(e))throw new TypeError("Physics worker sediment config only supports string or numeric accessors");return{binAccessor:"string"==typeof e.binAccessor?e.binAccessor:void 0,labelAccessor:"string"==typeof e.labelAccessor?e.labelAccessor:void 0,valueAccessor:"string"==typeof e.valueAccessor||"number"==typeof e.valueAccessor?e.valueAccessor:void 0,retainBodyIds:e.retainBodyIds}}}function ti(e){if(e)return{chartId:e.chartId,chartType:e.chartType,sensors:e.sensors}}function ii(e){return function(e){return!Zt(e?.timeAccessor)}(e)}function ni(e={}){if(e.engine)throw new TypeError("Physics workers use the built-in kernel adapter");const{engine:t,observation:i,sediment:n,...o}=e;return{...o,observation:ti(i),sediment:ei(n)}}function oi(){if("undefined"!=typeof DOMException)return new DOMException("Physics worker request aborted","AbortError");const e=Error("Physics worker request aborted");return e.name="AbortError",e}var ri=class{constructor(e=function(){const e="string"==typeof import.meta.url&&import.meta.url?new URL("./physicsWorker.js",import.meta.url):n("physicsWorker.js");return new Worker(e,{type:"module",name:"semiotic-physics"})}()){this.nextRequestId=1,this.pending=new Map,this.worker=e,this.worker.onmessage=e=>{const t=e.data,i=this.pending.get(t.requestId);i&&(this.pending.delete(t.requestId),i.cleanup(),t.ok?i.resolve(t.payload):i.reject(function(e){const t=Error(e.error.message);return t.name=e.error.name??"Error",e.error.stack&&(t.stack=e.error.stack),t}(t)))},this.worker.onerror=e=>{this.rejectAll(Error(e.message||"Physics worker failed")),this.worker.terminate()}}request(e,t){if(t?.aborted)return Promise.reject(oi());const i=this.nextRequestId;this.nextRequestId+=1;const n={command:e,requestId:i};return new Promise((e,o)=>{const r=()=>{this.pending.delete(i),t?.removeEventListener("abort",r),o(oi())},s=()=>t?.removeEventListener("abort",r);this.pending.set(i,{cleanup:s,reject:o,resolve:e}),t?.addEventListener("abort",r,{once:!0});try{this.worker.postMessage(n)}catch(e){this.pending.delete(i),s(),o(e)}})}async init(e,t,i,n){if(!ii(i))throw new TypeError("Physics worker spawn pacing only supports string time accessors");const o=await this.request({type:"init",config:ni(e),initialSpawns:t,initialSpawnPacing:i},n);if("frame"!==o.type)throw Error("Physics worker returned a non-frame init response");return o.frame}async restore(e,t){const i=await this.request({type:"restore",snapshot:e},t);if("frame"!==i.type)throw Error("Physics worker returned a non-frame restore response");return i.frame}async initFromSnapshot(e,t,i){const n=await this.request({type:"init",config:ni(e),snapshot:t},i);if("frame"!==n.type)throw Error("Physics worker returned a non-frame init response");return n.frame}async enqueue(e,t,i){if(!ii(t))throw new TypeError("Physics worker spawn pacing only supports string time accessors");const n=await this.request({type:"enqueue",spawns:e,pacing:t},i);if("frame"!==n.type)throw Error("Physics worker returned a non-frame enqueue response");return n.frame}async tick(e,t){const i=await this.request({type:"tick",deltaSeconds:e},t);if("frame"!==i.type)throw Error("Physics worker returned a non-frame tick response");return i.frame}async settle(e,t){const i=await this.request({type:"settle",maxSteps:e},t);if("frame"!==i.type)throw Error("Physics worker returned a non-frame settle response");return i.frame}async snapshot(e){const t=await this.request({type:"snapshot"},e);if("snapshot"!==t.type)throw Error("Physics worker returned a non-snapshot response");return t.snapshot}async remove(e,t){const i=await this.request({type:"remove",ids:e},t);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(e){for(const[t,i]of this.pending)this.pending.delete(t),i.cleanup(),i.reject(e)}};function si(e,t,i){const n=new pt(e);return t?.length&&n.enqueue(t,i),n}function ai(){return"undefined"!=typeof performance?performance.now():Date.now()}import*as ci from"react-dom/server";function li(e=[]){return e.map(e=>({id:e.id,label:e.label,count:e.count,...null!=e.secondary?{secondary:e.secondary}:{},...e.secondaryLabel?{secondaryLabel:e.secondaryLabel}:{},...null!=e.observed?{observed:e.observed}:{}}))}var di={fill:"#4e79a7",stroke:"#172033",strokeWidth:1,opacity:.85};function ui(e){const t=e.datum;if(t&&"object"==typeof t){const e=t.label??t.name??t.id;if(null!=e&&""!==e)return e+""}return e.id}function hi(e,t){const i="function"==typeof t?t(e):t;return{...di,...i??{}}}function pi(e,t={}){const i=e.settle(t.maxSteps),n=e.readBodies(),o=e.snapshot(),r=function(e,t={}){return e.map(e=>function(e,t={}){const i=function(e){return e.datum&&"object"==typeof e.datum?e.datum:null}(e),n={label:t.getBodyLabel?.(e)??ui(e)},o={style:hi(e,t.bodyStyle),datum:i,accessibleDatum:i,accessibility:n,_transitionKey:e.id};return"aabb"===e.shape.type?{type:"rect",x:e.x-e.shape.width/2,y:e.y-e.shape.height/2,w:e.shape.width,h:e.shape.height,...o}:{type:"point",x:e.x,y:e.y,r:e.shape.radius,pointId:e.id,...o}}(e,t))}(n,t),s=function(e,t={}){const i=t.bodies??function(e){return e.world.bodies.map(e=>({id:e.id,x:e.x,y:e.y,prevX:e.prevX,prevY:e.prevY,vx:e.vx,vy:e.vy,angle:e.angle,mass:e.mass,shape:{...e.shape},sleeping:e.sleeping,datum:e.datum}))}(e),n=i.filter(e=>e.sleeping).length;return{bodyCount:i.length,sleepingCount:n,settled:"settled"===e.simulationState&&0===e.queue.length&&n===i.length,stepsRun:Math.max(0,Math.floor(t.stepsRun??0)),seed:e.world.options.seed,binCounts:li(t.projectionRows)}}(o,{bodies:n,projectionRows:t.projectionRows,stepsRun:i});return{snapshot:o,bodies:n,sceneNodes:r,evidence:s,stepsRun:i}}import{jsx as mi,jsxs as yi}from"react/jsx-runtime";import{useEffect as fi,useRef as gi}from"react";function bi(){return"undefined"==typeof document||!document.hidden}function xi(e,t,i){const n=f(e,i.fill)??"#4e79a7",o=i.stroke,r=i.strokeWidth??0,s=i.opacity??1,a=i.fillOpacity??1,c=function(e,t){const i=t.mark;if(i)return i;const n=e.datum,o=n?.__physicsMark??n?.mark;return"circle"===o||"halo"===o||"faceted"===o||"pill"===o||"diamond"===o||"square"===o?o:"circle"===e.shape.type?"circle":"square"}(t,i),l="circle"===t.shape.type?i.r??t.shape.radius:Math.max(t.shape.width,t.shape.height)/2;if(e.save(),e.globalAlpha*=s,e.beginPath(),"pill"===c||"square"===c||"aabb"===t.shape.type){const i="pill"===c?2.4*l:"aabb"===t.shape.type?t.shape.width:1.7*l,n="pill"===c?1.35*l:"aabb"===t.shape.type?t.shape.height:1.7*l,o=t.x-i/2,r=t.y-n/2,s="pill"===c?n/2:Math.min(4,i/4);e.moveTo(o+s,r),e.arcTo(o+i,r,o+i,r+n,s),e.arcTo(o+i,r+n,o,r+n,s),e.arcTo(o,r+n,o,r,s),e.arcTo(o,r,o+i,r,s),e.closePath()}else if("diamond"===c)e.moveTo(t.x,t.y-l),e.lineTo(t.x+l,t.y),e.lineTo(t.x,t.y+l),e.lineTo(t.x-l,t.y),e.closePath();else if("faceted"===c){const i=6;for(let n=0;i>n;n+=1){const o=2*Math.PI*n/i-Math.PI/2,r=t.x+Math.cos(o)*l,s=t.y+Math.sin(o)*l;0===n?e.moveTo(r,s):e.lineTo(r,s)}e.closePath()}else e.arc(t.x,t.y,l,0,2*Math.PI);n&&(e.save(),e.globalAlpha*=a,e.fillStyle=n,e.fill(),e.restore()),"halo"===c&&(e.beginPath(),e.arc(t.x,t.y,1.35*l,0,2*Math.PI),e.strokeStyle=o??n,e.lineWidth=Math.max(1.5,r||1.5),e.globalAlpha*=.55,e.stroke(),e.globalAlpha/=.55),o&&r>0&&(e.strokeStyle=o,e.lineWidth=r,i.strokeDasharray&&e.setLineDash(i.strokeDasharray.split(/[,\s]+/).map(e=>Number(e)).filter(e=>Number.isFinite(e))),e.stroke()),e.restore()}function vi(e){return"circle"===e.shape.type?e.shape.radius:Math.max(e.shape.width,e.shape.height)/2}function wi(e){return e.sensorId??"stream-region-"+e.id}function ki(e){const t=wi(e),i={bodyFilter:e.bodyFilter,friction:e.friction,restitution:e.restitution};if("boundary"===e.collider&&"aabb"===e.shape.type){const n=e.colliderThickness??8,o=e.shape.x-e.shape.width/2,r=e.shape.x+e.shape.width/2,s=e.shape.y-e.shape.height/2,a=e.shape.y+e.shape.height/2;return[{...i,id:t+"-top",shape:{type:"segment",x1:o,y1:s,x2:r,y2:s,thickness:n}},{...i,id:t+"-right",shape:{type:"segment",x1:r,y1:s,x2:r,y2:a,thickness:n}},{...i,id:t+"-bottom",shape:{type:"segment",x1:r,y1:a,x2:o,y2:a,thickness:n}},{...i,id:t+"-left",shape:{type:"segment",x1:o,y1:a,x2:o,y2:s,thickness:n}}]}return e.collider?[{...i,id:t+"-collider",shape:e.shape}]:[]}function Mi(e){if(e)return{activeRegionIds:Array.from(e.activeRegionIds),regionIds:Array.from(e.regionIds),charges:{...e.charges},attributes:{...e.attributes},energy:e.energy}}function Si(e,t){const i="function"==typeof e?e(t):e;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 Ii(e){if(!1===e.semanticItem)return null;const t=e.shape,i=e.semanticItem??{},n="aabb"===t.type?{id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"region",x:t.x,y:t.y,width:t.width,height:t.height}:{id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"region",x:(t.x1+t.x2)/2,y:(t.y1+t.y2)/2,pathData:`M ${t.x1} ${t.y1} L ${t.x2} ${t.y2}`};return{...n,...i,id:i.id??n.id}}function Ai(e){return e.some(e=>null!=e.force||null!=e.damping||null!=e.impulseOnEnter||null!=e.impulseOnExit)}function Pi(e,t){const i="function"==typeof e?e(t):e;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 Ci=[];function Ri(e){const t=e.store.controls(),i=e.store.snapshot(),n=Math.max(0,e.result.steps*(i.config.fixedDt||1/60)),o=function(e,t,i,n){const o=Number.isFinite(n)?Math.max(0,n):0;if(0>=o||!Ai(t))return!1;const r=new Map(t.map(e=>[e.id,e])),s=e.readBodies();let a=!1;for(const t of s){const n=i.get(t.id);if(!n||!n.activeRegionIds.size)continue;const s=Mi(n);if(s)for(const i of n.activeRegionIds){const n=r.get(i);if(!n)continue;const c=Si(n.force,{body:t,region:n,regionState:s}),l=Number(n.damping??0),d=(c?.x??0)*o-(Number.isFinite(l)?t.vx*l*o:0),u=(c?.y??0)*o-(Number.isFinite(l)?t.vy*l*o:0);(d||u)&&(e.applyImpulse(t.id,d,u),a=!0)}}return a}(t,e.regionEffects,e.regionState,n),r=function(e,t,i,n,o,r){const s=Number.isFinite(r)?Math.max(0,r):0;if(0>=s||!t)return!1;const a=new Map(i.map(e=>[e.id,e])),c=e.readBodies();let l=!1;for(let i=0;c.length>i;i+=1){const r=c[i],d=n.get(r.id),u=Mi(d);let h=Ci;if(d&&d.activeRegionIds.size>0){const e=[];for(const t of d.activeRegionIds){const i=a.get(t);i&&e.push(i)}h=e}const p=Pi(t,{body:r,bodies:c,index:i,regionState:u,regions:h,simulationState:o});if(!p)continue;const m=(p.x??0)*s,y=(p.y??0)*s;(m||y)&&(e.applyImpulse(r.id,m,y),l=!0)}return l}(t,e.bodyForces,e.regionEffects,e.regionState,i.simulationState,n);return e.composed&&e.composed.onTick(e.result,t,{dt:n,elapsed:e.result.elapsedSeconds,getRegionState:t=>Mi(e.regionState.get(t))}),e.onTick?.(e.result,t),{regionEffectsApplied:o,bodyForcesApplied:r,snapshot:i}}function Bi(e,t,i,n,o,r,s,a,c,l){const d=function(e,t){return!!t?.isActive&&(t.predicate?.(e)??!0)}(e,o),u={selected:d,simulationState:t,regionState:r,regions:s},h="function"==typeof i?i(e,u):i,p=s.reduce((t,i)=>i.bodyStyle?{...t,..."function"==typeof i.bodyStyle?i.bodyStyle(e,u):i.bodyStyle}:t,{}),m=d?"function"==typeof n?n(e,u):n:void 0;return{fill:l?.color??a,stroke:l?.stroke??c,strokeWidth:l?.strokeWidth??1,opacity:l?.opacity??.9,...h,...p,...m}}import{useCallback as ji}from"react";import*as Ti from"react";import{jsx as Ni,jsxs as Oi}from"react/jsx-runtime";var Ei={border:0,clip:"rect(0 0 0 0)",height:1,margin:-1,overflow:"hidden",padding:0,position:"absolute",whiteSpace:"nowrap",width:1},$i="semiotic-accessible-data-table",qi=$i+" semiotic-accessible-data-table-hidden",Wi=$i+" semiotic-accessible-data-table-visible",Fi={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"},Di={marginBottom:8,paddingRight:28,color:"var(--semiotic-data-table-muted-text, var(--semiotic-text-secondary, #666))",fontSize:12,letterSpacing:"0.01em"},zi={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)"},Yi={width:"100%",borderCollapse:"collapse",fontSize:12,marginTop:4,fontVariantNumeric:"tabular-nums"},Li={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))"},Hi={padding:"4px 10px",borderBottom:"1px solid var(--semiotic-data-table-border, var(--semiotic-border, #e0e0e0))"},Xi={textAlign:"left",fontSize:11,color:"var(--semiotic-data-table-muted-text, var(--semiotic-text-secondary, #666))",marginBottom:4,fontStyle:"italic"},_i={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 Gi(e){return null==e?null:"string"==typeof e||"number"==typeof e||"boolean"==typeof e?e+"":null}function Vi(e){return{__semioticHoverData:!0,body:e,data:e.datum??e,id:e.id,type:"body",x:e.x,y:e.y}}function Ui(e){if("circle"===e.shape.type){const t=Math.max(4,2*e.shape.radius);return{height:t,shape:"circle",width:t}}return{height:e.shape.height,shape:"rect",width:e.shape.width}}function Ki(e){const t=e.datum;if(t&&"object"==typeof t){const e=t.label??t.name??t.id;if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e+""}return e.id}function Qi(e){const t=Zi(e.datum??e);return t.length?t.map(([e,t])=>`${e}: ${t}`).join(", "):"Physics body "+e.id}function Zi(e){return e&&"object"==typeof e?Object.entries(e).map(([e,t])=>{if(e.startsWith("_"))return null;const i=Gi(t);return null==i?null:[e,i]}).filter(e=>null!=e).slice(0,8):[]}function Ji({hover:e}){const t=Zi(e.data);return Oi("div",{className:"semiotic-tooltip",style:b,children:[Ni("div",{style:{fontWeight:700,marginBottom:t.length?4:0},children:e.id}),t.map(([e,t])=>Oi("div",{children:[Oi("span",{style:{opacity:.72},children:[e,": "]}),Ni("span",{children:t})]},e))]})}function en(e){return e.datum&&"object"==typeof e.datum?Object.entries(e.datum).map(([e,t])=>{const i=Gi(t);return null==i?null:`${e}: ${i}`}).filter(e=>null!=e).slice(0,8).join(", "):""}function tn(e){const t=[`${e.length} semantic item${1===e.length?"":"s"}.`],i=new Map;for(const t of e)t.group&&i.set(t.group,(i.get(t.group)??0)+1);return i.size&&t.push(Array.from(i).map(([e,t])=>`${e}: ${t}`).join(", ")),t.join(" ")}function nn(e){const{chartTitle:t,items:i,tableId:n}=e,[o,r]=Ti.useState(!1),[s,a]=Ti.useState(5),c=j(),l=c?.visible??!1,d=o||l,u=Ti.useRef(null),h="Data summary for "+(t??"physics chart");Ti.useEffect(()=>{d||a(5)},[d]);const p=Ti.useCallback(e=>{e.target===e.currentTarget&&(o||l||r(!0))},[o,l]),m=Ti.useCallback(e=>{l||u.current?.contains(e.relatedTarget)||r(!1)},[l]);if(!i.length)return Ni("span",{id:n,tabIndex:-1,style:Ei});if(!d)return Ni("div",{id:n,className:qi,role:"region","aria-label":h,tabIndex:-1,style:Ei,onFocus:p,children:Oi("button",{type:"button",onClick:()=>r(!0),children:["View data summary (",i.length," semantic items)"]})});const y=Math.min(s,i.length),f=i.slice(0,y),g=i.length-y;return Oi("div",{ref:u,id:n,className:Wi,role:"region","aria-label":h,tabIndex:-1,onBlur:m,style:Fi,children:[Ni("button",{type:"button",className:"semiotic-accessible-data-table-close","aria-label":"Close data summary",onClick:()=>{l&&c&&c.setVisible(!1),r(!1)},style:zi,children:"×"}),Ni("div",{className:"semiotic-accessible-data-table-summary",role:"note",style:Di,children:tn(i)}),Oi("table",{className:"semiotic-accessible-data-table-table",role:"table","aria-label":"Semantic items for "+(t??"physics chart"),style:Yi,children:[Ni("caption",{className:"semiotic-accessible-data-table-caption",style:Xi,children:g>0?`First ${y} of ${i.length} semantic items`:`All ${i.length} semantic items`}),Ni("thead",{children:Oi("tr",{children:[Ni("th",{scope:"col",style:Li,children:"Item"}),Ni("th",{scope:"col",style:Li,children:"Description"}),Ni("th",{scope:"col",style:Li,children:"Group"}),Ni("th",{scope:"col",style:Li,children:"Position"}),Ni("th",{scope:"col",style:Li,children:"Data"})]})}),Ni("tbody",{children:f.map((e,t)=>Oi("tr",{children:[Ni("th",{scope:"row",style:Hi,children:e.label}),Ni("td",{style:Hi,children:e.description??e.label}),Ni("td",{style:Hi,children:e.group??""}),Oi("td",{style:Hi,children:[Math.round(e.x),", ",Math.round(e.y)]}),Ni("td",{style:Hi,children:en(e)})]},e.id??`${e.label}-${t}`))})]}),g>0?Oi("button",{type:"button",className:"semiotic-accessible-data-table-show-more",onClick:()=>a(e=>e+25),style:_i,children:["Show ",Math.min(25,g)," more"," ",1===g?"row":"rows"," (",g," remaining)"]}):null]})}Ji.ownsChrome=!0;import{jsx as on,jsxs as rn}from"react/jsx-runtime";var sn=[640,360],an={top:0,right:0,bottom:0,left:0},cn=new Set(["ArrowRight","ArrowLeft","ArrowUp","ArrowDown","Home","End","PageUp","PageDown"]),ln="StreamPhysicsFrame",dn=jt(Bt(function(e,t){const{accessibleTable:i=!0,annotations:n,onAnnotationActivate:o,autoPlaceAnnotations:r,background:s,backgroundGraphics:m,bodySemanticItemLimit:y=200,bodySemanticItems:f=!1,bodySemanticUpdateMs:g=200,bodyForces:b,bodyStyle:x,chartId:M,className:I,frameScheduler:A,clock:P,random:C,seed:R,color:B,config:j,controllers:$,continuous:q=!1,description:W,emphasis:F,chartMode:D,enableHover:z=!0,foregroundGraphics:H,hoverRadius:X=16,initialSpawns:_,initialSpawnPacing:G,legend:V,legendClickBehavior:U,legendHighlightedCategory:Q,legendHoverBehavior:Z,legendIsolatedCategories:ee,legendLayout:te,legendPosition:ie,margin:ne,onClick:oe,onObservation:re,onRegionEvent:se,onSimulationExecutionChange:ae,onBodyHover:ce,onBodyPointerDown:le,onSemanticItemActivate:de,onSemanticItemFocus:ue,onTick:he,opacity:pe,paused:me=!1,regionEffects:ye=[],responsiveHeight:fe,responsiveWidth:ge,selectedBodyStyle:be={stroke:"#111827",strokeWidth:2,opacity:1},selection:xe,semanticItems:ve=[],simulationExecution:we="auto",size:ke=sn,stroke:Me,strokeWidth:Se,summary:Ie,suspendWhenHidden:Ae=!0,svgAnnotationRules:Pe,title:Ce,tooltipContent:Re,workerBodyThreshold:Be=Qt,renderBody:je,beforePaint:Te,afterPaint:Ne}=e,Oe=Rt.useMemo(()=>({color:B,stroke:Me,strokeWidth:Se,opacity:pe}),[B,pe,Me,Se]),Ee=$t(re);Ee.current=re;const $e=$t(M);$e.current=M;const qe=$t(new Map),We=$t(ye);We.current=ye;const Fe=$t(b);Fe.current=b;const De=$t(he);De.current=he;const ze=Rt.useMemo(()=>Pt($),[$]),Ye=$t(ze);Ye.current=ze;const Le=q||!!ze?.continuous,He=$t(Le);He.current=Le;const Xe=Rt.useMemo(()=>{if(!b&&!ze?.bodyForce)return b;if(!ze?.bodyForce)return b;if(!b)return ze.bodyForce;const e=ze.bodyForce;return t=>{const i="function"==typeof b?b(t):b,n="function"==typeof e?e(t):e;return i||n?{x:(i?.x??0)+(n?.x??0),y:(i?.y??0)+(n?.y??0)}:null}},[b,ze]);Fe.current=Xe;const _e=Rt.useMemo(()=>new Map(ye.map(e=>[wi(e),e])),[ye]),Ge=Rt.useMemo(()=>new Map(ye.map(e=>[e.id,e])),[ye]),Ve=Rt.useMemo(()=>ye.map(Ii).filter(e=>null!=e),[ye]),[Ue,Ke]=Rt.useState([]),Qe=Rt.useMemo(()=>Ue.length||Ve.length?[...ve,...Ue,...Ve]:ve,[Ue,Ve,ve]),Ze=Rt.useMemo(()=>Ai(ye),[ye]),Je=!!Xe,et=$t(null),tt=$t(P??ai);tt.current=P??ai;const it=Tt((e,t,i)=>{const n=et.current;if(!n||!i)return!1;const o=n.readBodies().find(t=>t.id===e),r=Mi(qe.current.get(e));if(!o||!r)return!1;const s=Si(i,{body:o,region:t,regionState:r});return!(!s||!s.x&&!s.y||(n.applyImpulse(e,s.x??0,s.y??0),0))},[]),nt=Tt((e,t,i)=>{if(!i.bodyId)return;const n=Mi(qe.current.get(i.bodyId));if(!n)return;const o={bodyId:i.bodyId,datum:i.datum,observation:i,region:t,regionState:n,type:e};"region-enter"===e?t.onEnter?.(o):t.onExit?.(o),se?.(o)},[se]),ot=Tt(e=>{const t=e.sensorId?_e.get(e.sensorId):void 0;if(!t||!e.bodyId)return;const i=function(e,t){let i=e.get(t);return i||(i={activeRegionIds:new Set,attributes:{},charges:{},energy:0,regionIds:new Set},e.set(t,i)),i}(qe.current,e.bodyId),n=et.current?.readBodies().find(t=>t.id===e.bodyId),o=Mi(i),r=n&&o?{body:n,region:t,regionState:o}:null;if("physics-proximity-enter"===e.type){if(i.activeRegionIds.add(t.id),i.regionIds.add(t.id),i.energy+=t.energyDelta??0,r){!function(e,t,i){const n="function"==typeof e.attributes?e.attributes(t):e.attributes;n&&(i.attributes={...i.attributes,...n})}(t,r,i);const e=function(e,t){return void 0!==e.charge?"function"==typeof e.charge?e.charge(t):e.charge:"charge-gate"===e.kind?1:void 0}(t,r);void 0!==e&&(i.charges[t.id]=e)}it(e.bodyId,t,t.impulseOnEnter),nt("region-enter",t,e)}else"physics-proximity-exit"===e.type&&(i.activeRegionIds.delete(t.id),it(e.bodyId,t,t.impulseOnExit),nt("region-exit",t,e))},[it,nt,_e]),rt=Rt.useMemo(()=>{if(!n?.length)return[];const e=n.filter(e=>"barrier"===e.physics||"sensor"===e.physics);return e.length?function(e=[],t={}){const i=t.idPrefix?t.idPrefix+"-":"",n=[];for(const o of e){if("barrier"!==o.physics&&"sensor"!==o.physics)continue;const e=o.axis??t.defaultAxis??"x",r=Kt(o,t),s=o.colliderId??`${i}${o.id}`;let a;if("x"===e){const e=Ut(o.x),i=Ut(o.y1)??Ut(t.plotBounds?.y)??Ut(o.y),n=Ut(o.y2)??(t.plotBounds?t.plotBounds.y+t.plotBounds.height:void 0)??Ut(o.y);if(null==e||null==i||null==n)continue;a={type:"segment",x1:e,y1:i,x2:e,y2:n,thickness:r}}else{const e=Ut(o.y),i=Ut(o.x1)??Ut(t.plotBounds?.x)??Ut(o.x),n=Ut(o.x2)??(t.plotBounds?t.plotBounds.x+t.plotBounds.width:void 0)??Ut(o.x);if(null==e||null==i||null==n)continue;a={type:"segment",x1:i,y1:e,x2:n,y2:e,thickness:r}}n.push({id:s,shape:a,sensor:"sensor"===o.physics,..."barrier"!==o.physics||null==o.restitution&&null==t.barrierRestitution?{}:{restitution:Ut(o.restitution)??Ut(t.barrierRestitution)},..."barrier"!==o.physics||null==o.friction&&null==t.barrierFriction?{}:{friction:Ut(o.friction)??Ut(t.barrierFriction)}})}return n}(e,{idPrefix:M?M+"-ann":"physics-ann",plotBounds:{x:0,y:0,width:ke?.[0]??sn[0],height:ke?.[1]??sn[1]}}):[]},[n,M,ke]),st=Rt.useMemo(()=>{const e=void 0===R||void 0!==j?.kernel?.seed?j:{...j,kernel:{...j?.kernel,seed:R}},t=ye.flatMap(e=>[{id:wi(e),sensor:!0,shape:e.shape,bodyFilter:e.bodyFilter,friction:e.friction,restitution:e.restitution},...ki(e)]),i=Object.fromEntries(ye.map(e=>[wi(e),{binId:e.binId??e.id,enterType:"physics-proximity-enter",exitType:"physics-proximity-exit"}])),n=e?.observation,o=ye.length>0;return o||t.length>0||rt.length>0||null!=M||n?{...e,colliders:[...e?.colliders??[],...t,...rt],observation:{...n,chartId:M??n?.chartId,chartType:n?.chartType??ln,sensors:{...n?.sensors??{},...i},onObservation:e=>{o&&ot(e),n?.onObservation?.(e)}}}:e},[rt,M,j,ot,ye,R]);if(!et.current){const e=si(st,_,G);e.setPaused(me),Ae&&e.setVisible(bi()),et.current=e}const at=$t(-1),ct=$t(null),lt=$t(!0),dt=O("StreamPhysicsFrame"),ut=$t(""),ht=Et().replace(/:/g,""),pt=$t(!1),mt=$t(!1),yt=$t(0),ft=$t(!1),gt=$t(null),bt=$t(!1),xt=T({sizeProp:ke,responsiveWidth:ge,responsiveHeight:fe,userMargin:ne,marginDefault:an,foregroundGraphics:H,backgroundGraphics:m,frameScheduler:A,clock:P,random:C,seed:R,paused:me,suspendWhenHidden:Ae}),{margin:vt,rafRef:wt,reducedMotionRef:kt,renderFnRef:Mt,cancelRender:St,resolvedBackground:It,resolvedForeground:At,responsiveRef:Ct,scheduleRender:Bt,size:jt,frameRuntime:Zt}=xt,ei=$t(Zt.now);ei.current=Zt.now;const ti=Y(),ni=L(),[oi,li]=Rt.useState(null),[di,ui]=Rt.useState(null),hi=$t(null),Pi=$t(0),Ci=$t(new Map),Ti=ht+"-physics-live",Ni=Tt((e,t,i=!1)=>{if(!f)return void Ke(e=>e.length?[]:e);const n=ei.current();if(!i&&g>0&&g>n-Pi.current)return;Pi.current=n;const o=function(e,t,i,n){if(!i)return[];const o=Math.max(0,Math.floor(n));if(!o)return[];const r=[];for(let n=0;e.length>n&&o>r.length;n+=1){const o=e[n],s="function"==typeof i?i(o,{index:n,simulationState:t}):void 0;if(!1===s)continue;const a=Ui(o);r.push({datum:o.datum??o,description:Qi(o),group:"body",label:Ki(o),...a,...s??{},bodyId:s?.bodyId??o.id,id:s?.id??"body:"+o.id,x:s?.x??o.x,y:s?.y??o.y})}return r}(e,t,f,y);Ke(e=>function(e,t){if(e.length!==t.length)return!0;for(let i=0;e.length>i;i+=1){const n=e[i],o=t[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}(e,o)?o:e)},[y,f,g]),Oi=Tt(e=>{if(!Qe.length)return;const t=Math.max(0,Math.min(e,Qe.length-1));at.current=t;const i=Qe[t];if(hi.current=i.bodyId??null,li(i),ue?.(i),i.bodyId&&et.current){const e=et.current.readBodies().find(e=>e.id===i.bodyId);if(e){const t=Vi(e);ui(t),ce?.(e,t)}}},[Qe,ce,ue]),$i=Tt(()=>{at.current=-1,hi.current=null,li(null),ue?.(null)},[ue]),qi=function({onObservationRef:e,chartIdRef:t,wallClockRef:i}){return ji((n,o)=>{const r=e.current;if(!r)return;const s={timestamp:i.current(),chartType:"StreamPhysicsFrame",chartId:t.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})},[t,e,i])}({onObservationRef:Ee,chartIdRef:$e,wallClockRef:tt}),Wi=Tt(()=>{ui(e=>e?(ce?.(null,null),qi("hover-end"),null):e)},[qi,ce]),Fi=Tt(e=>{if(!z||!et.current)return;const t=e.currentTarget.getBoundingClientRect(),i=et.current.hitTest(e.clientX-t.left,e.clientY-t.top,X);if(!i)return void Wi();const n=Vi(i);ui(e=>e&&e.id===n.id&&e.x===n.x&&e.y===n.y?e:(ce?.(i,n),qi("hover",{datum:i.datum,x:i.x,y:i.y}),n))},[Wi,qi,z,X,ce]),Di=Tt(e=>{$i();const t=et.current,i=e.currentTarget.getBoundingClientRect(),n=e.clientX-i.left,o=e.clientY-i.top,r=t?t.hitTest(n,o,Math.max(16,X)):null;le?.(r,e),r?(qi("click",{datum:r.datum,x:r.x,y:r.y}),qi("activate",{datum:r.datum,inputType:"touch"===e.pointerType?"touch":"pointer"}),oe?.(r.datum??null,{x:r.x,y:r.y,body:r})):(qi("click-end"),oe?.(null,{x:n,y:o,body:null}),Wi())},[Wi,$i,qi,X,le,oe]);Nt(()=>{if(!Qe.length)return void $i();const e=at.current;if(Qe.length>e){if(e>=0){const t=Qe[e];if(hi.current=t.bodyId??null,li(e=>null!=e&&e.id===t.id&&Math.round(e.x)===Math.round(t.x)&&Math.round(e.y)===Math.round(t.y)?e:t),t.bodyId&&et.current){const e=et.current.readBodies().find(e=>e.id===t.bodyId);if(e){const t=Vi(e);ui(e=>e?.id===t.id&&Math.round(e.x)===Math.round(t.x)&&Math.round(e.y)===Math.round(t.y)?e:t)}}}}else Oi(Qe.length-1)},[Qe,$i,Oi]),Nt(()=>{z||Wi()},[Wi,z]);const zi=Tt(e=>{if(w(e))return;if(!Qe.length)return;if("Escape"===e.key)return e.preventDefault(),void $i();if(("Enter"===e.key||" "===e.key)&&at.current>=0){e.preventDefault();const t=Qe[at.current];return qi("activate",{datum:t.datum??{id:t.id,label:t.label},inputType:"keyboard"}),void de?.(t)}if(!cn.has(e.key))return;e.preventDefault();const t=at.current;if(0>t){Oi(0);const e=Qe[0];return void qi("focus",{datum:e.datum??{id:e.id,label:e.label},inputType:"keyboard"})}const i=Math.max(1,Math.floor(.1*Qe.length));let n=t;if("Home"===e.key?n=0:"End"===e.key?n=Qe.length-1:"PageDown"===e.key?n=Math.min(Qe.length-1,t+i):"PageUp"===e.key?n=Math.max(0,t-i):"ArrowRight"===e.key||"ArrowDown"===e.key?n=Math.min(Qe.length-1,t+1):"ArrowLeft"!==e.key&&"ArrowUp"!==e.key||(n=Math.max(0,t-1)),Oi(n),n!==t){const e=Qe[n];qi("focus",{datum:e.datum??{id:e.id,label:e.label},inputType:"keyboard"})}},[$i,qi,Oi,de,Qe]),[Yi,Li]=Rt.useState([]),Hi=$t(0),Xi=!!n?.length&&n.some(e=>null!=e.pointId||null!=e.bodyId||"latest"===e.anchor),{canvasRef:_i}=N(xt,{hydrated:ti,wasHydratingFromSSR:ni,storeRef:et,dirtyRef:lt,manageFrameRuntime:!1,skipInitialCanvasPaintInvalidation:!0,canvasPaintDependencies:[s,m,Bt]}),Gi=Tt(()=>{const e=_i.current,t=et.current;if(!e||!t)return;const i=dt.current.beforeCompute(t.getLastUpdateResult(),!1),n=v(),o=S(e,jt,vt,n);if(!o)return void dt.current.afterCompute(i,!1,!1);const r=function(e){const t=Gt(e,Yt),i=Gt(e,Ft),n=Gt(e,_t),o=Gt(e,Lt),r=Gt(e,Wt),s=Gt(e,qt),a=Gt(e,Ht),c=Gt(e,Xt),l=Gt(e,Dt),d=Gt(e,zt);return{annotationBackground:Vt(s,.94),annotationStroke:r,annotationText:a,background:s,border:r,closedWindowFill:Vt(i,.08),closedWindowStroke:Vt(i,.55),danger:i,focus:l,grid:d,gutterFill:Vt(c,.14),lateFill:n,openWindowFill:Vt(t,.07),openWindowStroke:Vt(t,.3),primary:t,selectedFill:n,selectedStroke:l,success:o,text:a,textSecondary:c,warning:n}}(o);o.clearRect(-vt.left,-vt.top,jt[0],jt[1]),m||"transparent"===s||(o.fillStyle=s??r.background,o.fillRect(-vt.left,-vt.top,jt[0],jt[1]));const a=t.snapshot(),c=t.readBodies();if(Ni(c,a.simulationState),Xi){const e=ei.current();if(e-Hi.current>=100){Hi.current=e;const t=K(c);Li(e=>e.length===t.length&&e.every((e,i)=>e.pointId===t[i].pointId&&Math.round(e.x)===Math.round(t[i].x)&&Math.round(e.y)===Math.round(t[i].y))?e:t)}}Te&&(o.save(),Te(o,c),o.restore());for(const e of c){const t=qe.current.get(e.id),i=t?Array.from(t.activeRegionIds).map(e=>Ge.get(e)).filter(e=>null!=e):[],n=Bi(e,a.simulationState,x,be,xe,Mi(t),i,r.primary,r.text,Oe);je?(o.save(),je(o,e,n),o.restore()):xi(o,e,n)}Ne&&(o.save(),Ne(o,c),o.restore()),function(e,t,i){let n=!1;for(const[o,r]of t){const s=Math.min(1,Math.max(0,(i-r.startedAt)/r.durationMs));if(s>=1){t.delete(o);continue}n=!0;const a=1-Math.pow(1-s,3),{body:c}=r,l=r.radius+28*a,d=1-s;e.save(),e.globalAlpha*=d,e.strokeStyle=r.color,e.fillStyle=r.color,e.lineWidth=2.4*d+.4,e.beginPath(),e.arc(c.x,c.y,l,0,2*Math.PI),e.stroke(),e.globalAlpha*=.18,e.beginPath(),e.arc(c.x,c.y,.52*l,0,2*Math.PI),e.fill(),e.restore(),e.save(),e.globalAlpha*=d,e.strokeStyle=r.color,e.lineWidth=1.8;for(let t=0;8>t;t+=1){const i=t*(Math.PI/4)+1.4*s,n=r.radius+5+12*a,o=r.radius+12+34*a;e.beginPath(),e.moveTo(c.x+Math.cos(i)*n,c.y+Math.sin(i)*n),e.lineTo(c.x+Math.cos(i)*o,c.y+Math.sin(i)*o),e.stroke()}e.restore()}}(o,Ci.current,ei.current()),dt.current.afterCompute(i,!0,!1),lt.current=!1},[_i,dt,jt,vt,m,s,Ni,Xi,Te,Ne,x,be,xe,Oe,je,Ge]),Zi=Tt((e,t)=>{const i=et.current,n=`${we}:${e}:${t??""}`;ut.current!==n&&(ut.current=n,ae?.({execution:e,liveBodies:i?.liveBodyCount()??0,queuedBodies:i?.queueSize()??0,reason:t,requested:we}))},[ae,we]),en=Tt((e,t=!0)=>{yt.current+=1,pt.current=!1,ft.current=!1,bt.current=!1,gt.current?.terminate(),gt.current=null,t&&Zi("sync",e)},[Zi]),tn=Tt(()=>ti?"undefined"==typeof window||"undefined"==typeof Worker?"worker unavailable":Ze?"runtime region effects require sync":Je?"body forces require sync":ze?"physics controllers require sync":function(e){return!e||!e.engine&&Jt(e.sediment)&&(!(t=e.colliders)||t.every(e=>{const t=e.bodyFilter;return!t||"function"!=typeof t}));var t}(st??{})?ii(G)?mt.current?"worker fallback":null:"spawn pacing is not worker-cloneable":"config is not worker-cloneable":"hydrating",[st,ze,Je,Ze,ti,G]),dn=Tt(()=>{const e=et.current,t=tn();if(!e||t)return{reason:t,useWorker:!1};const i=e.liveBodyCount(),n=e.queueSize(),o=function(e,t,i=0,n=Qt){return"sync"!==e&&("worker"===e||t+i>=n)}(we,i,n,Be);return{reason:o?"worker"===we?"forced worker":"body threshold":"below threshold",useWorker:o}},[we,Be,tn]),un=Tt(e=>{const t=et.current;return t&&e.snapshot?(t.restore(e.snapshot),lt.current=!0,t):t},[]),hn=Tt((e,t=!0)=>{const i=un(e);if(!i)return;t&&he?.(e.result,i.controls()),Gi();const n=i.snapshot();!e.result.shouldContinue&&Ci.current.size<=0||n.paused||!n.visible||kt.current||Bt()},[un,he,Gi,kt,Bt]),pn=Tt(e=>{mt.current=!0,en("worker failed: "+((e instanceof Error?e.message:e+"")||"unknown error"))},[en]),mn=Tt(()=>{const e=et.current;if(!e)return!1;const t=dn();if(!t.useWorker)return pt.current||bt.current?en(t.reason??"sync fallback"):Zi("sync",t.reason??"sync"),!1;if(pt.current||bt.current)return!0;const i=gt.current??new ri;gt.current=i,bt.current=!0;const n=yt.current+1;return yt.current=n,i.initFromSnapshot(st??{},e.snapshot()).then(e=>{if(yt.current!==n)return;bt.current=!1,pt.current=!0,mt.current=!1,un(e),Zi("worker",t.reason??"worker"),Gi();const i=et.current?.snapshot();e.result.shouldContinue&&i&&!i.paused&&i.visible&&!kt.current&&(ct.current=null,Bt())}).catch(e=>{yt.current===n&&pn(e)}),!0},[un,st,pn,Gi,kt,Zi,Bt,en,dn]),yn=Tt(e=>"frame"===e.type||"removed"===e.type?e.frame:null,[]),fn=Tt((e,t=!0)=>{const i=gt.current;if(!i||!pt.current)return;const n=yt.current;i.request(e).then(e=>{if(yt.current!==n)return;const i=yn(e);i&&hn(i,t)}).catch(pn)},[hn,yn,pn]),gn=Tt(()=>{const e=et.current;if(!e)return;const t=mn(),i=e.snapshot(),n=Le||Je||Ze||!!ze;i.paused||!i.visible||!e.hasPendingWork()&&!n||kt.current?Mt.current():t&&bt.current||(ct.current=null,Bt())},[ze,Le,Je,Ze,kt,Mt,Bt,mn]),bn=Tt(()=>{St(),wt.current=null;const e=et.current;if(!e)return;if(pt.current&>.current){if(ft.current)return;let t=0;if(!kt.current){const e=ei.current();t=null!==ct.current?(e-ct.current)/1e3:0,ct.current=e}const i=gt.current,n=yt.current;return ft.current=!0,void(kt.current?i.settle():i.tick(t)).then(e=>{ft.current=!1,yt.current===n&&hn(e)}).catch(i=>{if(ft.current=!1,yt.current!==n)return;pn(i);const o=kt.current?e.settleWithObservations():e.tick(t);Ri({store:e,result:o,regionEffects:We.current,regionState:qe.current,bodyForces:Fe.current,composed:Ye.current,onTick:De.current}),Gi()})}let t;if(kt.current)t=e.settleWithObservations();else{const i=ei.current(),n=null!==ct.current?(i-ct.current)/1e3:0;ct.current=i,t=e.tick(n)}const i=Ye.current,{regionEffectsApplied:n,bodyForcesApplied:o,snapshot:r}=Ri({store:e,result:t,regionEffects:We.current,regionState:qe.current,bodyForces:Fe.current,composed:i,onTick:De.current});Gi(),(He.current||t.shouldContinue||n||o||i||Ci.current.size>0)&&!r.paused&&r.visible&&!kt.current&&Bt()},[hn,pn,Gi,St,Bt,kt,wt]);Mt.current=bn,Nt(()=>{mt.current=!1,(pt.current||bt.current)&&en("config changed",!1),et.current?.updateConfig(st??{}),gn()},[st,en]),Nt(()=>{mt.current=!1,gn()},[ti,we,Be]),function({cancelRender:e,frameRuntime:t,lastFrameTimeRef:i,paused:n,postWorkerCommand:o,requestRender:r,storeRef:s,suspendWhenHidden:a}){const c=gi(o);c.current=o;const l=gi(r);l.current=r,fi(()=>{const o=s.current;o&&(t.setPaused(n),o.setPaused(n),n&&(i.current=null,e()),c.current({type:"setPaused",paused:n},!1),l.current())},[e,t,n]),fi(()=>{if(!a){const e=s.current;return t.setVisible(!0),void(e&&!e.snapshot().visible&&(e.setVisible(!0),c.current({type:"setVisible",visible:!0},!1),l.current()))}if("undefined"==typeof document)return;const n=()=>{const n=s.current;if(!n)return;const o=bi();t.setVisible(o),n.setVisible(o),o||(i.current=null,e()),c.current({type:"setVisible",visible:o},!1),l.current()};return n(),document.addEventListener("visibilitychange",n),()=>document.removeEventListener("visibilitychange",n)},[e,t,a])}({cancelRender:St,frameRuntime:Zt,lastFrameTimeRef:ct,paused:me,postWorkerCommand:fn,requestRender:gn,storeRef:et,suspendWhenHidden:Ae}),Nt(()=>()=>en("unmount",!1),[en]),Nt(()=>{Gi()},[Gi]),Ot(t,()=>({...et.current.controls(),applyImpulse:(e,t,i)=>{et.current.applyImpulse(e,t,i),fn({type:"applyImpulse",id:e,ix:t,iy:i}),gn()},clear:()=>{et.current.clear(),qe.current.clear(),Ci.current.clear(),fn({type:"clear"}),gn()},clearRegionState:e=>{e?qe.current.delete(e):qe.current.clear(),gn()},getData:()=>et.current.readBodies(),getRegionState:e=>e?Mi(qe.current.get(e)):function(e){const t={};return e.forEach((e,i)=>{const n=Mi(e);n&&(t[i]=n)}),t}(qe.current),getStore:()=>et.current,pause:()=>{Zt.setPaused(!0),ct.current=null,St(),et.current.setPaused(!0),fn({type:"setPaused",paused:!0},!1),gn()},push:(e,t)=>{et.current.enqueue(e,t),ii(t)?fn({type:"enqueue",spawns:[e],pacing:t}):(pt.current||bt.current)&&en("spawn pacing is not worker-cloneable"),gn()},pushMany:(e,t)=>{et.current.enqueue(e,t),ii(t)?fn({type:"enqueue",spawns:e,pacing:t}):(pt.current||bt.current)&&en("spawn pacing is not worker-cloneable"),gn()},popBodies:(e,t={})=>{const i=et.current,n=new Map(i.readBodies().map(e=>[e.id,e])),o=i.remove(e),r=ei.current();for(const e of o){const i=n.get(e);i&&(qe.current.delete(e),Ci.current.set(e,{body:i,color:t.color??"#f59e0b",durationMs:Math.max(120,t.durationMs??520),radius:t.radius??vi(i),startedAt:r}),hi.current===e&&(hi.current=null,li(null)),ui(t=>t?.id===e?null:t))}return o.length&&(fn({type:"remove",ids:o}),gn()),o},remove:e=>{const t=et.current.remove(e);for(const t of e)qe.current.delete(t);return fn({type:"remove",ids:e}),gn(),t},restore:e=>{et.current.restore(e),qe.current.clear(),Ci.current.clear(),fn({type:"restore",snapshot:e},!1),gn()},resume:()=>{Zt.setPaused(!1),ct.current=null,et.current.setPaused(!1),fn({type:"setPaused",paused:!1},!1),gn()},settle:e=>{const t=et.current.settle(e);return fn({type:"settle",maxSteps:e}),gn(),t},settleWithObservations:e=>{const t=et.current.settleWithObservations(e);return fn({type:"settle",maxSteps:e}),gn(),t},step:e=>{const t=et.current,i=t.tick(e);return Ri({store:t,result:i,regionEffects:We.current,regionState:qe.current,bodyForces:Fe.current,composed:Ye.current,onTick:De.current}),fn({type:"tick",deltaSeconds:e}),Gi(),i}}),[St,Zt,Gi,fn,gn,en]);const xn=k||!ti&&ni,vn=["stream-physics-frame",D?"stream-physics-frame--mode-"+D:null,F?"stream-physics-frame--emphasis-"+F:null,I].filter(Boolean).join(" "),wn=W??("string"==typeof Ce?Ce:void 0)??"Physics chart",kn=ht+"-physics-table",Mn=Math.max(1,jt[0]-vt.left-vt.right),Sn=Math.max(1,jt[1]-vt.top-vt.bottom),In=z&&di?Re?Re(di):on(Ji,{hover:di}):null,An=In&&di?on(l,{x:di.x-vt.left,y:di.y-vt.top,containerWidth:Math.max(1,jt[0]-vt.left-vt.right),containerHeight:Math.max(1,jt[1]-vt.top-vt.bottom),margin:vt,className:"stream-physics-tooltip",children:In}):null;if(xn){const e=et.current??si(st,_,G),t="string"==typeof Ce?Ce:void 0,{svg:i}=function(e,t={}){const{width:i=640,height:n=360,title:o,description:r,background:s,className:a,idPrefix:c="physics",...l}=t,d=pi(e,l),u=function(e){const t=e.replace(/[^A-Za-z0-9_-]/g,"_");return!t||/^\d/.test(t)?"physics-"+t:t}(c),h=o?u+"-title":void 0,p=r?u+"-desc":void 0,m=[h,p].filter(Boolean).join(" ")||void 0;return{svg:ci.renderToStaticMarkup(yi("svg",{xmlns:"http://www.w3.org/2000/svg",className:a??"stream-physics-frame",width:i,height:n,viewBox:`0 0 ${i} ${n}`,role:"img","aria-labelledby":m,children:[o&&mi("title",{id:h,children:o}),r&&mi("desc",{id:p,children:r}),s&&"transparent"!==s?mi("rect",{x:0,y:0,width:i,height:n,fill:s}):null,mi("g",{id:u+"-data-area",children:d.sceneNodes.map((e,t)=>E(e,t,u))})]})),scene:d,evidence:d.evidence}}(e,{width:jt[0],height:jt[1],title:t,description:W,background:"transparent"===s?void 0:s,className:"stream-physics-frame__svg",idPrefix:"physics-"+ht});return rn("div",{ref:Ct,className:vn,"data-semiotic-mode":D,role:"img","aria-label":wn,style:{width:jt[0],height:jt[1]},children:[on(h,{summary:Ie}),on("div",{dangerouslySetInnerHTML:{__html:i}})]})}return rn("div",{ref:Ct,className:vn,"data-semiotic-mode":D,role:"group","aria-label":wn,"aria-describedby":oi?Ti:void 0,tabIndex:0,style:{position:"relative",width:jt[0],height:jt[1]},onKeyDown:zi,children:["production"!==process.env.NODE_ENV&&et.current&&on(u,{store:et.current,diagnostics:dt.current}),i?on(p,{tableId:kn}):null,i?on(nn,{chartTitle:"string"==typeof Ce?Ce:wn,items:Qe,tableId:kn}):null,on(h,{summary:Ie}),on(a,{hoverPoint:di}),on("div",{id:Ti,"aria-live":"polite","aria-atomic":"true",style:Ei,children:oi?oi.description??oi.label:""}),rn("div",{role:"img","aria-label":wn,style:{position:"relative",width:"100%",height:"100%"},children:[on(c,{size:jt,margin:vt,children:It}),on("canvas",{ref:_i,width:jt[0],height:jt[1],"aria-hidden":"true",onPointerDown:Di,onPointerMove:z?Fi:void 0,onPointerLeave:z?Wi:void 0}),At,on(J,{width:Mn,height:Sn,totalWidth:jt[0],totalHeight:jt[1],margin:vt,title:Ce,legend:V,legendPosition:ie,legendLayout:te,legendHoverBehavior:Z,legendClickBehavior:U,legendHighlightedCategory:Q,legendIsolatedCategories:ee,pointNodes:Yi,annotations:n,onAnnotationActivate:o,onObservation:re,chartId:M,chartType:ln,autoPlaceAnnotations:r,svgAnnotationRules:Pe}),on(d,{active:null!=oi,hoverPoint:oi?{x:oi.x,y:oi.y}:null,margin:vt,size:jt,shape:oi?.shape,width:oi?.width,height:oi?.height,pathData:oi?.pathData}),An]})]})}));dn.displayName="StreamPhysicsFrame";var un=dn;import{scaleLinear as hn}from"d3-scale";function pn(e){const[t,i]=e;return{width:t,height:i,plot:{x:32,y:24,width:Math.max(80,t-64),height:Math.max(80,i-58)}}}function mn(e){const t=(e??"")+"";if(!t)return"#4e79a7";const i=["#4e79a7","#59a14f","#e15759","#f28e2b","#76b7b2","#edc948","#b07aa1","#ff9da7"];let n=0;for(let e=0;t.length>e;e+=1)n=31*n+t.charCodeAt(e)>>>0;return i[n%i.length]}function yn(e,n="#4e79a7",o){const r=o?.styleRules,s=!!r&&r.length>0,a=s?t(o?.valueAccessor):void 0;return t=>{const o=t.datum,c=o&&e?"function"==typeof e?e(o,0):o[e]:void 0,l={fill:null==c?n:mn(c),stroke:"#111827",strokeWidth:1,opacity:.9};return s&&o&&Object.assign(l,i(o,r,{value:a?a(o):void 0,category:null==c?void 0:c+""})),l}}function fn(e,t,i,n){return{fixedDt:1/120,maxSubsteps:8,colliders:t,observation:{chartType:i},kernel:{seed:e,gravity:{x:0,y:760},cellSize:36,collisionIterations:6,velocityDamping:.995,restitution:.08,friction:.4,sleepSpeed:8,sleepAfter:.6,...n}}}function gn(e,t,i){if(!e.length)return[];const n=pn(t),o=n.plot.width/Math.max(1,e.length),r=Math.max(1,...e.map(e=>e.value)),s=.62*n.plot.height,a=n.plot.y+n.plot.height;return e.map((e,t)=>{const c=Math.max(8,e.value/r*s),l=`${i} ${e.label}: ${e.value}${null==e.secondary?"":`, ${e.secondary} secondary`}`;return{id:`${i}-${e.label}`,label:l,description:l,datum:e,x:n.plot.x+(t+.5)*o,y:a-c/2,shape:"rect",width:Math.max(12,.58*o),height:c,group:i}})}function bn(e,t,i){return"function"==typeof i?i(e,t):e[i]}function xn(e){if(e instanceof Date){const t=e.getTime();return Number.isFinite(t)?t:null}const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:null}function vn(e,t,i){return Math.max(t,Math.min(i,e))}function wn(e,t){const i=xn(e);return null!=i&&i>0?i:t}function kn(e){return((e??"unknown")+"").trim().replace(/[^A-Za-z0-9_-]+/g,"_")||"unknown"}function Mn(e){let t=e>>>0;return()=>{t+=1831565813;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}function Sn(e){const{data:t,valueAccessor:i,bins:n,ballRadius:o,seed:r,size:s,valueExtent:a}=e,c=pn(s),l=t.map((e,t)=>xn(bn(e,t,i))).filter(e=>null!=e),d=function(e){if(!e)return;const t=xn(e[0]),i=xn(e[1]);return null!=t&&null!=i?t>i?[i,t]:[t,i]:void 0}(a),u=d?.[0]??(l.length?Math.min(...l):0),h=d?.[1]??(l.length?Math.max(...l):1),p=h===u?1:h-u,m=hn().domain([0,n]).range([c.plot.x,c.plot.x+c.plot.width]),y=Array.from({length:n},()=>0),f=[];t.forEach((e,t)=>{const r=xn(bn(e,t,i));if(null==r)return;const s=Math.max(0,Math.min(n-1,Math.floor((r-u)/p*n)));y[s]+=1,f.push({id:(e.id??"galton-"+t)+"",x:m(s+.5),y:c.plot.y+o+2,vx:8*(t%5-2),vy:0,mass:1,shape:{type:"circle",radius:o},datum:{...e,value:r,bin:s}})});const g=c.plot.y+c.plot.height;return{config:fn(r,[...Ke({x:c.plot.x,y:c.plot.y,width:c.plot.width,height:c.plot.height},{idPrefix:"galton",wallThickness:20,floorThickness:20}),...Qe({idPrefix:"galton-bin",count:n,domainStart:0,domainStep:1,xScale:m,yTop:c.plot.y-400,yBottom:g,wallThickness:6})],"GaltonBoardChart"),initialSpawns:f,initialSpawnPacing:{pacing:{ratePerSec:55}},projectionRows:y.map((e,t)=>({label:t+1+"",value:e})),metadata:{kind:"galton-board",bins:n,plot:c.plot,valueExtent:[u,h]}}}import{scaleLinear as In}from"d3-scale";function An(e){const{count:t,idPrefix:i,wallThickness:n,xScale:o,yBottom:r,yTop:s,yTopForIndex:a}=e;return Array.from({length:t+1},(e,t)=>{const c=Math.min(r-1,a?.(t)??s),l=Math.max(1,r-c);return{id:`${i}-wall-${t}`,shape:{type:"aabb",x:o(t),y:c+l/2,width:n,height:l}}})}function Pn(e){const{data:t,timeAccessor:i,arrivalAccessor:n,windows:o,watermark:r,ballRadius:s,seed:a,size:c,timeExtent:l,timeScale:d=1}=e,u=pn(c),h=t.map((e,t)=>xn(bn(e,t,i))).filter(e=>null!=e),p=xn(l?.[0]),m=xn(l?.[1]),y=h.length?Math.min(...h):0,f=h.length?Math.max(...h):y+o.size,g=Math.min(p??y,y),b=Math.max(m??f,f),x=Math.floor(g/o.size)*o.size,v=Math.max(1,Math.ceil((b-x+o.size)/o.size)),w=h.length?Math.max(...h):0,k="function"==typeof r?r(w):xn(r?.value)??w-(r?.delay??o.size),M=Math.max(0,Math.min(v,Array.from({length:v},(e,t)=>t).reduce((e,t)=>x+(t+1)*o.size>k?e:e+1,0))),S=function(e,t){const i=Math.max(5*t,Math.min(92,.13*e.plot.width));return{gutter:{x:e.plot.x,y:e.plot.y,width:i,height:e.plot.height},windowPlot:{x:e.plot.x+i,y:e.plot.y,width:Math.max(40,e.plot.width-i),height:e.plot.height},wallTop:e.plot.y+.48*e.plot.height}}(u,s),I=x+v*o.size,A=In().domain([x,I]).range([S.windowPlot.x,S.windowPlot.x+S.windowPlot.width]),P=Array.from({length:v},()=>({value:0,secondary:0})),C=[];t.forEach((e,t)=>{const r=xn(bn(e,t,i));if(null==r)return;const a=xn(bn(e,t,n))??r,c=Math.max(0,Math.min(v-1,Math.floor((r-x)/o.size))),l=k>=x+(c+1)*o.size;P[c].value+=l?0:1,P[c].secondary+=l?1:0,C.push({id:(e.id??"event-"+t)+"",x:Math.max(S.windowPlot.x+s,Math.min(S.windowPlot.x+S.windowPlot.width-s,A(r))),y:u.plot.y+s+2,vx:8*(t%3-1),vy:0,mass:1,friction:.02,spawnAt:a,shape:{type:"circle",radius:s},datum:{...e,eventTime:r,arrivalTime:a,windowIndex:c,late:l}})});const R=u.plot.y+u.plot.height,B=function(e,t){const i=Math.max(0,Math.min(e.windowCount,e.closedWindowCount));if(!i)return[];const n=e.windowStart,o=e.windowStart+e.windowCount*e.windowSize,r=In().domain([n,o]).range([e.windowPlot.x,e.windowPlot.x+e.windowPlot.width]),s=r(e.windowStart+i*e.windowSize),a=e.windowPlot.x,c=t+Math.max(18,Math.min(.3*e.windowPlot.height,s-a)),l=e=>s===a?t:c+(e-a)/(s-a)*(t-c),d=[];for(let t=0;i>t;t+=1){const i=e.windowStart+t*e.windowSize,n=i+e.windowSize,o=r(i),s=r(n);d.push({id:"eventdrop-lid-"+t,windowIndex:t,x1:o,y1:l(o),x2:s,y2:l(s)})}return d}({closedWindowCount:M,gutter:S.gutter,plot:u.plot,windowCount:v,windowPlot:S.windowPlot,windowSize:o.size,windowStart:x},u.plot.y+.28*u.plot.height);return{config:fn(a,[...Ke({x:u.plot.x,y:u.plot.y,width:u.plot.width,height:u.plot.height},{idPrefix:"eventdrop",wallThickness:20,floorThickness:20}),...An({idPrefix:"eventdrop-window",count:v,xScale:e=>A(x+e*o.size),yTop:S.wallTop,yTopForIndex:e=>{const t=(e=>{if(0>e||e>M)return null;const t=0===e?B[0]?.y1:B[e-1]?.y2??B[e]?.y1;return"number"==typeof t&&Number.isFinite(t)?t:null})(e);return null==t?S.wallTop:t+1.25*s},yBottom:R,wallThickness:6}),...B.map(e=>({id:e.id,shape:{type:"segment",x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2,thickness:Math.max(4,.42*s)},friction:.02,restitution:.01}))],"EventDropChart",{friction:.08}),initialSpawns:C,initialSpawnPacing:{pacing:"arrival",timeAccessor:e=>e.datum?.arrivalTime,timeScale:d},projectionRows:P.map((e,t)=>({label:`${x+t*o.size}-${x+(t+1)*o.size}`,value:e.value,secondary:e.secondary})),metadata:{kind:"event-drop",closedWindowCount:M,gutter:S.gutter,lidSegments:B,lateCount:P.reduce((e,t)=>e+t.secondary,0),plot:u.plot,windowPlot:S.windowPlot,watermarkValue:k,windowCount:v,windowSize:o.size,windowStart:x}}}function Cn(e,t,i){const n=e.width/Math.max(1,t),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:t=>e.x+(t+.5)*n,pileHeight:e=>Math.ceil(Math.max(0,e)/s)*o}}function Rn(e){const{data:t,categoryAccessor:i,valueAccessor:n,unitValue:o,ballRadius:r,seed:s,size:a}=e,c=wn(o,1),l=pn(a),d=[],u=new Map,h=new Map,p=[];function m(e){let t=u.get(e);return null==t&&(t=d.length,d.push(e),u.set(e,t)),t}t.forEach((e,t)=>{m((bn(e,t,i)??"unknown")+"")});const y=Math.max(1,d.length),f=Cn(l.plot,y,r),g=Math.max(0,f.tubeWidth/2-r-1),b=d.map(()=>[]);t.forEach((e,t)=>{const o=(bn(e,t,i)??"unknown")+"",s=m(o),a=n?xn(bn(e,t,n)):1,d=Math.max(0,Math.round((a??0)/c)),u=f.centerX(s);for(let i=0;d>i;i+=1){const n=h.get(o)??0,a=f.perRow>1?((f.perRow>1?n%f.perRow:0)/(f.perRow-1)*2-1)*g:0;h.set(o,n+1),b[s].push({id:`${(e.id??"pile-"+t)+""}-${i}`,x:u+a,y:l.plot.y+r+2,vx:(i%3-1)*r/2,vy:0,mass:1,shape:{type:"circle",radius:r},datum:{...e,category:o,unitIndex:i}})}});const x=b.reduce((e,t)=>Math.max(e,t.length),0);for(let e=0;x>e;e+=1)for(const t of b)t.length>e&&p.push(t[e]);const v=l.plot.y+l.plot.height,w=[...Ke({x:l.plot.x,y:l.plot.y,width:l.plot.width,height:l.plot.height},{idPrefix:"pile",wallThickness:20,floorThickness:20})],k=l.plot.y-400;for(let e=0;y>e;e+=1){const t=f.centerX(e);for(const i of[-1,1])w.push({id:`pile-tube-${e}-${0>i?"l":"r"}`,shape:{type:"aabb",x:t+i*f.tubeWidth/2,y:(k+v)/2,width:6,height:v-k}})}return{config:fn(s,w,"PhysicsPileChart"),initialSpawns:p,initialSpawnPacing:{pacing:{ratePerSec:20}},projectionRows:d.map(e=>({label:e,value:h.get(e)??0}))}}import{scaleLinear as Bn}from"d3-scale";function jn(e){const{data:t,xAccessor:i,groupAccessor:n,radiusAccessor:o,pointRadius:r,seed:s,size:a,xExtent:c,collisionIterations:l,settle:d}=e,u=pn(a),h=Mn(s),p=[],m=[],y=new Map;t.forEach((e,t)=>{const s=xn(bn(e,t,i));if(null==s)return;const a=n?(bn(e,t,n)??"All")+"":"All",c=o?xn(bn(e,t,o)):null,l=vn(null!=c&&c>0?c:r,2,18);!function(e){let t=y.get(e);null==t&&(t=m.length,m.push(e),y.set(e,t))}(a),p.push({datum:e,index:t,value:s,group:a,radius:l})});const f=p.map(e=>e.value),g=c?xn(c[0]):null,b=c?xn(c[1]):null,x=f.length?Math.min(...f):0,v=f.length?Math.max(...f):1;let w=g??x,k=b??v;if(w===k&&(w-=.5,k+=.5),w>k){const e=k;k=w,w=e}const M=Math.max(r,...p.map(e=>e.radius)),S=u.plot.x+M+8,I=u.plot.x+u.plot.width-M-8,A=Bn().domain([w,k]).range([S,I]),P=Math.max(1,m.length),C=u.plot.y+Math.max(28,3*M),R=Math.max(0,u.plot.y+u.plot.height-Math.max(28,3*M)-C),B=e=>{const t=y.get(e)??0;return 1===P?u.plot.y+.54*u.plot.height:C+t/(P-1)*R},j=new Map,T=p.map((e,t)=>{j.set(e.group,(j.get(e.group)??0)+1);const i=A(e.value),n=B(e.group),o=(h()-.5)*e.radius*1.6,r=(h()-.5)*e.radius*1.6;return{id:(e.datum.id??"collision-swarm-"+t)+"",x:d?i+o:vn(i+(t%9-4)*e.radius*2.5,S,I),y:d?n+r:u.plot.y-18-t%12*e.radius,vx:d?0:22*(h()-.5),vy:d?0:24+18*h(),mass:1,shape:{type:"circle",radius:e.radius},datum:{...e.datum,xValue:e.value,group:e.group,radius:e.radius,targetX:i,targetY:n},springs:[{target:{type:"point",x:i,y:n},restLength:0,stiffness:34,damping:5.5}]}});return{config:fn(s,Ke({x:u.plot.x,y:u.plot.y,width:u.plot.width,height:u.plot.height},{idPrefix:"collision-swarm",includeCeiling:!1,wallThickness:20,floorThickness:20}),"CollisionSwarmChart",{gravity:{x:0,y:0},cellSize:Math.max(24,4*M),collisionIterations:Math.max(1,Math.round(l??6)),velocityDamping:.992,restitution:.02,friction:.18,sleepSpeed:3,sleepAfter:.5}),initialSpawns:T,projectionRows:m.map(e=>({label:e,value:j.get(e)??0})),metadata:{kind:"collision-swarm",xExtent:[w,k],xRange:[S,I],groups:m.map(e=>({label:e,y:B(e),count:j.get(e)??0})),plot:u.plot}}}function Tn(e){if(Array.isArray(e)&&e.length>=2){const t=xn(e[0]),i=xn(e[1]);return null!=t&&null!=i?{x:t,y:i}:null}if(e&&"object"==typeof e){const t=e,i=xn(t.x),n=xn(t.y);return null!=i&&null!=n?{x:i,y:n}:null}return null}function Nn(e){return Array.isArray(e)?e.map(Tn).filter(e=>null!=e):[]}function On(e,t,i){return"normalized"===i?{x:t.plot.x+e.x*t.plot.width,y:t.plot.y+e.y*t.plot.height}:{x:vn(e.x,t.plot.x,t.plot.x+t.plot.width),y:vn(e.y,t.plot.y,t.plot.y+t.plot.height)}}function En(e){let t=0;for(let i=1;e.length>i;i+=1)t+=Math.hypot(e[i].x-e[i-1].x,e[i].y-e[i-1].y);return t}function $n(e,t){if(0===e.length)return{x:0,y:0};if(1===e.length)return{...e[0]};const i=vn(t,0,1)*En(e);let n=0;for(let t=1;e.length>t;t+=1){const o=e[t-1],r=e[t],s=Math.hypot(r.x-o.x,r.y-o.y);if(s>0){if(n+s>=i){const e=(i-n)/s;return{x:o.x+(r.x-o.x)*e,y:o.y+(r.y-o.y)*e}}n+=s}}return{...e[e.length-1]}}function qn(e,t){const i=$n(e,Math.max(0,t-.02)),n=$n(e,Math.min(1,t+.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 Wn(e){const{coordinateMode:t,flowSpeed:i,links:n,maxParticles:o,nodeIdAccessor:r,nodeXAccessor:s,nodeYAccessor:a,nodes:c,particleRadius:l,particleRate:d,pathAccessor:u,pathConstraint:h="path",reducedMotion:p,seed:m,size:y,sourceAccessor:f,targetAccessor:g,throughputAccessor:b}=e,x=pn(y),v=Mn(m),w=new Map,k=new Map,M=[];function S(e){if(e&&"object"==typeof e){const t=e;if("function"==typeof r){const e=r(t,0);if(null!=e)return e+""}if("string"==typeof r&&null!=t[r])return t[r]+"";if(null!=t.id)return t.id+""}return(e??"unknown")+""}c.forEach((e,t)=>{const i=(bn(e,t,r)??e.id??t)+"",n=xn(bn(e,t,s)),o=xn(bn(e,t,a));if(null!=n&&null!=o){const e={x:n,y:o};w.set(i,e),M.push(e)}k.set(i,(e.label??e.name??i)+"")});const I=[];n.forEach((e,t)=>{const i=S(bn(e,t,f)),n=S(bn(e,t,g)),o=Math.max(0,xn(bn(e,t,b))??0),r=Nn(u?bn(e,t,u):void 0),s=r.length?r:Nn(e.path??e.points??e.route);s.forEach(e=>M.push(e)),I.push({id:(e.id??`physical-flow-${i}-${n}-${t}`)+"",link:e,index:t,source:i,target:n,throughput:o,rawPath:s})});const A=(C=M,"normalized"===(P=t)||"pixels"===P?P:C.length>0&&C.every(e=>!(0>e.x||e.x>1||0>e.y||e.y>1))?"normalized":"pixels");var P,C;const R=new Map;for(const[e,t]of w)R.set(e,On(t,x,A));const B=[];for(const e of I){let t=e.rawPath.map(e=>On(e,x,A));if(2>t.length){const i=R.get(e.source),n=R.get(e.target);i&&n&&(t=[i,n])}else R.has(e.source)||R.set(e.source,t[0]),R.has(e.target)||R.set(e.target,t[t.length-1]);t.length>=2&&e.throughput>0&&(k.has(e.source)||k.set(e.source,e.source),k.has(e.target)||k.set(e.target,e.target),B.push({...e,path:t,packetCount:0}))}const j=wn(d,.12),T=Math.max(1,Math.round(o)),N=B.map(e=>Math.max(1,Math.round(e.throughput*j))),O=N.reduce((e,t)=>e+t,0),E=O>T?T/O:1;B.forEach((e,t)=>{e.packetCount=Math.max(1,Math.floor(N[t]*E))});let $=B.reduce((e,t)=>e+t.packetCount,0);for(;$>T;){const e=B.reduce((e,t,i)=>t.packetCount>1&&(-1===e||t.packetCount>B[e].packetCount)?i:e,-1);if(-1===e)break;B[e].packetCount-=1,$-=1}const q=new Map,W=new Map,F=[],D=wn(i,90),z=wn(l,4);B.forEach((e,t)=>{q.set(e.target,(q.get(e.target)??0)+e.throughput),W.set(e.source,(W.get(e.source)??0)+e.throughput);const i=En(e.path);for(let n=0;e.packetCount>n;n+=1){const o=(n+.5)/e.packetCount,r=p?o:vn(.12+.84*o+.04*(v()-.5),.04,.98),s=p?r:Math.max(0,r-(.18+.12*v())),a=$n(e.path,s),c=$n(e.path,r),l=qn(e.path,s),d={x:-l.y,y:l.x},u=(v()-.5)*z*1.5;F.push({id:`${e.id}-packet-${n}`,x:a.x+d.x*u,y:a.y+d.y*u,vx:p?0:l.x*D+10*(v()-.5),vy:p?0:l.y*D+10*(v()-.5),mass:.8,spawnAt:p?0:.04*t+n/32,shape:{type:"circle",radius:z},datum:{...e.link,source:e.source,target:e.target,throughput:e.throughput,packetIndex:n,packetCount:e.packetCount,routeProgress:r,flowPath:e.path,flowPathLength:i,flowRouteId:e.id,flowSpeed:D,sourceLabel:k.get(e.source)??e.source,targetLabel:k.get(e.target)??e.target},springs:"none"!==h&&p?[{target:{type:"point",x:c.x,y:c.y},restLength:.7*z,stiffness:26,damping:4.25}]:void 0})}});const Y=Math.max(18,5*z),L=Array.from(R,([e,t])=>({nodeId:e,label:k.get(e)??e,sensorId:"physical-flow-node-"+kn(e),point:t})),H=L.map(e=>({id:e.sensorId,sensor:!0,shape:{type:"aabb",x:e.point.x,y:e.point.y,width:Y,height:Y}})),X=Object.fromEntries(L.map(e=>[e.sensorId,{binId:e.label,enterType:"physics-proximity-enter",exitType:"physics-proximity-exit"}])),_=fn(m,[...Ke({x:x.plot.x,y:x.plot.y,width:x.plot.width,height:x.plot.height},{idPrefix:"physical-flow",wallThickness:18,floorThickness:18}),...H],"PhysicalFlowChart",{gravity:{x:0,y:0},cellSize:Math.max(24,7*z),collisionIterations:3,velocityDamping:.994,restitution:.01,friction:.16,sleepSpeed:2.5,sleepAfter:.7});_.bodyLimit=T,_.eviction="oldest",_.observation={..._.observation,sensors:X};const G=Array.from(R,([e,t])=>({id:e,label:k.get(e)??e,x:t.x,y:t.y,sensorId:"physical-flow-node-"+kn(e),incoming:q.get(e)??0,outgoing:W.get(e)??0})),V=B.map(e=>({id:e.id,source:e.source,target:e.target,sourceLabel:k.get(e.source)??e.source,targetLabel:k.get(e.target)??e.target,throughput:e.throughput,packetCount:e.packetCount,path:e.path}));return{config:_,initialSpawns:F,projectionRows:G.filter(e=>e.incoming>0||e.outgoing>0).map(e=>({label:e.label,value:e.incoming,secondary:e.outgoing})),metadata:{kind:"physical-flow",coordinateMode:A,particleCount:F.length,totalThroughput:B.reduce((e,t)=>e+t.throughput,0),plot:x.plot,nodes:G,links:V}}}function Fn(e,t){if("region-enter"!==t.type)return e;const i=t.region.id,n=e[i]??{id:i,label:t.region.label??i,count:0,bodyIds:[]};if(n.bodyIds.includes(t.bodyId))return e;const o=[...n.bodyIds,t.bodyId];return{...e,[i]:{...n,count:o.length,bodyIds:o}}}function Dn(e,t){return(t??Object.keys(e)).map(t=>e[t]).filter(e=>null!=e).map(e=>({label:e.label??e.id,value:e.count}))}function zn(e,t){const i=t instanceof Set?t:new Set(t);return e.map(e=>{const t=e.bodyIds??[],n=t.filter(e=>!i.has(e)),o=t.length-n.length,r=e.completion?.mode??"allMembersAbsorbed",s=e.completion?.valueByBodyId,a=e=>{const t=s?.[e];return Number.isFinite(t)&&Number(t)>=0?Number(t):1},c=t.reduce((e,t)=>e+a(t),0),l=t.reduce((e,t)=>e+(i.has(t)?a(t):0),0),d=e.completion?.threshold,u="threshold"===r?Number.isFinite(d)&&Number(d)>=0?Number(d):c:void 0;return{id:e.id,label:e.label??e.id,mode:r,complete:t.length>0&&("anyAbsorbed"===r?o>0:"threshold"===r?l>=(u??c):0===n.length),absorbed:o,total:t.length,absorbedValue:l,totalValue:c,threshold:u,missing:n}})}function Yn(e,t,i){return Math.max(t,Math.min(i,e))}function Ln(e,t,i={}){const n=i.random??Math.random,o=e.stages.find(e=>e.id===t)??e.stages[e.stages.length-1],r=Yn(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,l=Math.min(1,o.width/2),d=Yn(c,o.x0+l,o.x1-l),u=e.boundaryY(d,"top")+a,h=e.boundaryY(d,"bottom")-a;return{x:d,y:h>u?u+n()*Math.max(1,h-u):e.midY}}function Hn(e){return"bowtie"===e.shape?[{id:"incoming",role:"incoming",points:[[e.left,e.topY],[e.centerLeft,e.pinchTop],[e.centerLeft,e.pinchBottom],[e.left,e.bottomY]]},{id:"center",role:"center",points:[[e.centerLeft,e.pinchTop],[e.centerRight,e.pinchTop],[e.centerRight,e.pinchBottom],[e.centerLeft,e.pinchBottom]]},{id:"outgoing",role:"outgoing",points:[[e.centerRight,e.pinchTop],[e.right,e.topY],[e.right,e.bottomY],[e.centerRight,e.pinchBottom]]}]:[{id:"volume",role:"volume",points:[[e.left,e.topY],[e.right,"funnel"===e.shape?e.pinchTop:e.topY],[e.right,"funnel"===e.shape?e.pinchBottom:e.bottomY],[e.left,e.bottomY]]}]}function Xn(e,t,i){return Math.max(t,Math.min(i,e))}function _n(e,t,i,n,o,r={}){return{id:e,friction:r.friction,restitution:r.restitution,bodyFilter:r.bodyFilter,shape:{type:"segment",x1:t,y1:i,x2:n,y2:o,thickness:r.thickness??8}}}function Gn(e){const t=e.shape??"lane",i=Math.max(1,Math.round(e.width)),n=Math.max(1,Math.round(e.height)),o=e.padX??46,r=e.padY??72,s=o,a=i-o,c=r,l=n-Math.max(24,Math.round(.45*r)),d=(c+l)/2,u=Math.max(1,l-c),h=Xn(e.pinchRatio??.18,.06,.5),p=Number(e.pinchHeightOffset??0),m=Number.isFinite(p)?p:0,y=Xn(u*h+m,.06*u,.5*u),f=y/2,g=d-f,b=d+f,x=e.idPrefix??"process",v=e.friction??.58,w=e.restitution??.18,k=e.wallThickness??8,M=e.stages;if(!M.length)throw Error("processStageLayout requires at least one stage");const S=Xn(e.centerStageIndex??Math.floor(M.length/2),0,M.length-1),I=function(e){const t=e.reduce((e,t)=>e+(t.share??1),0);return t>0?t:e.length}(M),A=a-s;let P=s;const C=M.map((e,t)=>{const i=P,n=t===M.length-1?a:P+(e.share??1)/I*A;return P=n,{id:e.id,label:e.label,description:e.description,kind:e.kind??"stage",index:t,x0:i,x1:n,x:(i+n)/2,width:n-i,y:d,height:u}}),R=C[S],B=R.x0,j=R.x1,T=(e,i)=>{if("lane"===t)return"top"===i?c:l;if("funnel"===t){const t=Xn((e-s)/Math.max(1,a-s),0,1);return"top"===i?c+(g-c)*t:l+(b-l)*t}if(B>=e){const t=Xn((e-s)/Math.max(1,B-s),0,1);return"top"===i?c+(g-c)*t:l+(b-l)*t}if(j>=e)return"top"===i?g:b;const n=Xn((e-j)/Math.max(1,a-j),0,1);return"top"===i?g+(c-g)*n:b+(l-b)*n},N=C.map(e=>{const t=Math.min(T(e.x0,"top"),T(e.x1,"top")),i=Math.max(T(e.x0,"bottom"),T(e.x1,"bottom"));return{...e,y:(t+i)/2,height:Math.max(1,i-t)}}),O={thickness:k,friction:v,restitution:w},E=[];"lane"===t?E.push(_n(x+"-top",s,c,a,c,O),_n(x+"-bottom",s,l,a,l,O),_n(x+"-left",s,c,s,l,{...O,thickness:Math.max(6,k-2)}),_n(x+"-right",a,c,a,l,{...O,thickness:Math.max(6,k)})):"funnel"===t?E.push(_n(x+"-top",s,c,a,g,O),_n(x+"-bottom",s,l,a,b,O),_n(x+"-left",s,c,s,l,{...O,thickness:Math.max(6,k-2)}),_n(x+"-right",a,g,a,b,{...O,thickness:Math.max(6,k)})):E.push(_n(x+"-left-top",s,c,B,g,O),_n(x+"-left-bottom",s,l,B,b,O),_n(x+"-center-top",B,g,j,g,O),_n(x+"-center-bottom",B,b,j,b,O),_n(x+"-right-top",j,g,a,c,O),_n(x+"-right-bottom",j,b,a,l,O),_n(x+"-left",s,c,s,l,{...O,thickness:Math.max(6,k-2)}),_n(x+"-right",a,c,a,l,{...O,thickness:Math.max(6,k)}));const $=e.membraneDampingScale??.5,q=s,W=Math.max(1,("bowtie"===t?B:a)-q),F=(e.membranes??[]).map(e=>{const t=q+Xn(e.offset,0,1)*W,i=e.width??18+18*e.cost,n=u-16,o=d+.25*(e.wobble??0);return{...e,x:t,y:o,width:i,height:n}}),D=!1===e.includeMembraneRegions?[]:F.map(e=>Kn({id:e.id,label:e.label??e.id,description:e.description??(e.label??e.id)+" is a permeable region. It taxes energy and damps velocity while bodies overlap it.",x:e.x,y:e.y,width:e.width,height:e.height,cost:e.cost,dampingScale:e.dampingScale??$,bodyStyle:e.bodyStyle,metadata:e.metadata,semanticItem:e.semanticItem,color:e.color}));return{shape:t,width:i,height:n,padX:o,padY:r,left:s,right:a,topY:c,bottomY:l,midY:d,centerLeft:B,centerRight:j,pinchHeight:y,pinchTop:g,pinchBottom:b,stages:N,membranes:F,colliders:E,regionEffects:D,boundaryY:T}}function Vn(e){return{id:e.id,label:e.label,description:e.description,kind:e.kind,shape:(t=e.x,i=e.y,n=e.width,o=e.height,{type:"aabb",x:t,y:i,width:n,height:o}),bodyFilter:e.bodyFilter,collider:e.collider,colliderThickness:e.colliderThickness,friction:e.friction,restitution:e.restitution,semanticItem:e.semanticItem,metadata:e.metadata,bodyStyle:e.bodyStyle,attributes:e.attributes,onEnter:e.onEnter,onExit:e.onExit};var t,i,n,o}function Un(e,t={}){const i=t.idPrefix??"stage",n=Math.max(0,t.insetX??0),o=Math.max(0,t.insetY??1);return e.stages.map(e=>{const r="function"==typeof t.metadata?t.metadata(e):t.metadata??{};return{...Vn({id:i?`${i}:${e.id}`:e.id,label:e.label??e.id,description:e.description,kind:"region",x:e.x,y:e.y,width:Math.max(1,e.width-2*n),height:Math.max(1,e.height-2*o),bodyFilter:t.bodyFilter,semanticItem:t.semanticItem,attributes:{primitive:"processStage",stageId:e.id,stageIndex:e.index},metadata:{...r,primitive:"processStage",stageId:e.id,stageIndex:e.index}})}})}function Kn(e){const t=e.dampingScale??.5,i=e.energyScale??1,n=Xn(e.cost,0,2);return{...Vn({...e,kind:e.kind??"membrane",attributes:{primitive:"membrane",membraneCost:n,..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),damping:n*t,energyDelta:-n*i}}function Qn(e){return{...Vn({...e,kind:e.kind??"charge-gate",attributes:{primitive:"chargeGate",..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),charge:e.charge??!0,energyDelta:e.energyDelta,impulseOnEnter:e.impulseOnEnter}}function Zn(e){const t="number"==typeof e.force?{x:e.force,y:0}:e.force??{x:12,y:0};return{...Vn({...e,kind:e.kind??"force-field",attributes:{primitive:"routeSurface",..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),force:t,damping:e.damping??.015}}function Jn(e){const t=e.pressure??e.occupancy??0,i=e.baseDamping??.08,n=e.dampingPerUnit??.12,o=e.energyPerUnit??0;return{...Vn({...e,kind:e.kind??"membrane",attributes:{primitive:"pressureField",pressure:t,..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),damping:i+t*n,energyDelta:o?-t*o:void 0,force:e.force}}function eo(e){const t="number"==typeof e.force?{x:e.force,y:0}:e.force;return{...Vn({...e,kind:e.kind??"force-field",attributes:{primitive:"capacitatedSensor",capacity:e.capacity,unitsPerSecond:e.unitsPerSecond??e.capacity,..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),force:t,damping:e.damping,charge:e.charge??e.capacity}}function to(e){return{...Vn({...e,kind:e.kind??"force-field",attributes:{primitive:"portal",targetStage:e.targetStage,..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),force:e.force,impulseOnEnter:e.impulseOnEnter,damping:e.damping??.08}}function io(e){const t="number"==typeof e.force?{x:e.force,y:0}:e.force??{x:24,y:0};return{...Vn({...e,kind:e.kind??"sink",attributes:{primitive:"absorb",..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),force:t,damping:e.damping??.02,charge:e.charge??"absorbed"}}function no(e){return{...Vn({...e,kind:e.kind??"force-field",attributes:{primitive:"forceField",..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),force:e.force,damping:e.damping,energyDelta:e.energyDelta}}function oo(e){const t=e.x??e.anchor?.x??0,i=e.y??e.anchor?.y??0;return{id:e.id,label:e.label,description:e.description,group:e.group,bodyIds:e.bodyIds,datum:e.datum,state:e.state,x:t,y:i,width:e.width,height:e.height,anchor:e.anchor??{x:t,y:i},completion:e.completion,tether:e.tether,semanticItem:e.semanticItem}}function ro(e){const t=e.idPrefix??"lane",i={thickness:e.thickness??8,friction:e.friction??.5,restitution:e.restitution??.16},n=[_n(t+"-top",e.left,e.top,e.right,e.top,i),_n(t+"-bottom",e.left,e.bottom,e.right,e.bottom,i)];return e.openEnds||n.push(_n(t+"-left",e.left,e.top,e.left,e.bottom,i),_n(t+"-right",e.right,e.top,e.right,e.bottom,i)),n}function so(e,t=12){return"number"==typeof e?{x:e,y:0}:e&&"object"==typeof e?{x:Number.isFinite(e.x)?Number(e.x):t,y:Number.isFinite(e.y)?Number(e.y):0}:{x:t,y:0}}function ao(e){const t=e.stages;if(!t.length)throw Error("buildProcessFlowPhysics requires at least one stage");const i=e.size,n=pn(i),o=vn(e.ballRadius??6,2,18),r=e.seed??1,s=Mn(r),a=e.idAccessor,c=e.stageAccessor??"stage",l=e.groupBy,d=e.groupLabelAccessor,u=e.workAccessor,h=e.radiusAccessor,p=e.groupCompletion??(l?"allAbsorbed":"none"),m=e.springStiffness??.28,y=e.springDamping??.72,f=!0===e.settle,g=t.map(e=>({id:e.id,label:e.label??e.id,description:e.description,share:e.share})),b=Gn({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((e,t)=>[e.id,t])),v=new Map(b.stages.map(e=>[e.id,e])),w=b.stages[0].id,k=b.stages[0],M=new Set(t.filter(e=>e.absorb).map(e=>e.id)),S=t.map(e=>{const t=v.get(e.id)??k;return function(e,t){const i={id:"process-stage-"+e.id,label:e.label??e.id,description:e.description,x:t.x,y:t.y,width:Math.max(12,.92*t.width),height:Math.max(40,.88*t.height),semanticItem:!1,attributes:{stageId:e.id}};if(e.absorb)return io({...i,kind:e.kind??"sink",force:so(e.force,28),damping:e.damping??.04,charge:"absorbed",attributes:{...i.attributes,primitive:"absorb"}});if(e.portal){const t=e.portal.force??e.force??{x:-40,y:0};return to({...i,kind:e.kind??"force-field",force:so(t,-40),damping:e.damping??.1,targetStage:e.portal.targetStageId,attributes:{...i.attributes,primitive:"portal",targetStage:e.portal.targetStageId}})}if(e.capacity){const t=Math.max(.1,e.capacity.unitsPerSecond);return eo({...i,kind:e.kind??"force-field",capacity:t,unitsPerSecond:t,force:so(e.force,10+.8*t),damping:e.damping??Math.max(.04,.32-.01*t),attributes:{...i.attributes,unitAccessor:e.capacity.unitAccessor,reviewerCapacity:t}})}if(e.pressure){const t="object"==typeof e.pressure&&e.pressure?e.pressure:{};return Jn({...i,kind:e.kind??"membrane",pressure:t.pressure,occupancy:t.occupancy,baseDamping:t.baseDamping??e.damping??.1,dampingPerUnit:t.dampingPerUnit??.1,energyPerUnit:t.energyPerUnit??0,force:so(e.force,8),attributes:{...i.attributes,primitive:"pressureField"}})}return null!=e.force||null!=e.damping?Zn({...i,kind:e.kind??"force-field",force:so(e.force,14),damping:e.damping??.02,attributes:{...i.attributes,primitive:"routeSurface"}}):no({...i,kind:e.kind??"force-field",force:{x:10,y:0},damping:.02,attributes:{...i.attributes,primitive:"forceField"}})}(e,{x:t.x,y:b.midY,width:t.width,height:b.bottomY-b.topY})});S.unshift(Zn({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 I=new Map;for(const e of b.stages)I.set(e.id,0);const A=[];e.data.forEach((e,t)=>{const i=(a?bn(e,t,a)??e.id??"process-flow-"+t:e.id??"process-flow-"+t)+"",n=(bn(e,t,c)??w)+"",r=x.has(n)?n:w;I.set(r,(I.get(r)??0)+1);const s=l?(bn(e,t,l)??"")+"":void 0,p=s&&d?(bn(e,t,d)??s)+"":s,m=u?xn(bn(e,t,u))??1:1,y=h?xn(bn(e,t,h)):null,f=vn(null!=y&&y>0?y:o,2,18);A.push({datum:e,id:i,stageId:r,groupId:s||void 0,groupLabel:p||void 0,work:m,radius:f,index:t})});const P=new Map,C=new Map;for(const e of A){if(!e.groupId)continue;const t=P.get(e.groupId)??[];t.push(e.id),P.set(e.groupId,t),e.groupLabel&&C.set(e.groupId,e.groupLabel)}const R=vn(e.groupAnchorAlong??.55,.15,.9),B=b.left+(b.right-b.left)*R,j=Array.from(P.keys()),T=j.map((e,i)=>{const n=P.get(e)??[],o=j.length>1?b.topY+28+i/Math.max(1,j.length-1)*(b.bottomY-b.topY-56):b.midY;return oo({id:e,label:C.get(e)??e,bodyIds:n,anchor:{x:B,y:o},x:B,y:o,completion:"allAbsorbed"===p?{mode:"allMembersAbsorbed",targetZone:t.find(e=>e.absorb)?.id??"merged"}:void 0,tether:{stiffness:.06,visible:!0,restLength:18}})}),N=zn(T,A.filter(e=>M.has(e.stageId)).map(e=>e.id)),O=new Map(T.map(e=>[e.id,e])),E=A.map((e,t)=>{const i=v.get(e.stageId)??k,n=i.x+(s()-.5)*Math.min(24,.2*i.width),o=b.boundaryY(n,"top")+e.radius+10,r=b.boundaryY(n,"bottom")-e.radius-10,a=r>o?o+s()*Math.max(1,r-o):b.midY,c=f?n:b.left+18+t%7*4,l=f?a:b.midY+(s()-.5)*(b.bottomY-b.topY)*.35,d=[{target:{type:"point",x:n,y:a},restLength:.45*e.radius,stiffness:m,damping:y}];if(e.groupId){const t=O.get(e.groupId);t?.anchor&&!M.has(e.stageId)&&d.push({target:{type:"point",x:t.anchor.x,y:t.anchor.y},restLength:t.tether?.restLength??22,stiffness:t.tether?.stiffness??.05,damping:.8})}return{id:e.id,x:c,y:l,vx:f?0:40+40*s(),vy:f?0:20*(s()-.5),mass:1,shape:{type:"circle",radius:e.radius},spawnAt:f?0:.03*t,springs:d,datum:{...e.datum,id:e.id,stage:e.stageId,groupId:e.groupId,groupLabel:e.groupLabel,work:e.work,__processFlow:!0}}}),$={kernel:{seed:r,gravity:{x:e.gravityX??22,y:e.gravityY??0},restitution:.14,friction:.48,velocityDamping:.988,maxVelocity:420,sleepSpeed:8,sleepAfter:.9,collisionIterations:4},colliders:b.colliders,fixedDt:1/60,maxSubsteps:8},q=b.stages.map(e=>({label:e.label??e.id,value:I.get(e.id)??0})),W=t.map(e=>{const t=v.get(e.id)??k;return{id:e.id,label:e.label??e.id,x:t.x,width:t.width,count:I.get(e.id)??0,capacity:e.capacity?.unitsPerSecond,absorb:!0===e.absorb,portalTarget:e.portal?.targetStageId}});return{config:$,initialSpawns:E,initialSpawnPacing:f?void 0:{pacing:"arrival",timeAccessor:"spawnAt",timeScale:1},projectionRows:q,metadata:{kind:"process-flow",plot:n.plot,volume:b,stages:W,groups:T,groupCompletion:N,regionEffects:S}}}import{forwardRef as co,useCallback as lo,useMemo as uo,useRef as ho}from"react";import{useImperativeHandle as po,useRef as mo}from"react";function yo(e,t){if(!t?.length)return[e];const i=t.filter(t=>{if(t.id===e||t.id.startsWith(e+"-"))return!0;const i=t.datum;return!(!i||"object"!=typeof i||null==i.id)&&i.id+""===e}).map(e=>e.id);return i.length?i:[e]}function fo(e,t,i){if("function"==typeof i)return i(e,t)+"";if("string"==typeof i){const t=e[i];if(null!=t)return t+""}return null!=e&&"object"==typeof e&&"id"in e&&null!=e.id?e.id+"":"physics-row-"+t}function go(e,t){const i=e?.getData().find(e=>e.id===t),n=i?.datum;if(n&&"object"==typeof n)return n}function bo(e,t){const{frameRef:i,spawnDatum:n,seedRows:o,idAccessor:r,bodyIdsForSeed:s,seedSpawns:a}=t,c=mo(new Map),l=mo(new Map),d=mo(""),u=o?o.map((e,t)=>fo(e,t,r)).join("\0"):"";if(u!==d.current&&(d.current=u,o))for(let e=0;o.length>e;e+=1){const t=o[e],i=fo(t,e,r);c.current.set(i,t),l.current.set(i,s?.(t,i,e)??yo(i,a))}po(e,()=>{const e=c.current,t=l.current;function o(e,t){const i=n(e,t);return{datumId:i.datumId||fo(e,t,r),spawns:i.spawns.map(e=>({...e,spawnAt:void 0}))}}function s(n){const o=[];for(const{datum:i,result:r}of n)e.set(r.datumId,i),t.set(r.datumId,r.spawns.map(e=>e.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=e.get(n);if(o)return o;const r=t.get(n)??[n];for(const o of r){const r=go(i.current,o);if(r)return e.set(n,r),t.has(n)||t.set(n,[o]),r}}return{push:t=>{s([{datum:t,result:o(t,e.size)}])},pushMany:t=>{const i=e.size;s(t.map((e,t)=>({datum:e,result:o(e,i+t)})))},remove:n=>{const o=Array.isArray(n)?n:[n],r=[],s=[];for(const i of o){const n=a(i);n&&r.push(n),e.delete(i),s.push(...t.get(i)??[i]),t.delete(i)}return s.length&&i.current?.remove(s),r},update:(n,r)=>{const c=Array.isArray(n)?n:[n],l=[];for(const n of c){const c=a(n);if(!c)continue;l.push(c);const d=t.get(n)??[n];i.current?.remove(d),e.delete(n),t.delete(n);const u=r(c);s([{datum:u,result:o(u,e.size)}])}return l},clear:()=>{e.clear(),t.clear(),d.current="",i.current?.clear()},getData:()=>{const t=i.current;if(!t)return Array.from(e.values());const n=t.getData().map(e=>e.datum).filter(e=>!!e&&"object"==typeof e);return n.length?n:Array.from(e.values())},getScales:()=>null,getCustomLayout:()=>i.current?.snapshot()??null,popBodies:(e,t)=>i.current?.popBodies(e,t)??[]}},[i,r,n])}import{useMemo as xo}from"react";import{Fragment as vo,jsx as wo,jsxs as ko}from"react/jsx-runtime";var Mo=new Set(["sample","mechanical"]);function So(e,t,i){const n=i?.hasSimulationMode?function(e){const t=e=>"string"==typeof e&&Mo.has(e);return e.simulationMode?{chartMode:t(e.mode)?void 0:e.mode,simulationMode:e.simulationMode}:t(e.mode)?{chartMode:void 0,simulationMode:e.mode}:{chartMode:e.mode,simulationMode:"sample"}}({mode:e.mode,simulationMode:e.simulationMode}):{chartMode:"sample"===e.mode||"mechanical"===e.mode?void 0:e.mode,simulationMode:"sample"},o=B(n.chartMode,{width:e.width,height:e.height,enableHover:e.enableHover,title:e.title,description:e.description,summary:e.summary,accessibleTable:e.accessibleTable,mobileInteraction:e.mobileInteraction,mobileSemantics:e.mobileSemantics,responsiveRules:e.responsiveRules},{width:t[0],height:t[1]}),r=e.size?.[0],s=e.size?.[1],a=t[0],c=t[1],l=xo(()=>{return e=[a,c],(null!=r&&null!=s?[r,s]:void 0)??[o.width??e[0],o.height??e[1]];var e},[c,a,o.height,o.width,s,r]),d=o.compactMode?"sparkline"===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=e.showProjection??!o.compactMode,h=e.showChrome??!o.compactMode,p=Co(e.tooltip,void 0),m=void 0!==p.enableHover?p.enableHover:o.enableHover,y=o.compactMode?o.title:o.title??e.title,f=[e.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:l,margin:d,showProjection:u,showChrome:h,enableHover:m,title:y,description:o.description??e.description,summary:o.summary??e.summary,accessibleTable:o.accessibleTable??e.accessibleTable,className:f,compactMode:o.compactMode,mobileInteraction:o.mobileInteraction,mobileSemantics:o.mobileSemantics}}function Io(e){const[t,i]=e.size;return z(e.loading,t,i,e.loadingContent)||D(e.data,t,i,e.emptyContent)}function Ao(e,t,i){return wo(F,{componentName:e,width:t[0],height:t[1],children:i})}function Po(e,t){return e?t?i=>ko(vo,{children:["function"==typeof e?e(i):e,"function"==typeof t?t(i):t]}):e:t}function Co(e,t){return!1===e?{enableHover:!1}:{enableHover:t?.enableHover,tooltipContent:M(e)||t?.tooltipContent}}function Ro(e,t,i,n){return{accessibleTable:n?.accessibleTable??e.accessibleTable??t?.accessibleTable,annotations:e.annotations??t?.annotations,autoPlaceAnnotations:e.autoPlaceAnnotations??t?.autoPlaceAnnotations,background:e.background??t?.background,chartId:e.chartId??t?.chartId,chartMode:n?.chartMode??t?.chartMode,className:n?.className??e.className??t?.className,color:e.color??t?.color,description:n?.description??e.description??t?.description,emphasis:e.emphasis??t?.emphasis,enableHover:n?.enableHover??t?.enableHover,hoverRadius:e.hoverRadius??t?.hoverRadius,legend:e.legend??t?.legend,legendLayout:e.legendLayout??t?.legendLayout,legendPosition:e.legendPosition??t?.legendPosition,margin:n?.margin??t?.margin,onClick:null!=e.onClick?(t,i)=>{t&&e.onClick?.(t,{x:i.x,y:i.y})}:t?.onClick,onObservation:e.onObservation??t?.onObservation,onAnnotationActivate:t?.onAnnotationActivate,opacity:e.opacity??t?.opacity,semanticItems:t?.semanticItems??i,stroke:e.stroke??t?.stroke,strokeWidth:e.strokeWidth??t?.strokeWidth,summary:n?.summary??e.summary??t?.summary,svgAnnotationRules:e.svgAnnotationRules??t?.svgAnnotationRules,title:n?.title??e.title??t?.title}}import{Fragment as Bo,jsx as jo,jsxs as To}from"react/jsx-runtime";var No=co(function(e,t){const{data:i,valueAccessor:n="value",styleRules:o,bins:r=21,ballRadius:s=6,colorBy:a,branchProbability:c=.5,emptyContent:l,frameProps:d,loading:u,loadingContent:h,mechanicalCount:p,paused:m,pegRows:y,referenceLines:f,responsiveHeight:g,responsiveWidth:b,seed:x=1,valueExtent:v}=e,w=So(e,[700,420],{hasSimulationMode:!0}),{chartSize:k,simulationMode:M,showProjection:S,className:I,title:A,chartMode:P,margin:C,enableHover:R,description:B,summary:j,accessibleTable:T}=w,N=ho(null),O=Math.max(1,Math.round(y??r-1)),E=uo(()=>"mechanical"===M?[0,O]:function(e){if(!e)return;const t=Number(e[0]),i=Number(e[1]);return Number.isFinite(t)&&Number.isFinite(i)?t>i?[i,t]:[t,i]:void 0}(v),[O,M,v]),$=uo(()=>"mechanical"===M?function(e){const t=Math.max(2,Math.round(e.bins)),i=Math.max(1,Math.round(e.pegRows??t-1)),n=Math.max(1,Math.round(e.count??Math.max(64,4*t))),o=vn(Number.isFinite(e.branchProbability)?e.branchProbability??.5:.5,0,1),r=Mn(e.seed??1),s=e.idPrefix??"mechanical";return Array.from({length:n},(e,t)=>{let n=0;for(let e=0;i>e;e+=1)r()<o&&(n+=1);const a=i/2;return{id:`${s}-${t}`,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:O,seed:x}):i??[],[r,c,i,p,O,x,M]),q=uo(()=>Sn({data:$,valueAccessor:n,bins:r,ballRadius:s,seed:x,size:k,valueExtent:E}),[s,r,$,k,E,x,n]);bo(t,{frameRef:N,spawnDatum:lo((e,t)=>{const i=Sn({data:[e],valueAccessor:n,bins:r,ballRadius:s,seed:x+t+1,size:k,valueExtent:E}).initialSpawns[0]??{id:(e.id??"galton-push-"+t)+"",x:pn(k).plot.x,y:pn(k).plot.y,mass:1,shape:{type:"circle",radius:s},datum:e};return{datumId:(e.id??i.id)+"",spawns:[i]}},[s,r,k,E,x,n]),seedRows:$,seedSpawns:q.initialSpawns});const W="mechanical"===M&&null==a?"side":a,F=uo(()=>yn(W,"#4e79a7",{styleRules:o,valueAccessor:n}),[W,o,n]),D=uo(()=>gn(q.projectionRows,k,"bin"),[k,q.projectionRows]),z=Io({data:"mechanical"===M?$:i,emptyContent:l,loading:u,loadingContent:h,size:k});if(z)return z;const Y=function(e,t,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=pn(s),c=Math.max(2,Math.round(t)),l=a.plot.width/c,d=a.plot.y+a.plot.height,u=Math.max(1,...e.map(e=>e.value)),h=!1!==i,[p,m]=n?.valueExtent??[0,c],y=m===p?1:m-p,f=e.map((e,t)=>{const i=d-e.value/u*a.plot.height*.9;return`${0===t?"M":"L"} ${(a.plot.x+(t+.5)*l).toFixed(1)} ${i.toFixed(1)}`}).join(" ");return To("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?To(Bo,{children:[Array.from({length:c+1},(e,t)=>{const i=a.plot.x+t*l;return jo("line",{"data-testid":"galton-board-bin-wall",x1:i,x2:i,y1:a.plot.y,y2:d,stroke:"var(--semiotic-border, #d1d5db)",strokeOpacity:.28,strokeWidth:1},"bin-wall-"+t)}),jo("line",{x1:a.plot.x,x2:a.plot.x+a.plot.width,y1:d,y2:d,stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:1.5}),jo("path",{d:f,fill:"none",stroke:"var(--semiotic-accent, #4e79a7)",strokeOpacity:.7,strokeWidth:2,strokeLinejoin:"round"}),e.map((e,t)=>e.value>0?jo("text",{x:a.plot.x+(t+.5)*l,y:Math.max(a.plot.y+10,d-e.value/u*a.plot.height*.9-6),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:e.value},`${e.label}-${t}`):null)]}):null,r.map((e,t)=>{const i=Number(e.value);if(!Number.isFinite(i))return null;const n=a.plot.x+Math.max(0,Math.min(1,(i-p)/y))*a.plot.width,o=e.color??"var(--semiotic-warning, #f28e2b)",r="bottom"===e.labelPosition?Math.min(s[1]-8,d+16):a.plot.y+16;return To("g",{className:e.className,"data-testid":"galton-board-reference-line",children:[jo("line",{x1:n,x2:n,y1:a.plot.y+8,y2:d-4,stroke:o,strokeDasharray:e.strokeDasharray??"6 5",strokeWidth:e.strokeWidth??2}),null==e.label?null:jo("text",{x:Math.min(a.plot.x+a.plot.width-4,n+6),y:r,fill:o,fontSize:10,fontWeight:700,children:e.label})]},`galton-reference-${t}-${i}`)})]})}}(q.projectionRows,r,S,q.metadata,f),L=Co(e.tooltip,d),H=Ro(e,d,D,{chartMode:P,className:I,title:A,description:B,summary:j,accessibleTable:T,enableHover:R,margin:C});return Ao("GaltonBoardChart",k,jo(un,{...d,...L,...H,ref:N,config:q.config,foregroundGraphics:Po(Y,d?.foregroundGraphics),initialSpawns:q.initialSpawns,initialSpawnPacing:q.initialSpawnPacing,paused:m,responsiveHeight:g,responsiveWidth:b,size:k,bodyStyle:F}))});import{forwardRef as Oo,useCallback as Eo,useMemo as $o,useRef as qo}from"react";import{jsx as Wo,jsxs as Fo}from"react/jsx-runtime";var Do=Oo(function(e,t){const{arrivalAccessor:i="arrivalTime",ballRadius:n=7,colorBy:o,styleRules:r,data:s,emptyContent:a,frameProps:c,loading:l,loadingContent:d,paused:u,responsiveHeight:h,responsiveWidth:p,seed:m=1,timeAccessor:y="time",timeExtent:f,timeScale:g=1,watermark:b,windows:x={size:10}}=e,v=So(e,[760,360]),{chartSize:w,showProjection:k,className:M,title:S,chartMode:I,margin:A,enableHover:P,description:C,summary:R,accessibleTable:B}=v,j=qo(null),T=$o(()=>s??[],[s]),N=$o(()=>Pn({data:T,timeAccessor:y,arrivalAccessor:i,windows:x,watermark:b,ballRadius:n,seed:m,size:w,timeExtent:f,timeScale:g}),[i,n,w,T,m,y,f,g,b,x]),O=N.metadata;bo(t,{frameRef:j,spawnDatum:Eo((e,t)=>{const o=O?function(e,t,i,n){const o=xn(bn(e,t,n.timeAccessor));if(null==o)return null;const r=xn(bn(e,t,n.arrivalAccessor))??o,{windowPlot:s,windowStart:a,windowCount:c,windowSize:l,watermarkValue:d}=i,u=a+c*l,h=In().domain([a,u]).range([s.x,s.x+s.width]),p=Math.max(0,Math.min(c-1,Math.floor((o-a)/l))),m=d>=a+(p+1)*l,{ballRadius:y}=n;return{id:(e.id??"event-push-"+t)+"",x:Math.max(s.x+y,Math.min(s.x+s.width-y,h(o))),y:s.y+y+2,vx:8*(t%3-1),vy:0,mass:1,friction:.02,shape:{type:"circle",radius:y},datum:{...e,eventTime:o,arrivalTime:r,windowIndex:p,late:m}}}(e,t,O,{timeAccessor:y,arrivalAccessor:i,ballRadius:n}):null,r=o??{id:(e.id??"event-push-"+t)+"",x:pn(w).plot.x,y:pn(w).plot.y,mass:1,shape:{type:"circle",radius:n},datum:e};return{datumId:(e.id??r.id)+"",spawns:[r]}},[i,n,w,O,y]),seedRows:T,seedSpawns:N.initialSpawns});const E=$o(()=>yn(o,"#4e79a7",{styleRules:r,valueAccessor:y}),[o,r,y]),$=$o(()=>function(e,t,i){if(!t)return gn(e,i,"window");const n=t.windowPlot.width/Math.max(1,e.length),o=Math.max(1,...e.map(e=>e.value+(e.secondary??0))),r=.62*t.windowPlot.height,s=t.windowPlot.y+t.windowPlot.height;return e.map((e,i)=>{const a=Math.max(8,(e.value+(e.secondary??0))/o*r),c=`window ${e.label}: ${e.value} on time${e.secondary?`, ${e.secondary} late`:""}`;return{id:"window-"+e.label,label:c,description:c,datum:e,x:t.windowPlot.x+(i+.5)*n,y:s-a/2,shape:"rect",width:Math.max(12,.58*n),height:a,group:"window"}})}(N.projectionRows,O,w),[w,N.projectionRows,O]),q=Io({data:s,emptyContent:a,loading:l,loadingContent:d,size:w});if(q)return q;const W=function(e,t,i){if(!1!==i&&t)return({size:i})=>{const n=[Number(i[0])||760,Number(i[1])||360],o=pn(n),r=Math.max(1,t.windowCount),s=t.plot??o.plot,a=t.gutter??{x:s.x,y:s.y,width:0,height:s.height},c=t.windowPlot??s,l=c.width/r,d=s.y+s.height,u=s.y+.48*s.height,h=t.lidSegments[0]?.y1??u,p=t.windowStart,m=t.windowStart+r*t.windowSize,y=c.x+Math.max(0,Math.min(1,m===p?0:(t.watermarkValue-p)/(m-p)))*c.width;return Fo("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:[Wo("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?Fo("g",{children:[Wo("rect",{x:a.x,y:h,width:a.width,height:d-h,fill:"var(--semiotic-negative, #e15759)",fillOpacity:.07,stroke:"var(--semiotic-border, #d1d5db)",strokeOpacity:.55,strokeWidth:1}),Wo("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=e[o],s=c.x+o*l,a=t.closedWindowCount>o,h=r?.secondary??0;return Fo("g",{children:[Wo("rect",{x:s,y:u,width:l,height:d-u,fill:a?"var(--semiotic-negative, #e15759)":"var(--semiotic-accent, #4e79a7)",fillOpacity:a?.08:.06,stroke:"var(--semiotic-border, #d1d5db)",strokeOpacity:.68,strokeWidth:1}),a?t.lidSegments.filter(e=>e.windowIndex===o).map(e=>Wo("line",{x1:e.x1,x2:e.x2,y1:e.y1,y2:e.y2,stroke:"var(--semiotic-negative, #e15759)",strokeOpacity:.78,strokeWidth:2,strokeLinecap:"round"},e.id)):null,Fo("text",{x:s+l/2,y:u-8,textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:[r?.value??0,h?` / ${h} late`:""]}),Wo("text",{x:s+l/2,y:Math.min(n[1]-8,d+16),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:r?.label??""})]},"window-"+o)}),t.lidSegments.filter(e=>null==e.windowIndex).map(e=>Wo("line",{x1:e.x1,x2:e.x2,y1:e.y1,y2:e.y2,stroke:"var(--semiotic-negative, #e15759)",strokeOpacity:.62,strokeWidth:2,strokeLinecap:"round"},e.id)),Wo("line",{x1:s.x,x2:s.x+s.width,y1:d,y2:d,stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:1.5}),Wo("line",{"data-testid":"event-drop-watermark",x1:y,x2:y,y1:s.y+8,y2:d,stroke:"var(--semiotic-warning, #f28e2b)",strokeDasharray:"5 4",strokeWidth:2}),Fo("text",{x:Math.min(s.x+s.width-4,y+6),y:s.y+16,fill:"var(--semiotic-warning, #f28e2b)",fontSize:10,fontWeight:700,children:["watermark ",Math.round(100*t.watermarkValue)/100]}),t.lateCount>0?Fo("text",{x:a.x+a.width/2,y:s.y+32,textAnchor:"middle",fill:"var(--semiotic-negative, #e15759)",fontSize:10,fontWeight:700,children:[t.lateCount," late"]}):null]})}}(N.projectionRows,N.metadata,k),F=Co(e.tooltip,c),D=Ro(e,c,$,{chartMode:I,className:M,title:S,description:C,summary:R,accessibleTable:B,enableHover:P,margin:A});return Ao("EventDropChart",w,Wo(un,{...c,...F,...D,ref:j,config:N.config,foregroundGraphics:Po(W,c?.foregroundGraphics),initialSpawns:N.initialSpawns,initialSpawnPacing:N.initialSpawnPacing,paused:u,responsiveHeight:h,responsiveWidth:p,size:w,bodyStyle:E}))});import{forwardRef as zo,useCallback as Yo,useMemo as Lo,useRef as Ho}from"react";import{jsx as Xo,jsxs as _o}from"react/jsx-runtime";var Go=zo(function(e,t){const{ballRadius:i=8,categoryAccessor:n="category",colorBy:o,data:r,emptyContent:s,frameProps:a,loading:c,loadingContent:l,mechanicalCategories:d,mechanicalCount:u,paused:h,responsiveHeight:p,responsiveWidth:m,seed:y=1,unitValue:f=1,valueAccessor:g,styleRules:b}=e,x=So(e,[700,380],{hasSimulationMode:!0}),{chartSize:v,simulationMode:w,showProjection:k,className:M,title:S,chartMode:I,margin:A,enableHover:P,description:C,summary:R,accessibleTable:B}=x,j=Ho(null),T="mechanical"===w&&null==g?"value":g,N=Lo(()=>"mechanical"===w?function(e={}){const t=(e.categories?.length?e.categories:["Intake","Review","Build","Ship"]).map(e=>(e+"").trim()).filter(Boolean),i=t.length?t:["Intake"],n=Math.max(i.length,Math.round(e.count??Math.max(48,12*i.length))),o=wn(e.unitValue,1),r=Mn(e.seed??1),s=e.idPrefix??"mechanical-pile",a=i.map(()=>.65+.9*r()),c=a.reduce((e,t)=>e+t,0)||1,l=n-i.length,d=a.map(e=>e/c*l),u=d.map(e=>1+Math.floor(e));let h=n-u.reduce((e,t)=>e+t,0);const p=d.map((e,t)=>({index:t,fraction:e-Math.floor(e)})).sort((e,t)=>t.fraction-e.fraction);for(let e=0;h>0;e=(e+1)%p.length)u[p[e].index]+=1,h-=1;return i.map((e,t)=>({id:`${s}-${t}`,category:e,value:u[t]*o,mechanical:!0,unitCount:u[t],unitValue:o,share:u[t]/n}))}({categories:d,count:u,seed:y,unitValue:f}):r??[],[r,d,u,y,w,f]),O=Lo(()=>Rn({data:N,categoryAccessor:n,valueAccessor:T,unitValue:f,ballRadius:i,seed:y,size:v}),[i,n,v,N,T,y,f]);bo(t,{frameRef:j,spawnDatum:Yo((e,t)=>{const o=Rn({data:[e],categoryAccessor:n,valueAccessor:T,unitValue:f,ballRadius:i,seed:y+t+1,size:v}),r={id:(e.id??"pile-push-"+t)+"",x:pn(v).plot.x,y:pn(v).plot.y,mass:1,shape:{type:"circle",radius:i},datum:e},s=o.initialSpawns.length?o.initialSpawns:[r];return{datumId:(e.id??s[0].id)+"",spawns:s}},[i,n,v,T,y,f]),seedRows:N,seedSpawns:O.initialSpawns});const E="mechanical"===w&&null==o?"category":o,$=Lo(()=>yn(E,"#4e79a7",{styleRules:b,valueAccessor:g}),[E,b,g]),q=Lo(()=>gn(O.projectionRows,v,"category"),[v,O.projectionRows]),W=Io({data:"mechanical"===w?N:r,emptyContent:s,loading:c,loadingContent:l,size:v});if(W)return W;const F=function(e,t,i){if(!1!==i&&0!==e.length)return({size:i})=>{const n=[Number(i[0])||700,Number(i[1])||380],o=pn(n),r=Cn(o.plot,e.length,t),s=o.plot.y+o.plot.height;return _o("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:[Xo("line",{x1:o.plot.x,x2:o.plot.x+o.plot.width,y1:s,y2:s,stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:1}),e.map((e,t)=>{const i=Math.min(o.plot.height,r.pileHeight(e.value)),a=r.tubeWidth,c=r.centerX(t),l=s-i;return _o("g",{children:[Xo("rect",{x:c-a/2,y:l,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"}),Xo("text",{x:c,y:Math.max(o.plot.y+12,l-6),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:11,fontWeight:700,children:e.value}),Xo("text",{x:c,y:Math.min(n[1]-8,s+16),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:e.label})]},`${e.label}-${t}`)})]})}}(O.projectionRows,i,k),D=Co(e.tooltip,a),z=Ro(e,a,q,{chartMode:I,className:M,title:S,description:C,summary:R,accessibleTable:B,enableHover:P,margin:A});return Ao("PhysicsPileChart",v,Xo(un,{...a,...D,...z,ref:j,config:O.config,foregroundGraphics:Po(F,a?.foregroundGraphics),initialSpawns:O.initialSpawns,initialSpawnPacing:O.initialSpawnPacing,paused:h,responsiveHeight:p,responsiveWidth:m,size:v,bodyStyle:$}))});import{forwardRef as Vo,useCallback as Uo,useMemo as Ko,useRef as Qo}from"react";import{jsx as Zo,jsxs as Jo}from"react/jsx-runtime";function er(e){return e.toLocaleString(void 0,Math.abs(e)>=1e3||.01>Math.abs(e)?{maximumFractionDigits:0}:{maximumFractionDigits:2})}var tr=Vo(function(e,t){const{colorBy:i,styleRules:n,collisionIterations:o,data:r,emptyContent:s,frameProps:a,groupAccessor:c,loading:l,loadingContent:d,paused:u,pointRadius:h=5,radiusAccessor:p,responsiveHeight:m,responsiveWidth:y,seed:f=1,settle:g,xAccessor:b="x",xExtent:x}=e,v=So(e,[700,360]),{chartSize:w,showProjection:k,className:M,title:S,chartMode:I,margin:A,enableHover:P,description:C,summary:R,accessibleTable:B}=v,j=Qo(null),T=Ko(()=>r??[],[r]),N=Ko(()=>jn({data:T,xAccessor:b,groupAccessor:c,radiusAccessor:p,pointRadius:h,seed:f,size:w,xExtent:x,collisionIterations:o,settle:g}),[T,w,o,c,h,p,f,g,b,x]);bo(t,{frameRef:j,spawnDatum:Uo((e,t)=>{const i=jn({data:[e],xAccessor:b,groupAccessor:c,radiusAccessor:p,pointRadius:h,seed:f+t+1,size:w,xExtent:x,collisionIterations:o,settle:g}).initialSpawns[0]??{id:(e.id??"collision-swarm-push-"+t)+"",x:pn(w).plot.x,y:pn(w).plot.y,mass:1,shape:{type:"circle",radius:h},datum:e};return{datumId:(e.id??i.id)+"",spawns:[i]}},[w,o,c,h,p,f,g,b,x]),seedRows:T,seedSpawns:N.initialSpawns});const O=i??c,E=Ko(()=>yn(O,"#4e79a7",{styleRules:n,valueAccessor:b}),[O,n,b]),$=Io({data:r,emptyContent:s,loading:l,loadingContent:d,size:w});if($)return $;const q=function(e,t){if(!1!==t&&e)return({size:t})=>{const i=[Number(t[0])||700,Number(t[1])||360],n=pn(i),o=n.plot.y+n.plot.height,[r,s]=e.xExtent,a=r+(s-r)/2,c=[{label:er(r),x:e.xRange[0]},{label:er(a),x:e.xRange[0]+(e.xRange[1]-e.xRange[0])/2},{label:er(s),x:e.xRange[1]}];return Jo("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:[e.groups.map(e=>Jo("g",{children:[Zo("line",{x1:n.plot.x,x2:n.plot.x+n.plot.width,y1:e.y,y2:e.y,stroke:"var(--semiotic-border, #d1d5db)",strokeDasharray:"3 5",strokeWidth:1}),Zo("text",{x:n.plot.x+4,y:e.y-7,fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:e.label}),Jo("text",{x:n.plot.x+n.plot.width-4,y:e.y-7,textAnchor:"end",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:["n=",e.count]})]},e.label)),Zo("line",{x1:e.xRange[0],x2:e.xRange[1],y1:o,y2:o,stroke:"var(--semiotic-text-secondary, #555)",strokeWidth:1}),c.map(e=>Jo("g",{children:[Zo("line",{x1:e.x,x2:e.x,y1:o,y2:o+5,stroke:"var(--semiotic-text-secondary, #555)",strokeWidth:1}),Zo("text",{x:e.x,y:Math.min(i[1]-8,o+18),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:e.label})]},`${e.label}-${e.x}`))]})}}(N.metadata,k),W=function(e){if(!e)return[];const t=Math.max(24,e.xRange[1]-e.xRange[0]),i=e.xRange[0]+t/2;return e.groups.map(e=>{const n=`${e.label} lane: ${e.count} points`;return{id:"collision-swarm-"+e.label,label:n,description:n,datum:e,x:i,y:e.y,shape:"rect",width:t,height:28,group:"lane"}})}(N.metadata),F=Co(e.tooltip,a),D=Ro(e,a,W,{chartMode:I,className:M,title:S,description:C,summary:R,accessibleTable:B,enableHover:P,margin:A});return Ao("CollisionSwarmChart",w,Zo(un,{...a,...F,...D,ref:j,config:N.config,foregroundGraphics:Po(q,a?.foregroundGraphics),initialSpawns:N.initialSpawns,paused:u,responsiveHeight:m,responsiveWidth:y,size:w,bodyStyle:E}))});function ir(e,t={}){const i=t.id??"physics-process-boundary",n={bodyFilter:t.bodyFilter,friction:t.friction,restitution:t.restitution};if("segment"===e.type)return[{...n,id:i,shape:e}];const o=t.thickness??8,r=e.x-e.width/2,s=e.x+e.width/2,a=e.y-e.height/2,c=e.y+e.height/2;return[{...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 nr(e){if(!1===e.semanticItem)return null;const t=e.semanticItem??{},i=e.shape,n="aabb"===i.type?{id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"region",x:i.x,y:i.y,width:i.width,height:i.height}:{id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"region",x:(i.x1+i.x2)/2,y:(i.y1+i.y2)/2,pathData:`M ${i.x1} ${i.y1} L ${i.x2} ${i.y2}`};return{...n,...t,id:t.id??n.id}}function or(e){return e.map(e=>({id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"stage",x:e.x??0,y:e.y??0,width:e.width,height:e.height}))}function rr(e){return e.flatMap(e=>{if(!1===e.semanticItem)return[];const t=e.semanticItem??{},i={id:e.id,label:e.label??e.id,description:e.description,datum:e.datum,group:e.group??e.state??"body group",x:e.x??0,y:e.y??0,width:e.width,height:e.height};return[{...i,...t,id:t.id??i.id}]})}function sr(e){return e?Array.isArray(e)?[...e]:Object.entries(e).flatMap(([e,t])=>Array.from({length:Math.max(0,Math.round(Number(t)||0))},()=>e)):[]}function ar(e,t){return t?Array.isArray(t)?[...t]:t.ids?[...t.ids]:t.candidates?t.candidates.filter(t=>e.includes(t)).slice(0,t.count??1):[]:[]}function cr(e,t){return ar(e.activePositiveIds,t.popPositive)}function lr(e){const t=Number(e.budget),i=Number.isFinite(t)?Math.max(0,t):0,n=e.properties instanceof Map?e.properties:new Map(e.properties.map(e=>[e.id,e])),o=e.candidates?new Set(e.candidates):null,r=e.attachedIds.map((e,t)=>{const i=n.get(e),o=Number(i?.work??1),r=Number(i?.priority??t);return{id:e,index:t,priority:Number.isFinite(r)?r:t,work:Number.isFinite(o)&&o>0?o:1}}).filter(e=>!o||o.has(e.id)).sort((e,t)=>e.priority-t.priority||e.index-t.index),s=[],a=[];let c=0;for(const e of r)c+e.work>i+Number.EPSILON?a.push(e.id):(s.push(e.id),c+=e.work);return{ids:s,used:c,budget:i,remaining:Math.max(0,i-c),skippedIds:a}}function dr(e,t){if(!t.from||!t.to||t.from===t.to)return{};const i=Math.max(0,Math.floor(Number(t.count??1)||0)),n=e.negativeIds.filter(e=>e===t.from).length,o=Math.min(i,n);return o?{addNegative:{[t.to]:o},popNegative:{ids:Array.from({length:o},()=>t.from)}}:{}}function ur(e,t){const i=ar(e.negativeIds,t.popNegative);if(!i.length)return[];const n=new Map;for(const e of i)n.set(e,(n.get(e)??0)+1);const o=[];return e.negativeIds.forEach((e,t)=>{const i=n.get(e)??0;i>0&&(o.push({propertyId:e,index:t}),n.set(e,i-1))}),o}function hr(e,t,i){if(t.when&&!t.when(i))return e;let n={...e};const o=cr(n,t);o.length&&(n={...n,activePositiveIds:n.activePositiveIds.filter(e=>!o.includes(e)),poppedPositiveIds:Array.from(new Set([...n.poppedPositiveIds,...o]))});const r=ur(n,t);if(r.length){const e=new Set(r.map(e=>e.index));n={...n,negativeIds:n.negativeIds.filter((t,i)=>!e.has(i)),poppedNegativeIds:[...n.poppedNegativeIds,...r.map(e=>e.propertyId)]}}const s=sr(t.addPositive);s.length&&(n={...n,activePositiveIds:Array.from(new Set([...n.activePositiveIds,...s])),missingPositiveIds:n.missingPositiveIds.filter(e=>!s.includes(e))});const a=sr(t.addNegative);if(a.length&&(n={...n,negativeIds:[...n.negativeIds,...a]}),t.delayDelta&&(n={...n,delay:n.delay+t.delayDelta}),t.metricsDelta){const e={...n.metrics};for(const[i,n]of Object.entries(t.metricsDelta))e[i]=Number(e[i]??0)+n;n={...n,metrics:e}}return t.viabilityDelta&&(n={...n,viability:n.viability+t.viabilityDelta}),t.stage&&(n={...n,stage:t.stage}),t.outcome&&(n={...n,outcome:t.outcome}),n}function pr(e,t){return{id:e.id,label:e.label??e.id,summary:e.summary??t.find(e=>e.summary)?.summary,time:e.time}}function mr(e,t){return e.eventsApplied.includes(t.id)?e:{...e,eventsApplied:[...e.eventsApplied,t.id],eventHistory:[...e.eventHistory??[],t],lastEvent:t,stage:t.label??e.stage}}import{forwardRef as yr,useCallback as fr,useEffect as gr,useImperativeHandle as br,useMemo as xr,useRef as vr,useState as wr}from"react";var kr="gauntlet-core",Mr="gauntlet-positive",Sr="gauntlet-negative";function Ir(e){return[{id:"gauntlet-left",restitution:.12,friction:.42,shape:{type:"segment",x1:28,y1:76,x2:28,y2:e.floorY,thickness:8}},{id:"gauntlet-ceiling",restitution:.12,friction:.42,shape:{type:"segment",x1:28,y1:76,x2:e.width-30,y2:76,thickness:8}},{id:"gauntlet-floor",restitution:.12,friction:.42,shape:{type:"segment",x1:28,y1:e.floorY,x2:e.width-30,y2:e.floorY,thickness:8}},{id:"gauntlet-right",restitution:.12,friction:.42,shape:{type:"segment",x1:e.width-30,y1:76,x2:e.width-30,y2:e.floorY,thickness:8}}]}function Ar(e,t,i,n){return i?"function"==typeof i?i(e,t):e[i]??n:n}function Pr(e){return e?.label??e?.id??"property"}function Cr(e){return`gauntlet:${e}:core`}function Rr(e,t){return`gauntlet:${e}:positive:${t}`}function Br(e,t,i){return`gauntlet:${e}:negative:${t}:${i}`}function jr(e,t,i,n){const o=Math.max(2,i+2),r=80+o,s=n.floorY-o;return{x:Math.max(32+o,Math.min(n.width-30-4-o,e)),y:Math.max(r,Math.min(s,t))}}function Tr(e){return{graveyardX:e.graveyardX,graveyardY:e.graveyardY,routeY:e.routeY,socketX:e.socketX,socketY:e.routeY-4,startX:e.startX,startY:e.routeY}}function Nr(e,t,i,n){const o=Tr(i),r=n?.(e,t,i)??{};return{...o,...r,startY:r.startY??r.routeY??o.startY,socketY:r.socketY??r.routeY??o.socketY,graveyardY:r.graveyardY??o.graveyardY}}function Or(e,t){const i=[...e].sort((e,t)=>e.localeCompare(t)),n=Math.max(0,i.indexOf(t));return{angle:.82*-Math.PI+(i.length>1?n/(i.length-1):.5)*Math.PI*.64,index:n,radius:48+n%2*6}}function Er(e,t,i){const n=e.activePositiveIds.reduce((e,i)=>e+(t.get(i)?.value??1),0),o=e.missingPositiveIds.length+e.poppedPositiveIds.length,r=e.negativeIds.reduce((e,t)=>e+(i.get(t)?.load??1),0);return Math.max(0,Math.min(100,75+3*n-8*r-1.2*e.delay-5*o))}function $r(e,t,i,n,o){const r=Ar(e,t,i.idAccessor,null!=e.id?e.id+"":"project-"+t)+"",s=n.map(e=>e.id),a=[...Ar(e,t,i.positiveAccessor,s)],c=[...Ar(e,t,i.negativeAccessor,[])].filter(e=>o.has(e));return{id:r,activePositiveIds:a,datum:e,delay:0,eventsApplied:[],eventHistory:[],killed:!1,metrics:{...Ar(e,t,i.metricsAccessor,{})},missingPositiveIds:s.filter(e=>!a.includes(e)),negativeIds:c,outcome:"in_process",poppedPositiveIds:[],poppedNegativeIds:[],startedAt:Math.max(0,Number(Ar(e,t,i.startTimeAccessor,0))||0),stage:"project filed",viability:Ar(e,t,i.initialViability,100)}}function qr(e,t,i,n,o,r,s){const a=n.startX,c=n.startY+(n.startY===i.routeY?38*t:0),l=s?.(e,t,i,n)??{},d={__gauntlet:!0,kind:kr,projectId:e.id,sourceDatum:e.datum},u=[{...l,id:Cr(e.id),x:l.x??a,y:l.y??c,vx:l.vx??42,vy:l.vy??0,mass:l.mass??7,bodyCollisions:l.bodyCollisions??!0,shape:l.shape??{type:"circle",radius:28},spawnAt:l.spawnAt??e.startedAt,datum:d}],h=jr(a,c,l.shape&&"radius"in l.shape&&Number(l.shape.radius)||28,i);u[0].x=h.x,u[0].y=h.y;for(const t of e.activePositiveIds){const n=o.get(t);if(!n)continue;const r=Or(e.activePositiveIds,t),s=n.radius??10,a=jr(h.x+Math.cos(r.angle)*r.radius,h.y+Math.sin(r.angle)*r.radius,s,i);u.push({id:Rr(e.id,t),x:a.x,y:a.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:l.spawnAt??e.startedAt,datum:{__gauntlet:!0,kind:Mr,projectId:e.id,property:n,sourceDatum:e.datum},springs:!1===n.spring?[]:[{target:{type:"body",bodyId:Cr(e.id)},stiffness:.56,damping:.9,restLength:52+r.index%2*4,...n.spring??{}}]})}return e.negativeIds.forEach((t,n)=>{const o=r.get(t);o&&u.push(Wr(e,o,n,h.x,h.y,i,l.spawnAt??e.startedAt))}),u}function Wr(e,t,i,n,o,r,s){const a=t.radius??7.2,c=jr(n-12+i%4*12,o+54+12*Math.floor(i/4),a,r);return{id:Br(e.id,t.id,i),x:c.x,y:c.y,vx:10,vy:6,mass:t.mass??.72,bodyCollisions:!1,shape:{type:"circle",radius:a},spawnAt:s,datum:{__gauntlet:!0,kind:Sr,projectId:e.id,property:t,sourceDatum:e.datum},springs:!1===t.spring?[]:[{target:{type:"body",bodyId:Cr(e.id)},stiffness:.62,damping:.92,restLength:52+i%4*3,...t.spring??{}}]}}function Fr(e,t){const i=e.datum;return!(!i?.__gauntlet||i.projectId!==t||i.kind!==Sr)}function Dr(e){const t=e.id.slice(e.id.lastIndexOf(":")+1),i=Number(t);return Number.isFinite(i)?i:-1}import{jsx as zr,jsxs as Yr}from"react/jsx-runtime";function Lr(e){const t=e.data;return t?.__gauntlet?Yr("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:[zr("strong",{children:t.kind===kr?"string"==typeof t.sourceDatum?.label?t.sourceDatum.label:t.projectId:Pr(t.property)}),zr("div",{children:t.kind===Mr?"Positive property":t.kind===Sr?"Negative property":"Project core"})]}):null}function Hr(e,t,i){const n=t.datum;if(!n?.__gauntlet)return;const o="circle"===t.shape.type?t.shape.radius:8;if(e.save(),e.translate(t.x,t.y),n.kind===kr)e.fillStyle=Xr(e,i.fill,"#0f766e"),e.strokeStyle=Xr(e,i.stroke,"#f8fafc"),e.lineWidth=2.4,e.beginPath(),e.arc(0,0,o,0,2*Math.PI),e.fill(),e.stroke();else{const t=n.property;e.fillStyle=Xr(e,i.fill??t?.color,"#38bdf8"),e.strokeStyle=Xr(e,i.stroke,"#0f172a"),e.lineWidth=1.1,e.beginPath(),n.kind===Sr?e.rect(-o,-o,2*o,2*o):e.arc(0,0,o,0,2*Math.PI),e.fill(),e.stroke(),e.fillStyle=Xr(e,"var(--semiotic-background, #07111f)","#07111f"),e.font=`900 ${n.kind===Sr?9:8}px system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,e.textAlign="center",e.textBaseline="middle",e.fillText(t?.short??t?.id?.slice(0,1).toUpperCase()??"?",0,.5)}e.restore()}function Xr(e,t,i){if("string"!=typeof t)return i;if("function"!=typeof getComputedStyle||!e.canvas)return t||i;const n=t.startsWith("var(")?t.match(/var\((--[^,\s)]+)/)?.[1]:t.startsWith("--")?t:null;return n?getComputedStyle(e.canvas).getPropertyValue(n).trim()||i:t||i}function _r({layout:e,states:t}){return Yr("svg",{"aria-hidden":"true",viewBox:`0 0 ${e.width} ${e.height}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[zr("path",{d:`M ${e.startX-42} ${e.routeY} C ${.24*e.width} ${e.routeY-70}, ${.42*e.width} ${e.routeY+78}, ${.58*e.width} ${e.routeY} S ${.78*e.width} ${e.routeY-82}, ${e.socketX+36} ${e.routeY}`,fill:"none",stroke:"var(--semiotic-accent, #38bdf8)",strokeDasharray:"18 12",strokeLinecap:"round",strokeOpacity:.45,strokeWidth:7}),zr("line",{x1:Math.round(.06*e.width),x2:Math.round(.94*e.width),y1:e.crashY,y2:e.crashY,stroke:"var(--semiotic-negative, #ef4444)",strokeDasharray:"3 7",strokeOpacity:.64}),zr("text",{x:Math.round(.07*e.width),y:e.crashY-8,fill:"var(--semiotic-negative, #ef4444)",fontSize:9,fontWeight:800,children:"CRASH LINE"}),e.gates.map(t=>Yr("g",{children:[zr("rect",{x:t.x-t.width/2,y:Math.max(80,e.routeY-180),width:t.width,height:Math.min(360,e.height-170),rx:12,fill:t.color??"var(--semiotic-accent, #38bdf8)",fillOpacity:.1,stroke:t.color??"var(--semiotic-accent, #38bdf8)",strokeDasharray:"5 5",strokeOpacity:.7}),zr("text",{x:t.x,y:Math.max(64,e.routeY-196),fill:"var(--semiotic-text-secondary, #64748b)",fontSize:10,fontWeight:800,textAnchor:"middle",children:t.label??t.id})]},t.id)),Yr("g",{children:[zr("rect",{x:e.socketX-52,y:e.routeY-56,width:104,height:112,rx:13,fill:"var(--semiotic-positive, #22c55e)",fillOpacity:.12,stroke:"var(--semiotic-positive, #22c55e)",strokeWidth:1.5}),zr("text",{x:e.socketX,y:e.routeY-72,fill:"var(--semiotic-text-secondary, #64748b)",fontSize:10,fontWeight:800,textAnchor:"middle",children:"SOCKET"})]}),Yr("g",{children:[zr("rect",{x:e.graveyardX-82,y:e.graveyardY-34,width:164,height:58,rx:11,fill:"var(--semiotic-negative, #ef4444)",fillOpacity:.16,stroke:"var(--semiotic-negative, #ef4444)",strokeOpacity:.7}),zr("text",{x:e.graveyardX,y:e.graveyardY-8,fill:"var(--semiotic-negative, #ef4444)",fontSize:10,fontWeight:800,textAnchor:"middle",children:"GRAVEYARD"}),zr("text",{x:e.graveyardX,y:e.graveyardY+12,fill:"var(--semiotic-text-secondary, #64748b)",fontSize:9,fontWeight:700,textAnchor:"middle",children:t.some(e=>e.killed)?"lift shut off":"too heavy or too small"})]})]})}function Gr(e){const t=e.datum;return!!t?.__gauntlet&&(t.kind===kr?{label:t.projectId+" project core",group:"project",description:"Project core carrying positive and negative properties."}:{label:`${Pr(t.property)} ${t.kind===Mr?"positive":"negative"} property`,group:t.kind===Mr?"positive property":"negative property",description:`${Pr(t.property)} attached to ${t.projectId}.`})}function Vr({states:e,layout:t}){const i=function(e){return e.map(e=>({label:e.id,value:Math.max(0,Number(e.viability)||0),outcome:e.outcome||e.stage||"in-process"}))}(e);if(!i.length)return null;const n=Math.max(1,...i.map(e=>e.value)),o=Math.max(40,(t.width-80)/i.length);return Yr("svg",{"aria-hidden":"true","data-testid":"gauntlet-projection-overlay",width:t.width,height:t.height,viewBox:`0 0 ${t.width} ${t.height}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[zr("text",{x:36,y:18,fill:"var(--semiotic-text-secondary, #64748b)",fontSize:9,fontWeight:800,children:"SETTLED · viability / outcome"}),i.map((e,t)=>{const i=40+t*o,r=Math.max(2,e.value/n*28),s=/kill|crash|block|grave/i.test(e.outcome);return Yr("g",{children:[zr("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}),zr("text",{x:i+.4*o,y:62,textAnchor:"middle",fill:"var(--semiotic-text-secondary, #64748b)",fontSize:9,fontWeight:700,children:e.label})]},e.label)})]})}import{jsx as Ur}from"react/jsx-runtime";import{createElement as Kr}from"react";var Qr=[],Zr=yr(function(e,t){const{bodyGroups:i,coreBody:n,coreForceMode:o="route",crashDetection:r=!0,crashOffset:s=30,data:a,emptyContent:c,events:l,frameProps:d={},gates:u,initialSpawnPacing:h,loading:p,loadingContent:m,negativeProperties:y,onCapacityChange:f,onClick:g,onStateChange:b,outcome:v,paused:w,positiveProperties:k=Qr,projectPlacement:M,responsiveHeight:S,responsiveWidth:I,showTethers:A=!0,terminalBehavior:P="outcome",viability:C}=e,R=vr(null),B=xr(()=>({idAccessor:e.idAccessor,initialViability:e.initialViability,metricsAccessor:e.metricsAccessor,negativeAccessor:e.negativeAccessor,positiveAccessor:e.positiveAccessor,startTimeAccessor:e.startTimeAccessor}),[e.idAccessor,e.initialViability,e.metricsAccessor,e.negativeAccessor,e.positiveAccessor,e.startTimeAccessor]),j=So(e,[900,520]),{chartSize:T,showProjection:N,showChrome:O,className:E,title:$,chartMode:q,margin:W,enableHover:F,description:D,summary:z,accessibleTable:Y}=j,L=Io({data:a,emptyContent:c,loading:p,loadingContent:m,size:T}),H=xr(()=>x(a??[]),[a]),X=xr(()=>H.map((e,t)=>Ar(e,t,B.idAccessor,null!=e.id?e.id+"":"project-"+t)+"").join("|"),[H,B.idAccessor]),_=xr(()=>new Map(k.map(e=>[e.id,e])),[k]),G=xr(()=>new Map(y.map(e=>[e.id,e])),[y]),V=xr(()=>function(e,t,i){const[n,o]=e,r=Math.round(.48*o),s=o-36,a=(t??[]).filter(e=>!1!==e.enabled),c=Math.max(1,a.length),l=.22*n,d=c>1?(.78*n-l)/(c-1):0,u=Math.max(Math.round(.14*n),110);return{crashY:s-i,floorY:s,gates:a.map((e,t)=>({...e,id:e.id,x:e.x??Math.round(l+t*d),width:e.width??Math.max(54,Math.round(.07*n))})),graveyardX:Math.round(.84*n),graveyardY:s-4,height:o,routeY:r,socketX:Math.round(.92*n),startX:u,width:n}}(T,u,s),[T,s,u]),U=xr(()=>new Map(V.gates.map(e=>[e.id,e])),[V.gates]),K=xr(()=>V.gates.map(e=>({kind:"force-field",damping:.035,force:{x:12,y:0},semanticItem:!1,...e.regionEffect,id:"gauntlet-gate-"+e.id,label:e.label??e.id,description:e.description,bodyFilter:e.capacity?{property:"datum.kind",equals:kr}:e.regionEffect?.bodyFilter,shape:{type:"aabb",x:e.x,y:V.routeY,width:e.capacity?e.capacity.sensorWidth??Math.max(96,6*e.width):Math.max(e.width,54),height:Math.min(360,V.height-170)}})),[V.gates,V.height,V.routeY]),[Q,Z]=wr(()=>H.map((e,t)=>{const i=$r(e,t,B,k,G);return{...i,viability:C?.(i,{negativeProperties:G,positiveProperties:_})??Er(i,_,G)}})),J=vr(Q),ee=vr(0),te=vr(new Map),ie=vr([]),ne=vr(f);ne.current=f;const oe=xr(()=>function(e){const{dataKey:t,gates:i,statesRef:n,processedGateVisitsRef:o}=e;return i.flatMap(e=>e.capacity&&e.capacity.unitsPerSecond>0?[xt({id:`gauntlet-capacity-${t}-${e.id}`,regionId:"gauntlet-gate-"+e.id,unitsPerSecond:e.capacity.unitsPerSecond,bodyFilter:{property:"datum.kind",equals:kr},maxQueue:e.capacity.maxQueue,queueLayout:e.capacity.queueLayout,queueSlotSpacing:e.capacity.queueSlotSpacing,queueStiffness:e.capacity.queueStiffness??24,releaseImpulse:{x:36,y:0},unitAccessor:t=>{const i=t.datum,o=i?.sourceDatum,r=e.capacity?.unitAccessor,s=n.current.find(e=>e.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:t=>{const i=t.datum;if(!i?.projectId)return;const n=`${i.projectId}:${e.id}`;o.current.set(n,(o.current.get(n)??0)+1)}})]:[])}({dataKey:X,gates:V.gates,statesRef:J,processedGateVisitsRef:te}),[X,V.gates]),re=xr(()=>[...oe,...d.controllers??[]],[oe,d.controllers]),se=vr(H);se.current=H;const ae=vr(b);ae.current=b;const ce=vr({negativeById:G,positiveById:_,positiveProperties:k,stateAccessors:B,viability:C});ce.current={negativeById:G,positiveById:_,positiveProperties:k,stateAccessors:B,viability:C};const le=fr((e,t,i=0)=>{const n=ce.current,o=$r(e,t,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})??Er(o,n.positiveById,n.negativeById)}},[]);gr(()=>{te.current.clear(),ie.current=[];const e=se.current.map((e,t)=>le(e,t));J.current=e,Z(e)},[le,X]),gr(()=>{J.current=Q,ae.current?.(Q)},[Q]);const de=fr(e=>[...("function"==typeof l?l(e,V):l)??[]].sort((e,t)=>e.time-t.time),[l,V]),ue=fr((e,t,i)=>{if(!t.gateId||!U.get(t.gateId)?.capacity)return!0;const n=Number(t.gateVisit),o=Number.isFinite(n)&&n>0?Math.floor(n):i.filter(e=>e.gateId===t.gateId).findIndex(e=>e.id===t.id)+1;return o>0&&(te.current.get(`${e.id}:${t.gateId}`)??0)>=o},[U]),he=fr(()=>{if(!oe.length)return;const e=oe.flatMap(e=>{const t=e.getSnapshot?.();return t?[t]:[]});var t,i;(t=ie.current).length===(i=e).length&&t.every((e,t)=>{const n=i[t];return!!n&&e.regionId===n.regionId&&e.queueDepth===n.queueDepth&&e.blockedDepth===n.blockedDepth&&e.processedCount===n.processedCount&&e.metricRevision===n.metricRevision})||(ie.current=e,ne.current?.(e))},[oe]),pe=xr(()=>Q.flatMap((e,t)=>{const i=Nr(e,t,V,M);return qr(e,t,V,i,_,G,n)}),[n,V,G,_,M,Q]),me=fr((e,t)=>{let i=!1;const n=J.current.map(n=>{if(n.id!==e)return n;const o=t(n);return i=i||o!==n,o});i&&(J.current=n,Z(n))},[]);br(t,()=>function(e){const{statesRef:t,setStates:i,elapsedRef:n,frameRef:o,layout:r,projectPlacement:s,positiveById:a,negativeById:c,coreBody:l,createState:d}=e;return{push:e=>{const u=d(e,t.current.length,n.current),h=Nr(u,t.current.length,r,s),p=qr(u,t.current.length,r,h,a,c,l),m=[...t.current,u];t.current=m,i(m),o.current?.pushMany(p),o.current?.step(0)},pushMany:e=>{const u=[...t.current],h=[],p=n.current;e.forEach(e=>{const t=d(e,u.length,p),i=Nr(t,u.length,r,s);h.push(...qr(t,u.length,r,i,a,c,l)),u.push(t)}),t.current=u,i(u),h.length&&o.current?.pushMany(h),o.current?.step(0)},remove:e=>{const n=Array.isArray(e)?e:[e],r=[],s=[];for(const e of n){const i=t.current.find(t=>t.id===e);i&&(r.push(i.datum),s.push(Cr(i.id),...i.activePositiveIds.map(e=>Rr(i.id,e))),i.negativeIds.forEach((e,t)=>{s.push(Br(i.id,e,t))}))}return t.current=t.current.filter(e=>!n.includes(e.id)),i(t.current),o.current?.remove(s),r},update:(e,u)=>{const h=Array.isArray(e)?e:[e],p=[];for(const e of h){const i=t.current.find(t=>t.id===e);if(!i)continue;const h=t.current.findIndex(t=>t.id===e);p.push(i.datum);const m=u(i.datum),y=d(m,0>h?t.current.length:h,i.startedAt??n.current),f=Nr(y,0>h?t.current.length:h,r,s);o.current?.remove([Cr(i.id),...i.activePositiveIds.map(e=>Rr(i.id,e)),...i.negativeIds.map((e,t)=>Br(i.id,e,t))]),o.current?.pushMany(qr(y,0>h?t.current.length:h,r,f,a,c,l)),t.current=t.current.map(t=>t.id===e?y:t)}return i(t.current),p},clear:()=>{t.current=[],i([]),o.current?.clear()},getData:()=>t.current.map(e=>e.datum),getScales:()=>null,getCustomLayout:()=>o.current?.snapshot()??null,popBodies:(e,t)=>o.current?.popBodies(e,t)??[]}}({statesRef:J,setStates:Z,elapsedRef:ee,frameRef:R,layout:V,projectPlacement:M,positiveById:_,negativeById:G,coreBody:n,createState:le}),[n,le,V,G,_,M]);const ye=fr((e,t,i)=>{!function(e){const{project:t,effect:i,controls:n,layout:o,positiveById:r,negativeById:s,coreBody:a,popBodies:c}=e,l=n.readBodies().find(e=>e.id===Cr(t.id)),d=n.readBodies(),u=l?.x??o.startX,h=l?.y??o.routeY,p=function(e,t){let i=-1;for(const n of t)Fr(n,e.id)&&(i=Math.max(i,Dr(n)));return Math.max(e.negativeIds.length,i+1)}(t,d),m=sr(i.addNegative).flatMap((e,i)=>{const n=s.get(e);return n?[Wr(t,n,p+i,u,h,o)]:[]}),y=sr(i.addPositive).flatMap(e=>{if(!r.get(e)||t.activePositiveIds.includes(e))return[];const i={...Tr(o),routeY:h,socketY:h,startX:u,startY:h};return qr({...t,activePositiveIds:[e],negativeIds:[]},0,o,i,r,s,a).filter(e=>e.id.includes(":positive:"))});(m.length||y.length)&&n.pushMany([...m,...y]);const f=cr(t,i);for(const e of f){const i=r.get(e);c([Rr(t.id,e)],{color:i?.popColor??i?.color,durationMs:900,radius:(i?.radius??10)+3})}const g=ur(t,i),b=function(e,t,i){const n=t.filter(t=>Fr(t,e.id)).sort((e,t)=>Dr(e)-Dr(t)||e.id.localeCompare(t.id)),o=new Set;return i.map(t=>{const i=n.find(e=>!o.has(e.id)&&e.datum.property?.id===t.propertyId);return i?(o.add(i.id),i.id):Br(e.id,t.propertyId,t.index)})}(t,d,g);g.forEach((e,t)=>{const i=s.get(e.propertyId);c([b[t]],{color:i?.popColor??i?.color,durationMs:900,radius:(i?.radius??7)+3})})}({project:e,effect:t,controls:i,layout:V,positiveById:_,negativeById:G,coreBody:n,popBodies:(e,t)=>R.current?.popBodies(e,t)})},[n,V,G,_]),fe=fr(({body:e,bodies:t})=>function(e){const{body:t,bodies:i,layout:n,states:o,projectPlacement:r,positiveById:s,negativeById:a,projectEvents:c,gateById:l,coreForceMode:d,terminalBehavior:u,elapsed:h}=e,p=t.datum;if(!p?.__gauntlet)return null;const m=o.findIndex(e=>e.id===p.projectId),y=0>m?void 0:o[m];if(!y)return null;const f=Nr(y,m,n,r),g=i.find(e=>e.id===Cr(y.id)),b=y.negativeIds.reduce((e,t)=>e+(a.get(t)?.load??1),0),x=y.killed?0:58;if(p.kind!==kr){if(!g)return null;let e;const o=p.property;if(o?.target){const r=i.filter(e=>{const t=e.datum;return t?.__gauntlet&&t.projectId===y.id&&t.kind===p.kind}).sort((e,t)=>(e.id+"").localeCompare(t.id+"")),s=Math.max(0,r.findIndex(e=>e.id===t.id));e=o.target({body:t,bodies:i,core:g,index:s,layout:n,placement:f,project:y})??{x:g.x,y:g.y}}else if(p.kind===Mr&&p.property){const t=Or(y.activePositiveIds,p.property.id);e={x:g.x+Math.cos(t.angle)*t.radius,y:g.y+Math.sin(t.angle)*t.radius-2}}else{const n=i.filter(e=>e.datum?.kind===Sr&&e.datum.projectId===y.id).sort((e,t)=>(e.id+"").localeCompare(t.id+"")),o=Math.max(0,n.findIndex(e=>e.id===t.id)),r=Math.floor(o/4);e={x:g.x+18*(o%4-(Math.min(4,n.length-4*r)-1)/2),y:g.y+54+13*r}}const r="circle"===t.shape.type?t.shape.radius:8;e=jr(e.x,e.y,r,n);const s=jr(t.x,t.y,r,n);if(Math.abs(s.x-t.x)>.5||Math.abs(s.y-t.y)>.5)return{x:48*(s.x-t.x)-6*t.vx,y:48*(s.y-t.y)-6*t.vy};const a=p.kind!==Mr||y.killed?0:3.2*(o?.buoyancy??o?.value??1),c=p.kind===Sr?{x:.22*(o?.pull?.x??-8),y:.22*(o?.pull?.y??22)}:{x:0,y:0};return{x:28*(e.x-t.x)-3*(t.vx-g.vx)+c.x+.01*x,y:28*(e.y-t.y)-3*(t.vy-g.vy)+c.y-a}}if(y.killed)return{x:44*((y.crashX??y.metrics.lastX??t.x)-t.x)-9*t.vx,y:160+12*b-1.6*t.vy};const v=c(y),w=function(e,t,i,n,o,r,s){if(t.killed)return{x:t.metrics.lastX??n.graveyardX,y:n.graveyardY};const a=o[o.length-1];if(!a)return{x:n.socketX,y:n.routeY};const c=o.find(i=>e>=i.time&&!t.eventsApplied.includes(i.id)&&!(!i.gateId||!r.get(i.gateId)?.capacity)),l=c?Math.min(e,c.time):e,d="built"===t.outcome||"built_diminished"===t.outcome;if(l>a.time+.85){if("hold-last"===s){const e=a.gateId?r.get(a.gateId):void 0;return{x:a.routeX??e?.x??n.socketX,y:a.routeY??n.routeY}}return d?{x:n.socketX,y:n.socketY}:{x:n.graveyardX,y:n.graveyardY-14}}const u=.85*t.delay+12*t.negativeIds.length+8*(t.poppedPositiveIds.length+t.missingPositiveIds.length),h=[{time:0,x:n.startX,y:n.startY},...o.map(e=>{const t=e.gateId?r.get(e.gateId):void 0;return{time:e.time,x:e.routeX??t?.x??n.startX,y:e.routeY??n.routeY+.28*Math.min(180,u)}})].sort((e,t)=>e.time-t.time);let p=h[0],m=h[h.length-1];for(let e=1;h.length>e;e+=1){if(h[e].time>=l){m=h[e];break}p=h[e]}const y=Math.max(0,Math.min(1,(l-p.time)/Math.max(.1,m.time-p.time))),f=y*y*(3-2*y);return{x:p.x+(m.x-p.x)*f,y:p.y+(m.y-p.y)*f+7*Math.sin(2.6*l)}}(Math.max(0,h-(y.startedAt??0)),y,0,f,v,l,u),k=y.activePositiveIds.reduce((e,t)=>e+(s.get(t)?.buoyancy??s.get(t)?.value??1),0);return"net"===d?{x:15*(w.x-t.x)-1.8*t.vx+.18*x,y:1.25*(f.routeY-t.y)-1.4*t.vy+32*(b-k)}:{x:15*(w.x-t.x)-1.8*t.vx+.18*x,y:15*(w.y-t.y)-1.8*t.vy+13*b-2.2*k}}({body:e,bodies:t,layout:V,states:J.current,projectPlacement:M,positiveById:_,negativeById:G,projectEvents:de,gateById:U,coreForceMode:o,terminalBehavior:P,elapsed:ee.current}),[o,U,V,G,_,de,M,P]),ge=fr((e,t)=>{!function(e,t,i){const{frameProps:n,elapsedRef:o,statesRef:r,crashDetection:s,layout:a,projectEvents:c,gateById:l,capacityEventReady:d,addBodiesForEffect:u,updateProjectState:h,viability:p,positiveById:m,negativeById:y,outcome:f,reportCapacity:g}=i;n.onTick?.(e,t),o.current=e.elapsedSeconds??t.snapshot().elapsedSeconds,g();for(const e of r.current){const i=t.readBodies().find(t=>t.id===Cr(e.id));if(!i)continue;if(s&&!e.killed&&i.y+("circle"===i.shape.type?i.shape.radius:28)>=a.crashY){t.readBodies().forEach(i=>{const n=i.datum;n?.__gauntlet&&n.projectId===e.id&&t.applyImpulse(i.id,-i.vx*i.mass,0)}),h(e.id,e=>{const t={appliedAt:Math.max(0,o.current-(e.startedAt??0)),id:"gauntlet-crash-line",label:"Crash Line",summary:"The project hit the crash threshold; lift and forward motion shut off.",time:Math.max(0,o.current-(e.startedAt??0))};return{...e,crashX:i.x,eventHistory:[...e.eventHistory??[],t],killed:!0,lastEvent:t,metrics:{...e.metrics,lastX:i.x},outcome:"bad_design_crash",stage:"Crash Line",viability:Math.min(0,e.viability)}});continue}if(e.killed)continue;const n=Math.max(0,o.current-(e.startedAt??0)),r=c(e),g=r.filter(t=>n>=t.time&&!e.eventsApplied.includes(t.id)&&d(e,t,r));let b=e;for(const i of g){const o=i.gateId?l.get(i.gateId):void 0,r=i.effects??[];for(const e of r){const n={event:i,gate:o,negativeProperties:y,positiveProperties:m,project:b};e.when&&!e.when(n)||(u(b,e,t),b=hr(b,e,n))}const s={...pr(i,r),appliedAt:n};b=mr(b,s),h(e.id,e=>{let t=mr(e,s);if(t===e)return e;for(const e of r)t=hr(t,e,{event:i,gate:o,negativeProperties:y,positiveProperties:m,project:t});const n=p?.(t,{negativeProperties:y,positiveProperties:m})??Er(t,m,y);return t={...t,viability:n},i.final&&(t={...t,outcome:i.outcome??f?.(t,{layout:a,negativeProperties:y,positiveProperties:m})??(t.viability>20?"built":"approved_not_built")}),t})}}}(e,t,{frameProps:d,elapsedRef:ee,statesRef:J,crashDetection:r,layout:V,projectEvents:de,gateById:U,capacityEventReady:ue,addBodiesForEffect:ye,updateProjectState:me,viability:C,positiveById:_,negativeById:G,outcome:v,reportCapacity:he})},[ye,ue,r,d,U,V,G,v,_,de,he,me,C]),be=fr((e,t)=>{const i="function"==typeof d.bodyStyle?d.bodyStyle(e,t):d.bodyStyle,n=e.datum;return n?.__gauntlet?{fill:n.kind===kr?"var(--semiotic-accent, #0f766e)":n.property?.color??"var(--semiotic-accent, #38bdf8)",stroke:n.kind===kr?"#f8fafc":"#0f172a",opacity:.96,...i}:i??{}},[d]),xe=xr(()=>"function"==typeof i?i(Q,V):i??[],[i,V,Q]),ve=xr(()=>rr(xe),[xe]),we=xr(()=>N?function(e,t){if(!e.length)return[];const i=Math.max(40,(t.width-80)/e.length);return e.map((e,t)=>{const n=`${e.id}: viability ${Math.round(e.viability)}, ${e.outcome||e.stage}`;return{id:"gauntlet-projection-"+e.id,label:n,description:n,datum:e,x:40+(t+.5)*i,y:28,shape:"rect",width:Math.max(16,.55*i),height:22,group:"settled projection"}})}(Q,V):[],[V,N,Q]),ke=xr(()=>[...we,...ve],[ve,we]),Me=fr((e,t)=>{d.onBodyPointerDown?.(e,t)},[d]),Se=fr((e,t)=>{g&&(e&&"object"==typeof e&&e.__gauntlet?g(e.sourceDatum,{x:t.x,y:t.y}):e&&g(e,{x:t.x,y:t.y}))},[g]),Ie=fr((e,t)=>{d.beforePaint?.(e,t),A&&function(e,t){const i=new Map(t.filter(e=>e.datum?.kind===kr).map(e=>[e.datum.projectId,e]));e.save(),e.lineWidth=1.1,e.setLineDash([3,4]);for(const n of t){const t=n.datum;if(!t?.__gauntlet||t.kind===kr)continue;const o=i.get(t.projectId);o&&(e.globalAlpha=t.kind===Sr?.24:.36,e.strokeStyle=t.kind===Sr?"#d94a45":"#7a8794",e.beginPath(),e.moveTo(o.x,o.y),e.lineTo(n.x,n.y),e.stroke())}e.restore()}(e,t)},[d,A]),Ae=xr(()=>({fixedDt:1/60,maxSubsteps:8,kernel:{gravity:{x:0,y:0},restitution:.16,friction:.44,velocityDamping:.982,maxVelocity:520,sleepAfter:.8,sleepSpeed:7,...d.config?.kernel??{}},colliders:[...Ir(V),...d.config?.colliders??[]]}),[d.config?.colliders,d.config?.kernel,V]),Pe=xr(()=>[...K,...d.regionEffects??[]],[d.regionEffects,K]);if(L)return L;const Ce=Co(e.tooltip,d),Re=Ro(e,d,ke,{chartMode:q,className:E,title:$,description:D,summary:z,accessibleTable:Y,enableHover:F,margin:W}),Be=N?Ur(Vr,{states:Q,layout:V}):void 0,je=Po(O?Ur(_r,{layout:V,states:Q}):void 0,d.backgroundGraphics),Te=Po(Be,d.foregroundGraphics),Ne=d.renderBody??Hr,Oe=Ce.tooltipContent??Lr;return Ao("GauntletChart",T,Kr(un,{...d,...Ce,...Re,key:`${T[0]}x${T[1]}:${X}`,ref:R,accessibleTable:e.accessibleTable??d.accessibleTable,backgroundGraphics:je,bodyForces:fe,bodySemanticItems:d.bodySemanticItems??Gr,bodyStyle:be,beforePaint:Ie,onClick:g?Se:Re.onClick,config:Ae,controllers:re,enableHover:Ce.enableHover??!0,foregroundGraphics:Te,hoverRadius:e.hoverRadius??d.hoverRadius??18,initialSpawns:pe,initialSpawnPacing:h,onBodyPointerDown:Me,onTick:ge,paused:w,regionEffects:Pe,renderBody:Ne,responsiveHeight:S,responsiveWidth:I,size:T,tooltipContent:Oe}))});Zr.displayName="GauntletChart";var Jr=Zr;import{forwardRef as es,useCallback as ts,useMemo as is,useRef as ns}from"react";import{jsx as os,jsxs as rs}from"react/jsx-runtime";function ss(e){return e.toLocaleString(void 0,1e3>Math.abs(e)?{maximumFractionDigits:1}:{maximumFractionDigits:0})}function as(e){return e.map((e,t)=>`${0===t?"M":"L"} ${e.x} ${e.y}`).join(" ")}function cs(e){if(!e||"object"!=typeof e)return null;const t=e,i=Number(t.x),n=Number(t.y);return Number.isFinite(i)&&Number.isFinite(n)?{x:i,y:n}:null}function ls(e){if(!e||"object"!=typeof e)return[];const t=e.flowPath;return Array.isArray(t)?t.map(cs).filter(e=>null!=e):[]}function ds(e,t){if(2>t.length)return null;let i=0;const n=[];for(let e=1;t.length>e;e+=1){const o=Math.hypot(t[e].x-t[e-1].x,t[e].y-t[e-1].y);n.push(o),i+=o}if(0>=i)return null;let o=null,r=0;for(let s=1;t.length>s;s+=1){const a=t[s-1],c=t[s],l=n[s-1];if(0>=l)continue;const d=c.x-a.x,u=c.y-a.y,h=Math.max(0,Math.min(1,((e.x-a.x)*d+(e.y-a.y)*u)/(l*l))),p={x:a.x+d*h,y:a.y+u*h},m={distance:Math.hypot(e.x-p.x,e.y-p.y),point:p,progress:(r+h*l)/i,tangent:{x:d/l,y:u/l},totalLength:i};o&&m.distance>=o.distance||(o=m),r+=l}return o}function us(e,t,i){if(0===e.length)return{x:0,y:0};if(1===e.length||0>=i)return{...e[0]};let n=0;const o=Math.max(0,Math.min(1,t))*i;for(let t=1;e.length>t;t+=1){const i=e[t-1],r=e[t],s=Math.hypot(r.x-i.x,r.y-i.y);if(s>0){if(n+s>=o){const e=(o-n)/s;return{x:i.x+(r.x-i.x)*e,y:i.y+(r.y-i.y)*e}}n+=s}}return{...e[e.length-1]}}function hs(e){return"circle"===e.shape.type?e.shape.radius:Math.max(e.shape.width,e.shape.height)/2}function ps(e,t,i){const n=Math.hypot(e,t);if(i>=n||0>=n)return[e,t];const o=i/n;return[e*o,t*o]}function ms(e,t,i){const n=ds({...e,x:t[0].x,y:t[0].y},t),o=n?.tangent??{x:t[1].x-t[0].x,y:t[1].y-t[0].y},r=Math.hypot(o.x,o.y)||1,s=o.x/r,a=o.y/r,c=hs(e),l=function(e,t){let i=0;for(let t=0;e.length>t;t+=1)i=31*i+e.charCodeAt(t)>>>0;return(i%1e3/1e3-.5)*t*1.4}(e.id,c);return{id:e.id,x:t[0].x+-a*l,y:t[0].y+s*l,vx:s*i,vy:a*i,mass:e.mass,shape:e.shape,datum:{...e.datum&&"object"==typeof e.datum?e.datum:{},routeProgress:0}}}var ys=es(function(e,t){const{chartId:i,colorBy:n,coordinateMode:o="auto",data:r,edges:s,emptyContent:a,flowSpeed:c=90,frameProps:l,links:d,loading:u,loadingContent:h,maxParticles:p=180,nodeIdAccessor:m="id",nodeXAccessor:y="x",nodeYAccessor:f="y",nodes:g,onObservation:b,particleRadius:x=4,particleRate:v=.16,pathAccessor:w="path",pathConstraint:k="path",paused:M,reducedMotion:S=!1,responsiveHeight:I,responsiveWidth:A,seed:P=1,showNodeLabels:C=!0,showSensors:R=!1,showStaticFlow:B=!0,sourceAccessor:j="source",styleRules:T,targetAccessor:N="target",throughputAccessor:O="value"}=e,E=So(e,[760,420]),{chartSize:$,className:q,title:W,chartMode:F,margin:D,enableHover:z,description:Y,summary:L,accessibleTable:H}=E,X=ns(null),_=is(()=>g??[],[g]),G=is(()=>d??s??r??[],[r,s,d]),V=is(()=>Wn({nodes:_,links:G,nodeIdAccessor:m,nodeXAccessor:y,nodeYAccessor:f,sourceAccessor:j,targetAccessor:N,throughputAccessor:O,pathAccessor:w,coordinateMode:o,particleRate:v,maxParticles:p,particleRadius:x,flowSpeed:c,pathConstraint:k,reducedMotion:S,seed:P,size:$}),[G,_,$,o,c,p,m,y,f,x,v,w,k,S,P,j,N,O]);bo(t,{frameRef:X,spawnDatum:ts((e,t)=>{const i=Wn({nodes:_,links:[e],nodeIdAccessor:m,nodeXAccessor:y,nodeYAccessor:f,sourceAccessor:j,targetAccessor:N,throughputAccessor:O,pathAccessor:w,coordinateMode:o,particleRate:v,maxParticles:p,particleRadius:x,flowSpeed:c,pathConstraint:k,reducedMotion:S,seed:P+t+1,size:$}),n={id:(e.id??"physical-flow-push-"+t)+"",x:pn($).plot.x,y:pn($).plot.y,mass:1,shape:{type:"circle",radius:x},datum:e},r=i.initialSpawns.length?i.initialSpawns:[n];return{datumId:(e.id??r[0].id)+"",spawns:r}},[_,$,o,c,p,m,y,f,x,v,w,k,S,P,j,N,O]),seedRows:G,seedSpawns:V.initialSpawns});const U=n??"source",K=is(()=>yn(U,"#2563eb",{styleRules:T,valueAccessor:O}),[U,T,O]),Q=is(()=>function(e,t,i){return{...e,observation:{...e.observation,chartId:t??e.observation?.chartId??"physical-flow",chartType:"PhysicalFlowChart",onObservation:i??e.observation?.onObservation}}}(V.config,i,b),[i,V.config,b]),Z=ns(l?.onTick);Z.current=l?.onTick;const J=ts((e,t)=>{S||"none"===k||function(e,t){const i=e.readBodies(),n=[],o=[];for(const r of i){const i=ls(r.datum);if(2>i.length)continue;const s=ds(r,i);if(!s)continue;const a=r.datum,c=Number(a?.flowSpeed),l=Number.isFinite(c)&&c>0?c:t;if(s.progress>=.985||s.distance>Math.max(90,14*hs(r))){n.push(r.id),o.push(ms(r,i,l));continue}const d=us(i,Math.min(1,s.progress+Math.max(.035,Math.min(.12,l/s.totalLength*.16))),s.totalLength),u=s.tangent,h=(u.x*l-r.vx)*r.mass*.16+(d.x-r.x)*r.mass*.045+(s.point.x-r.x)*r.mass*.08,p=(u.y*l-r.vy)*r.mass*.16+(d.y-r.y)*r.mass*.045+(s.point.y-r.y)*r.mass*.08,[m,y]=ps(h,p,r.mass*l*.35);e.applyImpulse(r.id,m,y)}n.length&&e.remove(n),o.length&&e.pushMany(o)}(t,c),Z.current?.(e,t)},[c,k,S]),ee=Io({data:null==d&&null==s&&null==r?void 0:G,emptyContent:a,loading:u,loadingContent:h,size:$});if(ee)return ee;const te=function(e,t){const{showNodeLabels:i,showSensors:n,showStaticFlow:o}=t;if(e&&(o||n))return({size:t})=>{const r=[Number(t[0])||760,Number(t[1])||420],s=Math.max(1,...e.links.map(e=>e.throughput)),a=new Set(e.nodes.map(e=>e.sensorId));return rs("svg",{"aria-hidden":"true","data-testid":"physical-flow-static-flow-overlay",width:r[0],height:r[1],viewBox:`0 0 ${r[0]} ${r[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[o?e.links.map(e=>{const t=3+e.throughput/s*16,i=e.path[Math.floor(e.path.length/2)];return rs("g",{children:[os("path",{d:as(e.path),fill:"none",stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:t+5,strokeLinecap:"round",strokeLinejoin:"round",opacity:.26}),os("path",{d:as(e.path),fill:"none",stroke:"var(--semiotic-accent, #4e79a7)",strokeWidth:t,strokeLinecap:"round",strokeLinejoin:"round",opacity:.16}),i?os("text",{x:i.x,y:i.y-t/2-5,textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:ss(e.throughput)}):null]},e.id)}):null,e.nodes.map(e=>rs("g",{children:[n&&a.has(e.sensorId)?os("rect",{"data-testid":"physical-flow-sensor-overlay",x:e.x-12,y:e.y-12,width:24,height:24,rx:4,fill:"none",stroke:"var(--semiotic-warning, #f59e0b)",strokeDasharray:"3 3",strokeWidth:1.5,opacity:.88}):null,o?os("circle",{cx:e.x,cy:e.y,r:6,fill:"var(--semiotic-bg, #fff)",stroke:"var(--semiotic-text-secondary, #555)",strokeWidth:1.2}):null,i?os("text",{x:e.x,y:e.y-14,textAnchor:"middle",fill:"var(--semiotic-text-primary, #111827)",fontSize:11,fontWeight:800,children:e.label}):null]},e.id))]})}}(V.metadata,{showNodeLabels:C,showSensors:R,showStaticFlow:B}),ie=(ne=V.metadata)?ne.links.map(e=>{const t=e.path[Math.floor(e.path.length/2)]??e.path[0],i=`${e.sourceLabel} to ${e.targetLabel}: ${ss(e.throughput)} throughput, ${e.packetCount} packets`;return{id:e.id,label:i,description:i,datum:e,x:t?.x??0,y:t?.y??0,shape:"path",pathData:as(e.path),group:"flow"}}):[];var ne;const oe=Co(e.tooltip,l),re=Ro(e,l,ie,{chartMode:F,className:q,title:W,description:Y,summary:L,accessibleTable:H,enableHover:z,margin:D});return Ao("PhysicalFlowChart",$,os(un,{...l,...oe,...re,ref:X,config:Q,continuous:!S&&"none"!==k,foregroundGraphics:Po(te,l?.foregroundGraphics),initialSpawns:V.initialSpawns,onTick:J,paused:M||S,responsiveHeight:I,responsiveWidth:A,simulationExecution:"none"===k?l?.simulationExecution:"sync",size:$,bodyStyle:K,workerBodyThreshold:l?.workerBodyThreshold??1/0}))});ys.displayName="PhysicalFlowChart";import{Fragment as fs,jsx as gs,jsxs as bs}from"react/jsx-runtime";var xs={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 vs(e,t,i){return Math.max(t,Math.min(i,e))}function ws(e){return 6.2*e.length}function ks(e,t){const i=e.trim();if(t>=i.length)return i;if(1>=t)return i.slice(0,1);const n=i.split(/\s+/).filter(Boolean).map(e=>e[0]).join("").toUpperCase();return n.length>1&&t>=n.length?n:t>3?i.slice(0,Math.max(1,t-2))+"..":i.slice(0,t).toUpperCase()}function Ms(e,t,i="auto"){const n=Math.max(1,Math.floor(t/6.2)),o="compact"===i?ks(e,n):"full"===i?e:ws(e)>t?ks(e,n):e;return{text:o,textLength:ws(o)>t?Math.max(4,t):void 0}}function Ss(e,t={}){const{showFlowSpine:i=!0,showStageCounts:n=!0,showCapacityBadges:o=!0,showGroupSockets:r=!0,stageLabelMode:s="auto",outlineStages:a=!1,testId:c="process-flow-chrome"}=t,{width:l,height:d,left:u,right:h,topY:p,bottomY:m,midY:y,stages:f,groups:g=[]}=e,b=m-p;return bs("svg",{"aria-hidden":"true","data-testid":c,"data-outline-stages":a?"true":void 0,width:l,height:d,viewBox:`0 0 ${l} ${d}`,style:{position:"absolute",inset:0,pointerEvents:"none"},className:["semiotic-process-chrome",a?"semiotic-process-chrome--outline-stages":null].filter(Boolean).join(" "),children:[gs("defs",{children:bs("linearGradient",{id:"semiotic-process-floor",x1:"0",x2:"0",y1:"0",y2:"1",children:[gs("stop",{offset:"0%",stopColor:"var(--semiotic-process-floor, var(--semiotic-bg, #0f172a))",stopOpacity:"0.2"}),gs("stop",{offset:"100%",stopColor:"var(--semiotic-process-lane, var(--semiotic-surface, #1e293b))",stopOpacity:"0.55"})]})}),gs("rect",{x:0,y:0,width:l,height:d,fill:"url(#semiotic-process-floor)"}),gs("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?gs("line",{x1:u+8,x2:h-8,y1:y,y2:y,stroke:"var(--semiotic-process-border, var(--semiotic-border, #475569))",strokeWidth:2,strokeDasharray:"6 8",opacity:.55}):null,f.map((e,t)=>{const i=function(e){return e.absorb?"absorb":e.portalTarget?"portal":null!=e.capacity?"capacity":"flow"}(e),r=xs[i],c=Math.max(12,e.width-8),l=vs(c-8,22,88),u=Ms(e.label,Math.max(8,l-10),s),h="none"!==s&&c-8>=22,g=function(e){if(null!=e.capacity){const t=null!=e.queueDepth?" · q "+e.queueDepth:"";return e.capacityLabel?`${e.capacityLabel}${t}`:`cap ${Number.isInteger(e.capacity)?e.capacity+"":e.capacity.toFixed(1)}${t}`}return e.absorb?"absorb":e.portalTarget?"portal":"flow"}(e),x=Ms(g,Math.max(16,c-10),"auto"),v=o&&!1!==e.showBadge&&c>=32,w=null!=e.count?`n=${e.count}${null!=e.processed?" done "+e.processed:""}`:"",k=Ms(w,Math.max(16,c-8),"auto"),M=Math.max(30,p-15),S=M-13;return bs("g",{"data-stage":e.id,"data-role":i,children:[gs("rect",{className:"semiotic-process-chrome__stage-bay",x:e.x0+4,y:p+6,width:c,height:b-12,rx:10,fill:a?"none":r.fill,stroke:r.stroke,strokeWidth:a?1.85:"flow"===i?1:1.6}),f.length-1>t?gs("polygon",{points:`${e.x1-2},${y-7} ${e.x1+8},${y} ${e.x1-2},${y+7}`,fill:r.accent,opacity:.85}):null,h?bs(fs,{children:[gs("rect",{className:"semiotic-process-chrome__stage-label-bg",x:e.x-l/2,y:S,width:l,height:18,rx:9,fill:"var(--semiotic-bg, #0f172a)",fillOpacity:.75,stroke:r.stroke}),bs("text",{x:e.x,y:M,textAnchor:"middle",fill:r.accent,fontSize:10,fontWeight:800,className:"semiotic-process-chrome__stage-label",textLength:u.textLength,lengthAdjust:u.textLength?"spacingAndGlyphs":void 0,children:[gs("title",{children:e.label}),u.text]})]}):null,v?bs("text",{x:e.x,y:p+22,textAnchor:"middle",fill:"var(--semiotic-process-muted, var(--semiotic-text-secondary, #94a3b8))",fontSize:9,fontWeight:700,textLength:x.textLength,lengthAdjust:x.textLength?"spacingAndGlyphs":void 0,children:[gs("title",{children:g}),x.text]}):null,n&&null!=e.count?bs("text",{x:e.x,y:Math.min(d-8,m+16),textAnchor:"middle",fill:"var(--semiotic-process-text, var(--semiotic-text, #e2e8f0))",fontSize:11,fontWeight:800,textLength:k.textLength,lengthAdjust:k.textLength?"spacingAndGlyphs":void 0,children:[gs("title",{children:w}),k.text]}):null]},e.id)}),r?g.map((e,t)=>{const i=e.total??0,n=e.absorbed??0,o=e.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 "+(t+1),l=vs(Math.max(54,ws(e.label)+18,ws(c)+16),54,104),d=Ms(e.label,l-12,"auto"),u=Ms(c,l-12,"auto");return bs("g",{"data-group":e.id,children:[gs("rect",{x:e.x-l/2,y:e.y-22,width:l,height:44,rx:10,fill:s,stroke:a,strokeWidth:1.5}),bs("text",{x:e.x,y:e.y-4,textAnchor:"middle",fill:"var(--semiotic-process-text, var(--semiotic-text, #f8fafc))",fontSize:10,fontWeight:800,textLength:d.textLength,lengthAdjust:d.textLength?"spacingAndGlyphs":void 0,children:[gs("title",{children:e.label}),d.text]}),bs("text",{x:e.x,y:e.y+12,textAnchor:"middle",fill:a,fontSize:9,fontWeight:700,textLength:u.textLength,lengthAdjust:u.textLength?"spacingAndGlyphs":void 0,children:[gs("title",{children:c}),u.text]})]},e.id)}):null]})}import{forwardRef as Is,useCallback as As,useEffect as Ps,useMemo as Cs,useRef as Rs,useState as Bs}from"react";import{jsx as js}from"react/jsx-runtime";var Ts=Is(function(e,t){const{ballRadius:i=6,chromeOptions:n,colorBy:o,data:r,emptyContent:s,frameProps:a={},groupAnchorAlong:c,groupBy:l,groupCompletion:d,groupLabelAccessor:u,gravityX:h,gravityY:p,idAccessor:m,initialSpawnPacing:y,liveCapacity:f=!0,onCapacityChange:g,selection:b,bodyLimit:v,bodyMark:w,loading:k,loadingContent:M,paused:S,radiusAccessor:I,responsiveHeight:A,responsiveWidth:P,route:C="horizontal",seed:R=1,settle:B,springDamping:j,springStiffness:T,stageAccessor:N="stage",stages:O,workAccessor:E}=e,$=So(e,[900,420]),{chartSize:q,showProjection:W,showChrome:F,className:D,title:z,chartMode:Y,margin:L,enableHover:H,description:X,summary:_,accessibleTable:G}=$,V=Rs(null),U=Cs(()=>x(r??[]),[r]),K=Cs(()=>({data:U,stages:O,size:q,idAccessor:m,stageAccessor:N,groupBy:l,groupLabelAccessor:u,workAccessor:E,radiusAccessor:I,ballRadius:i,seed:R,route:C,groupCompletion:d,groupAnchorAlong:c,springStiffness:T,springDamping:j,gravityX:h,gravityY:p,settle:B}),[i,q,h,p,c,l,d,u,m,I,C,U,R,B,j,T,N,O,E]),Q=Cs(()=>ao(K),[K]),Z=Q.metadata;bo(t,{frameRef:V,spawnDatum:As((e,t)=>{const n=ao({...K,data:[e],seed:R+t+1,settle:!0}).initialSpawns[0]??{id:(e.id??"process-flow-push-"+t)+"",x:pn(q).plot.x,y:pn(q).plot.y,mass:1,shape:{type:"circle",radius:i},datum:e};return{datumId:(e.id??n.id)+"",spawns:[n]}},[i,K,q,R]),seedRows:U,seedSpawns:Q.initialSpawns});const J=Cs(()=>yn(o),[o]),ee=Cs(()=>{if(!f)return a.controllers;const e=[...O.filter(e=>e.capacity&&e.capacity.unitsPerSecond>0).map(e=>{const t=e.capacity.unitsPerSecond;return xt({id:"process-capacity-"+e.id,regionId:"process-stage-"+e.id,unitsPerSecond:t,unitAccessor:e.capacity.unitAccessor??(E?"string"==typeof E?E:e=>{const t=e.datum;if(!t)return 1;try{return Number(E(t,0))||1}catch{return 1}}:"work"),releaseImpulse:{x:70+Math.min(40,2*t),y:0},queueLayout:"lane",continuous:!0})}),...a.controllers??[]];return e.length?e:void 0},[a.controllers,f,O,E]),[te,ie]=Bs({}),ne=Rs(ee);ne.current=ee;const oe=Rs(a.onTick);oe.current=a.onTick;const re=!1!==F||null!=g;Ps(()=>{if(!g)return;const e=Object.values(te);e.length&&g(e)},[te,g]);const se=As((e,t)=>{if(oe.current?.(e,t),!re)return;const i=ne.current;if(!i?.length)return;const n={};for(const e of i){const t=e.getSnapshot?.();t&&"string"==typeof t.regionId&&(n[t.regionId]=t)}ie(e=>function(e,t){const i=Object.keys(e),n=Object.keys(t);if(i.length!==n.length)return!1;for(const n of i){const i=e[n],o=t[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}(e,n)?e:n)},[re]),ae=Cs(()=>{const e=J,t=a.bodyStyle;return w||t?(i,n)=>{const o="function"==typeof t?t(i,n):t;return{..."function"==typeof e?e(i):e,...o,mark:o?.mark??i.datum?.__physicsMark??i.datum?.mark??w}}:e},[w,J,a.bodyStyle]),ce=Io({data:r,emptyContent:s,loading:k,loadingContent:M,size:q});if(ce)return ce;if(!O?.length)return Ao("ProcessFlowChart",q,js("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 le=function(e,t,i={},n){if(!1===t||!e)return;const{volume:o,stages:r,groups:s,groupCompletion:a}=e,c=new Map(o.stages.map(e=>[e.id,e])),l=new Map(a.map(e=>[e.id,e]));return({size:e})=>{const t=Number(e[0])||o.width,a=Number(e[1])||o.height,d=r.map(e=>{const t=c.get(e.id),n=i["process-stage-"+e.id];return{id:e.id,label:e.label,x0:t?.x0??e.x-e.width/2,x1:(t?.x0??e.x-e.width/2)+(t?.width??e.width),x:e.x,width:t?.width??e.width,count:e.count,capacity:e.capacity,absorb:e.absorb,portalTarget:e.portalTarget,queueDepth:n?.queueDepth,processed:n?.processedCount}}),u=s.map(e=>{const t=l.get(e.id);return{id:e.id,label:e.label??e.id,x:e.anchor?.x??e.x??0,y:e.anchor?.y??e.y??0,absorbed:t?.absorbed,total:t?.total,complete:t?.complete}});return Ss({width:t,height:a,left:o.left,right:o.right,topY:o.topY,bottomY:o.bottomY,midY:o.midY,stages:d,groups:u},{showCapacityBadges:!0,showGroupSockets:!0,...n})}}(Z,F,te,n),de=function(e,t,i){if(!1===i||!t||0===e.length)return;const n=new Map(t.volume.stages.map(e=>[e.id,e]));return({size:i})=>{const o=[Number(i[0])||t.volume.width,Number(i[1])||t.volume.height],r=pn(o),s=Math.max(1,...e.map(e=>e.value)),a=Math.min(48,.18*r.plot.height),c=r.plot.y+6;return js("svg",{"aria-hidden":"true","data-testid":"process-flow-projection-overlay",width:o[0],height:o[1],viewBox:`0 0 ${o[0]} ${o[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:t.stages.map((t,i)=>{const o=e[i];if(!o)return null;const r=n.get(t.id);if(!r)return null;const l=Math.max(2,o.value/s*a),d=Math.max(8,.35*r.width);return js("rect",{x:r.x-d/2,y:c,width:d,height:l,rx:2,fill:"var(--semiotic-primary, #4e79a7)",fillOpacity:.18,stroke:"var(--semiotic-primary, #4e79a7)",strokeOpacity:.45,strokeWidth:1},t.id)})})}}(Q.projectionRows,Z,W),ue=[...gn(Q.projectionRows,q,"stage"),...rr(Z?.groups??[])],he=Co(e.tooltip,a),pe=Ro(e,a,ue,{chartMode:Y,className:D,title:z,description:X,summary:_,accessibleTable:G,enableHover:H,margin:L}),me=[...Z?.regionEffects??[],...a.regionEffects??[]];return Ao("ProcessFlowChart",q,js(un,{...a,...he,...pe,ref:V,controllers:ee,regionEffects:me,selection:b??a.selection,backgroundGraphics:Po(le,a.backgroundGraphics),foregroundGraphics:Po(de,a.foregroundGraphics),initialSpawns:Q.initialSpawns,initialSpawnPacing:y??Q.initialSpawnPacing,onTick:se,paused:S,responsiveHeight:A,responsiveWidth:P,size:q,bodyStyle:ae,config:{...Q.config,...null!=v?{bodyLimit:v,eviction:"oldest"}:{},...a.config}}))});Ts.displayName="ProcessFlowChart";import{forwardRef as Ns,useCallback as Os,useMemo as Es,useRef as $s}from"react";import{scaleLinear as qs}from"d3-scale";function Ws(e,t){const i=t.config??{},n=(t.sensors??[]).map(e=>({...e,sensor:!0})),o=[...t.colliders??[],...n],r=[...e.colliders??[],...i.colliders??[],...o];return{...e,...i,observation:{...e.observation,...i.observation},...r.length>0&&{colliders:r}}}function Fs(e){const t=function(e,t,i){const n=e?.observation;return{...e,observation:{...n,chartId:t??n?.chartId??"physics-custom",chartType:n?.chartType??"PhysicsCustomChart",onObservation:i??n?.onObservation}}}(e.config,e.chartId,e.onObservation),i=r(e.colorScheme,e.themeCategorical,C),n=pn(e.size),s={data:e.data,scales:{x:qs().domain(e.xExtent??[0,1]).range([n.plot.x,n.plot.x+n.plot.width]),y:qs().domain(e.yExtent??[0,1]).range([n.plot.y+n.plot.height,n.plot.y])},dimensions:n,theme:{semantic:e.semantic,categorical:[...i]},resolveColor:o(i,e.colorScheme),config:e.layoutConfig??{},world:new pt(t)},a=e.skipLayout?{}:e.layout(s)??{},c=function(e,t){if(!t?.length)return e;const i=new Map;for(const e of t){const{bodyId:t,...n}=e,o=i.get(t)??[];o.push(n),i.set(t,o)}return e.map(e=>{const t=i.get(e.id);return t?.length?{...e,springs:[...e.springs??[],...t]}:e})}([...a.initialSpawns??a.bodies??[]],a.constraints);return{config:Ws(t,a),context:s,initialSpawnPacing:a.initialSpawnPacing,initialSpawns:c,result:a}}import{jsx as Ds}from"react/jsx-runtime";var zs=Ns(function(e,t){const{chartId:i,color:n,colorBy:o,colorScheme:r,config:s,controllers:a,data:c,emptyContent:l,frameProps:d={},layout:u,layoutConfig:h,loading:p,loadingContent:m,onObservation:y,opacity:f,paused:g,spawnDatum:b,stroke:v,strokeWidth:w,title:k,xExtent:M,yExtent:S}=e,I=So(e,[700,380]),{chartSize:A,className:P,title:C,chartMode:R,margin:B,enableHover:j,description:T,summary:N,accessibleTable:O}=I,E=$s(null),F=$s(null),D=$s(""),z=Io({data:c,emptyContent:l,loading:p,loadingContent:m,size:A}),Y=null!=z,L=Es(()=>x(c??[]),[c]),H=W(e=>e.theme),X=Es(()=>q(H)??{},[H]),_=H?.colors?.categorical??$.colors.categorical,G=Es(()=>[A[0],A[1],L.length,L.map((e,t)=>(e.id??t)+"").join("|"),M?.join(",")??"",S?.join(",")??""].join("::"),[A,L,M,S]),V=Es(()=>Fs({chartId:i,colorScheme:r,config:s,data:L,layout:u,layoutConfig:h,onObservation:y,semantic:X,skipLayout:Y,size:A,themeCategorical:_,xExtent:M,yExtent:S}),[i,A,r,s,u,h,y,L,X,Y,_,M,S]);D.current===G&&null!=F.current||(D.current=G,F.current=V.initialSpawns);const U=F.current,K=Es(()=>{const e=[...V.result.controllers??[],...a??[],...d.controllers??[]];return e.length?e:void 0},[d.controllers,a,V.result.controllers]),Q=Es(()=>{const e=[...V.result.regionEffects??[],...d.regionEffects??[]];return e.length?e:void 0},[d.regionEffects,V.result.regionEffects]),Z=Os(e=>{const t=e.datum,i=t&&o?function(e,t,i){return"function"==typeof i?i(e,0):e[i]}(t,0,o)+"":e.id;return{fill:n??V.context.resolveColor(i,t),stroke:v??"#111827",strokeWidth:w??1,opacity:f??.9}},[n,o,f,V.context,v,w]);bo(t,{frameRef:E,spawnDatum:Os((e,t)=>{const n=e;if(b)return function(e,t,i){return Array.isArray(i)?{datumId:(e.id??i[0]?.id??"physics-custom-"+t)+"",spawns:i}:"spawns"in i?i:{datumId:(e.id??i.id??"physics-custom-"+t)+"",spawns:[i]}}(e,t,b(n,t,V.context));const o=Fs({chartId:i,colorScheme:r,config:s,data:[n],layout:u,layoutConfig:h,onObservation:y,semantic:X,size:A,themeCategorical:_,xExtent:M,yExtent:S}),a=o.initialSpawns.length?o.initialSpawns:[{id:(e.id??"physics-custom-"+t)+"",x:o.context.dimensions.plot.x+o.context.dimensions.plot.width/2,y:o.context.dimensions.plot.y+12,mass:1,shape:{type:"circle",radius:5},datum:e}];return{datumId:(e.id??a[0].id)+"",spawns:a}},[i,A,r,s,b,u,h,y,V.context,X,_,M,S]),seedRows:L,seedSpawns:U});const J=Os((e,t)=>{d.onBodyPointerDown?.(e,t)},[d]);if(z)return z;const ee=Co(e.tooltip,d),te=Ro(e,d,V.result.semanticItems,{chartMode:R,className:P,title:C??k,description:T,summary:N,accessibleTable:O,enableHover:j,margin:B});return Ao("PhysicsCustomChart",A,Ds(un,{...d,...ee,...te,ref:E,backgroundGraphics:Po(d.backgroundGraphics,V.result.backgroundOverlays),bodyForces:V.result.bodyForces??d.bodyForces,bodyStyle:V.result.bodyStyle??d.bodyStyle??Z,config:V.config,controllers:K,foregroundGraphics:Po(d.foregroundGraphics,V.result.overlays),initialSpawnPacing:V.initialSpawnPacing,initialSpawns:U,onBodyPointerDown:J,paused:g,regionEffects:Q,responsiveHeight:e.responsiveHeight,responsiveWidth:e.responsiveWidth,selectedBodyStyle:V.result.selectedBodyStyle??d.selectedBodyStyle,size:A}))});zs.displayName="PhysicsCustomChart";export{K as bodiesToAnnotationAnchors,Q as buildPhysicsAnnotationContext,Z as normalizePhysicsAnnotations,J as PhysicsSVGOverlay,ke as BuiltInPhysicsEngineAdapter,Me as createDefaultPhysicsEngineAdapter,Ne as PhysicsSedimentAccumulator,Oe as sedimentHeightfield,$e as evaluatePhysicsBodyBudget,Ke as collidersFromPlotBounds,Qe as collidersFromXScaleBins,pt as PhysicsPipelineStore,xt as createCapacityQueueController,kt as createServiceResourcePoolController,St as createServiceLevelController,It as createDependencyGateController,Pt as composePhysicsControllers,Ct as createPortalController,dn as StreamPhysicsFrame,un as StreamPhysicsFrame_default,Sn as buildGaltonBoardPhysics,Pn as buildEventDropPhysics,Rn as buildPhysicsPile,jn as buildCollisionSwarmPhysics,Wn as buildPhysicalFlowPhysics,Fn as aggregateRegionCounts,Dn as regionCountsToProjectionRows,zn as groupCompletionRows,Ln as stageTargetInVolume,Hn as processVolumePolygons,Gn as processStageLayout,Un as processStageRegions,Kn as membraneRegion,Qn as chargeGateRegion,Zn as routeSurfaceRegion,Jn as pressureFieldRegion,eo as capacitatedRegion,to as portalRegion,io as absorbRegion,no as forceFieldRegion,oo as bodyGroupSpec,ro as processLaneWalls,ao as buildProcessFlowPhysics,No as GaltonBoardChart,Do as EventDropChart,Go as PhysicsPileChart,tr as CollisionSwarmChart,ir as physicsProcessBoundaryColliders,nr as physicsProcessRegionSemanticItem,or as physicsProcessStageSemanticItems,rr as physicsProcessGroupSemanticItems,lr as planGauntletPropertyWork,dr as replaceGauntletNegative,Zr as GauntletChart,Jr as GuantletChart,ys as PhysicalFlowChart,Ss as processChrome,Ts as ProcessFlowChart,zs as PhysicsCustomChart};
|