semiotic 3.8.8 → 3.8.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/CLAUDE.md +5 -4
  2. package/README.md +44 -44
  3. package/ai/schema.json +263 -1
  4. package/ai/surface-manifest.json +1 -1
  5. package/ai/system-prompt.md +1 -1
  6. package/dist/chunk-chunk-2X3FJCME.module.min.js +1 -0
  7. package/dist/{chunk-chunk-UEZ6SHW5.module.min.js → chunk-chunk-2ZHHWZQM.module.min.js} +1 -1
  8. package/dist/chunk-chunk-5ZON5NMV.module.min.js +2 -0
  9. package/dist/{chunk-chunk-L6FFYGYS.module.min.js → chunk-chunk-6S3YGYW7.module.min.js} +1 -1
  10. package/dist/chunk-chunk-7C5EDZ3Z.module.min.js +2 -0
  11. package/dist/chunk-chunk-A3I4HBD5.module.min.js +1 -0
  12. package/dist/{chunk-chunk-4MLLQUGW.module.min.js → chunk-chunk-AFQHURLO.module.min.js} +1 -1
  13. package/dist/{chunk-chunk-OG3TTJGJ.module.min.js → chunk-chunk-DDB4TLQG.module.min.js} +1 -1
  14. package/dist/{chunk-chunk-W5HWGQMD.module.min.js → chunk-chunk-DTH3SUOU.module.min.js} +1 -1
  15. package/dist/{chunk-chunk-H5IFO6CU.module.min.js → chunk-chunk-DVCWU7MT.module.min.js} +1 -1
  16. package/dist/{chunk-chunk-JRHXQGEV.module.min.js → chunk-chunk-FSIHAW6L.module.min.js} +1 -1
  17. package/dist/{chunk-chunk-BWV55BZK.module.min.js → chunk-chunk-G2RGVEYY.module.min.js} +1 -1
  18. package/dist/chunk-chunk-HAJVODLO.module.min.js +2 -0
  19. package/dist/{chunk-chunk-BZNOAHJV.module.min.js → chunk-chunk-HIV7AW2V.module.min.js} +1 -1
  20. package/dist/{chunk-chunk-LJDH3WV3.module.min.js → chunk-chunk-JZAMMSQQ.module.min.js} +1 -1
  21. package/dist/{chunk-chunk-VUWYT7DY.module.min.js → chunk-chunk-MXMRXSCI.module.min.js} +1 -1
  22. package/dist/chunk-chunk-MXVBXFKW.module.min.js +2 -0
  23. package/dist/{chunk-chunk-7LE56WAE.module.min.js → chunk-chunk-OFAP623Y.module.min.js} +1 -1
  24. package/dist/{chunk-chunk-SFLUSZ73.module.min.js → chunk-chunk-OHLRAEQZ.module.min.js} +1 -1
  25. package/dist/{chunk-chunk-CD6PVVS3.module.min.js → chunk-chunk-PRNXOCYZ.module.min.js} +1 -1
  26. package/dist/chunk-chunk-RLKZVJMQ.module.min.js +2 -0
  27. package/dist/chunk-chunk-SK2TQMG4.module.min.js +2 -0
  28. package/dist/chunk-chunk-SKLYXNYW.module.min.js +2 -0
  29. package/dist/{chunk-chunk-57RBPDBQ.module.min.js → chunk-chunk-U4NZCU5T.module.min.js} +1 -1
  30. package/dist/{chunk-chunk-QQJNG23C.module.min.js → chunk-chunk-VKL6DI43.module.min.js} +1 -1
  31. package/dist/chunk-chunk-W62673ZE.module.min.js +1 -0
  32. package/dist/{chunk-chunk-WSDJFBKX.module.min.js → chunk-chunk-XCC25CZZ.module.min.js} +1 -1
  33. package/dist/{chunk-chunk-AF53TBSN.module.min.js → chunk-chunk-XECNOUZY.module.min.js} +1 -1
  34. package/dist/{chunk-chunk-FC3NZWYR.module.min.js → chunk-chunk-XYZDTYAF.module.min.js} +1 -1
  35. package/dist/components/Tooltip/Tooltip.d.ts +54 -1
  36. package/dist/components/charts/physics/chainReactionTypes.d.ts +1 -0
  37. package/dist/components/charts/physics/physicsHocUtils.d.ts +1 -1
  38. package/dist/components/charts/realtime/RealtimeHeatmap.d.ts +2 -0
  39. package/dist/components/charts/realtime/RealtimeHistogram.d.ts +2 -0
  40. package/dist/components/charts/realtime/RealtimeLineChart.d.ts +2 -0
  41. package/dist/components/charts/realtime/RealtimeSwarmChart.d.ts +2 -0
  42. package/dist/components/charts/realtime/RealtimeWaterfallChart.d.ts +2 -0
  43. package/dist/components/charts/shared/formatUtils.d.ts +40 -9
  44. package/dist/components/charts/shared/streamPropsHelpers.d.ts +1 -0
  45. package/dist/components/charts/shared/types.d.ts +8 -1
  46. package/dist/components/semiotic-utils-core.d.ts +1 -0
  47. package/dist/components/semiotic.d.ts +4 -3
  48. package/dist/components/stream/GeoTileRenderer.d.ts +1 -0
  49. package/dist/components/stream/canvasSetup.d.ts +15 -4
  50. package/dist/components/stream/geoTypes.d.ts +2 -0
  51. package/dist/components/stream/networkFramePaint.d.ts +8 -0
  52. package/dist/components/stream/networkTypes.d.ts +2 -0
  53. package/dist/components/stream/ordinalTypes.d.ts +2 -0
  54. package/dist/components/stream/physics/StreamPhysicsTypes.d.ts +2 -0
  55. package/dist/components/stream/pipelineConfig.d.ts +2 -0
  56. package/dist/components/stream/pipelineDomainResolution.d.ts +1 -1
  57. package/dist/components/stream/types.d.ts +8 -1
  58. package/dist/components/stream/useCanvasFrameHost.d.ts +9 -0
  59. package/dist/components/stream/xyFrameAxisTypes.d.ts +5 -0
  60. package/dist/geo.min.js +1 -1
  61. package/dist/geo.module.min.js +1 -1
  62. package/dist/network.min.js +1 -1
  63. package/dist/network.module.min.js +1 -1
  64. package/dist/ordinal.min.js +1 -1
  65. package/dist/ordinal.module.min.js +1 -1
  66. package/dist/physics.min.js +1 -1
  67. package/dist/physics.module.min.js +1 -1
  68. package/dist/realtime.min.js +1 -1
  69. package/dist/realtime.module.min.js +1 -1
  70. package/dist/semiotic-ai-core.min.js +1 -1
  71. package/dist/semiotic-ai-core.module.min.js +1 -1
  72. package/dist/semiotic-ai.min.js +1 -1
  73. package/dist/semiotic-ai.module.min.js +1 -1
  74. package/dist/semiotic-experimental.min.js +1 -1
  75. package/dist/semiotic-experimental.module.min.js +1 -1
  76. package/dist/semiotic-realtime-core.min.js +1 -1
  77. package/dist/semiotic-realtime-core.module.min.js +1 -1
  78. package/dist/semiotic-server-edge.min.js +1 -1
  79. package/dist/semiotic-server-edge.module.min.js +1 -1
  80. package/dist/semiotic-server-node.min.js +1 -1
  81. package/dist/semiotic-server-node.module.min.js +1 -1
  82. package/dist/semiotic-utils-core.d.ts +1 -0
  83. package/dist/semiotic-utils-core.min.js +1 -1
  84. package/dist/semiotic-utils-core.module.min.js +1 -1
  85. package/dist/semiotic-utils.min.js +1 -1
  86. package/dist/semiotic-utils.module.min.js +1 -1
  87. package/dist/semiotic.d.ts +4 -3
  88. package/dist/semiotic.min.js +1 -1
  89. package/dist/semiotic.module.min.js +1 -1
  90. package/dist/server.min.js +1 -1
  91. package/dist/server.module.min.js +1 -1
  92. package/dist/xy.min.js +1 -1
  93. package/dist/xy.module.min.js +1 -1
  94. package/package.json +1 -1
  95. package/dist/chunk-chunk-3GCILWPB.module.min.js +0 -2
  96. package/dist/chunk-chunk-46KRGJQP.module.min.js +0 -1
  97. package/dist/chunk-chunk-7T25U75Z.module.min.js +0 -2
  98. package/dist/chunk-chunk-BTZYH2IE.module.min.js +0 -1
  99. package/dist/chunk-chunk-FRGBMTZR.module.min.js +0 -1
  100. package/dist/chunk-chunk-HCNDE26Q.module.min.js +0 -2
  101. package/dist/chunk-chunk-JJ4BSUYL.module.min.js +0 -2
  102. package/dist/chunk-chunk-N3Q33XCB.module.min.js +0 -2
  103. package/dist/chunk-chunk-RGJ6TKAH.module.min.js +0 -2
  104. package/dist/chunk-chunk-WGROBM3I.module.min.js +0 -2
@@ -1 +1 @@
1
- import{resolveCSSColor as t}from"./chunk-chunk-IY7RYD4S.module.min.js";import{createStore as e}from"./chunk-chunk-HADHLMY5.module.min.js";var i=class{constructor(t){if(this._capacity=t,this.head=0,this._size=0,1>t)throw Error("RingBuffer capacity must be at least 1");this.buffer=Array(t)}push(t){let e;return this._size===this._capacity?e=this.buffer[this.head]:this._size++,this.buffer[this.head]=t,this.head=(this.head+1)%this._capacity,e}pushMany(t){const e=[];for(const i of t){const t=this.push(i);void 0!==t&&e.push(t)}return e}get(t){if(t>=0&&this._size>t)return this.buffer[(this.head-this._size+t+this._capacity)%this._capacity]}peek(){if(0!==this._size)return this.buffer[(this.head-1+this._capacity)%this._capacity]}peekOldest(){if(0!==this._size)return this.buffer[(this.head-this._size+this._capacity)%this._capacity]}[Symbol.iterator](){let t=0;return{next:()=>this._size>t?{done:!1,value:this.get(t++)}:{done:!0,value:void 0}}}forEach(t){const e=(this.head-this._size+this._capacity)%this._capacity;for(let i=0;this._size>i;i++)t(this.buffer[(e+i)%this._capacity],i)}toArray(){const t=Array(this._size),e=(this.head-this._size+this._capacity)%this._capacity;for(let i=0;this._size>i;i++)t[i]=this.buffer[(e+i)%this._capacity];return t}resize(t){if(1>t)throw Error("RingBuffer capacity must be at least 1");const e=this.toArray();let i=0,n=[];e.length>t&&(i=e.length-t,n=e.slice(0,i)),this._capacity=t,this.buffer=Array(t),this.head=0,this._size=0;for(let t=i;e.length>t;t++)this.push(e[t]);return n}update(t,e){const i=[],n=(this.head-this._size+this._capacity)%this._capacity;for(let r=0;this._size>r;r++){const a=(n+r)%this._capacity,o=this.buffer[a];if(t(o)){let t;t="object"!=typeof o||null===o?o:Array.isArray(o)?[...o]:{...o},i.push(t),this.buffer[a]=e(o)}}return i}remove(t){const e=[],i=[];if(this.forEach(n=>{t(n)?i.push(n):e.push(n)}),0===i.length)return i;this.buffer=Array(this._capacity),this.head=0,this._size=0;for(const t of e)this.push(t);return i}clear(){this.buffer=Array(this._capacity),this.head=0,this._size=0}get size(){return this._size}get capacity(){return this._capacity}get full(){return this._size===this._capacity}},n=class{constructor(){this._min=1/0,this._max=-1/0,this._dirty=!1}push(t){Number.isFinite(t)&&(this._min>t&&(this._min=t),t>this._max&&(this._max=t))}evict(t){t!==this._min&&t!==this._max||(this._dirty=!0)}recalculate(t,e){this._min=1/0,this._max=-1/0;for(const i of t){const t=e?e(i):i;Number.isFinite(t)&&(this._min>t&&(this._min=t),t>this._max&&(this._max=t))}this._dirty=!1}clear(){this._min=1/0,this._max=-1/0,this._dirty=!1}get extent(){return[this._min,this._max]}get min(){return this._min}get max(){return this._max}get dirty(){return this._dirty}};function r(t,e,i){return i.x>t||t>i.x+i.w||i.y>e||e>i.y+i.h?{hit:!1,cx:0,cy:0}:{hit:!0,cx:i.x+i.w/2,cy:i.y+i.h/2}}function a(t,e=30){return Math.max((t??4)+5,12,e)}function o(t){return t instanceof Date?t:"number"==typeof t&&t>1e9?new Date(t):null}function s(t,e){const i=o(t);if(!i)return!1;const n=o(e);return!n||i.getFullYear()!==n.getFullYear()||i.getMonth()!==n.getMonth()}function l(t){let e=t%(2*Math.PI);return 0>e&&(e+=2*Math.PI),e}function c(t){return{type:"hatch",background:t.background,stroke:t.stroke,lineWidth:t.lineWidth,spacing:t.spacing,angle:t.angle}}var u=null;function h(t={},e){const{background:i="transparent",stroke:n="#000",lineWidth:r=1.5,spacing:a=6,angle:o=45}=t,s={background:i,stroke:n,lineWidth:r,spacing:a,angle:o},l=Math.max(8,Math.ceil(2*a));let h;try{h=function(t){return"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(t,t):(u||(u=document.createElement("canvas")),u.width=t,u.height=t,u)}(l)}catch{return c(s)}const f=h.getContext("2d");if(!f)return c(s);i&&"transparent"!==i?(f.fillStyle=i,f.fillRect(0,0,l,l)):f.clearRect(0,0,l,l),f.strokeStyle=n,f.lineWidth=r,f.lineCap="square";const p=o*Math.PI/180;if(45===o||-45===o){const t=o>0?1:-1;for(let e=-l;2*l>=e;e+=a)f.beginPath(),f.moveTo(e,0),f.lineTo(e+t*l,l),f.stroke()}else{f.save(),f.translate(l/2,l/2),f.rotate(p);const t=2*l;for(let e=-t;t>=e;e+=a)f.beginPath(),f.moveTo(-t,e),f.lineTo(t,e),f.stroke();f.restore()}return(e||f).createPattern(h,"repeat")}import{jsx as f,jsxs as p}from"react/jsx-runtime";function d(t){return"object"==typeof t&&null!==t&&"hatch"===t.type}function y(t){return["hatch",t.background??"transparent",t.stroke??"#000",t.lineWidth??1.5,t.spacing??6,t.angle??45,t.lineOpacity??1].join("|")}function m(t,e){let i=2166136261;const n=y(e);for(let t=0;n.length>t;t++)i^=n.charCodeAt(t),i=Math.imul(i,16777619);return`${t}-hatch-${(i>>>0).toString(36)}`}var b=new Map;function g(e,i){const n=e.background??"transparent",r=e.stroke??"#000",a="transparent"===n||"none"===n?n:t(i,n)||n,o=t(i,r)||r||"#000",s="undefined"!=typeof window&&window.devicePixelRatio||1,l=`${y(e)}|${a}|${o}@${s}`,c=b.get(l);if(void 0!==c)return c;const u=h({background:a,stroke:o,lineWidth:e.lineWidth,spacing:e.spacing,angle:e.angle},i),f=d(u)?null:u;return b.set(l,f),f}function v(t,e){const{background:i="transparent",stroke:n="#000",lineWidth:r=1.5,spacing:a=6,angle:o=45,lineOpacity:s=1}=t,l=Math.max(8,Math.ceil(2*a));return p("pattern",{id:e,width:l,height:l,patternUnits:"userSpaceOnUse",patternTransform:0!==o?`rotate(${o})`:void 0,children:[i&&"transparent"!==i&&f("rect",{width:l,height:l,fill:i}),f("line",{x1:0,y1:0,x2:0,y2:l,stroke:n,strokeWidth:r,strokeOpacity:s}),f("line",{x1:a,y1:0,x2:a,y2:l,stroke:n,strokeWidth:r,strokeOpacity:s})]},e)}function x(t,e,i="#4e79a7"){if(d(t)){const i=m(e,t);return{fill:`url(#${i})`,def:v(t,i)}}return t&&"string"==typeof t?{fill:t}:{fill:i}}function _(t,e){return"touch"===e?Math.max(t,24):t}function k(t){return Array.isArray(t)?t[0]:t}function w(t,e,i,n){return{data:k(t),x:e,y:i,__semioticHoverData:!0,...n}}var A=["name","label","title"],N=["type","kind","category","group","class","status","role","shape"],z=["value","amount","total","count","weight","score"],S=new Set(["x","y","z","x0","x1","y0","y1","r","cx","cy","radius","layer","row","rowindex","col","column","depth","index","order","sankeywidth","coincidentpoints","sourcelinks","targetlinks","parent","children","fx","fy","vx","vy"]);function O(t,e){for(const i of e){const e=t.find(t=>t.lower===i);if(e)return e}}function W(t,e={}){if(!t||"object"!=typeof t)return{entries:[]};const i=e.maxEntries??6,n=!1!==e.skipPositional,r=[];for(const[e,i]of Object.entries(t)){if(e.startsWith("_"))continue;if("data"===e)continue;if(n&&S.has(e.toLowerCase()))continue;if(null==i)continue;const t=typeof i;("string"===t||"number"===t||"boolean"===t||i instanceof Date)&&r.push({key:e,lower:e.toLowerCase(),value:i})}if(0===r.length)return{entries:[]};let a=r.findIndex(t=>A.includes(t.lower));const o=a>=0;0>a&&(a=r.findIndex(t=>"id"===t.lower)),0>a&&(a=r.findIndex(t=>"string"==typeof t.value));const s=0>a?void 0:r[a];let l=r.filter((t,e)=>e!==a);o&&(l=l.filter(t=>"id"!==t.lower));const c=O(l,N),u=O(l,z),h=new Set(N),f=new Set(z),p=[];c&&p.push({key:c.key,value:c.value}),u&&p.push({key:u.key,value:u.value});for(const t of l){if(p.length>=i)break;t!==c&&t!==u&&(h.has(t.lower)||f.has(t.lower)||p.push({key:t.key,value:t.value}))}return{titleKey:s?.key,title:s?.value,entries:p}}import{jsx as j,jsxs as M}from"react/jsx-runtime";var I={background:"var(--semiotic-tooltip-bg, rgba(0, 0, 0, 0.85))",color:"var(--semiotic-tooltip-text, white)",padding:"8px 12px",borderRadius:"var(--semiotic-tooltip-radius, 6px)",fontSize:"var(--semiotic-tooltip-font-size, 14px)",fontFamily:"var(--semiotic-font-family, inherit)",lineHeight:"1.5",boxShadow:"var(--semiotic-tooltip-shadow, 0 2px 8px rgba(0, 0, 0, 0.15))",pointerEvents:"none",maxWidth:"300px",wordWrap:"break-word"};function C(t,e){return"function"==typeof e?e(t):t[e]}function E(t,e){if(e)return e(t);if(null==t)return"";if("number"==typeof t){if(!Number.isFinite(t))return t+"";const e=Number.isInteger(t)?t:parseFloat(t.toPrecision(6));return Math.abs(e)>9999?e.toLocaleString():e+""}return t instanceof Date?t.toLocaleDateString():"object"==typeof t&&null!==t?void 0!==t.id?t.id+"":void 0!==t.name?t.name+"":JSON.stringify(t):t+""}function D(t={}){const{fields:e,title:i,format:n,style:r={},className:a=""}=t;return t=>{if(!t||"object"!=typeof t)return null;let o;const s=[];if(i){const e=C(t,i);o=E(e,n)}if(e&&e.length>0)e.forEach(e=>{let i,r,a;"string"==typeof e?(i=e,r=e,a=n):(i=e.label,r=e.accessor||e.key||"",a=e.format||n);const o=C(t,r);s.push({label:i,value:E(o,a)})});else if(!i){const e=["value","y","name","id","label"];for(const i of e)if(void 0!==t[i]){o=E(t[i],n);break}if(!o){const e=Object.keys(t).filter(t=>!t.startsWith("_"));e.length>0&&(o=E(t[e[0]],n))}}const l={...I,...r};return M("div",{className:("semiotic-tooltip "+a).trim(),style:l,children:[o&&j("div",{style:{fontWeight:s.length>0?"bold":"normal"},children:o}),s.map((t,e)=>M("div",{style:{marginTop:0===e&&o?"4px":0},children:[t.label&&M("span",{children:[t.label,": "]}),t.value]},e))]})}}function R(){return t=>{const e=t.allSeries;if(!e||0===e.length)return j("div",{className:"semiotic-tooltip",style:I,children:j("div",{children:E(t.data?.value??t.data?.y)})});const i=t.xValue??t.data?.time??t.data?.x;return M("div",{className:"semiotic-tooltip",style:I,children:[null!=i&&j("div",{style:{fontWeight:600,marginBottom:4,fontSize:"0.9em",borderBottom:"1px solid var(--semiotic-border, #eee)",paddingBottom:4},children:E(i)}),e.map((t,e)=>M("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"1px 0"},children:[j("span",{style:{width:8,height:8,borderRadius:"50%",backgroundColor:t.color,flexShrink:0}}),j("span",{style:{flex:1,fontSize:"0.85em"},children:t.group}),j("span",{style:{fontWeight:500,fontSize:"0.85em"},children:E(t.value)})]},e))]})}}function T(t){if(!0!==t){if("function"==typeof t){const e=t;return t=>{const i=!0===t?.__semioticHoverData||t&&void 0!==t.data&&"number"==typeof t.x&&"number"==typeof t.y&&t&&("node"===t.type||"edge"===t.type||void 0!==t.nodeOrEdge||void 0!==t.allSeries||void 0!==t.stats||void 0!==t.__chartType);let n=k(i?t.data??{}:t);if(!n)return null;if(("node"===t?.nodeOrEdge&&"number"==typeof n?.x0&&"number"==typeof n?.x1||"edge"===t?.nodeOrEdge&&"number"==typeof n?.sankeyWidth)&&n.data&&"object"==typeof n.data&&(n=n.data),!n)return null;if(i&&(void 0!==t.allSeries||void 0!==t.xValue)){const e={...n};void 0!==t.allSeries&&void 0===e.allSeries&&(e.allSeries=t.allSeries),void 0!==t.xValue&&void 0===e.xValue&&(e.xValue=t.xValue),n=e}const r=e(n);return null==r?null:j("div",{className:"semiotic-tooltip",style:I,children:r})}}return!1!==t&&void 0!==t&&("object"==typeof t&&null!==t&&("fields"in t||"title"in t)?D(t):"multi"===t?("undefined"!=typeof process&&"production"!==process.env?.NODE_ENV&&console.warn('[semiotic] tooltip="multi" reached normalizeTooltip — prefer charts that set tooltipMode (LineChart, AreaChart, StackedAreaChart, DifferenceChart). Rendering MultiLineTooltip content as a fallback.'),function(t={}){const{fields:e=[],title:i,format:n,style:r={},className:a="",showLabels:o=!0,separator:s=": "}=t;return t=>{if(!t||"object"!=typeof t)return null;const l=[];if(i){const e=C(t,i);l.push({value:E(e,n)})}if(e&&Array.isArray(e)&&e.length>0)e.forEach(e=>{let i,r,a;"string"==typeof e?(i=e,r=e,a=n):(i=e.label,r=e.accessor||e.key||"",a=e.format||n);const s=E(C(t,r),a);l.push({label:o?i:void 0,value:s})});else{const e=W(t,{skipPositional:!1});null!=e.title&&l.push({label:void 0,value:E(e.title,n),bold:!0}),e.entries.forEach(t=>{l.push({label:o?t.key:void 0,value:E(t.value,n)})})}const c={...I,...r};return Array.isArray(l)&&0!==l.length?j("div",{className:("semiotic-tooltip semiotic-tooltip-multiline "+a).trim(),style:c,children:l.map((t,e)=>M("div",{style:{marginBottom:l.length-1>e?"4px":0,fontWeight:t.bold?"bold":void 0},children:[t.label&&M("strong",{children:[t.label,s]}),t.value]},e))}):null}}()):D())}}function P(t){return!!t&&"object"==typeof t&&!Array.isArray(t)}function F(t,e){const{when:i}=t,n=e.width,r=e.height,a=function(t){if("number"==typeof t.height&&t.height>0)return t.width/t.height}(e),o=function(t){if("number"==typeof t.height&&t.height>0)return t.height>t.width?"portrait":"landscape"}(e);return!("number"==typeof i.minWidth&&i.minWidth>n||"number"==typeof i.maxWidth&&n>i.maxWidth||"number"==typeof i.minHeight&&("number"!=typeof r||i.minHeight>r)||"number"==typeof i.maxHeight&&("number"!=typeof r||r>i.maxHeight)||"number"==typeof i.minAspectRatio&&("number"!=typeof a||i.minAspectRatio>a)||"number"==typeof i.maxAspectRatio&&("number"!=typeof a||a>i.maxAspectRatio)||i.orientation&&o!==i.orientation)}function $(t,e,i=t.responsiveRules){if(!Array.isArray(i)||0===i.length)return{props:t,matches:[]};const n=i.map((t,e)=>({rule:t,index:e})).filter(t=>F(t.rule,e)).sort((t,e)=>("number"==typeof t.rule.priority?t.rule.priority:t.index)-("number"==typeof e.rule.priority?e.rule.priority:e.index));return{props:n.reduce((t,e)=>function(t,e){const i={...t,...e};for(const n of["margin","frameProps","mobileSemantics","style"])P(t[n])&&P(e[n])&&(i[n]={...t[n],...e[n]});return"string"==typeof t.className&&"string"==typeof e.className&&(i.className=`${t.className} ${e.className}`),i}(t,e.rule.transform),t),matches:n}}var H=/^\d{4}-\d{1,2}$/;function L(t){const e=t.trim();if(!e||!Number.isNaN(Number(e)))return NaN;const i=H.test(e)?e+"-01":e;if(i===e&&10>e.length)return NaN;const n=Date.parse(i);return Number.isFinite(n)?n:NaN}function V(t){return t instanceof Date?t.getTime():"string"==typeof t?L(t):+t}import*as B from"react";var[Y,U]=e(t=>({observations:[],maxObservations:100,version:0,pushObservation(e){t(t=>{const i=t.observations;return i.push(e),i.length>t.maxObservations&&i.shift(),{version:t.version+1}})},clearObservations(){t(()=>({observations:[],version:0}))}}));function q(t){const e=U(t=>t.pushObservation),i=B.useCallback(i=>{t.onObservation?.(i),e?.(i)},[t,e]);return B.useMemo(()=>({...t,onObservation:i}),[i,t])}function J(t){const e=t.provenance,i=t.id??t.stableId??e?.stableId;return null==i||""===i?void 0:i+""}function K(t,e={}){const i=J(t);return{"data-semiotic-annotation-widget":"",...i?{"data-semiotic-annotation-id":i}:{},onClickCapture(n){const r=function(t){const e=t.nativeEvent;return"touch"===e.pointerType?"touch":0===e.detail?"keyboard":"pointer"}(n);e.onAnnotationActivate?.({annotation:t,annotationId:i,chartId:e.chartId,inputType:r}),i&&e.onObservation&&e.onObservation({type:"annotation-activate",annotationId:i,inputType:r,timestamp:Date.now(),chartType:e.chartType??"unknown",chartId:e.chartId})}}}function G(t){return t instanceof Element&&null!=t.closest("[data-semiotic-annotation-widget]")}function Q(t){const e={};if(null==t||"object"!=typeof t)return e;for(const[i,n]of Object.entries(t))i.startsWith("_")||null!=n&&""!==n&&("number"==typeof n?Number.isFinite(n)&&(e[i]=n):"string"==typeof n?e[i]=n:"boolean"==typeof n?e[i]=n+"":n instanceof Date&&(e[i]=n.toISOString().slice(0,10)));return e}function X(t){return t&&"object"==typeof t?t:{}}function Z(t){return X(t.accessibility).tableFields??t.accessibleDatum??t.datum}function tt(t){const e=[];if(!Array.isArray(t))return e;const i=t.some(t=>t&&("line"===t.type||"area"===t.type));for(const n of t)if(n&&"object"==typeof n&&null!==n.datum)try{switch(n.type){case"point":if(i)break;e.push({label:"Point",values:Q(Z(n))});break;case"line":case"area":{const t=Z(n),i=Array.isArray(t)?t:[],r="line"===n.type?"Line point":"Area point";for(const t of i)e.push({label:r,values:Q(t)});break}case"rect":{const t=Z(n),i=null!=t&&"object"==typeof t?t:{},r=i.category??n.group??"",a=i.value??i.__aggregateValue??i.total,o=Q(i);null==o.category&&""!==r&&(o.category=r+""),null==o.value&&null!=a&&(o.value="number"==typeof a||"string"==typeof a?a:a+""),e.push({label:"Bar",values:o});break}case"heatcell":{const t=Q(Z(n));null==t.value&&"number"==typeof n.value&&Number.isFinite(n.value)&&(t.value=n.value),e.push({label:"Cell",values:t});break}case"wedge":{const t=Z(n),i=Q(t);if(null==i.category){const e=X(t),n=e.category??e.label;null!=n&&(i.category=n+"")}e.push({label:"Wedge",values:i});break}case"circle":e.push({label:"Node",values:Q(Z(n))});break;case"arc":e.push({label:"Arc",values:Q(Z(n))});break;case"candlestick":e.push({label:"Candlestick",values:Q(Z(n))});break;case"geoarea":{const t=X(Z(n)),i=Q(t);if(null==i.name){const e=X(t.properties).name??t.name;null!=e&&(i.name=e+"")}e.push({label:"Region",values:i});break}}}catch{}return e}export{i as RingBuffer,n as IncrementalExtent,L as parseDateLikeString,V as coerceDateLikeValue,r as hitTestRect,a as getHitRadius,s as isTimeLandmark,l as normalizeAngle,h as createHatchPattern,d as isHatchFill,y as hatchFillKey,m as hatchFillId,g as resolveHatchCanvasPattern,v as hatchPatternDef,x as resolveSvgFill,U as useObservationSelector,q as useAnnotationActivationOptions,J as annotationStableId,K as annotationActivationProps,G as isAnnotationActivationTarget,tt as extractAllRows,_ as getPointerHitRadius,w as buildHoverData,W as smartTooltipEntries,I as defaultTooltipStyle,R as MultiPointTooltip,T as normalizeTooltip,F as responsiveRuleMatches,$ as resolveResponsiveRules};
1
+ import{resolveCSSColor as t}from"./chunk-chunk-IY7RYD4S.module.min.js";import{createStore as e}from"./chunk-chunk-HADHLMY5.module.min.js";var i=class{constructor(t){if(this._capacity=t,this.head=0,this._size=0,1>t)throw Error("RingBuffer capacity must be at least 1");this.buffer=Array(t)}push(t){let e;return this._size===this._capacity?e=this.buffer[this.head]:this._size++,this.buffer[this.head]=t,this.head=(this.head+1)%this._capacity,e}pushMany(t){const e=[];for(const i of t){const t=this.push(i);void 0!==t&&e.push(t)}return e}get(t){if(t>=0&&this._size>t)return this.buffer[(this.head-this._size+t+this._capacity)%this._capacity]}peek(){if(0!==this._size)return this.buffer[(this.head-1+this._capacity)%this._capacity]}peekOldest(){if(0!==this._size)return this.buffer[(this.head-this._size+this._capacity)%this._capacity]}[Symbol.iterator](){let t=0;return{next:()=>this._size>t?{done:!1,value:this.get(t++)}:{done:!0,value:void 0}}}forEach(t){const e=(this.head-this._size+this._capacity)%this._capacity;for(let i=0;this._size>i;i++)t(this.buffer[(e+i)%this._capacity],i)}toArray(){const t=Array(this._size),e=(this.head-this._size+this._capacity)%this._capacity;for(let i=0;this._size>i;i++)t[i]=this.buffer[(e+i)%this._capacity];return t}resize(t){if(1>t)throw Error("RingBuffer capacity must be at least 1");const e=this.toArray();let i=0,n=[];e.length>t&&(i=e.length-t,n=e.slice(0,i)),this._capacity=t,this.buffer=Array(t),this.head=0,this._size=0;for(let t=i;e.length>t;t++)this.push(e[t]);return n}update(t,e){const i=[],n=(this.head-this._size+this._capacity)%this._capacity;for(let r=0;this._size>r;r++){const a=(n+r)%this._capacity,o=this.buffer[a];if(t(o)){let t;t="object"!=typeof o||null===o?o:Array.isArray(o)?[...o]:{...o},i.push(t),this.buffer[a]=e(o)}}return i}remove(t){const e=[],i=[];if(this.forEach(n=>{t(n)?i.push(n):e.push(n)}),0===i.length)return i;this.buffer=Array(this._capacity),this.head=0,this._size=0;for(const t of e)this.push(t);return i}clear(){this.buffer=Array(this._capacity),this.head=0,this._size=0}get size(){return this._size}get capacity(){return this._capacity}get full(){return this._size===this._capacity}},n=class{constructor(){this._min=1/0,this._max=-1/0,this._dirty=!1}push(t){Number.isFinite(t)&&(this._min>t&&(this._min=t),t>this._max&&(this._max=t))}evict(t){t!==this._min&&t!==this._max||(this._dirty=!0)}recalculate(t,e){this._min=1/0,this._max=-1/0;for(const i of t){const t=e?e(i):i;Number.isFinite(t)&&(this._min>t&&(this._min=t),t>this._max&&(this._max=t))}this._dirty=!1}clear(){this._min=1/0,this._max=-1/0,this._dirty=!1}get extent(){return[this._min,this._max]}get min(){return this._min}get max(){return this._max}get dirty(){return this._dirty}};function r(t,e,i){return i.x>t||t>i.x+i.w||i.y>e||e>i.y+i.h?{hit:!1,cx:0,cy:0}:{hit:!0,cx:i.x+i.w/2,cy:i.y+i.h/2}}function a(t,e=30){return Math.max((t??4)+5,12,e)}function o(t){return t instanceof Date?t:"number"==typeof t&&t>1e9?new Date(t):null}function s(t,e){const i=o(t);if(!i)return!1;const n=o(e);return!n||i.getFullYear()!==n.getFullYear()||i.getMonth()!==n.getMonth()}function l(t){let e=t%(2*Math.PI);return 0>e&&(e+=2*Math.PI),e}function c(t){return{type:"hatch",background:t.background,stroke:t.stroke,lineWidth:t.lineWidth,spacing:t.spacing,angle:t.angle}}var u=null;function h(t={},e){const{background:i="transparent",stroke:n="#000",lineWidth:r=1.5,spacing:a=6,angle:o=45}=t,s={background:i,stroke:n,lineWidth:r,spacing:a,angle:o},l=Math.max(8,Math.ceil(2*a));let h;try{h=function(t){return"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(t,t):(u||(u=document.createElement("canvas")),u.width=t,u.height=t,u)}(l)}catch{return c(s)}const f=h.getContext("2d");if(!f)return c(s);i&&"transparent"!==i?(f.fillStyle=i,f.fillRect(0,0,l,l)):f.clearRect(0,0,l,l),f.strokeStyle=n,f.lineWidth=r,f.lineCap="square";const p=o*Math.PI/180;if(45===o||-45===o){const t=o>0?1:-1;for(let e=-l;2*l>=e;e+=a)f.beginPath(),f.moveTo(e,0),f.lineTo(e+t*l,l),f.stroke()}else{f.save(),f.translate(l/2,l/2),f.rotate(p);const t=2*l;for(let e=-t;t>=e;e+=a)f.beginPath(),f.moveTo(-t,e),f.lineTo(t,e),f.stroke();f.restore()}return(e||f).createPattern(h,"repeat")}import{jsx as f,jsxs as p}from"react/jsx-runtime";function d(t){return"object"==typeof t&&null!==t&&"hatch"===t.type}function y(t){return["hatch",t.background??"transparent",t.stroke??"#000",t.lineWidth??1.5,t.spacing??6,t.angle??45,t.lineOpacity??1].join("|")}function m(t,e){let i=2166136261;const n=y(e);for(let t=0;n.length>t;t++)i^=n.charCodeAt(t),i=Math.imul(i,16777619);return`${t}-hatch-${(i>>>0).toString(36)}`}var b=new Map;function g(e,i){const n=e.background??"transparent",r=e.stroke??"#000",a="transparent"===n||"none"===n?n:t(i,n)||n,o=t(i,r)||r||"#000",s="undefined"!=typeof window&&window.devicePixelRatio||1,l=`${y(e)}|${a}|${o}@${s}`,c=b.get(l);if(void 0!==c)return c;const u=h({background:a,stroke:o,lineWidth:e.lineWidth,spacing:e.spacing,angle:e.angle},i),f=d(u)?null:u;return b.set(l,f),f}function v(t,e){const{background:i="transparent",stroke:n="#000",lineWidth:r=1.5,spacing:a=6,angle:o=45,lineOpacity:s=1}=t,l=Math.max(8,Math.ceil(2*a));return p("pattern",{id:e,width:l,height:l,patternUnits:"userSpaceOnUse",patternTransform:0!==o?`rotate(${o})`:void 0,children:[i&&"transparent"!==i&&f("rect",{width:l,height:l,fill:i}),f("line",{x1:0,y1:0,x2:0,y2:l,stroke:n,strokeWidth:r,strokeOpacity:s}),f("line",{x1:a,y1:0,x2:a,y2:l,stroke:n,strokeWidth:r,strokeOpacity:s})]},e)}function x(t,e,i="#4e79a7"){if(d(t)){const i=m(e,t);return{fill:`url(#${i})`,def:v(t,i)}}return t&&"string"==typeof t?{fill:t}:{fill:i}}function _(t,e){return"touch"===e?Math.max(t,24):t}function k(t){return Array.isArray(t)?t[0]:t}function w(t,e,i,n){return{data:k(t),x:e,y:i,__semioticHoverData:!0,...n}}var A=["name","label","title"],N=["type","kind","category","group","class","status","role","shape"],z=["value","amount","total","count","weight","score"],S=new Set(["x","y","z","x0","x1","y0","y1","r","cx","cy","radius","layer","row","rowindex","col","column","depth","index","order","sankeywidth","coincidentpoints","sourcelinks","targetlinks","parent","children","fx","fy","vx","vy"]);function O(t,e){for(const i of e){const e=t.find(t=>t.lower===i);if(e)return e}}function W(t,e={}){if(!t||"object"!=typeof t)return{entries:[]};const i=e.maxEntries??6,n=!1!==e.skipPositional,r=[];for(const[e,i]of Object.entries(t)){if(e.startsWith("_"))continue;if("data"===e)continue;if(n&&S.has(e.toLowerCase()))continue;if(null==i)continue;const t=typeof i;("string"===t||"number"===t||"boolean"===t||i instanceof Date)&&r.push({key:e,lower:e.toLowerCase(),value:i})}if(0===r.length)return{entries:[]};let a=r.findIndex(t=>A.includes(t.lower));const o=a>=0;0>a&&(a=r.findIndex(t=>"id"===t.lower)),0>a&&(a=r.findIndex(t=>"string"==typeof t.value));const s=0>a?void 0:r[a];let l=r.filter((t,e)=>e!==a);o&&(l=l.filter(t=>"id"!==t.lower));const c=O(l,N),u=O(l,z),h=new Set(N),f=new Set(z),p=[];c&&p.push({key:c.key,value:c.value}),u&&p.push({key:u.key,value:u.value});for(const t of l){if(p.length>=i)break;t!==c&&t!==u&&(h.has(t.lower)||f.has(t.lower)||p.push({key:t.key,value:t.value}))}return{titleKey:s?.key,title:s?.value,entries:p}}import{jsx as j,jsxs as C}from"react/jsx-runtime";var M={background:"var(--semiotic-tooltip-bg, rgba(0, 0, 0, 0.85))",color:"var(--semiotic-tooltip-text, white)",padding:"8px 12px",borderRadius:"var(--semiotic-tooltip-radius, 6px)",fontSize:"var(--semiotic-tooltip-font-size, 14px)",fontFamily:"var(--semiotic-font-family, inherit)",lineHeight:"1.5",boxShadow:"var(--semiotic-tooltip-shadow, 0 2px 8px rgba(0, 0, 0, 0.15))",pointerEvents:"none",maxWidth:"300px",wordWrap:"break-word"};function E(t,e){return"function"==typeof e?e(t):t[e]}function D(t,e){if(e)return e(t);if(null==t)return"";if("number"==typeof t){if(!Number.isFinite(t))return t+"";const e=Number.isInteger(t)?t:parseFloat(t.toPrecision(6));return Math.abs(e)>9999?e.toLocaleString():e+""}return t instanceof Date?t.toLocaleDateString():"object"==typeof t&&null!==t?void 0!==t.id?t.id+"":void 0!==t.name?t.name+"":JSON.stringify(t):t+""}function I(t={}){const{fields:e,title:i,format:n,style:r={},className:a=""}=t;return t=>{if(!t||"object"!=typeof t)return null;let o;const s=[];if(i){const e=E(t,i);o=D(e,n)}if(e&&e.length>0)e.forEach(e=>{let i,r,a;"string"==typeof e?(i=e,r=e,a=n):(i=e.label,r=e.accessor||e.key||"",a=e.format||n);const o=E(t,r);s.push({label:i,value:D(o,a)})});else if(!i){const e=["value","y","name","id","label"];for(const i of e)if(void 0!==t[i]){o=D(t[i],n);break}if(!o){const e=Object.keys(t).filter(t=>!t.startsWith("_"));e.length>0&&(o=D(t[e[0]],n))}}const l={...M,...r};return C("div",{className:("semiotic-tooltip "+a).trim(),style:l,children:[o&&j("div",{style:{fontWeight:s.length>0?"bold":"normal"},children:o}),s.map((t,e)=>C("div",{style:{marginTop:0===e&&o?"4px":0},children:[t.label&&C("span",{children:[t.label,": "]}),t.value]},e))]})}}function T(){return t=>{const e=t.allSeries;if(!e||0===e.length)return j("div",{className:"semiotic-tooltip",style:M,children:j("div",{children:D(t.data?.value??t.data?.y)})});const i=t.xValue??t.data?.time??t.data?.x;return C("div",{className:"semiotic-tooltip",style:M,children:[null!=i&&j("div",{style:{fontWeight:600,marginBottom:4,fontSize:"0.9em",borderBottom:"1px solid var(--semiotic-border, #eee)",paddingBottom:4},children:D(i)}),e.map((t,e)=>C("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"1px 0"},children:[j("span",{style:{width:8,height:8,borderRadius:"50%",backgroundColor:t.color,flexShrink:0}}),j("span",{style:{flex:1,fontSize:"0.85em"},children:t.group}),j("span",{style:{fontWeight:500,fontSize:"0.85em"},children:D(t.value)})]},e))]})}}function R(t){if(!0!==t){if("function"==typeof t){const e=t;return t=>{const i=!0===t?.__semioticHoverData||t&&void 0!==t.data&&"number"==typeof t.x&&"number"==typeof t.y&&t&&("node"===t.type||"edge"===t.type||void 0!==t.nodeOrEdge||void 0!==t.allSeries||void 0!==t.stats||void 0!==t.__chartType);let n=k(i?t.data??{}:t);if(!n)return null;if(("node"===t?.nodeOrEdge&&"number"==typeof n?.x0&&"number"==typeof n?.x1||"edge"===t?.nodeOrEdge&&"number"==typeof n?.sankeyWidth)&&n.data&&"object"==typeof n.data&&(n=n.data),!n)return null;if(i&&(void 0!==t.allSeries||void 0!==t.xValue)){const e={...n};void 0!==t.allSeries&&void 0===e.allSeries&&(e.allSeries=t.allSeries),void 0!==t.xValue&&void 0===e.xValue&&(e.xValue=t.xValue),n=e}const r=e(n);return null==r?null:j("div",{className:"semiotic-tooltip",style:M,children:r})}}return!1!==t&&void 0!==t&&(function(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)&&"mode"in t&&"multi"===t.mode}(t)?"function"==typeof t.content?R(t.content):("undefined"!=typeof process&&"production"!==process.env?.NODE_ENV&&console.warn('[semiotic] tooltip={{ mode: "multi" }} reached normalizeTooltip without a chart that wires tooltipMode. Prefer LineChart/AreaChart/StackedAreaChart/DifferenceChart, or pass frameProps.tooltipMode: "multi".'),T()):"object"==typeof t&&null!==t&&("fields"in t||"title"in t)?I(t):"multi"===t?("undefined"!=typeof process&&"production"!==process.env?.NODE_ENV&&console.warn('[semiotic] tooltip="multi" reached normalizeTooltip — prefer charts that set tooltipMode (LineChart, AreaChart, StackedAreaChart, DifferenceChart). Rendering MultiLineTooltip content as a fallback.'),function(t={}){const{fields:e=[],title:i,format:n,style:r={},className:a="",showLabels:o=!0,separator:s=": "}=t;return t=>{if(!t||"object"!=typeof t)return null;const l=[];if(i){const e=E(t,i);l.push({value:D(e,n)})}if(e&&Array.isArray(e)&&e.length>0)e.forEach(e=>{let i,r,a;"string"==typeof e?(i=e,r=e,a=n):(i=e.label,r=e.accessor||e.key||"",a=e.format||n);const s=D(E(t,r),a);l.push({label:o?i:void 0,value:s})});else{const e=W(t,{skipPositional:!1});null!=e.title&&l.push({label:void 0,value:D(e.title,n),bold:!0}),e.entries.forEach(t=>{l.push({label:o?t.key:void 0,value:D(t.value,n)})})}const c={...M,...r};return Array.isArray(l)&&0!==l.length?j("div",{className:("semiotic-tooltip semiotic-tooltip-multiline "+a).trim(),style:c,children:l.map((t,e)=>C("div",{style:{marginBottom:l.length-1>e?"4px":0,fontWeight:t.bold?"bold":void 0},children:[t.label&&C("strong",{children:[t.label,s]}),t.value]},e))}):null}}()):I())}}function P(t){return!!t&&"object"==typeof t&&!Array.isArray(t)}function F(t,e){const{when:i}=t,n=e.width,r=e.height,a=function(t){if("number"==typeof t.height&&t.height>0)return t.width/t.height}(e),o=function(t){if("number"==typeof t.height&&t.height>0)return t.height>t.width?"portrait":"landscape"}(e);return!("number"==typeof i.minWidth&&i.minWidth>n||"number"==typeof i.maxWidth&&n>i.maxWidth||"number"==typeof i.minHeight&&("number"!=typeof r||i.minHeight>r)||"number"==typeof i.maxHeight&&("number"!=typeof r||r>i.maxHeight)||"number"==typeof i.minAspectRatio&&("number"!=typeof a||i.minAspectRatio>a)||"number"==typeof i.maxAspectRatio&&("number"!=typeof a||a>i.maxAspectRatio)||i.orientation&&o!==i.orientation)}function $(t,e,i=t.responsiveRules){if(!Array.isArray(i)||0===i.length)return{props:t,matches:[]};const n=i.map((t,e)=>({rule:t,index:e})).filter(t=>F(t.rule,e)).sort((t,e)=>("number"==typeof t.rule.priority?t.rule.priority:t.index)-("number"==typeof e.rule.priority?e.rule.priority:e.index));return{props:n.reduce((t,e)=>function(t,e){const i={...t,...e};for(const n of["margin","frameProps","mobileSemantics","style"])P(t[n])&&P(e[n])&&(i[n]={...t[n],...e[n]});return"string"==typeof t.className&&"string"==typeof e.className&&(i.className=`${t.className} ${e.className}`),i}(t,e.rule.transform),t),matches:n}}var L=/^\d{4}-\d{1,2}$/;function H(t){const e=t.trim();if(!e||!Number.isNaN(Number(e)))return NaN;const i=L.test(e)?e+"-01":e;if(i===e&&10>e.length)return NaN;const n=Date.parse(i);return Number.isFinite(n)?n:NaN}function V(t){return t instanceof Date?t.getTime():"string"==typeof t?H(t):+t}import*as B from"react";var[Y,U]=e(t=>({observations:[],maxObservations:100,version:0,pushObservation(e){t(t=>{const i=t.observations;return i.push(e),i.length>t.maxObservations&&i.shift(),{version:t.version+1}})},clearObservations(){t(()=>({observations:[],version:0}))}}));function q(t){const e=U(t=>t.pushObservation),i=B.useCallback(i=>{t.onObservation?.(i),e?.(i)},[t,e]);return B.useMemo(()=>({...t,onObservation:i}),[i,t])}function J(t){const e=t.provenance,i=t.id??t.stableId??e?.stableId;return null==i||""===i?void 0:i+""}function K(t,e={}){const i=J(t);return{"data-semiotic-annotation-widget":"",...i?{"data-semiotic-annotation-id":i}:{},onClickCapture(n){const r=function(t){const e=t.nativeEvent;return"touch"===e.pointerType?"touch":0===e.detail?"keyboard":"pointer"}(n);e.onAnnotationActivate?.({annotation:t,annotationId:i,chartId:e.chartId,inputType:r}),i&&e.onObservation&&e.onObservation({type:"annotation-activate",annotationId:i,inputType:r,timestamp:Date.now(),chartType:e.chartType??"unknown",chartId:e.chartId})}}}function G(t){return t instanceof Element&&null!=t.closest("[data-semiotic-annotation-widget]")}function Q(t){const e={};if(null==t||"object"!=typeof t)return e;for(const[i,n]of Object.entries(t))i.startsWith("_")||null!=n&&""!==n&&("number"==typeof n?Number.isFinite(n)&&(e[i]=n):"string"==typeof n?e[i]=n:"boolean"==typeof n?e[i]=n+"":n instanceof Date&&(e[i]=n.toISOString().slice(0,10)));return e}function X(t){return t&&"object"==typeof t?t:{}}function Z(t){return X(t.accessibility).tableFields??t.accessibleDatum??t.datum}function tt(t){const e=[];if(!Array.isArray(t))return e;const i=t.some(t=>t&&("line"===t.type||"area"===t.type));for(const n of t)if(n&&"object"==typeof n&&null!==n.datum)try{switch(n.type){case"point":if(i)break;e.push({label:"Point",values:Q(Z(n))});break;case"line":case"area":{const t=Z(n),i=Array.isArray(t)?t:[],r="line"===n.type?"Line point":"Area point";for(const t of i)e.push({label:r,values:Q(t)});break}case"rect":{const t=Z(n),i=null!=t&&"object"==typeof t?t:{},r=i.category??n.group??"",a=i.value??i.__aggregateValue??i.total,o=Q(i);null==o.category&&""!==r&&(o.category=r+""),null==o.value&&null!=a&&(o.value="number"==typeof a||"string"==typeof a?a:a+""),e.push({label:"Bar",values:o});break}case"heatcell":{const t=Q(Z(n));null==t.value&&"number"==typeof n.value&&Number.isFinite(n.value)&&(t.value=n.value),e.push({label:"Cell",values:t});break}case"wedge":{const t=Z(n),i=Q(t);if(null==i.category){const e=X(t),n=e.category??e.label;null!=n&&(i.category=n+"")}e.push({label:"Wedge",values:i});break}case"circle":e.push({label:"Node",values:Q(Z(n))});break;case"arc":e.push({label:"Arc",values:Q(Z(n))});break;case"candlestick":e.push({label:"Candlestick",values:Q(Z(n))});break;case"geoarea":{const t=X(Z(n)),i=Q(t);if(null==i.name){const e=X(t.properties).name??t.name;null!=e&&(i.name=e+"")}e.push({label:"Region",values:i});break}}}catch{}return e}export{i as RingBuffer,n as IncrementalExtent,H as parseDateLikeString,V as coerceDateLikeValue,r as hitTestRect,a as getHitRadius,s as isTimeLandmark,l as normalizeAngle,h as createHatchPattern,d as isHatchFill,y as hatchFillKey,m as hatchFillId,g as resolveHatchCanvasPattern,v as hatchPatternDef,x as resolveSvgFill,U as useObservationSelector,q as useAnnotationActivationOptions,J as annotationStableId,K as annotationActivationProps,G as isAnnotationActivationTarget,tt as extractAllRows,_ as getPointerHitRadius,w as buildHoverData,W as smartTooltipEntries,M as defaultTooltipStyle,T as MultiPointTooltip,R as normalizeTooltip,F as responsiveRuleMatches,$ as resolveResponsiveRules};
@@ -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 n}from"./chunk-chunk-EMO5NUGE.module.min.js";import{commonJsWorkerModuleUrl as i}from"./chunk-chunk-SV4XAZ3Q.module.min.js";import{buildResolveColor as o,resolveCustomLayoutPalette as r}from"./chunk-chunk-OHLRAEQZ.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 f,coerceCanvasFill as y,createDefaultAnnotationRules as g,defaultTooltipStyle as b,filterSparseArray as v,getDevicePixelRatio as x,isInteractiveKeyboardTarget as w,isServerEnvironment as S,normalizeTooltip as k,prepareCanvas as M,renderAnnotationPass as I,renderLegendFromConfig as A,resolveCSSColor as B,schemeCategory10 as R,useAnnotationActivationOptions as C,useChartMode as P,useChartSelection as T,useDataSummary as q,useFrame as O,useFrameCanvasHost as E,useSceneRevisionDiagnostics as F,xySceneNodeToSVG as D}from"./chunk-chunk-SK2TQMG4.module.min.js";import{LIGHT_THEME as j,resolveThemeSemanticColors as N,useThemeSelector as z}from"./chunk-chunk-PMR47KRY.module.min.js";import{SafeRender as W,renderEmptyState as $,renderLoadingState as L,useHydration as H,useWasHydratingFromSSR as Y}from"./chunk-chunk-ACLDBMRH.module.min.js";var X={annotationBackground:"rgba(248, 250, 252, 0.94)",annotationStroke:"#334155",annotationText:"#0f172a",background:"#f8fafc",border:"#334155",closedWindowFill:"rgba(220, 38, 38, 0.08)",closedWindowStroke:"rgba(220, 38, 38, 0.55)",danger:"#dc2626",focus:"#f97316",grid:"#cbd5e1",gutterFill:"rgba(71, 85, 105, 0.14)",lateFill:"#f97316",openWindowFill:"rgba(14, 165, 233, 0.07)",openWindowStroke:"rgba(14, 165, 233, 0.3)",primary:"#0ea5e9",selectedFill:"#f97316",selectedStroke:"#7c2d12",success:"#22c55e",text:"#0f172a",textSecondary:"#475569",warning:"#f97316"},V={background:{names:["--semiotic-bg","--surface-1","--surface-0"],fallback:"#f8fafc"},border:{names:["--semiotic-border","--surface-3"],fallback:X.border},danger:{names:["--semiotic-danger","--viz-4"],fallback:X.danger},focus:{names:["--semiotic-focus","--accent","--viz-9"],fallback:X.focus},grid:{names:["--semiotic-grid","--surface-3"],fallback:X.grid},primary:{names:["--semiotic-primary","--accent","--viz-5"],fallback:"#0ea5e9"},success:{names:["--semiotic-success","--viz-2"],fallback:"#22c55e"},text:{names:["--semiotic-text","--text-primary"],fallback:X.text},textSecondary:{names:["--semiotic-text-secondary","--text-secondary"],fallback:"#475569"},warning:{names:["--semiotic-warning","--viz-9","--viz-3"],fallback:"#f97316"}};function _(e,t){const n=e.canvas;if("function"!=typeof getComputedStyle||!n)return t.fallback;const i=getComputedStyle(n);for(const n of t.names){const t=i.getPropertyValue(n).trim();if(t)return B(e,t)??t}return t.fallback}function K(e,t){const n=Math.max(0,Math.min(1,t)),i=e.trim(),o=i.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);if(o){const[,e,t,i]=o;return K(`#${e}${e}${t}${t}${i}${i}`,n)}const r=i.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(r){const[,e,t,i]=r;return`rgba(${parseInt(e,16)}, ${parseInt(t,16)}, ${parseInt(i,16)}, ${n})`}const s=i.match(/^rgb\s*\(\s*([^)]+?)\s*\)$/i);if(s)return`rgba(${s[1]}, ${n})`;const a=i.match(/^rgba\s*\(\s*([^,]+,\s*[^,]+,\s*[^,]+),\s*[^)]+\)$/i);return a?`rgba(${a[1]}, ${n})`:i}function G(e){const t=_(e,V.primary),n=_(e,V.danger),i=_(e,V.warning),o=_(e,V.success),r=_(e,V.border),s=_(e,V.background),a=_(e,V.text),c=_(e,V.textSecondary),l=_(e,V.focus),d=_(e,V.grid);return{annotationBackground:K(s,.94),annotationStroke:r,annotationText:a,background:s,border:r,closedWindowFill:K(n,.08),closedWindowStroke:K(n,.55),danger:n,focus:l,grid:d,gutterFill:K(c,.14),lateFill:i,openWindowFill:K(t,.07),openWindowStroke:K(t,.3),primary:t,selectedFill:i,selectedStroke:l,success:o,text:a,textSecondary:c,warning:i}}import*as U from"react";import{scaleLinear as Q}from"d3-scale";import{Fragment as Z,jsx as J,jsxs as ee}from"react/jsx-runtime";function te(e){return"circle"===e.shape.type?e.shape.radius:Math.max(e.shape.width,e.shape.height)/2}function ne(e){return e.map(e=>({pointId:e.id,x:e.x,y:e.y,r:Math.max(1,te(e))}))}function ie(e){const{width:t,height:n,pointNodes:i=[],data:o}=e;return{scales:{x:Q().domain([0,Math.max(1,t)]).range([0,Math.max(1,t)]),y:Q().domain([0,Math.max(1,n)]).range([0,Math.max(1,n)])},width:t,height:n,frameType:"network",pointNodes:i,data:o,xAccessor:"x",yAccessor:"y"}}function oe(e){return e?.length?e.map(e=>null!=e.pointId||null==e.bodyId?e:{...e,pointId:e.bodyId+""}):e}function re(e){const{width:t,height:n,totalWidth:i,totalHeight:o,margin:r,title:a,legend:c,legendHoverBehavior:l,legendClickBehavior:d,legendHighlightedCategory:u,legendIsolatedCategories:h,legendPosition:p="right",legendLayout:m,pointNodes:y=[],annotations:b,onAnnotationActivate:v,onObservation:x,chartId:w,chartType:S,autoPlaceAnnotations:k,svgAnnotationRules:M,children:B}=e,R=C({onAnnotationActivate:v,onObservation:x,chartId:w,chartType:S}),P=U.useMemo(()=>oe(b),[b]),T=U.useMemo(()=>ie({width:t,height:n,pointNodes:y}),[n,y,t]),q=U.useMemo(()=>P&&k?f({annotations:P,context:T,..."object"==typeof k?k:{}}):P,[T,k,P]),O=U.useMemo(()=>g("network",R),[R]),E=q?I(q,O,M,T):null,F=!0===q?.some(e=>"widget"===e.type&&!0===e._annotationDeferred);return ee(Z,{children:[F?J("style",{children:s},"physics-annotation-disclosure-style"):null,ee("svg",{className:"stream-physics-frame__overlay","data-testid":"stream-physics-overlay",role:"presentation",width:i,height:o,style:{position:"absolute",top:0,left:0,pointerEvents:"none",overflow:"visible"},children:[ee("g",{transform:`translate(${r.left},${r.top})`,children:[E,B]}),a&&"string"==typeof a?J("text",{x:i/2,y:16,textAnchor:"middle",fontWeight:600,fill:"var(--semiotic-text, #333)",fontSize:14,className:"semiotic-chart-title",style:{fontSize:"var(--semiotic-title-font-size, 14px)"},children:a}):a?J("foreignObject",{x:0,y:0,width:i,height:Math.max(r.top,28),children:a}):null,c?A({legend:c,totalWidth:i,totalHeight:o,margin:r,legendPosition:p,legendLayout:m,title:a,legendHoverBehavior:l,legendClickBehavior:d,legendHighlightedCategory:u,legendIsolatedCategories:h}):null]})]})}var se={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},ae=1e-9,ce=.005;function le(e){return"circle"===e.type?{type:"circle",radius:e.radius}:{type:"aabb",width:e.width,height:e.height}}function de(e){return"aabb"===e.type?{type:"aabb",x:e.x,y:e.y,width:e.width,height:e.height}:{type:"segment",x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2,thickness:e.thickness}}function ue(e,t,n){return Math.max(t,Math.min(n,e))}function he(e,t,n){return Math.min(e??n,t??n)}function pe(e,t,n){return ue(Math.max(e??n,t??n),0,1)}function me(e){return 0>e?-1:1}function fe(e){if("circle"===e.shape.type){const t=e.shape.radius;return{minX:e.x-t,minY:e.y-t,maxX:e.x+t,maxY:e.y+t}}const t=e.shape.width/2,n=e.shape.height/2;return{minX:e.x-t,minY:e.y-n,maxX:e.x+t,maxY:e.y+n}}function ye(e){const t=e.shape;if("aabb"===t.type){const e=t.width/2,n=t.height/2;return{minX:t.x-e,minY:t.y-n,maxX:t.x+e,maxY:t.y+n}}const n=(t.thickness??0)/2;return{minX:Math.min(t.x1,t.x2)-n,minY:Math.min(t.y1,t.y2)-n,maxX:Math.max(t.x1,t.x2)+n,maxY:Math.max(t.y1,t.y2)+n}}function ge(e,t){return!(e.minX>t.maxX||t.minX>e.maxX||e.minY>t.maxY||t.minY>e.maxY)}function be(e,t,n,i,o,r,s,a){const c=o-e,l=(n+s)/2-Math.abs(c);if(0>=l)return null;const d=r-t,u=(i+a)/2-Math.abs(d);return u>0?u>l?{nx:me(c),ny:0,penetration:l}:{nx:0,ny:me(d),penetration:u}:null}function ve(e,t,n,i,o,r,s){const a=r/2,c=s/2,l=e-ue(e,i-a,i+a),d=t-ue(t,o-c,o+c),u=l*l+d*d;if(u>n*n)return null;if(ae>=u){const r=Math.abs(e-(i-a)),s=Math.abs(e-(i+a)),l=Math.abs(t-(o-c)),d=Math.abs(t-(o+c)),u=Math.min(r,s,l,d);return u===r?{nx:-1,ny:0,penetration:n+r}:u===s?{nx:1,ny:0,penetration:n+s}:u===l?{nx:0,ny:-1,penetration:n+l}:{nx:0,ny:1,penetration:n+d}}const h=Math.sqrt(u);return{nx:l/h,ny:d/h,penetration:n-h}}function xe(e,t){if("circle"===e.shape.type&&"circle"===t.shape.type)return function(e,t,n,i,o,r){const s=i-e,a=o-t,c=n+r,l=s*s+a*a;if(l>=c*c)return null;if(ae>=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 be(e.x,e.y,e.shape.width,e.shape.height,t.x,t.y,t.shape.width,t.shape.height);if("circle"===e.shape.type&&"aabb"===t.shape.type){const n=ve(e.x,e.y,e.shape.radius,t.x,t.y,t.shape.width,t.shape.height);return n?{nx:-n.nx,ny:-n.ny,penetration:n.penetration}:null}return"aabb"===e.shape.type&&"circle"===t.shape.type?ve(t.x,t.y,t.shape.radius,e.x,e.y,e.shape.width,e.shape.height):null}function we(e,t){const n=t.shape;return"aabb"===n.type?"circle"===e.shape.type?ve(e.x,e.y,e.shape.radius,n.x,n.y,n.width,n.height):be(n.x,n.y,n.width,n.height,e.x,e.y,e.shape.width,e.shape.height):function(e,t,n,i,o,r,s,a=0){const c=r-i,l=s-o,d=c*c+l*l,u=d>ae?ue(((e-i)*c+(t-o)*l)/d,0,1):0,h=n+a/2,p=e-(i+c*u),m=t-(o+l*u),f=p*p+m*m;if(f>=h*h)return null;if(ae>=f){const e=Math.sqrt(d);return e>ae?{nx:-l/e,ny:c/e,penetration:h}:{nx:1,ny:0,penetration:h}}const y=Math.sqrt(f);return{nx:p/y,ny:m/y,penetration:h-y}}(e.x,e.y,"circle"===e.shape.type?e.shape.radius:Math.sqrt(e.shape.width*e.shape.width+e.shape.height*e.shape.height)/2,n.x1,n.y1,n.x2,n.y2,n.thickness??0)}function Se(e,t){return`${e}\0${t}`}function ke(e){const t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}function Me(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:le(e.shape),sleeping:e.sleeping,datum:e.datum,index:e.index,sleepTime:e.sleepTime,restitution:e.restitution,friction:e.friction}}function Ie(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 Ae(e){return{id:e.id,shape:de(e.shape),sensor:e.sensor,restitution:e.restitution,friction:e.friction,bodyFilter:Ie(e.bodyFilter),index:e.index}}function Be(e,t){if(!t)return;let n=e;for(const e of t.split(".")){if(null==n||"object"!=typeof n)return;n=n[e]}return n}function Re(e,t){return!!t?.some(t=>Object.is(e,t))}function Ce(e,t){if(!t)return!0;if("function"==typeof t)return t(e);const n=Be(e,t.property);return!("equals"in t&&!Object.is(n,t.equals)||"notEquals"in t&&Object.is(n,t.notEquals)||t.oneOf&&!Re(n,t.oneOf)||t.notOneOf&&Re(n,t.notOneOf))}function Pe(e,t){return Ce(t,e.bodyFilter)}var Te=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={...se,...t},this.random=e(this.options.seed)}init(t={}){this.options={...se,...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(ae,e.mass??1),bodyCollisions:e.bodyCollisions??!0,shape:le(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))ke(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:de(t.shape),bodyFilter:Ie(t.bodyFilter),index:this.nextColliderIndex}),this.nextColliderIndex+=1}setConstraint(e){const t=e.id??"spring-"+this.nextSpringIndex;return this.springs.set(t,{id:t,bodyId:e.bodyId,target:e.target,restLength:e.restLength??0,stiffness:e.stiffness??40,damping:e.damping??3}),this.nextSpringIndex+=1,t}removeConstraint(e){this.springs.delete(e)}applyImpulse(e,t,n){const i=this.bodies.get(e);i&&(i.vx+=t/i.mass,i.vy+=n/i.mass,this.wake(i))}step(e=this.options.fixedDt){const t=Math.max(0,e);if(this.lastEvents=[],0===t)return;const n=this.sortedBodies();for(const e of n)e.prevX=e.x,e.prevY=e.y;this.applySprings(t);const i=this.options.maxVelocity;for(const e of n)if(!e.sleeping){if(e.vx+=this.options.gravity.x*t,e.vy+=this.options.gravity.y*t,e.vx*=this.options.velocityDamping,e.vy*=this.options.velocityDamping,i>0){const t=Math.sqrt(e.vx*e.vx+e.vy*e.vy);if(t>i){const n=i/t;e.vx*=n,e.vy*=n}}e.x+=e.vx*t,e.y+=e.vy*t}this.supportedThisStep.clear();const o=this.bodyPairKeys(n),r=this.sortedColliders().filter(e=>!e.sensor);for(let e=0;this.options.collisionIterations>e;e+=1)this.resolveBodyPairs(n,o,0===e),this.resolveColliders(n,r,0===e);this.updateSensors(n),this.updateSleeping(n,t)}settle(e=1200,t=this.options.fixedDt){let n=0;for(;e>n&&!this.allSleeping();)this.step(t),n+=1;return n}readState(e=[]){e.length=0;for(const t of this.sortedBodies())e.push({id:t.id,x:t.x,y:t.y,prevX:t.prevX,prevY:t.prevY,vx:t.vx,vy:t.vy,angle:t.angle,mass:t.mass,shape:le(t.shape),sleeping:t.sleeping,datum:t.datum});return e}events(){return this.lastEvents.slice()}activeSensorPairs(){return Array.from(this.activeSensors).sort().map(ke)}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(Me),colliders:this.sortedColliders().map(Ae),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=Me(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=Ae(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 n=this.bodies.get(t.bodyId);if(!n||n.sleeping)continue;const i="point"===t.target.type?t.target:this.bodies.get(t.target.bodyId);if(!i)continue;const o=i.x-n.x,r=i.y-n.y,s=Math.sqrt(o*o+r*r);if(ae>=s)continue;const a=o/s,c=r/s,l=(s-t.restLength)*t.stiffness+((("vx"in i?i.vx:0)-n.vx)*a+(("vy"in i?i.vy:0)-n.vy)*c)*t.damping;n.vx+=l*a*e/n.mass,n.vy+=l*c*e/n.mass}}resolveBodyPairs(e,t,n){for(const i of t){const[t,o]=i.split(":").map(Number),r=e[t],s=e[o];if(!r||!s)continue;const a=xe(r,s);a&&(this.resolveDynamicCollision(r,s,a),n&&this.lastEvents.push({type:"contact",bodyId:r.id,otherId:s.id,sensor:!1}))}}bodyPairKeys(e){const t=Math.max(1,this.options.cellSize),n=new Map;for(let i=0;e.length>i;i+=1){if(!1===e[i].bodyCollisions)continue;const o=fe(e[i]),r=Math.floor(o.minX/t),s=Math.floor(o.maxX/t),a=Math.floor(o.minY/t),c=Math.floor(o.maxY/t);for(let e=r;s>=e;e+=1)for(let t=a;c>=t;t+=1){const o=`${e}:${t}`,r=n.get(o);r?r.push(i):n.set(o,[i])}}const i=new Set;for(const t of Array.from(n.keys()).sort()){const o=n.get(t)??[];o.sort((e,t)=>e-t);for(let t=0;o.length>t;t+=1)for(let n=t+1;o.length>n;n+=1){const r=o[t],s=o[n];!1!==e[r].bodyCollisions&&!1!==e[s].bodyCollisions&&ge(fe(e[r]),fe(e[s]))&&i.add(`${r}:${s}`)}}return Array.from(i).sort((e,t)=>{const[n,i]=e.split(":").map(Number),[o,r]=t.split(":").map(Number);return n===o?i-r:n-o})}resolveDynamicCollision(e,t,n){e.sleeping&&this.contactOpposesGravity(n.nx,n.ny)&&this.supportedThisStep.add(t.id),t.sleeping&&this.contactOpposesGravity(-n.nx,-n.ny)&&this.supportedThisStep.add(e.id);const i=e.sleeping?0:1/e.mass,o=t.sleeping?0:1/t.mass,r=i+o;if(ae>=r)return;const s=Math.max(0,n.penetration-ce)/r;e.x-=n.nx*s*i,e.y-=n.ny*s*i,t.x+=n.nx*s*o,t.y+=n.ny*s*o;const a=(t.vx-e.vx)*n.nx+(t.vy-e.vy)*n.ny;if(a>0)return;const c=Math.abs(a),l=-(1+he(e.restitution,t.restitution,this.options.restitution))*a/r,d=l*n.nx,u=l*n.ny;e.vx-=d*i,e.vy-=u*i,t.vx+=d*o,t.vy+=u*o,this.applyFriction(e,t,n,l,i,o),c>this.options.contactWakeSpeed&&(this.wake(e),this.wake(t))}applyFriction(e,t,n,i,o,r){const s=-n.ny,a=n.nx,c=(t.vx-e.vx)*s+(t.vy-e.vy)*a,l=o+r;if(ae>=Math.abs(c)||ae>=l)return;const d=pe(e.friction,t.friction,this.options.friction),u=ue(-c/l,-i*d,i*d),h=u*s,p=u*a;e.vx-=h*o,e.vy-=p*o,t.vx+=h*r,t.vy+=p*r}resolveColliders(e,t,n){for(const i of e)for(const e of t){if(!Pe(e,i))continue;if(!ge(fe(i),ye(e)))continue;const t=we(i,e);t&&(this.resolveStaticCollision(i,e,t),this.contactOpposesGravity(t.nx,t.ny)&&this.supportedThisStep.add(i.id),n&&this.lastEvents.push({type:"contact",bodyId:i.id,otherId:e.id,sensor:!1}))}}resolveStaticCollision(e,t,n){e.x+=n.nx*Math.max(0,n.penetration-ce),e.y+=n.ny*Math.max(0,n.penetration-ce);const i=e.vx*n.nx+e.vy*n.ny;if(0>i){const o=he(e.restitution,t.restitution,this.options.restitution);e.vx-=(1+o)*i*n.nx,e.vy-=(1+o)*i*n.ny;const r=-n.ny,s=n.nx,a=e.vx*r+e.vy*s,c=pe(e.friction,t.friction,this.options.friction);e.vx-=a*r*c,e.vy-=a*s*c}}updateSensors(e){const t=new Set,n=this.sortedColliders().filter(e=>e.sensor);for(const i of e){const e=fe(i);for(const o of n){if(!Pe(o,i))continue;if(!ge(e,ye(o)))continue;if(!we(i,o))continue;const n=Se(o.id,i.id);t.add(n),this.activeSensors.has(n)||this.lastEvents.push({type:"sensor-enter",bodyId:i.id,sensorId:o.id})}}for(const e of Array.from(this.activeSensors).sort()){if(t.has(e))continue;const{sensorId:n,bodyId:i}=ke(e);this.lastEvents.push({type:"sensor-exit",bodyId:i,sensorId:n})}this.activeSensors=t}updateSleeping(e,t){const n=Math.hypot(this.options.gravity.x,this.options.gravity.y)>1;for(const i of e)Math.sqrt(i.vx*i.vx+i.vy*i.vy)>=this.options.sleepSpeed||Math.sqrt((i.x-i.prevX)*(i.x-i.prevX)+(i.y-i.prevY)*(i.y-i.prevY))>=this.options.sleepSpeed*t||n&&!this.supportedThisStep.has(i.id)?i.sleeping?this.wake(i):i.sleepTime=0:(i.sleepTime+=t,i.sleeping||this.options.sleepAfter>i.sleepTime||(i.sleeping=!0,i.vx=0,i.vy=0,this.lastEvents.push({type:"sleep",bodyId:i.id})))}contactOpposesGravity(e,t){const{x:n,y:i}=this.options.gravity,o=Math.hypot(n,i);return 1e-9>=o||-.2>(e*n+t*i)/o}wake(e){e.sleeping&&this.lastEvents.push({type:"wake",bodyId:e.id}),e.sleeping=!1,e.sleepTime=0}nextRandom(){return this.random()}},qe=class{constructor(e={}){this.id="builtin",this.capabilities={...(new Te).capabilities,engine:"builtin"},this.world=new Te(e)}init(e={}){this.world.init(e)}spawn(e){this.world.spawn(e)}remove(e){this.world.remove(e)}setColliders(e){this.world.setColliders(e)}setConstraint(e){return this.world.setConstraint(e)}removeConstraint(e){this.world.removeConstraint(e)}applyImpulse(e,t,n){this.world.applyImpulse(e,t,n)}step(e){this.world.step(e)}settle(e,t){return this.world.settle(e,t)}readState(e){return this.world.readState(e)}events(){return this.world.events()}activeSensorPairs(){return this.world.activeSensorPairs()}allSleeping(){return this.world.allSleeping()}snapshot(){return this.world.snapshot()}restore(e){this.world.restore(e)}nextRandom(){return this.world.nextRandom()}dispose(){this.world.dispose()}};function Oe(e={}){return new qe(e)}function Ee(e,t={}){return e?"function"==typeof e?e(t):(e.init(t),e):Oe(t)}var Fe=["binId","targetBin","category","windowIndex","lane","group"];function De(e,t){if(!Number.isFinite(t))return;e.count+=1,e.total+=t,e.min=Math.min(e.min,t),e.max=Math.max(e.max,t);const n=t-e.mean;e.mean+=n/e.count,e.m2+=n*(t-e.mean)}function je(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 Ne(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 ze(e,t){if(null!=e[t])return e[t];const n=e.datum;return n&&"object"==typeof n?n[t]:void 0}function We(e,t,n){return"function"==typeof e?e(t,n):"string"==typeof e?ze(t,e):void 0}function $e(e){if(null==e)return;const t=e+"";return t.trim()?t:void 0}function Le(e){const t=je(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:je(e.x),y:je(e.y),value:t}}var He=class{constructor(e=!1){this.bins=new Map,this.nextIndex=0,this.config=e}updateConfig(e){void 0!==e&&(this.config=e,!1===e&&this.clear())}isEnabled(){return!1!==this.config}add(e){if(!1===this.config)return null;const t=this.nextIndex;this.nextIndex+=1;const n=$e(We(this.config.binAccessor,e,t))??function(e){for(const t of Fe){const n=$e(ze(e,t));if(n)return n}return"sediment"}(e),i=$e(We(this.config.labelAccessor,e,t))??n,o=function(e,t,n){if("number"==typeof e)return e;const i="function"==typeof e?e(t,n):"string"==typeof e?ze(t,e):1,o="number"==typeof i?i:Number(i);return Number.isFinite(o)?o:1}(this.config.valueAccessor,e,t),r=Math.max(0,Math.floor(this.config.retainBodyIds??12));let s=this.bins.get(n);return s||(s={id:n,label:i,bodyIds:[],x:{count:0,total:0,mean:0,m2:0,min:1/0,max:-1/0},y:{count:0,total:0,mean:0,m2:0,min:1/0,max:-1/0},value:{count:0,total:0,mean:0,m2:0,min:1/0,max:-1/0}},this.bins.set(n,s)),s.label=i,s.lastBodyId=e.id,s.lastDatum=e.datum,De(s.x,e.x),De(s.y,e.y),De(s.value,o),r>0&&(s.bodyIds.push(e.id),s.bodyIds.length>r&&(s.bodyIds=s.bodyIds.slice(s.bodyIds.length-r))),Le(s)}clear(){this.bins.clear(),this.nextIndex=0}snapshot(){return Array.from(this.bins.values()).map(Le)}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:Ne(t.x),y:Ne(t.y),value:Ne(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 Ye(e,t={}){const{baselineY:n=0,binWidth:i=24,gap:o=2,maxHeight:r=80,value:s="count",x:a}=t,c=Math.max(1,...e.map(e=>e[s]));return e.map((e,t)=>{const l=Math.max(0,e[s]/c*r),d=a?.(e,t)??t*(i+o);return{binId:e.id,label:e.label,index:t,count:e.count,total:e.total,x:d,y:n-l,width:i,height:l,meanX:e.x.mean,meanY:e.y.mean}})}function Xe(e){const t=Number(e);if(Number.isFinite(t)&&t>0)return Math.floor(t)}function Ve(e){const t=Math.max(0,Math.floor(e.liveBodies)),n=Math.max(0,Math.floor(e.queuedBodies??0)),i=t+n,o=Xe(e.bodyLimit),r=Xe(e.engineMaxBodiesHint),s=function(e,t,n){if(!1===n)return;const i=Xe(n?.warnAt);return null!=i?i:null!=e?Math.max(1,Math.floor(.8*e)):null!=t?Math.max(1,Math.floor(.8*t)):void 0}(o,r,e.options),a=null==o?0:Math.max(0,t-o),c=a>0?"overflow":null==s||s>i?"ok":"warning";return{action:"overflow"!==c?"continue":e.sedimentEnabled?"sediment":e.evictionEnabled?"evict":"retain",bodyLimit:o,engineMaxBodiesHint:r,liveBodies:t,overflow:a,projectedBodies:i,queuedBodies:n,state:c,warnAt:s}}var _e={bodyLimit:1/0,eviction:"oldest",fixedDt:1/120,maxDeltaSeconds:.1,maxSubsteps:8,settleStepLimit:1200,timeScale:1},Ke={chartId:"physics",chartType:"physics",sensors:{},onObservation:void 0,onSimulationStateChange:void 0};function Ge(e={},t=Ke){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 Ue(e){return{...e,shape:{...e.shape},datum:e.datum,springs:e.springs?.map(e=>({...e,target:{...e.target}}))}}function Qe(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 Ze(e,t){if(null!=e[t])return e[t];const n=e.datum;return n&&"object"==typeof n?n[t]:void 0}function Je(e,t={}){const n=Qe(t.startAt)??0,i=t.pacing??"immediate";if("arrival"===i){const i=e.map((e,n)=>function(e,t,n){return"function"==typeof n?Qe(n(e,t)):"string"==typeof n?Qe(Ze(e,n)):Qe(e.spawnAt)??Qe(Ze(e,"arrivalTime"))??Qe(Ze(e,"timestamp"))??Qe(Ze(e,"time"))??Qe(Ze(e,"eventTime"))}(e,n,t.timeAccessor)),o=i.filter(e=>null!=e),r=o.length>0?Math.min(...o):0,s=Qe(t.timeScale)??1,a=s>0?s:1;return e.map((e,t)=>{const o=i[t],s=null==o?0:Math.max(0,o-r);return{...Ue(e),spawnAt:n+s/a}})}if("object"==typeof i){const t=Qe(i.ratePerSec);if(t&&t>0)return e.map((e,i)=>({...Ue(e),spawnAt:n+i/t}))}return e.map(e=>({...Ue(e),spawnAt:n}))}function et(e){return{...Ue(e),sequence:e.sequence,spawnAt:e.spawnAt}}function tt(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 nt(e){return!1!==e&&{...e}}function it(e,t){return e.spawnAt===t.spawnAt?e.sequence-t.sequence:e.spawnAt-t.spawnAt}function ot(e){return{...e,gravity:{...e.gravity}}}function rt(e,t,n,i){if("circle"===e.shape.type){const o=e.x-t,r=e.y-n,s=e.shape.radius+i,a=o*o+r*r;return a>s*s?null:a}const o=Math.max(Math.abs(t-e.x)-e.shape.width/2,0),r=Math.max(Math.abs(n-e.y)-e.shape.height/2,0),s=o*o+r*r;return s>i*i?null:s}function st(e){const t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}function at(e,t={}){const{idPrefix:n="plot",includeFloor:i=!0,includeCeiling:o=!1,includeLeftWall:r=!0,includeRightWall:s=!0,wallThickness:a=20,floorThickness:c=a}=t,l=[],d=e.x+e.width/2,u=e.y+e.height/2;return i&&l.push({id:n+"-floor",shape:{type:"aabb",x:d,y:e.y+e.height+c/2,width:e.width+2*a,height:c}}),o&&l.push({id:n+"-ceiling",shape:{type:"aabb",x:d,y:e.y-c/2,width:e.width+2*a,height:c}}),r&&l.push({id:n+"-left-wall",shape:{type:"aabb",x:e.x-a/2,y:u,width:a,height:e.height+2*c}}),s&&l.push({id:n+"-right-wall",shape:{type:"aabb",x:e.x+e.width+a/2,y:u,width:a,height:e.height+2*c}}),l}function ct(e){const{idPrefix:t="bin",count:n,domainStart:i,domainStep:o,xScale:r,yTop:s,yBottom:a,wallThickness:c=4,includeBoundaryWalls:l=!0,includeInteriorWalls:d=!0,closedBefore:u,lidY:h=s,lidThickness:p=Math.max(2,c)}=e,m=[],f=s+(a-s)/2,y=Math.abs(a-s),g=l?n:n-1;if(d||l)for(let e=l?0:1;g>=e;e+=1){if(!d&&e>0&&n>e)continue;const s=r(i+e*o);m.push({id:`${t}-wall-${e}`,shape:{type:"aabb",x:s,y:f,width:c,height:y}})}if(null!=u)for(let e=0;n>e;e+=1){const n=i+e*o,s=n+o;if(s>=u)continue;const a=r(n),l=r(s);m.push({id:`${t}-lid-${e}`,shape:{type:"segment",x1:Math.min(a,l)+c/2,y1:h,x2:Math.max(a,l)-c/2,y2:h,thickness:p}})}return m}import{quadtree as lt}from"d3-quadtree";var dt=class{constructor(){this.maxSearchRadius=0,this.revision=-1,this.tree=null}hitTest(e,t,n,i,o,r=0){const s=this.ensure(e,t);if(!s)return null;let a=null,c=1/0;const l=Math.max(0,r)+this.maxSearchRadius,d=i-l,u=i+l,h=o-l,p=o+l;return s.visit((e,t,s,l,m)=>{if(d>l||t>u||h>m||s>p)return!0;if(e.length)return!1;let f=e;for(;f;){const e=f.data;if(e){const t=rt(e,i,o,Math.max(0,r));null!=t&&(c>t||t===c&&n.indexOf(e.id)>n.indexOf(a?.id??""))&&(a=e,c=t)}f=f.next}return!1}),a}ensure(e,t){if(this.tree&&this.revision===t)return this.tree;const n=e.readState();return 0===n.length?(this.tree=null,this.maxSearchRadius=0,this.revision=t,null):(this.maxSearchRadius=n.reduce((e,t)=>Math.max(e,function(e){return"circle"===e.shape.type?e.shape.radius:Math.hypot(e.shape.width,e.shape.height)/2}(t)),0),this.tree=lt().x(e=>e.x).y(e=>e.y).addAll(n),this.revision=t,this.tree)}},ut=["data","scene-geometry","data-paint","accessibility","evidence"],ht=["scene-geometry","data-paint","accessibility","evidence"],pt=["overlay","accessibility","evidence"],mt=(e,t)=>({retainedData:e,invalidations:t}),ft=["layout","scene-geometry","data-paint","overlay","accessibility","evidence"],yt=["scene-geometry","data-paint","accessibility","evidence"],gt=[],bt={engine:mt("rebuild",["scene-geometry","data-paint","accessibility","evidence"]),kernel:mt("preserve",yt),colliders:mt("preserve",yt),sediment:mt("preserve",yt),bodyBudget:mt("preserve",ft),bodyLimit:mt("preserve",ft),eviction:mt("preserve",ft),fixedDt:mt("preserve",gt),maxDeltaSeconds:mt("preserve",gt),maxSubsteps:mt("preserve",gt),settleStepLimit:mt("preserve",gt),timeScale:mt("preserve",gt),observation:mt("preserve",gt)},vt=mt("preserve",ft);function xt(e){let t="preserve";const n=new Set;for(const i of e){const e=bt[i]??vt;"rebuild"===e.retainedData&&(t="rebuild");for(const t of e.invalidations)n.add(t)}return{retainedData:t,invalidations:n}}var wt=["seed","fixedDt","cellSize","collisionIterations","velocityDamping","sleepSpeed","sleepAfter","restitution","friction","maxVelocity","contactWakeSpeed"];function St(e,t){return e===t||!(!e||!t)&&e.gravity?.x===t.gravity?.x&&e.gravity?.y===t.gravity?.y&&wt.every(n=>e[n]===t[n])}function kt(e,t,n,i){return e||!t?"paused":n||!i?"running":"settled"}var Mt=class{constructor(){this.seconds=0,this.speed=8,this.scratch=[]}setKernelOptions(e){this.speed=function(e){const t=e?.sleepSpeed;return"number"==typeof t&&Number.isFinite(t)&&t>0?t:8}(e)}reset(){this.seconds=0}isAtRest(){return this.seconds>=.6}refresh(e,t,n){if(n>0)return void(this.seconds=0);const i=e.readState(this.scratch),o=this.speed*this.speed;let r=!0;for(const e of i)if(!e.sleeping&&e.vx*e.vx+e.vy*e.vy>=o){r=!1;break}this.seconds=r?this.seconds+Math.max(0,t):0}},It=class{constructor(e={}){this.activeSensorPairs=new Set,this.accumulator=0,this.bodyBudgetObservationKey="ok",this.bodySpatialIndex=new dt,this.elapsedSeconds=0,this.liveBodyOrder=[],this.nextSequence=0,this.paused=!1,this.queue=[],this.revision=0,this.updateResults=new m,this.simulationState="settled",this.visible=!0,this.quiescence=new Mt;const{bodyBudget:t,colliders:n,engine:i,kernel:o,observation:r,sediment:s,...a}=e;this.config={..._e,...a},this.configInput={...e},this.bodyBudget=t??{},this.engineInput=i,this.observation=Ge(r),this.sediment=new He(s??!1),this.world=Ee(i,{fixedDt:this.config.fixedDt,...o}),this.quiescence.setKernelOptions(o),n&&this.world.setColliders(tt(n))}updateConfig(e){const t=function(e,t){return Object.keys(e).filter(n=>"kernel"===n?!St(e.kernel,t.kernel):e[n]!==t[n])}(e,this.configInput),{colliders:n,bodyBudget:i,engine:o,kernel:r,observation:s,sediment:a,...c}=e;if(this.config={...this.config,...c},void 0!==i&&(this.bodyBudget=i,!1===i&&(this.bodyBudgetObservationKey="ok")),o&&o!==this.engineInput){const e=this.world.snapshot();this.world.dispose(),this.engineInput=o,this.world=Ee(o,e.options),this.world.restore(e),this.revision+=1}if(r&&!St(r,this.configInput.kernel)){const e=this.world.snapshot(),t={...e.options,...r,gravity:{...e.options.gravity,...r.gravity}};this.world.restore({...e,options:t}),this.quiescence.setKernelOptions(t),this.revision+=1}s&&(this.observation=Ge(s,this.observation)),this.sediment.updateConfig(a),n&&(this.world.setColliders(tt(n)),this.revision+=1),this.configInput={...this.configInput,...e};const l=xt(t);this.updateResults.record({kind:"config",keys:t},l.invalidations)}updateConfigWithResult(e){return this.updateConfig(e),this.updateResults.last}setColliders(e){this.world.setColliders(tt(e)),this.revision+=1,this.updateResults.record({kind:"config",keys:["colliders"]},xt(["colliders"]).invalidations)}enqueue(e,t){const n=Array.isArray(e)?e:[e],i=t?Je(n,{...t,startAt:t.startAt??this.elapsedSeconds}):n;for(const e of i)this.queue.push({...Ue(e),sequence:this.nextSequence,spawnAt:e.spawnAt??this.elapsedSeconds}),this.nextSequence+=1;this.queue.sort(it),i.length>0&&(this.revision+=1),this.updateResults.record({kind:"enqueue",count:i.length},i.length?ut:[])}enqueueWithResult(e,t){return this.enqueue(e,t),this.updateResults.last}spawnNow(e){this.spawnOne(Ue(e)),this.nextSequence+=1,this.observeBodyBudget(),this.evictOverflow(),this.revision+=1,this.updateResults.record({kind:"enqueue",count:1},ut)}materializeDueSpawns(){const e=this.revision,t=[],n=[];return this.spawnDue(t,n),0===t.length||(this.observeBodyBudget(n),this.evictOverflow(n),this.syncSimulationState(n),this.revision+=1,this.updateResults.record({kind:"enqueue",count:t.length},this.revision!==e?ut:[])),t}clear(){const e=this.world.snapshot().options;this.world.init({...e,fixedDt:this.config.fixedDt}),this.activeSensorPairs.clear(),this.liveBodyOrder=[],this.queue=[],this.accumulator=0,this.elapsedSeconds=0,this.nextSequence=0,this.quiescence.reset(),this.sediment.clear(),this.bodyBudgetObservationKey="ok",this.revision+=1,this.syncSimulationState(),this.updateResults.record({kind:"clear"},ut)}tick(e){const t=this.revision,n=[],i=[],o=[],r=[],s=[];if(this.paused||!this.visible){const e=this.result(0,n,i,o,r,s,!1);return this.updateResults.record({kind:"tick",count:0},[]),e}const a=Math.max(0,Math.min(e,this.config.maxDeltaSeconds))*this.config.timeScale;this.elapsedSeconds+=a,this.spawnDue(n,s);const c=this.observeBodyBudget(s),l=this.evictOverflow(s);i.push(...l.evicted),o.push(...l.sedimented),this.syncSimulationState(s),this.accumulator+=a;let d=0;for(;this.accumulator>=this.config.fixedDt&&this.config.maxSubsteps>d;){this.world.step(this.config.fixedDt);const e=this.world.events();r.push(...e),this.observeKernelEvents(e,s),this.observeSensorTransitions(s),this.accumulator-=this.config.fixedDt,d+=1}d===this.config.maxSubsteps&&(this.accumulator=Math.min(this.accumulator,this.config.fixedDt)),this.quiescence.refresh(this.world,a,n.length),(d>0||n.length>0||i.length>0||o.length>0||r.length>0)&&(this.revision+=1);const u=this.result(d,n,i,o,r,s,void 0,c);return this.updateResults.record({kind:"tick",count:d},this.revision!==t?n.length||i.length||o.length?ut:ht:[]),u}settle(e=this.config.settleStepLimit){return this.runSettle(e,!1).steps}settleWithObservations(e=this.config.settleStepLimit){return this.runSettle(e,!0)}settleHost(){return{fixedDt:this.config.fixedDt,queueSize:()=>this.queue.length,atRest:()=>this.atRest(),advanceTime:e=>{this.elapsedSeconds+=e},spawnDue:(e,t)=>this.spawnDue(e,t),observeBodyBudget:e=>this.observeBodyBudget(e),evictOverflow:e=>this.evictOverflow(e),step:e=>this.world.step(e),drainEvents:()=>this.world.events(),observeKernelEvents:(e,t)=>this.observeKernelEvents(e,t),observeSensorTransitions:e=>this.observeSensorTransitions(e),refreshQuiescence:(e,t)=>this.quiescence.refresh(this.world,e,t)}}runSettle(e,t){const n=this.revision,i=[],o=[],r=[],s=[],a=t?[]:void 0;if(t&&(this.paused||!this.visible)){const e=this.result(0,i,o,r,s,a??[],!1);return this.updateResults.record({kind:"settle",count:0},[]),e}this.spawnDue(i,a);const c=this.observeBodyBudget(a),l=this.evictOverflow(a);o.push(...l.evicted),r.push(...l.sedimented),this.syncSimulationState(a),i.length>0&&this.quiescence.reset();const d=t?{spawned:i,evicted:o,sedimented:r,events:s,observations:a}:{spawned:i},{steps:u,budget:h}=function(e,t,n){let i,o=0;for(;t>o&&(e.queueSize()>0||!e.atRest());){e.advanceTime(e.fixedDt);const t=[];if(e.spawnDue(t,n.observations),t.length>0){n.spawned.push(...t),i=e.observeBodyBudget(n.observations);const o=e.evictOverflow(n.observations);n.evicted?.push(...o.evicted),n.sedimented?.push(...o.sedimented)}e.step(e.fixedDt);const r=e.drainEvents();n.events&&(n.events.push(...r),e.observeKernelEvents(r,n.observations),e.observeSensorTransitions(n.observations)),o+=1,e.refreshQuiescence(e.fixedDt,t.length)}return{steps:o,budget:i}}(this.settleHost(),e,d),p=i.length+o.length+r.length>0;(u>0||p||s.length>0)&&(this.revision+=1);const m=this.result(u,i,o,r,s,a??[],void 0,h??c);return this.updateResults.record({kind:"settle",count:u},this.revision===n?[]:p?ut:ht),m}readBodies(e=[]){return this.world.readState(e)}readSediment(){return this.sediment.snapshot()}bodyBudgetStatus(){return this.evaluateBodyBudget()}sedimentTotals(){return this.sediment.totals()}sedimentHeightfield(e={}){return Ye(this.readSediment(),e)}hitTest(e,t,n=0){return this.bodySpatialIndex.hitTest(this.world,this.revision,this.liveBodyOrder,e,t,n)}events(){return this.world.events()}allSleeping(){return this.world.allSleeping()}atRest(){return this.world.allSleeping()||this.quiescence.isAtRest()}hasPendingWork(){return this.queue.length>0||!this.atRest()}queueSize(){return this.queue.length}liveBodyCount(){return this.liveBodyOrder.length}elapsed(){return this.elapsedSeconds}recordObservation(e){const{timestamp:t,chartType:n,chartId:i,...o}=e,r={...o,timestamp:t??this.elapsedSeconds,chartType:n??this.observation.chartType,chartId:i??this.observation.chartId};return this.emitObservation(r),this.updateResults.record({kind:"update",count:1},["evidence"]),r}getLastUpdateResult(){return this.updateResults.last}getUpdateSnapshot(){return this.updateResults.last}subscribeUpdateResult(e){return this.updateResults.subscribe(e)}version(){return this.revision}setPaused(e){const t=this.paused!==e;this.paused=e,this.syncSimulationState(),this.updateResults.record({kind:"pause"},t?pt:[])}setVisible(e){const t=this.visible!==e;this.visible=e,this.syncSimulationState(),this.updateResults.record({kind:"visibility"},t?pt:[])}remove(e){const t=new Set(e),n=new Set(this.liveBodyOrder),i=new Set(this.queue.map(e=>e.id));this.queue=this.queue.filter(e=>!t.has(e.id)),this.liveBodyOrder=this.liveBodyOrder.filter(e=>!t.has(e)),this.world.remove(e),this.removeActiveSensorPairsForBodies(t);const o=e.filter(e=>n.has(e)||i.has(e));return o.length>0&&(this.revision+=1,this.syncSimulationState()),this.updateResults.record({kind:"remove",keys:o,count:o.length},o.length?ut:[]),o}setConstraint(e){const t=this.world.setConstraint(e);return this.revision+=1,this.updateResults.record({kind:"constraint",keys:[t]},ht),t}removeConstraint(e){this.world.removeConstraint(e),this.revision+=1,this.updateResults.record({kind:"constraint",keys:[e]},ht)}applyImpulse(e,t,n){this.world.applyImpulse(e,t,n),this.revision+=1,this.updateResults.record({kind:"impulse",keys:[e]},ht)}nextRandom(){return this.world.nextRandom()}controls(){return e=this,{applyImpulse:(t,n,i)=>e.applyImpulse(t,n,i),clear:()=>e.clear(),hitTest:(t,n,i)=>e.hitTest(t,n,i),pause:()=>e.setPaused(!0),push:(t,n)=>e.enqueue(t,n),pushMany:(t,n)=>e.enqueue(t,n),bodyBudgetStatus:()=>e.bodyBudgetStatus(),readBodies:t=>e.readBodies(t),readSediment:()=>e.readSediment(),recordObservation:t=>e.recordObservation(t),remove:t=>e.remove(t),restore:t=>e.restore(t),resume:()=>e.setPaused(!1),settle:t=>e.settle(t),settleWithObservations:t=>e.settleWithObservations(t),snapshot:()=>e.snapshot(),sedimentHeightfield:t=>e.sedimentHeightfield(t),sedimentTotals:()=>e.sedimentTotals(),step:t=>e.tick(t)};var e}snapshot(){const e=this.world.snapshot();return{accumulator:this.accumulator,activeSensorPairs:Array.from(this.activeSensorPairs).sort(),bodyBudget:nt(this.bodyBudget),config:{...this.config,kernel:ot(e.options)},elapsedSeconds:this.elapsedSeconds,paused:this.paused,queue:this.queue.map(et),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:nt(e.bodyBudget??{}),kernel:ot(e.world.options)},this.bodyBudget=nt(e.bodyBudget??{}),this.bodyBudgetObservationKey="ok",this.quiescence.setKernelOptions(e.world.options),this.quiescence.reset(),this.activeSensorPairs=new Set(e.activeSensorPairs),this.accumulator=e.accumulator,this.elapsedSeconds=e.elapsedSeconds,this.paused=e.paused,this.queue=e.queue.map(et).sort(it),this.revision=e.revision,this.sediment.restore(e.sediment??[]),this.simulationState=e.simulationState??kt(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"},ut)}spawnDue(e,t){for(;this.queue.length>0&&this.elapsedSeconds>=this.queue[0].spawnAt;){const n=this.queue.shift();if(!n)return;this.spawnOne(n,t),e.push(n.id)}}spawnOne(e,t){this.liveBodyOrder=this.liveBodyOrder.filter(t=>t!==e.id),this.removeActiveSensorPairsForBodies(new Set([e.id])),this.world.spawn(e),this.liveBodyOrder.push(e.id);for(const t of e.springs??[])this.world.setConstraint({...t,bodyId:e.id});const n=this.world.readState().find(t=>t.id===e.id);this.emitObservation({type:"physics-spawn",timestamp:this.elapsedSeconds,chartType:this.observation.chartType,chartId:this.observation.chartId,bodyId:e.id,datum:n?.datum??e.datum,x:n?.x??e.x,y:n?.y??e.y},t)}result(e,t,n,i,o,r,s,a=this.evaluateBodyBudget()){this.syncSimulationState(r);const c=this.world.allSleeping();return{budget:a,elapsedSeconds:this.elapsedSeconds,evicted:n,events:o,observations:r,queueSize:this.queue.length,revision:this.revision,shouldContinue:s??(this.queue.length>0||!this.atRest()),sleeping:c,sedimented:i,spawned:t,steps:e}}observeKernelEvents(e,t){!function(e,t,n){if(0===t.length)return;const i=new Map(e.readState().map(e=>[e.id,e]));for(const e of t){if("sleep"!==e.type)continue;const t=i.get(e.bodyId);n.emit({type:"physics-settle",timestamp:n.elapsedSeconds,chartType:n.observation.chartType,chartId:n.observation.chartId,bodyId:e.bodyId,datum:t?.datum,x:t?.x,y:t?.y})}}(this.world,e,this.observationContext(t))}observeSensorTransitions(e){this.activeSensorPairs=function(e,t,n){const i=new Set(e.activeSensorPairs().map(e=>`${e.sensorId}\0${e.bodyId}`));if(0===i.size&&0===t.size)return i;const o=new Map(e.readState().map(e=>[e.id,e])),r=(e,t)=>{const{sensorId:i,bodyId:r}=st(t),s=n.observation.sensors[i],a=o.get(r);n.emit({type:"enter"===e?s?.enterType??"physics-bin-enter":s?.exitType??"physics-bin-exit",timestamp:n.elapsedSeconds,chartType:n.observation.chartType,chartId:n.observation.chartId,bodyId:r,datum:a?.datum,x:a?.x,y:a?.y,sensorId:i,binId:s?.binId??i})};for(const e of Array.from(i).sort())t.has(e)||r("enter",e);for(const e of Array.from(t).sort())i.has(e)||r("exit",e);return i}(this.world,this.activeSensorPairs,this.observationContext(e))}removeActiveSensorPairsForBodies(e){!function(e,t){for(const n of e)t.has(st(n).bodyId)&&e.delete(n)}(this.activeSensorPairs,e)}observationContext(e){return{elapsedSeconds:this.elapsedSeconds,observation:this.observation,emit:t=>this.emitObservation(t,e)}}emitObservation(e,t){t?.push(e),this.observation.onObservation?.(e)}evaluateBodyBudget(){return Ve({bodyLimit:this.config.bodyLimit,engineMaxBodiesHint:this.world.capabilities.maxBodiesHint,evictionEnabled:!1!==this.config.eviction,liveBodies:this.liveBodyOrder.length,queuedBodies:this.queue.length,sedimentEnabled:this.sediment.isEnabled(),options:this.bodyBudget})}observeBodyBudget(e){const t=this.evaluateBodyBudget();if("ok"===t.state||!1===this.bodyBudget)return this.bodyBudgetObservationKey="ok",t;const n=`${t.state}:${t.action}`;return n===this.bodyBudgetObservationKey||(this.bodyBudgetObservationKey=n,this.emitObservation({type:"overflow"===t.state?"physics-budget-overflow":"physics-budget-warning",timestamp:this.elapsedSeconds,chartType:this.observation.chartType,chartId:this.observation.chartId,budgetAction:t.action,bodyLimit:t.bodyLimit,engineMaxBodiesHint:t.engineMaxBodiesHint,liveBodies:t.liveBodies,overflow:t.overflow,projectedBodies:t.projectedBodies,queuedBodies:t.queuedBodies,warnAt:t.warnAt},e)),t}syncSimulationState(e){const t=kt(this.paused,this.visible,this.queue.length>0,this.atRest());if(t===this.simulationState)return;const n=this.simulationState;this.simulationState=t,function(e,t,n){n.observation.onSimulationStateChange?.(t,e),"running"!==t&&"settled"!==t||n.emit({type:"running"===t?"sim-active":"sim-idle",timestamp:n.elapsedSeconds,chartType:n.observation.chartType,chartId:n.observation.chartId,simulationState:t,previousSimulationState:e})}(n,t,this.observationContext(e))}evictOverflow(e){const{evicted:t,sedimented:n,liveBodyOrder:i}=function(e,t,n,i,o,r){const s={evicted:[],sedimented:[],liveBodyOrder:o};if(!1===n)return s;const a=Math.max(0,Math.floor(i));if(!Number.isFinite(a))return s;const c=o.length-a;if(0>=c)return s;const l=function(e,t,n){if("sleeping-first"!==t)return n.slice();const i=new Map(e.readState().map(e=>[e.id,e.sleeping])),o=[],r=[];for(const e of n)i.get(e)?o.push(e):r.push(e);return[...o,...r]}(e,n,o),d=l.slice(0,c);if(0===d.length)return s;const u=function(e,t,n,i){const o=new Map(e.readState().map(e=>[e.id,e])),r=[];for(const e of n){const n=o.get(e);if(!n)continue;const s=t.add(n);s&&(r.push(e),i.emit({type:"physics-sediment",timestamp:i.elapsedSeconds,chartType:i.observation.chartType,chartId:i.observation.chartId,bodyId:e,datum:n.datum,x:n.x,y:n.y,binId:s.id,count:s.count,total:s.total}))}return r}(e,t,d,r);e.remove(d);const h=new Set(d);return{evicted:d,sedimented:u,liveBodyOrder:o.filter(e=>!h.has(e))}}(this.world,this.sediment,this.config.eviction,this.config.bodyLimit,this.liveBodyOrder,this.observationContext(e));return t.length>0&&(this.liveBodyOrder=i,this.removeActiveSensorPairsForBodies(new Set(t))),{evicted:t,sedimented:n}}};function At(e=[]){return e.map(e=>({id:e.id,label:e.label,count:e.count,...null!=e.secondary?{secondary:e.secondary}:{},...e.secondaryLabel?{secondaryLabel:e.secondaryLabel}:{},...null!=e.observed?{observed:e.observed}:{}}))}function Bt(e,t={}){const n=t.bodies??function(e){return e.world.bodies.map(e=>({id:e.id,x:e.x,y:e.y,prevX:e.prevX,prevY:e.prevY,vx:e.vx,vy:e.vy,angle:e.angle,mass:e.mass,shape:{...e.shape},sleeping:e.sleeping,datum:e.datum}))}(e),i=n.filter(e=>e.sleeping).length,o=e.queue.length,r=e.sediment.reduce((e,t)=>e+t.count,0),s="settled"===e.simulationState&&0===o&&i===n.length,a=[];o>0&&a.push("PHYSICS_QUEUE_UNDRAINED");const c=null!=t.charge&&Number.isFinite(t.charge)?function(e,t,n,i){const o=e-(t+n+i);return{charge:e,live:t,queued:n,sedimented:i,unaccounted:o,balanced:0===o}}(t.charge,n.length,o,r):void 0;return c&&!c.balanced&&a.push("PHYSICS_LEDGER_MISMATCH"),{bodyCount:n.length,sleepingCount:i,settled:s,stepsRun:Math.max(0,Math.floor(t.stepsRun??0)),seed:e.world.options.seed,binCounts:At(t.projectionRows),queuedCount:o,sedimentedCount:r,...c?{ledger:c}:{},warnings:a}}var Rt={fill:"#4e79a7",stroke:"#172033",strokeWidth:1,opacity:.85};function Ct(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 Pt(e,t){const n="function"==typeof t?t(e):t;return{...Rt,...n??{}}}function Tt(e,t={}){const n=function(e){return e.datum&&"object"==typeof e.datum?e.datum:null}(e),i={label:t.getBodyLabel?.(e)??Ct(e)},o={style:Pt(e,t.bodyStyle),datum:n,accessibleDatum:n,accessibility:i,_transitionKey:e.id};return"aabb"===e.shape.type?{type:"rect",x:e.x-e.shape.width/2,y:e.y-e.shape.height/2,w:e.shape.width,h:e.shape.height,...o}:{type:"point",x:e.x,y:e.y,r:e.shape.radius,pointId:e.id,...o}}function qt(e,t={}){return e.map(e=>Tt(e,t))}function Ot(e,t={}){const n=e.settle(t.maxSteps),i=e.readBodies(),o=e.snapshot();return{snapshot:o,bodies:i,sceneNodes:qt(i,t),evidence:Bt(o,{bodies:i,projectionRows:t.projectionRows,stepsRun:n,charge:t.charge}),stepsRun:n}}import*as Et from"react-dom/server";import{jsx as Ft,jsxs as Dt}from"react/jsx-runtime";var jt={top:0,right:0,bottom:0,left:0};function Nt(e,t,n){return"function"==typeof e?e({size:t,margin:n}):e}function zt(e,t={}){const{width:n=640,height:i=360,title:o,description:r,background:s,backgroundGraphics:a,className:c,foregroundGraphics:l,idPrefix:d="physics",margin:u,renderBodySVG:h,...p}=t,m=Ot(e,p),f={...jt,...u},y=[n,i],g=Nt(a,y,f),b=Nt(l,y,f),v=function(e){const t=e.replace(/[^A-Za-z0-9_-]/g,"_");return!t||/^\d/.test(t)?"physics-"+t:t}(d),x=o?v+"-title":void 0,w=r?v+"-desc":void 0,S=[x,w].filter(Boolean).join(" ")||void 0;return{svg:Et.renderToStaticMarkup(Dt("svg",{xmlns:"http://www.w3.org/2000/svg",className:c??"stream-physics-frame",width:n,height:i,viewBox:`0 0 ${n} ${i}`,role:"img","aria-labelledby":S,children:[o&&Ft("title",{id:x,children:o}),r&&Ft("desc",{id:w,children:r}),!a&&s&&"transparent"!==s?Ft("rect",{x:0,y:0,width:n,height:i,fill:s}):null,g,Ft("g",{id:v+"-data-area",children:m.sceneNodes.map((e,t)=>{const n=m.bodies[t];return(n&&h?h(n,e.style??{},t,v):void 0)??D(e,t,v)})}),b]})),scene:m,evidence:m.evidence}}function Wt(e,t){if("function"==typeof t){const n=t(e);return Number.isFinite(n)&&n>0?Number(n):1}const n=e.datum;if(t&&n&&"object"==typeof n){const e=Number(n[t]);if(Number.isFinite(e)&&e>0)return e}const i=Number(n?.work??n?.reviewWork??n?.value);return Number.isFinite(i)&&i>0?i:1}function $t(e,t){if("function"==typeof t){const n=t(e);if(null!=n&&(n+"").length>0)return n+""}else if(t){const n=Be(e.datum,t),i=Be(e,t),o=n??i;if(null!=o&&(o+"").length>0)return o+""}return e.id}function Lt(e,t){if(0===e.length)return 0;if(1===e.length)return e[0];const n=Math.max(0,Math.min(1,t))*(e.length-1),i=Math.floor(n);return e[i]+(e[Math.ceil(n)]-e[i])*(n-i)}function Ht(e){const t=e.regionId,n=Math.max(0,e.unitsPerSecond),i=e.queueLayout??"lane",o=e.queueSlotSpacing??14,r=e.queueStiffness??.35,s=Number.isFinite(e.maxQueue)?Math.max(0,Math.floor(Number(e.maxQueue))):1/0,a=Math.max(.25,e.metricWindowSeconds??30),c=Math.max(1/60,e.snapshotIntervalSeconds??.25),l=e.releaseImpulse??{x:90,y:0},d=new Map,u=new Map,h=new Map,p=new Map,m=new Map,f=new Map,y=new Map,g=[];let b=0,v=new Map,x=new Map,w=0,S=0,k=0,M=null,I=0,A=0,B=0,R=0,C=0,P=0,T=0,q=0,O=0,E=0,F=0,D=0,j=-1,N=!1;function z(e,n){const i=n(e);return!!i&&i.activeRegionIds.includes(t)}function W(){D+=1}function $(e){return{bodyId:e.bodyId,jobId:e.jobId,visitId:e.visitId,visit:e.visit,regionId:t,work:e.total,queuedAt:e.queuedAt}}function L(n,i,o,r){const s={bodyId:n.id,jobId:i.jobId,visitId:i.visitId,visit:i.visit,remaining:i.work,total:i.work,queuedAt:i.queuedAt,sequence:r};return d.set(i.jobId,s),y.delete(n.id),f.set(n.id,i.jobId),A+=1,B+=i.work,W(),function(n,i,o){const r=$(i);e.onQueued?.(n,r),o.controls.recordObservation({type:"physics-capacity-queued",bodyId:n.id,datum:n.datum,x:n.x,y:n.y,regionId:t,work:i.total,jobId:i.jobId,visitId:i.visitId,visit:i.visit,queuedAt:i.queuedAt,queueDepth:d.size})}(n,s,o),s}function H(e){if(d.size>=s||0===u.size)return;const t=Array.from(u.values()).sort((e,t)=>e.sequence-t.sequence);for(const n of t){if(d.size>=s)break;const t=m.get(n.jobId);t&&h.has(n.jobId)?(u.delete(n.jobId),y.delete(n.bodyId),L(t,n,e,n.sequence)):u.delete(n.jobId)}}function Y(){let e=0;for(const t of d.values())e+=t.remaining;return e}function X(){O=Math.max(O,d.size),E=Math.max(E,Y())}function V(){const e=k-a,t=Math.max(0,Math.min(a,k-(M??k)));let i=0,o=0,r=0,s=0,c=0;for(const t of g){if(e>t.end)continue;i+=t.arrivals,o+=t.arrivalWork,r+=t.completions,s+=t.completedWork;const n=t.end-t.start;c+=n>0&&e>t.start?t.processedWork*Math.min(1,Math.max(0,t.end-e)/n):t.processedWork}const l=t>0?o/t:0;return{seconds:t,arrivals:i,arrivalWork:o,completions:r,completedWork:s,processedWork:c,arrivalsPerSecond:t>0?i/t:0,throughputPerSecond:t>0?r/t:0,utilization:t>0&&n>0?Math.max(0,Math.min(1,c/(n*t))):0,pressure:n>0?l/n:0}}return{id:e.id??"capacity-queue:"+t,continuous:!1!==e.continuous,tick:i=>{const o=i.controls.readBodies(),r=new Map,A=new Map;for(const t of o){if(r.set(t.id,t),!z(t.id,i.getRegionState))continue;if(!Ce(t,e.bodyFilter))continue;const n=$t(t,e.jobKey),o=A.get(n)??[];o.push(t),A.set(n,o)}const B=Number.isFinite(i.dt)?Math.max(0,i.dt):0;if(!N){const e=Number.isFinite(i.elapsed)?Math.max(0,i.elapsed):B;k=Math.max(0,e-B),N=!0}const O=k,E=O+B;k=E,M=null==M?O:Math.min(M,O);const D={start:O,end:E,arrivals:0,arrivalWork:0,completions:0,completedWork:0,processedWork:0},Y=new Map;for(const[e,t]of A){const n=h.get(e)?.bodyId,i=t.find(e=>e.id===n)??t[0];Y.set(e,i),m.set(e,i)}for(const[n,o]of h){if(Y.has(n))continue;const s=d.get(n),a=r.get(o.bodyId)??m.get(n);if(s){d.delete(n),f.delete(s.bodyId),T+=1,q+=s.remaining,W();const r={...$(s),abandonedAt:k,remainingWork:s.remaining,queueSeconds:Math.max(0,k-s.queuedAt)};a&&e.onAbandoned?.(a,r),i.controls.recordObservation({type:"physics-capacity-abandoned",bodyId:o.bodyId,datum:a?.datum,x:a?.x,y:a?.y,regionId:t,work:s.total,remainingWork:s.remaining,jobId:n,visitId:s.visitId,visit:s.visit,queuedAt:s.queuedAt,abandonedAt:k,queueSeconds:r.queueSeconds,queueDepth:d.size})}u.delete(n),y.delete(o.bodyId),h.delete(n),m.delete(n)}for(const[n,o]of Y){if(h.has(n))continue;const r=(p.get(n)??0)+1;p.set(n,r);const a=Wt(o,e.unitAccessor),c={bodyId:o.id,jobId:n,visitId:`${t}:${n}:${r}`,visit:r,regionId:t,work:a,queuedAt:k};h.set(n,c),I+=1,D.arrivals+=1,D.arrivalWork+=a;const l=b++;if(s>d.size)L(o,c,i,l);else{const s={...c,blockedAt:k,sequence:l};u.set(n,s),y.set(o.id,n),P+=1,W(),e.onBlocked?.(o,s),i.controls.recordObservation({type:"physics-capacity-blocked",bodyId:o.id,datum:o.datum,x:o.x,y:o.y,regionId:t,work:a,jobId:n,visitId:c.visitId,visit:r,queuedAt:k,blockedAt:k,queueDepth:d.size,blockedDepth:u.size})}}H(i),X();const V=Array.from(d.values()).sort((e,t)=>e.sequence-t.sequence);let _=n*B;for(const n of V){if(0>=_)break;const o=Math.min(n.remaining,_);if(n.remaining-=o,_-=o,R+=o,D.processedWork+=o,n.remaining>1e-6)continue;d.delete(n.jobId),f.delete(n.bodyId),S+=1,C+=n.total,D.completions+=1,D.completedWork+=n.total;const s=Math.max(0,k-n.queuedAt);F+=s,W();const a=r.get(n.bodyId);if(!a)continue;i.controls.applyImpulse(n.bodyId,l.x??0,l.y??0);const c={...$(n),completedAt:k,queueSeconds:s};e.onProcessed?.(a,c),i.controls.recordObservation({type:"physics-capacity-processed",bodyId:n.bodyId,datum:a.datum,x:a.x,y:a.y,regionId:t,work:n.total,jobId:n.jobId,visitId:n.visitId,visit:n.visit,queuedAt:n.queuedAt,completedAt:k,queueSeconds:s,queueDepth:d.size})}H(i),X(),function(){const e=Array.from(d.values()).sort((e,t)=>e.sequence-t.sequence);v=new Map(e.map((e,t)=>[e.bodyId,t]));const t=Array.from(u.values()).sort((e,t)=>e.sequence-t.sequence);x=new Map(t.map((e,t)=>[e.bodyId,t])),w=e.length}(),function(e){(e.end>e.start||e.arrivals>0||e.completions>0||e.processedWork>0)&&g.push(e);const t=k-a;for(;g.length>0&&t>g[0].end;)g.shift()}(D);const K=Math.floor(k/c);K!==j&&(j=K,W())},getSnapshot:()=>{const e=Y(),i=function(){let e=0;for(const t of u.values())e+=t.work;return e}(),o=d.size,r=Array.from(d.values()).map(e=>Math.max(0,k-e.queuedAt)).sort((e,t)=>e-t),s=r.reduce((e,t)=>e+t,0);return{regionId:t,queueDepth:o,processedCount:S,unitsPerSecond:n,remainingWork:e,meanRemainingWork:o>0?e/o:0,waitingWork:e+i,blockedDepth:u.size,blockedWork:i,arrivalCount:I,admittedCount:A,admittedWork:B,processedWork:R,completedWork:C,blockedCount:P,abandonedCount:T,abandonedWork:q,peakQueueDepth:O,peakRemainingWork:E,queueAge:{count:r.length,meanSeconds:r.length>0?s/r.length:0,p50Seconds:Lt(r,.5),p95Seconds:Lt(r,.95),oldestSeconds:r.at(-1)??0},meanCompletedQueueSeconds:S>0?F/S:0,window:V(),simulatedAt:k,metricRevision:D}},bodyForce:e=>{if("none"===i)return null;const n=f.get(e.body.id),s=y.get(e.body.id),a=n?d.get(n):void 0,c=s?u.get(s):void 0;if(!a&&!c)return null;const l=a?v.get(e.body.id):x.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 Yt(e){const t=e.resources.map(e=>({...e,bodyId:e.bodyId??e.id})),n=new Map(t.map(e=>[e.bodyId,e])),i=new Map,o=new Map,r=e.assignmentForce??.45,s=e.returnForce??.35,a=e.caseAttraction??.08,c=e.assignmentOffset??{x:0,y:0};let l=new Map,d=0,u=0;return{id:e.id??"service-resource-pool",continuous:!0,assign:e=>{const n=i.get(e);if(n)return n;const r=t.find(e=>!o.has(e.id));if(!r)return null;const s={resourceId:r.id,resourceBodyId:r.bodyId,caseBodyId:e,assignedAt:d};return i.set(e,s),o.set(r.id,s),u+=1,s},release:e=>{const t=i.get(e);return!!t&&(i.delete(e),o.delete(t.resourceId),u+=1,!0)},getAssignment:e=>i.get(e),tick:e=>{d=Math.max(d,e.elapsed),l=new Map(e.controls.readBodies().map(e=>[e.id,e]));for(const[e,t]of i)l.has(e)&&l.has(t.resourceBodyId)||(i.delete(e),o.delete(t.resourceId),u+=1)},getSnapshot:()=>({total:t.length,available:t.length-o.size,assigned:o.size,assignments:Array.from(i.values()),simulatedAt:d,metricRevision:u}),bodyForce:e=>{const t=n.get(e.body.id);if(t){const n=o.get(t.id),i=n?l.get(n.caseBodyId):void 0,a=n?r:s;return{x:((i?i.x+(c.x??0):t.home.x)-e.body.x)*a,y:((i?i.y+(c.y??0):t.home.y)-e.body.y)*a}}const d=i.get(e.body.id);if(!d||0>=a)return null;const u=l.get(d.resourceBodyId);return u?{x:(u.x-e.body.x)*a,y:(u.y-e.body.y)*a}:null}}}function Xt(e,t){const n="function"==typeof t.deadlineAccessor?t.deadlineAccessor(e):Be(e.datum,t.deadlineAccessor)??Be(e,t.deadlineAccessor);return Number.isFinite(Number(n))?Math.max(0,Number(n)):0}function Vt(e){const t=new Map;let n=0,i=0;function o(n){t.set(n.bodyId,n),i+=1,e.onStateChange?.({...n})}function r(e){const i=t.get(e);return!(!i||null!=i.completedAt||(o({...i,completedAt:n,state:"unhappy"===i.state?"resolved-unhappy":"resolved"}),0))}return{id:e.id??"service-level",continuous:!0,protect:e=>{const i=t.get(e);return!(!i||null!=i.completedAt||"unhappy"===i.state||(o({...i,state:"protected",protectedAt:n}),0))},complete:r,getCase:e=>t.get(e),tick:i=>{n=Math.max(n,i.elapsed);for(const s of i.controls.readBodies()){if(!Ce(s,e.bodyFilter))continue;if(!t.has(s.id)){const t=Xt(s,e);o({bodyId:s.id,openedAt:n,deadlineAt:n+t,state:"waiting"})}const a=t.get(s.id);a&&null==a.completedAt&&(e.completionRegionId&&i.getRegionState(s.id)?.activeRegionIds.includes(e.completionRegionId)?r(s.id):"waiting"!==a.state||a.deadlineAt>n||o({...a,state:"unhappy"}))}},getSnapshot:()=>{const e=Array.from(t.values()),o=t=>e.filter(e=>e.state===t).length;return{total:e.length,waiting:o("waiting"),protected:o("protected"),unhappy:o("unhappy"),resolved:o("resolved"),resolvedUnhappy:o("resolved-unhappy"),simulatedAt:n,metricRevision:i}}}}function _t(e){const t=new Set;let n=0,i=0,o=0,r=!1;return{id:e.id??"dependency-gate:"+e.regionId,continuous:!0,tick:s=>{n=Math.max(n,s.elapsed);const a=r;var c;c=n,r=e.isOpen?e.isOpen(c):null!=e.opensAt&&c>=e.opensAt;const l=s.controls.readBodies(),d=new Map(l.map(e=>[e.id,e]));for(const n of l){const i=s.getRegionState(n.id)?.activeRegionIds.includes(e.regionId);i&&Ce(n,e.bodyFilter)&&(r||t.has(n.id)||(t.add(n.id),o+=1,e.onHeld?.(n)))}if(r&&!a){for(const n of t){const t=d.get(n);t&&(s.controls.applyImpulse(n,e.releaseImpulse?.x??86,e.releaseImpulse?.y??0),i+=1,e.onReleased?.(t))}t.clear(),o+=1}for(const e of t)d.has(e)||(t.delete(e),o+=1)},getSnapshot:()=>({regionId:e.regionId,isOpen:r,blocked:t.size,released:i,simulatedAt:n,metricRevision:o}),bodyForce:n=>{if(r||!t.has(n.body.id))return null;const i=n.regions?.find(t=>t.id===e.regionId),o=i?.shape;if(!o||"aabb"!==o.type)return{x:.8*-n.body.vx,y:.8*-n.body.vy};const s=e.holdForce??.4;return{x:(o.x-n.body.x)*s-.45*n.body.vx,y:(o.y-n.body.y)*s-.45*n.body.vy}}}}function Kt(e,t){return e||t?{x:(e?.x??0)+(t?.x??0),y:(e?.y??0)+(t?.y??0)}:null}function Gt(e){if(!e?.length)return null;const t=e.slice(),n=t.some(e=>!1!==e.continuous);return{controllers:t,continuous:n,onTick:(e,n,i)=>{const o={result:e,controls:n,dt:i.dt,elapsed:i.elapsed,getRegionState:i.getRegionState};for(const e of t)e.tick(o)},bodyForce:e=>{let n=null;for(const i of t)i.bodyForce&&(n=Kt(n,i.bodyForce(e)));return n}}}function Ut(e){const t=new Set,n=e.impulse??{x:-60,y:0};return{id:e.id??"portal:"+e.fromRegionId,continuous:!0===e.continuous,tick:i=>{const o=i.controls.readBodies();for(const r of o){const o=i.getRegionState(r.id),s=o?.activeRegionIds.includes(e.fromRegionId);s?t.has(r.id)||(t.add(r.id),i.controls.applyImpulse(r.id,n.x??0,n.y??0),e.onPortal?.(r)):t.delete(r.id)}}}}function Qt(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function Zt(e,t){const n="sensor"===e.physics?t.sensorThickness:t.barrierThickness;return Math.max(0,Qt(e.thickness)??Qt(n)??Qt(t.thickness)??4)}function Jt(e=[],t={}){const n=t.idPrefix?t.idPrefix+"-":"",i=[];for(const o of e){if("barrier"!==o.physics&&"sensor"!==o.physics)continue;const e=o.axis??t.defaultAxis??"x",r=Zt(o,t),s=o.colliderId??`${n}${o.id}`;let a;if("x"===e){const e=Qt(o.x),n=Qt(o.y1)??Qt(t.plotBounds?.y)??Qt(o.y),i=Qt(o.y2)??(t.plotBounds?t.plotBounds.y+t.plotBounds.height:void 0)??Qt(o.y);if(null==e||null==n||null==i)continue;a={type:"segment",x1:e,y1:n,x2:e,y2:i,thickness:r}}else{const e=Qt(o.y),n=Qt(o.x1)??Qt(t.plotBounds?.x)??Qt(o.x),i=Qt(o.x2)??(t.plotBounds?t.plotBounds.x+t.plotBounds.width:void 0)??Qt(o.x);if(null==e||null==n||null==i)continue;a={type:"segment",x1:n,y1:e,x2:i,y2:e,thickness:r}}i.push({id:s,shape:a,sensor:"sensor"===o.physics,..."barrier"!==o.physics||null==o.restitution&&null==t.barrierRestitution?{}:{restitution:Qt(o.restitution)??Qt(t.barrierRestitution)},..."barrier"!==o.physics||null==o.friction&&null==t.barrierFriction?{}:{friction:Qt(o.friction)??Qt(t.barrierFriction)}})}return i}function en(e,t){if(0===e.length||0===t.length)return[];const n=new Map(t.map(e=>[e.id,e]));return e.flatMap(e=>{const t=n.get(e.bodyId);if(!t)return[];const i=e.dx??18,o=e.dy??-24;return[{...e,anchorX:t.x,anchorY:t.y,labelX:t.x+i,labelY:t.y+o,body:t}]})}function tn(e=[],t=[]){return{bodyCount:t.length,barrierCount:e.filter(e=>"barrier"===e.physics).length,sensorCount:e.filter(e=>"sensor"===e.physics).length,staticCount:e.length,totalCount:e.length+t.length}}import*as nn from"react";import{forwardRef as on,memo as rn,useCallback as sn,useEffect as an,useImperativeHandle as cn,useId as ln,useRef as dn}from"react";var un=2500;function hn(e){return"function"==typeof e}function pn(e){return void 0===e||!1===e||!hn(e.binAccessor)&&!hn(e.labelAccessor)&&!hn(e.valueAccessor)}function mn(e){if(void 0!==e){if(!1===e)return!1;if(!pn(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 fn(e){if(e)return{chartId:e.chartId,chartType:e.chartType,sensors:e.sensors}}function yn(e){return function(e){return!hn(e?.timeAccessor)}(e)}function gn(e={}){if(e.engine)throw new TypeError("Physics workers use the built-in kernel adapter");const{engine:t,observation:n,sediment:i,...o}=e;return{...o,observation:fn(n),sediment:mn(i)}}function bn(){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 vn=class{constructor(e=function(){const e="string"==typeof import.meta.url&&import.meta.url?new URL("./physicsWorker.js",import.meta.url):i("physicsWorker.js");return new Worker(e,{type:"module",name:"semiotic-physics"})}()){this.nextRequestId=1,this.pending=new Map,this.worker=e,this.worker.onmessage=e=>{const t=e.data,n=this.pending.get(t.requestId);n&&(this.pending.delete(t.requestId),n.cleanup(),t.ok?n.resolve(t.payload):n.reject(function(e){const t=Error(e.error.message);return t.name=e.error.name??"Error",e.error.stack&&(t.stack=e.error.stack),t}(t)))},this.worker.onerror=e=>{this.rejectAll(Error(e.message||"Physics worker failed")),this.worker.terminate()}}request(e,t){if(t?.aborted)return Promise.reject(bn());const n=this.nextRequestId;this.nextRequestId+=1;const i={command:e,requestId:n};return new Promise((e,o)=>{const r=()=>{this.pending.delete(n),t?.removeEventListener("abort",r),o(bn())},s=()=>t?.removeEventListener("abort",r);this.pending.set(n,{cleanup:s,reject:o,resolve:e}),t?.addEventListener("abort",r,{once:!0});try{this.worker.postMessage(i)}catch(e){this.pending.delete(n),s(),o(e)}})}async init(e,t,n,i){if(!yn(n))throw new TypeError("Physics worker spawn pacing only supports string time accessors");const o=await this.request({type:"init",config:gn(e),initialSpawns:t,initialSpawnPacing:n},i);if("frame"!==o.type)throw Error("Physics worker returned a non-frame init response");return o.frame}async restore(e,t){const n=await this.request({type:"restore",snapshot:e},t);if("frame"!==n.type)throw Error("Physics worker returned a non-frame restore response");return n.frame}async initFromSnapshot(e,t,n){const i=await this.request({type:"init",config:gn(e),snapshot:t},n);if("frame"!==i.type)throw Error("Physics worker returned a non-frame init response");return i.frame}async enqueue(e,t,n){if(!yn(t))throw new TypeError("Physics worker spawn pacing only supports string time accessors");const i=await this.request({type:"enqueue",spawns:e,pacing:t},n);if("frame"!==i.type)throw Error("Physics worker returned a non-frame enqueue response");return i.frame}async tick(e,t){const n=await this.request({type:"tick",deltaSeconds:e},t);if("frame"!==n.type)throw Error("Physics worker returned a non-frame tick response");return n.frame}async settle(e,t){const n=await this.request({type:"settle",maxSteps:e},t);if("frame"!==n.type)throw Error("Physics worker returned a non-frame settle response");return n.frame}async snapshot(e){const t=await this.request({type:"snapshot"},e);if("snapshot"!==t.type)throw Error("Physics worker returned a non-snapshot response");return t.snapshot}async remove(e,t){const n=await this.request({type:"remove",ids:e},t);if("removed"!==n.type)throw Error("Physics worker returned a non-remove response");return{frame:n.frame,removed:n.removed}}terminate(){this.rejectAll(Error("Physics worker terminated")),this.worker.terminate()}rejectAll(e){for(const[t,n]of this.pending)this.pending.delete(t),n.cleanup(),n.reject(e)}};function xn(e,t,n){const i=new It(e);return t?.length&&(i.enqueue(t,n),i.materializeDueSpawns()),i}function wn(){return"undefined"!=typeof performance?performance.now():Date.now()}import{useEffect as Sn,useRef as kn}from"react";function Mn(){return"undefined"==typeof document||!document.hidden}function In(e,t,n){const i=y(e,n.fill)??"#4e79a7",o=y(e,n.stroke),r="none"!==o?o:void 0,s=n.strokeWidth??0,a=n.opacity??1,c=n.fillOpacity??1,l=function(e,t){const n=t.mark;if(n)return n;const i=e.datum,o=i?.__physicsMark??i?.mark;return"circle"===o||"halo"===o||"faceted"===o||"pill"===o||"diamond"===o||"square"===o?o:"circle"===e.shape.type?"circle":"square"}(t,n),d="circle"===t.shape.type?n.r??t.shape.radius:Math.max(t.shape.width,t.shape.height)/2;if(e.save(),e.globalAlpha*=a,e.beginPath(),"pill"===l||"square"===l||"aabb"===t.shape.type){const n="pill"===l?2.4*d:"aabb"===t.shape.type?t.shape.width:1.7*d,i="pill"===l?1.35*d:"aabb"===t.shape.type?t.shape.height:1.7*d,o=t.x-n/2,r=t.y-i/2,s="pill"===l?i/2:Math.min(4,n/4);e.moveTo(o+s,r),e.arcTo(o+n,r,o+n,r+i,s),e.arcTo(o+n,r+i,o,r+i,s),e.arcTo(o,r+i,o,r,s),e.arcTo(o,r,o+n,r,s),e.closePath()}else if("diamond"===l)e.moveTo(t.x,t.y-d),e.lineTo(t.x+d,t.y),e.lineTo(t.x,t.y+d),e.lineTo(t.x-d,t.y),e.closePath();else if("faceted"===l){const n=6;for(let i=0;n>i;i+=1){const o=2*Math.PI*i/n-Math.PI/2,r=t.x+Math.cos(o)*d,s=t.y+Math.sin(o)*d;0===i?e.moveTo(r,s):e.lineTo(r,s)}e.closePath()}else e.arc(t.x,t.y,d,0,2*Math.PI);i&&(e.save(),e.globalAlpha*=c,e.fillStyle=i,e.fill(),e.restore()),"halo"===l&&(e.beginPath(),e.arc(t.x,t.y,1.35*d,0,2*Math.PI),e.strokeStyle=r??i,e.lineWidth=Math.max(1.5,s||1.5),e.globalAlpha*=.55,e.stroke(),e.globalAlpha/=.55),r&&s>0&&(e.strokeStyle=r,e.lineWidth=s,n.strokeDasharray&&e.setLineDash(n.strokeDasharray.split(/[,\s]+/).map(e=>Number(e)).filter(e=>Number.isFinite(e))),e.stroke()),e.restore()}function An(e){return"circle"===e.shape.type?e.shape.radius:Math.max(e.shape.width,e.shape.height)/2}function Bn(e){return e.sensorId??"stream-region-"+e.id}function Rn(e){const t=Bn(e),n={bodyFilter:e.bodyFilter,friction:e.friction,restitution:e.restitution};if("boundary"===e.collider&&"aabb"===e.shape.type){const i=e.colliderThickness??8,o=e.shape.x-e.shape.width/2,r=e.shape.x+e.shape.width/2,s=e.shape.y-e.shape.height/2,a=e.shape.y+e.shape.height/2;return[{...n,id:t+"-top",shape:{type:"segment",x1:o,y1:s,x2:r,y2:s,thickness:i}},{...n,id:t+"-right",shape:{type:"segment",x1:r,y1:s,x2:r,y2:a,thickness:i}},{...n,id:t+"-bottom",shape:{type:"segment",x1:r,y1:a,x2:o,y2:a,thickness:i}},{...n,id:t+"-left",shape:{type:"segment",x1:o,y1:a,x2:o,y2:s,thickness:i}}]}return e.collider?[{...n,id:t+"-collider",shape:e.shape}]:[]}function Cn(e){if(e)return{activeRegionIds:Array.from(e.activeRegionIds),regionIds:Array.from(e.regionIds),charges:{...e.charges},attributes:{...e.attributes},energy:e.energy}}function Pn(e,t){const n="function"==typeof e?e(t):e;if(!n)return null;const i=Number(n.x??0),o=Number(n.y??0);return Number.isFinite(i)||Number.isFinite(o)?{x:Number.isFinite(i)?i:0,y:Number.isFinite(o)?o:0}:null}function Tn(e){if(!1===e.semanticItem)return null;const t=e.shape,n=e.semanticItem??{},i="aabb"===t.type?{id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"region",x:t.x,y:t.y,width:t.width,height:t.height}:{id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"region",x:(t.x1+t.x2)/2,y:(t.y1+t.y2)/2,pathData:`M ${t.x1} ${t.y1} L ${t.x2} ${t.y2}`};return{...i,...n,id:n.id??i.id}}function qn(e){return e.some(e=>null!=e.force||null!=e.damping||null!=e.impulseOnEnter||null!=e.impulseOnExit)}function On(e,t){const n="function"==typeof e?e(t):e;if(!n)return null;const i=Number(n.x??0),o=Number(n.y??0);return Number.isFinite(i)||Number.isFinite(o)?{x:Number.isFinite(i)?i:0,y:Number.isFinite(o)?o:0}:null}var En=[];function Fn(e){const t=e.store.controls(),n=e.store.snapshot(),i=Math.max(0,e.result.steps*(n.config.fixedDt||1/60)),o=function(e,t,n,i){const o=Number.isFinite(i)?Math.max(0,i):0;if(0>=o||!qn(t))return!1;const r=new Map(t.map(e=>[e.id,e])),s=e.readBodies();let a=!1;for(const t of s){const i=n.get(t.id);if(!i||!i.activeRegionIds.size)continue;const s=Cn(i);if(s)for(const n of i.activeRegionIds){const i=r.get(n);if(!i)continue;const c=Pn(i.force,{body:t,region:i,regionState:s}),l=Number(i.damping??0),d=(c?.x??0)*o-(Number.isFinite(l)?t.vx*l*o:0),u=(c?.y??0)*o-(Number.isFinite(l)?t.vy*l*o:0);(d||u)&&(e.applyImpulse(t.id,d,u),a=!0)}}return a}(t,e.regionEffects,e.regionState,i),r=function(e,t,n,i,o,r){const s=Number.isFinite(r)?Math.max(0,r):0;if(0>=s||!t)return!1;const a=new Map(n.map(e=>[e.id,e])),c=e.readBodies();let l=!1;for(let n=0;c.length>n;n+=1){const r=c[n],d=i.get(r.id),u=Cn(d);let h=En;if(d&&d.activeRegionIds.size>0){const e=[];for(const t of d.activeRegionIds){const n=a.get(t);n&&e.push(n)}h=e}const p=On(t,{body:r,bodies:c,index:n,regionState:u,regions:h,simulationState:o});if(!p)continue;const m=(p.x??0)*s,f=(p.y??0)*s;(m||f)&&(e.applyImpulse(r.id,m,f),l=!0)}return l}(t,e.bodyForces,e.regionEffects,e.regionState,n.simulationState,i);return e.composed&&e.composed.onTick(e.result,t,{dt:i,elapsed:e.result.elapsedSeconds,getRegionState:t=>Cn(e.regionState.get(t))}),e.onTick?.(e.result,t),{regionEffectsApplied:o,bodyForcesApplied:r,snapshot:n}}function Dn(e,t,n,i,o,r,s,a,c,l){const d=function(e,t){return!!t?.isActive&&(t.predicate?.(e)??!0)}(e,o),u={selected:d,simulationState:t,regionState:r,regions:s},h="function"==typeof n?n(e,u):n,p=s.reduce((t,n)=>n.bodyStyle?{...t,..."function"==typeof n.bodyStyle?n.bodyStyle(e,u):n.bodyStyle}:t,{}),m=d?"function"==typeof i?i(e,u):i:void 0;return{fill:l?.color??a,stroke:l?.stroke??c,strokeWidth:l?.strokeWidth??1,opacity:l?.opacity??.9,...h,...p,...m}}import{useCallback as jn}from"react";import*as Nn from"react";import{jsx as zn,jsxs as Wn}from"react/jsx-runtime";var $n={border:0,clip:"rect(0 0 0 0)",height:1,margin:-1,overflow:"hidden",padding:0,position:"absolute",whiteSpace:"nowrap",width:1},Ln="semiotic-accessible-data-table",Hn=Ln+" semiotic-accessible-data-table-hidden",Yn=Ln+" semiotic-accessible-data-table-visible",Xn={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"},Vn={marginBottom:8,paddingRight:28,color:"var(--semiotic-data-table-muted-text, var(--semiotic-text-secondary, #666))",fontSize:12,letterSpacing:"0.01em"},_n={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)"},Kn={width:"100%",borderCollapse:"collapse",fontSize:12,marginTop:4,fontVariantNumeric:"tabular-nums"},Gn={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))"},Un={padding:"4px 10px",borderBottom:"1px solid var(--semiotic-data-table-border, var(--semiotic-border, #e0e0e0))"},Qn={textAlign:"left",fontSize:11,color:"var(--semiotic-data-table-muted-text, var(--semiotic-text-secondary, #666))",marginBottom:4,fontStyle:"italic"},Zn={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 Jn(e){return null==e?null:"string"==typeof e||"number"==typeof e||"boolean"==typeof e?e+"":null}function ei(e){return{__semioticHoverData:!0,body:e,data:e.datum??e,id:e.id,type:"body",x:e.x,y:e.y}}function ti(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 ni(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 ii(e){const t=oi(e.datum??e);return t.length?t.map(([e,t])=>`${e}: ${t}`).join(", "):"Physics body "+e.id}function oi(e){return e&&"object"==typeof e?Object.entries(e).map(([e,t])=>{if(e.startsWith("_"))return null;const n=Jn(t);return null==n?null:[e,n]}).filter(e=>null!=e).slice(0,8):[]}function ri({hover:e}){const t=oi(e.data);return Wn("div",{className:"semiotic-tooltip",style:b,children:[zn("div",{style:{fontWeight:700,marginBottom:t.length?4:0},children:e.id}),t.map(([e,t])=>Wn("div",{children:[Wn("span",{style:{opacity:.72},children:[e,": "]}),zn("span",{children:t})]},e))]})}function si(e){return e.datum&&"object"==typeof e.datum?Object.entries(e.datum).map(([e,t])=>{const n=Jn(t);return null==n?null:`${e}: ${n}`}).filter(e=>null!=e).slice(0,8).join(", "):""}function ai(e){const t=[`${e.length} semantic item${1===e.length?"":"s"}.`],n=new Map;for(const t of e)t.group&&n.set(t.group,(n.get(t.group)??0)+1);return n.size&&t.push(Array.from(n).map(([e,t])=>`${e}: ${t}`).join(", ")),t.join(" ")}function ci(e){const{chartTitle:t,items:n,tableId:i}=e,[o,r]=Nn.useState(!1),[s,a]=Nn.useState(5),c=q(),l=c?.visible??!1,d=o||l,u=Nn.useRef(null),h="Data summary for "+(t??"physics chart");Nn.useEffect(()=>{d||a(5)},[d]);const p=Nn.useCallback(e=>{e.target===e.currentTarget&&(o||l||r(!0))},[o,l]),m=Nn.useCallback(e=>{l||u.current?.contains(e.relatedTarget)||r(!1)},[l]);if(!n.length)return zn("span",{id:i,tabIndex:-1,style:$n});if(!d)return zn("div",{id:i,className:Hn,role:"region","aria-label":h,tabIndex:-1,style:$n,onFocus:p,children:Wn("button",{type:"button",onClick:()=>r(!0),children:["View data summary (",n.length," semantic items)"]})});const f=Math.min(s,n.length),y=n.slice(0,f),g=n.length-f;return Wn("div",{ref:u,id:i,className:Yn,role:"region","aria-label":h,tabIndex:-1,onBlur:m,style:Xn,children:[zn("button",{type:"button",className:"semiotic-accessible-data-table-close","aria-label":"Close data summary",onClick:()=>{l&&c&&c.setVisible(!1),r(!1)},style:_n,children:"×"}),zn("div",{className:"semiotic-accessible-data-table-summary",role:"note",style:Vn,children:ai(n)}),Wn("table",{className:"semiotic-accessible-data-table-table",role:"table","aria-label":"Semantic items for "+(t??"physics chart"),style:Kn,children:[zn("caption",{className:"semiotic-accessible-data-table-caption",style:Qn,children:g>0?`First ${f} of ${n.length} semantic items`:`All ${n.length} semantic items`}),zn("thead",{children:Wn("tr",{children:[zn("th",{scope:"col",style:Gn,children:"Item"}),zn("th",{scope:"col",style:Gn,children:"Description"}),zn("th",{scope:"col",style:Gn,children:"Group"}),zn("th",{scope:"col",style:Gn,children:"Position"}),zn("th",{scope:"col",style:Gn,children:"Data"})]})}),zn("tbody",{children:y.map((e,t)=>Wn("tr",{children:[zn("th",{scope:"row",style:Un,children:e.label}),zn("td",{style:Un,children:e.description??e.label}),zn("td",{style:Un,children:e.group??""}),Wn("td",{style:Un,children:[Math.round(e.x),", ",Math.round(e.y)]}),zn("td",{style:Un,children:si(e)})]},e.id??`${e.label}-${t}`))})]}),g>0?Wn("button",{type:"button",className:"semiotic-accessible-data-table-show-more",onClick:()=>a(e=>e+25),style:Zn,children:["Show ",Math.min(25,g)," more"," ",1===g?"row":"rows"," (",g," remaining)"]}):null]})}ri.ownsChrome=!0;import{jsx as li,jsxs as di}from"react/jsx-runtime";var ui=[640,360],hi={top:0,right:0,bottom:0,left:0},pi=new Set(["ArrowRight","ArrowLeft","ArrowUp","ArrowDown","Home","End","PageUp","PageDown"]),mi="StreamPhysicsFrame",fi=rn(on(function(e,t){const{accessibleTable:n=!0,annotations:i,onAnnotationActivate:o,autoPlaceAnnotations:r,background:s,backgroundGraphics:m,maxDevicePixelRatio:f,bodySemanticItemLimit:y=200,bodySemanticItems:g=!1,bodySemanticUpdateMs:b=200,bodyForces:v,bodyStyle:k,chartId:I,className:A,frameScheduler:B,clock:R,random:C,seed:P,color:T,config:q,controllers:D,continuous:j=!1,description:N,emphasis:z,chartMode:W,enableHover:$=!0,foregroundGraphics:L,hoverRadius:X=16,initialSpawns:V,initialSpawnPacing:_,legend:K,legendClickBehavior:U,legendHighlightedCategory:Q,legendHoverBehavior:Z,legendIsolatedCategories:J,legendLayout:ee,legendPosition:te,margin:ie,onClick:oe,onObservation:se,onRegionEvent:ae,onSimulationExecutionChange:ce,onBodyHover:le,onBodyPointerDown:de,onSemanticItemActivate:ue,onSemanticItemFocus:he,onTick:pe,opacity:me,paused:fe=!1,regionEffects:ye=[],responsiveHeight:ge,responsiveWidth:be,selectedBodyStyle:ve={stroke:"#111827",strokeWidth:2,opacity:1},selection:xe,semanticItems:we=[],simulationExecution:Se="auto",size:ke=ui,stroke:Me,strokeWidth:Ie,summary:Ae,suspendWhenHidden:Be=!0,svgAnnotationRules:Re,title:Ce,tooltipContent:Pe,workerBodyThreshold:Te=un,renderBody:qe,beforePaint:Oe,afterPaint:Ee}=e,Fe=nn.useMemo(()=>({color:T,stroke:Me,strokeWidth:Ie,opacity:me}),[T,me,Me,Ie]),De=dn(se);De.current=se;const je=dn(I);je.current=I;const Ne=dn(new Map),ze=dn(ye);ze.current=ye;const We=dn(v),$e=dn(pe);$e.current=pe;const Le=nn.useMemo(()=>Gt(D),[D]),He=dn(Le);He.current=Le;const Ye=j||!!Le?.continuous,Xe=dn(Ye);Xe.current=Ye;const Ve=nn.useMemo(()=>{if(!v&&!Le?.bodyForce)return v;if(!Le?.bodyForce)return v;if(!v)return Le.bodyForce;const e=Le.bodyForce;return t=>{const n="function"==typeof v?v(t):v,i="function"==typeof e?e(t):e;return n||i?{x:(n?.x??0)+(i?.x??0),y:(n?.y??0)+(i?.y??0)}:null}},[v,Le]);We.current=Ve;const _e=nn.useMemo(()=>new Map(ye.map(e=>[Bn(e),e])),[ye]),Ke=nn.useMemo(()=>new Map(ye.map(e=>[e.id,e])),[ye]),Ge=nn.useMemo(()=>ye.map(Tn).filter(e=>null!=e),[ye]),[Ue,Qe]=nn.useState([]),Ze=nn.useMemo(()=>Ue.length||Ge.length?[...we,...Ue,...Ge]:we,[Ue,Ge,we]),Je=nn.useMemo(()=>qn(ye),[ye]),et=!!Ve,tt=dn(null),nt=dn(R??wn);nt.current=R??wn;const it=sn((e,t,n)=>{const i=tt.current;if(!i||!n)return!1;const o=i.readBodies().find(t=>t.id===e),r=Cn(Ne.current.get(e));if(!o||!r)return!1;const s=Pn(n,{body:o,region:t,regionState:r});return!(!s||!s.x&&!s.y||(i.applyImpulse(e,s.x??0,s.y??0),0))},[]),ot=sn((e,t,n)=>{if(!n.bodyId)return;const i=Cn(Ne.current.get(n.bodyId));if(!i)return;const o={bodyId:n.bodyId,datum:n.datum,observation:n,region:t,regionState:i,type:e};"region-enter"===e?t.onEnter?.(o):t.onExit?.(o),ae?.(o)},[ae]),rt=sn(e=>{const t=e.sensorId?_e.get(e.sensorId):void 0;if(!t||!e.bodyId)return;const n=function(e,t){let n=e.get(t);return n||(n={activeRegionIds:new Set,attributes:{},charges:{},energy:0,regionIds:new Set},e.set(t,n)),n}(Ne.current,e.bodyId),i=tt.current?.readBodies().find(t=>t.id===e.bodyId),o=Cn(n),r=i&&o?{body:i,region:t,regionState:o}:null;if("physics-proximity-enter"===e.type){if(n.activeRegionIds.add(t.id),n.regionIds.add(t.id),n.energy+=t.energyDelta??0,r){!function(e,t,n){const i="function"==typeof e.attributes?e.attributes(t):e.attributes;i&&(n.attributes={...n.attributes,...i})}(t,r,n);const e=function(e,t){return void 0!==e.charge?"function"==typeof e.charge?e.charge(t):e.charge:"charge-gate"===e.kind?1:void 0}(t,r);void 0!==e&&(n.charges[t.id]=e)}it(e.bodyId,t,t.impulseOnEnter),ot("region-enter",t,e)}else"physics-proximity-exit"===e.type&&(n.activeRegionIds.delete(t.id),it(e.bodyId,t,t.impulseOnExit),ot("region-exit",t,e))},[it,ot,_e]),st=nn.useMemo(()=>function({annotations:e,chartId:t,chartType:n,config:i,onRegionObservation:o,regionEffects:r,seed:s,size:a}){const c=Jt((e??[]).filter(e=>"barrier"===e.physics||"sensor"===e.physics),{idPrefix:t?t+"-ann":"physics-ann",plotBounds:{x:0,y:0,width:a[0],height:a[1]}}),l=void 0===s||void 0!==i?.kernel?.seed?i:{...i,kernel:{...i?.kernel,seed:s}},d=r.flatMap(e=>[{id:Bn(e),sensor:!0,shape:e.shape,bodyFilter:e.bodyFilter,friction:e.friction,restitution:e.restitution},...Rn(e)]),u=Object.fromEntries(r.map(e=>[Bn(e),{binId:e.binId??e.id,enterType:"physics-proximity-enter",exitType:"physics-proximity-exit"}])),h=l?.observation,p=r.length>0;return p||d.length>0||c.length>0||null!=t||h?{...l,colliders:[...l?.colliders??[],...d,...c],observation:{...h,chartId:t??h?.chartId,chartType:h?.chartType??n,sensors:{...h?.sensors??{},...u},onObservation:e=>{p&&o(e),h?.onObservation?.(e)}}}:l}({annotations:i,chartId:I,chartType:mi,config:q,onRegionObservation:rt,regionEffects:ye,seed:P,size:ke}),[i,I,q,rt,ye,P,ke]);if(!tt.current){const e=xn(st,V,_);e.setPaused(fe),Be&&e.setVisible(Mn()),tt.current=e}const at=dn(-1),ct=dn(null),lt=dn(!0),dt=F("StreamPhysicsFrame"),ut=dn(""),ht=ln().replace(/:/g,""),pt=dn(!1),mt=dn(!1),ft=dn(0),yt=dn(!1),gt=dn(!1),bt=dn(null),vt=dn(!1),xt=O({sizeProp:ke,responsiveWidth:be,responsiveHeight:ge,userMargin:ie,marginDefault:hi,foregroundGraphics:L,backgroundGraphics:m,frameScheduler:B,clock:R,random:C,seed:P,paused:fe,suspendWhenHidden:Be}),{margin:wt,rafRef:St,reducedMotion:kt,reducedMotionRef:Mt,renderFnRef:It,cancelRender:At,resolvedBackground:Bt,resolvedForeground:Rt,responsiveRef:Ct,scheduleRender:Pt,size:Tt,frameRuntime:qt}=xt,Ot=dn(qt.now);Ot.current=qt.now;const Et=H(),Ft=Y(),[Dt,jt]=nn.useState(null),[Nt,Wt]=nn.useState(null),$t=dn(null),Lt=dn(0),Ht=dn(new Map),Yt=ht+"-physics-live",Xt=sn((e,t,n=!1)=>{if(!g)return void Qe(e=>e.length?[]:e);const i=Ot.current();if(!n&&b>0&&b>i-Lt.current)return;Lt.current=i;const o=function(e,t,n,i){if(!n)return[];const o=Math.max(0,Math.floor(i));if(!o)return[];const r=[];for(let i=0;e.length>i&&o>r.length;i+=1){const o=e[i],s="function"==typeof n?n(o,{index:i,simulationState:t}):void 0;if(!1===s)continue;const a=ti(o);r.push({datum:o.datum??o,description:ii(o),group:"body",label:ni(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,g,y);Qe(e=>function(e,t){if(e.length!==t.length)return!0;for(let n=0;e.length>n;n+=1){const i=e[n],o=t[n];if(i.id!==o.id||i.label!==o.label||i.description!==o.description||i.group!==o.group||i.bodyId!==o.bodyId||Math.round(i.x)!==Math.round(o.x)||Math.round(i.y)!==Math.round(o.y))return!0}return!1}(e,o)?o:e)},[y,g,b]),Vt=sn(e=>{if(!Ze.length)return;const t=Math.max(0,Math.min(e,Ze.length-1));at.current=t;const n=Ze[t];if($t.current=n.bodyId??null,jt(n),he?.(n),n.bodyId&&tt.current){const e=tt.current.readBodies().find(e=>e.id===n.bodyId);if(e){const t=ei(e);Wt(t),le?.(e,t)}}},[Ze,le,he]),_t=sn(()=>{at.current=-1,$t.current=null,jt(null),he?.(null)},[he]),Kt=function({onObservationRef:e,chartIdRef:t,wallClockRef:n}){return jn((i,o)=>{const r=e.current;if(!r)return;const s={timestamp:n.current(),chartType:"StreamPhysicsFrame",chartId:t.current};r("hover"===i||"click"===i?{...s,type:i,datum:o?.datum??{},x:o?.x??0,y:o?.y??0}:"focus"===i?{...s,type:i,datum:o?.datum??{},inputType:"touch"===o?.inputType?"pointer":o?.inputType??"keyboard"}:"activate"===i?{...s,type:i,datum:o?.datum??{},inputType:o?.inputType??"keyboard"}:{...s,type:i})},[t,e,n])}({onObservationRef:De,chartIdRef:je,wallClockRef:nt}),Ut=sn(()=>{Wt(e=>e?(le?.(null,null),Kt("hover-end"),null):e)},[Kt,le]),Qt=sn(e=>{if(!$||!tt.current)return;const t=e.currentTarget.getBoundingClientRect(),n=tt.current.hitTest(e.clientX-t.left,e.clientY-t.top,X);if(!n)return void Ut();const i=ei(n);Wt(e=>e&&e.id===i.id&&e.x===i.x&&e.y===i.y?e:(le?.(n,i),Kt("hover",{datum:n.datum,x:n.x,y:n.y}),i))},[Ut,Kt,$,X,le]),Zt=sn(e=>{_t();const t=tt.current,n=e.currentTarget.getBoundingClientRect(),i=e.clientX-n.left,o=e.clientY-n.top,r=t?t.hitTest(i,o,Math.max(16,X)):null;de?.(r,e),r?(Kt("click",{datum:r.datum,x:r.x,y:r.y}),Kt("activate",{datum:r.datum,inputType:"touch"===e.pointerType?"touch":"pointer"}),oe?.(r.datum??null,{x:r.x,y:r.y,body:r})):(Kt("click-end"),oe?.(null,{x:i,y:o,body:null}),Ut())},[Ut,_t,Kt,X,de,oe]);an(()=>{if(!Ze.length)return void _t();const e=at.current;if(Ze.length>e){if(e>=0){const t=Ze[e];if($t.current=t.bodyId??null,jt(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&&tt.current){const e=tt.current.readBodies().find(e=>e.id===t.bodyId);if(e){const t=ei(e);Wt(e=>e?.id===t.id&&Math.round(e.x)===Math.round(t.x)&&Math.round(e.y)===Math.round(t.y)?e:t)}}}}else Vt(Ze.length-1)},[Ze,_t,Vt]),an(()=>{$||Ut()},[Ut,$]);const en=sn(e=>{if(w(e))return;if(!Ze.length)return;if("Escape"===e.key)return e.preventDefault(),void _t();if(("Enter"===e.key||" "===e.key)&&at.current>=0){e.preventDefault();const t=Ze[at.current];return Kt("activate",{datum:t.datum??{id:t.id,label:t.label},inputType:"keyboard"}),void ue?.(t)}if(!pi.has(e.key))return;e.preventDefault();const t=at.current;if(0>t){Vt(0);const e=Ze[0];return void Kt("focus",{datum:e.datum??{id:e.id,label:e.label},inputType:"keyboard"})}const n=Math.max(1,Math.floor(.1*Ze.length));let i=t;if("Home"===e.key?i=0:"End"===e.key?i=Ze.length-1:"PageDown"===e.key?i=Math.min(Ze.length-1,t+n):"PageUp"===e.key?i=Math.max(0,t-n):"ArrowRight"===e.key||"ArrowDown"===e.key?i=Math.min(Ze.length-1,t+1):"ArrowLeft"!==e.key&&"ArrowUp"!==e.key||(i=Math.max(0,t-1)),Vt(i),i!==t){const e=Ze[i];Kt("focus",{datum:e.datum??{id:e.id,label:e.label},inputType:"keyboard"})}},[_t,Kt,Vt,ue,Ze]),[tn,on]=nn.useState([]),rn=dn(0),hn=!!i?.length&&i.some(e=>null!=e.pointId||null!=e.bodyId||"latest"===e.anchor),{canvasRef:mn,resolutionDirtyRef:fn}=E(xt,{hydrated:Et,wasHydratingFromSSR:Ft,storeRef:tt,dirtyRef:lt,manageFrameRuntime:!1,skipInitialCanvasPaintInvalidation:!0,maxDevicePixelRatio:f,canvasPaintDependencies:[s,m,Pt]}),gn=sn(()=>{const e=mn.current,t=tt.current;if(!e||!t)return;const n=dt.current.beforeCompute(t.getLastUpdateResult(),!1);fn.current=!1;const i=x(f),o=M(e,Tt,wt,i);if(!o)return void dt.current.afterCompute(n,!1,!1);const r=G(o);o.clearRect(-wt.left,-wt.top,Tt[0],Tt[1]),m||"transparent"===s||(o.fillStyle=s??r.background,o.fillRect(-wt.left,-wt.top,Tt[0],Tt[1]));const a=t.snapshot(),c=t.readBodies();if(Xt(c,a.simulationState),hn){const e=Ot.current();if(e-rn.current>=100){rn.current=e;const t=ne(c);on(e=>e.length===t.length&&e.every((e,n)=>e.pointId===t[n].pointId&&Math.round(e.x)===Math.round(t[n].x)&&Math.round(e.y)===Math.round(t[n].y))?e:t)}}Oe&&(o.save(),Oe(o,c),o.restore());for(const e of c){const t=Ne.current.get(e.id),n=t?Array.from(t.activeRegionIds).map(e=>Ke.get(e)).filter(e=>null!=e):[],i=Dn(e,a.simulationState,k,ve,xe,Cn(t),n,r.primary,r.text,Fe);qe?(o.save(),qe(o,e,i),o.restore()):In(o,e,i)}Ee&&(o.save(),Ee(o,c),o.restore()),function(e,t,n){let i=!1;for(const[o,r]of t){const s=Math.min(1,Math.max(0,(n-r.startedAt)/r.durationMs));if(s>=1){t.delete(o);continue}i=!0;const a=1-Math.pow(1-s,3),{body:c}=r,l=r.scale>0?r.scale:1,d=(r.radius+28*a)*l,u=1-s;e.save(),e.globalAlpha*=u,e.strokeStyle=r.color,e.fillStyle=r.color,e.lineWidth=Math.max(.5,(2.4*u+.4)*l),e.beginPath(),e.arc(c.x,c.y,d,0,2*Math.PI),e.stroke(),e.globalAlpha*=.18,e.beginPath(),e.arc(c.x,c.y,.52*d,0,2*Math.PI),e.fill(),e.restore(),e.save(),e.globalAlpha*=u,e.strokeStyle=r.color,e.lineWidth=Math.max(.5,1.8*l);for(let t=0;8>t;t+=1){const n=t*(Math.PI/4)+1.4*s,i=(r.radius+5+12*a)*l,o=(r.radius+12+34*a)*l;e.beginPath(),e.moveTo(c.x+Math.cos(n)*i,c.y+Math.sin(n)*i),e.lineTo(c.x+Math.cos(n)*o,c.y+Math.sin(n)*o),e.stroke()}e.restore()}}(o,Ht.current,Ot.current()),dt.current.afterCompute(n,!0,!1),lt.current=!1},[mn,fn,dt,Tt,wt,m,s,f,Xt,hn,Oe,Ee,k,ve,xe,Fe,qe,Ke]),bn=sn((e,t)=>{const n=tt.current,i=`${Se}:${e}:${t??""}`;ut.current!==i&&(ut.current=i,ce?.({execution:e,liveBodies:n?.liveBodyCount()??0,queuedBodies:n?.queueSize()??0,reason:t,requested:Se}))},[ce,Se]),On=sn((e,t=!0)=>{ft.current+=1,pt.current=!1,yt.current=!1,gt.current=!1,vt.current=!1,bt.current?.terminate(),bt.current=null,t&&bn("sync",e)},[bn]),En=sn(()=>Et?"undefined"==typeof window||"undefined"==typeof Worker?"worker unavailable":Je?"runtime region effects require sync":et?"body forces require sync":Le?"physics controllers require sync":function(e){return!e||!e.engine&&pn(e.sediment)&&(!(t=e.colliders)||t.every(e=>{const t=e.bodyFilter;return!t||"function"!=typeof t}));var t}(st??{})?yn(_)?mt.current?"worker fallback":null:"spawn pacing is not worker-cloneable":"config is not worker-cloneable":"hydrating",[st,Le,et,Je,Et,_]),Nn=sn(()=>{const e=tt.current,t=En();if(!e||t)return{reason:t,useWorker:!1};const n=e.liveBodyCount(),i=e.queueSize(),o=function(e,t,n=0,i=un){return"sync"!==e&&("worker"===e||t+n>=i)}(Se,n,i,Te);return{reason:o?"worker"===Se?"forced worker":"body threshold":"below threshold",useWorker:o}},[Se,Te,En]),zn=sn(e=>{const t=tt.current;return t&&e.snapshot?(t.restore(e.snapshot),lt.current=!0,t):t},[]),Wn=sn((e,t=!0)=>{const n=zn(e);if(!n)return;t&&pe?.(e.result,n.controls()),gn();const i=n.snapshot();!e.result.shouldContinue&&Ht.current.size<=0||i.paused||!i.visible||Mt.current||Pt()},[zn,pe,gn,Mt,Pt]),Ln=sn(e=>{mt.current=!0,On("worker failed: "+((e instanceof Error?e.message:e+"")||"unknown error"))},[On]),Hn=sn(()=>{const e=tt.current;if(!e)return!1;const t=Nn();if(!t.useWorker)return pt.current||vt.current?On(t.reason??"sync fallback"):bn("sync",t.reason??"sync"),!1;if(pt.current||vt.current)return!0;const n=bt.current??new vn;bt.current=n,vt.current=!0;const i=ft.current+1;return ft.current=i,n.initFromSnapshot(st??{},e.snapshot()).then(e=>{if(ft.current!==i)return;vt.current=!1,pt.current=!0,mt.current=!1,zn(e),bn("worker",t.reason??"worker"),gn();const n=tt.current?.snapshot();e.result.shouldContinue&&n&&!n.paused&&n.visible&&!Mt.current&&(ct.current=null,Pt())}).catch(e=>{ft.current===i&&Ln(e)}),!0},[zn,st,Ln,gn,Mt,bn,Pt,On,Nn]),Yn=sn(e=>"frame"===e.type||"removed"===e.type?e.frame:null,[]),Xn=sn((e,t=!0)=>{const n=bt.current;if(!n||!pt.current)return;const i=ft.current;n.request(e).then(e=>{if(ft.current!==i)return;const n=Yn(e);n&&Wn(n,t)}).catch(Ln)},[Wn,Yn,Ln]),Vn=sn(()=>{const e=tt.current;if(!e)return;const t=Hn(),n=e.snapshot(),i=Ye||et||Je||!!Le;n.paused||!n.visible||!e.hasPendingWork()&&!i||Mt.current?It.current():t&&vt.current||Pt()},[Le,Ye,et,Je,Mt,It,Pt,Hn]),_n=sn(()=>{At(),St.current=null;const e=tt.current;if(!e)return;const t=Mt.current;if(t&&(ct.current=null),pt.current&&bt.current){if(yt.current)return void(gt.current=!0);let n=0;if(!t){const e=Ot.current();n=null!==ct.current?(e-ct.current)/1e3:0,ct.current=e}const i=bt.current,o=ft.current;return yt.current=!0,void(t?i.settle():i.tick(n)).then(e=>{yt.current=!1;const t=gt.current;gt.current=!1,ft.current===o&&(Wn(e),t&&Vn())}).catch(i=>{yt.current=!1;const r=gt.current;if(gt.current=!1,ft.current!==o)return;Ln(i);const s=t?e.settleWithObservations():e.tick(n);Fn({store:e,result:s,regionEffects:ze.current,regionState:Ne.current,bodyForces:We.current,composed:He.current,onTick:$e.current}),gn(),r&&Vn()})}const n=He.current,i=t=>Fn({store:e,result:t,composed:n,regionEffects:ze.current,regionState:Ne.current,bodyForces:We.current,onTick:$e.current});let o;if(t)o=function(e,t,n=4){let i,o=!1,r=!1,s=0;do{const n=e.settleWithObservations(),a=t(n);o=o||a.regionEffectsApplied,r=r||a.bodyForcesApplied,i={...a,regionEffectsApplied:o,bodyForcesApplied:r,result:n},s+=1}while(n>s&&e.hasPendingWork());return i}(e,i);else{const t=Ot.current(),n=ct.current;ct.current=t;const r=e.tick(null===n?0:(t-n)/1e3);o={...i(r),result:r}}const{result:r,regionEffectsApplied:s,bodyForcesApplied:a,snapshot:c}=o;gn(),(Xe.current||r.shouldContinue||s||a||n||Ht.current.size>0)&&!c.paused&&c.visible&&!Mt.current&&Pt()},[Wn,Ln,gn,At,Vn,Pt,Mt,St]);It.current=_n,an(()=>{mt.current=!1,(pt.current||vt.current)&&On("config changed",!1),tt.current?.updateConfig(st??{}),Vn()},[st,On]),an(()=>{mt.current=!1,Vn()},[Et,Se,Te]),an(()=>{Vn()},[kt,Vn]),function({cancelRender:e,frameRuntime:t,lastFrameTimeRef:n,paused:i,postWorkerCommand:o,requestRender:r,storeRef:s,suspendWhenHidden:a}){const c=kn(o);c.current=o;const l=kn(r);l.current=r,Sn(()=>{const o=s.current;o&&(t.setPaused(i),o.setPaused(i),i&&(n.current=null,e()),c.current({type:"setPaused",paused:i},!1),l.current())},[e,t,i]),Sn(()=>{if(!a){const e=s.current;return t.setVisible(!0),void(e&&!e.snapshot().visible&&(e.setVisible(!0),c.current({type:"setVisible",visible:!0},!1),l.current()))}if("undefined"==typeof document)return;const i=()=>{const i=s.current;if(!i)return;const o=Mn();t.setVisible(o),i.setVisible(o),o||(n.current=null,e()),c.current({type:"setVisible",visible:o},!1),l.current()};return i(),document.addEventListener("visibilitychange",i),()=>document.removeEventListener("visibilitychange",i)},[e,t,a])}({cancelRender:At,frameRuntime:qt,lastFrameTimeRef:ct,paused:fe,postWorkerCommand:Xn,requestRender:Vn,storeRef:tt,suspendWhenHidden:Be}),an(()=>()=>On("unmount",!1),[On]),an(()=>{gn()},[gn]),cn(t,()=>({...tt.current.controls(),applyImpulse:(e,t,n)=>{tt.current.applyImpulse(e,t,n),Xn({type:"applyImpulse",id:e,ix:t,iy:n}),Vn()},clear:()=>{tt.current.clear(),Ne.current.clear(),Ht.current.clear(),Xn({type:"clear"}),Vn()},clearRegionState:e=>{e?Ne.current.delete(e):Ne.current.clear(),Vn()},getData:()=>tt.current.readBodies(),getRegionState:e=>e?Cn(Ne.current.get(e)):function(e){const t={};return e.forEach((e,n)=>{const i=Cn(e);i&&(t[n]=i)}),t}(Ne.current),getStore:()=>tt.current,pause:()=>{qt.setPaused(!0),ct.current=null,At(),tt.current.setPaused(!0),Xn({type:"setPaused",paused:!0},!1),Vn()},push:(e,t)=>{tt.current.enqueue(e,t),yn(t)?Xn({type:"enqueue",spawns:[e],pacing:t}):(pt.current||vt.current)&&On("spawn pacing is not worker-cloneable"),Vn()},pushMany:(e,t)=>{tt.current.enqueue(e,t),yn(t)?Xn({type:"enqueue",spawns:e,pacing:t}):(pt.current||vt.current)&&On("spawn pacing is not worker-cloneable"),Vn()},popBodies:(e,t={})=>{const n=tt.current,i=new Map(n.readBodies().map(e=>[e.id,e])),o=n.remove(e),r=Ot.current();for(const e of o){const n=i.get(e);n&&(Ne.current.delete(e),Ht.current.set(e,{body:n,color:t.color??"#f59e0b",durationMs:Math.max(120,t.durationMs??520),radius:t.radius??An(n),scale:null!=t.scale&&t.scale>0?t.scale:1,startedAt:r}),$t.current===e&&($t.current=null,jt(null)),Wt(t=>t?.id===e?null:t))}return o.length&&(Xn({type:"remove",ids:o}),Vn()),o},remove:e=>{const t=tt.current.remove(e);for(const t of e)Ne.current.delete(t);return Xn({type:"remove",ids:e}),Vn(),t},restore:e=>{tt.current.restore(e),Ne.current.clear(),Ht.current.clear(),Xn({type:"restore",snapshot:e},!1),Vn()},resume:()=>{qt.setPaused(!1),ct.current=null,tt.current.setPaused(!1),Xn({type:"setPaused",paused:!1},!1),Vn()},settle:e=>{const t=tt.current.settle(e);return Xn({type:"settle",maxSteps:e}),Vn(),t},settleWithObservations:e=>{const t=tt.current.settleWithObservations(e);return Xn({type:"settle",maxSteps:e}),Vn(),t},step:e=>{const t=tt.current,n=t.tick(e);return Fn({store:t,result:n,regionEffects:ze.current,regionState:Ne.current,bodyForces:We.current,composed:He.current,onTick:$e.current}),Xn({type:"tick",deltaSeconds:e}),gn(),n}}),[At,qt,gn,Xn,Vn,On]);const Kn=S||!Et&&Ft,Gn=["stream-physics-frame",W?"stream-physics-frame--mode-"+W:null,z?"stream-physics-frame--emphasis-"+z:null,A].filter(Boolean).join(" "),Un=N??("string"==typeof Ce?Ce:void 0)??"Physics chart",Qn=ht+"-physics-table",Zn=Math.max(1,Tt[0]-wt.left-wt.right),Jn=Math.max(1,Tt[1]-wt.top-wt.bottom),oi=$&&Nt?Pe?Pe(Nt):li(ri,{hover:Nt}):null,si=oi&&Nt?li(l,{x:Nt.x-wt.left,y:Nt.y-wt.top,containerWidth:Zn,containerHeight:Jn,margin:wt,className:"stream-physics-tooltip",children:oi}):null;if(Kn){const e=tt.current??xn(st,V,_),t="string"==typeof Ce?Ce:void 0,{svg:n}=zt(e,{width:Tt[0],height:Tt[1],title:t,description:N,background:m||"transparent"===s?void 0:s,backgroundGraphics:Bt,className:"stream-physics-frame__svg",foregroundGraphics:Rt,idPrefix:"physics-"+ht,margin:wt});return di("div",{ref:Ct,className:Gn,"data-semiotic-mode":W,role:"img","aria-label":Un,style:{width:Tt[0],height:Tt[1]},children:[li(h,{summary:Ae}),li("div",{dangerouslySetInnerHTML:{__html:n}})]})}return di("div",{ref:Ct,className:Gn,"data-semiotic-mode":W,role:"group","aria-label":Un,"aria-describedby":Dt?Yt:void 0,tabIndex:0,style:{position:"relative",width:Tt[0],height:Tt[1]},onKeyDown:en,children:["production"!==process.env.NODE_ENV&&tt.current&&li(u,{store:tt.current,diagnostics:dt.current}),n?li(p,{tableId:Qn}):null,n?li(ci,{chartTitle:"string"==typeof Ce?Ce:Un,items:Ze,tableId:Qn}):null,li(h,{summary:Ae}),li(a,{hoverPoint:Nt}),li("div",{id:Yt,"aria-live":"polite","aria-atomic":"true",style:$n,children:Dt?Dt.description??Dt.label:""}),di("div",{role:"img","aria-label":Un,style:{position:"relative",width:"100%",height:"100%"},children:[li(c,{size:Tt,margin:wt,children:Bt}),li("canvas",{ref:mn,width:Tt[0],height:Tt[1],"aria-hidden":"true",style:{position:"absolute",left:0,top:0,display:"block"},onPointerDown:Zt,onPointerMove:$?Qt:void 0,onPointerLeave:$?Ut:void 0}),Rt,li(re,{width:Zn,height:Jn,totalWidth:Tt[0],totalHeight:Tt[1],margin:wt,title:Ce,legend:K,legendPosition:te,legendLayout:ee,legendHoverBehavior:Z,legendClickBehavior:U,legendHighlightedCategory:Q,legendIsolatedCategories:J,pointNodes:tn,annotations:i,onAnnotationActivate:o,onObservation:se,chartId:I,chartType:mi,autoPlaceAnnotations:r,svgAnnotationRules:Re}),li(d,{active:null!=Dt,hoverPoint:Dt?{x:Dt.x,y:Dt.y}:null,margin:wt,size:Tt,shape:Dt?.shape,width:Dt?.width,height:Dt?.height,pathData:Dt?.pathData}),si]})]})}));fi.displayName="StreamPhysicsFrame";var yi=fi;import{scaleLinear as gi}from"d3-scale";function bi(e){const[t,n]=e,i=160>t||116>n,o=i?Math.min(12,Math.max(2,.08*t)):32,r=i?Math.min(8,Math.max(2,.12*n)):24,s=i?r:34;return{width:t,height:n,plot:{x:o,y:r,width:Math.max(1,t-2*o),height:Math.max(1,n-r-s)}}}function vi(e){const t=(e??"")+"";if(!t)return"#4e79a7";const n=["#4e79a7","#59a14f","#e15759","#f28e2b","#76b7b2","#edc948","#b07aa1","#ff9da7"];let i=0;for(let e=0;t.length>e;e+=1)i=31*i+t.charCodeAt(e)>>>0;return n[i%n.length]}function xi(e,i="#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?i:vi(c),stroke:"#111827",strokeWidth:1,opacity:.9};return s&&o&&Object.assign(l,n(o,r,{value:a?a(o):void 0,category:null==c?void 0:c+""})),l}}function wi(e,t,n,i){return{fixedDt:1/120,maxSubsteps:8,colliders:t,observation:{chartType:n},kernel:{seed:e,gravity:{x:0,y:760},cellSize:36,collisionIterations:6,velocityDamping:.995,restitution:.08,friction:.4,sleepSpeed:8,sleepAfter:.6,...i}}}function Si(e,t,n){if(!e.length)return[];const i=bi(t),o=i.plot.width/Math.max(1,e.length),r=Math.max(1,...e.map(e=>e.value)),s=.62*i.plot.height,a=i.plot.y+i.plot.height;return e.map((e,t)=>{const c=Math.max(8,e.value/r*s),l=`${n} ${e.label}: ${e.value}${null==e.secondary?"":`, ${e.secondary} secondary`}`;return{id:`${n}-${e.label}`,label:l,description:l,datum:e,x:i.plot.x+(t+.5)*o,y:a-c/2,shape:"rect",width:Math.max(12,.58*o),height:c,group:n}})}function ki(e,t,n){return"function"==typeof n?n(e,t):e[n]}function Mi(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 Ii(e,t,n){return Math.max(t,Math.min(n,e))}function Ai(e,t){const n=Mi(e);return null!=n&&n>0?n:t}function Bi(e){return((e??"unknown")+"").trim().replace(/[^A-Za-z0-9_-]+/g,"_")||"unknown"}function Ri(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 Ci(e){const t=Math.max(2,Math.round(e.bins)),n=Math.max(1,Math.round(e.pegRows??t-1)),i=Math.max(1,Math.round(e.count??Math.max(64,4*t))),o=Ii(Number.isFinite(e.branchProbability)?e.branchProbability??.5:.5,0,1),r=Ri(e.seed??1),s=e.idPrefix??"mechanical";return Array.from({length:i},(e,t)=>{let i=0;for(let e=0;n>e;e+=1)r()<o&&(i+=1);const a=n/2;return{id:`${s}-${t}`,value:i,mechanical:!0,pegRows:n,branchProbability:o,pathRights:i,side:a>i?"left":i>a?"right":"center"}})}function Pi(e){const{data:t,valueAccessor:n,bins:i,ballRadius:o,seed:r,size:s,valueExtent:a}=e,c=bi(s),l=t.map((e,t)=>Mi(ki(e,t,n))).filter(e=>null!=e),d=function(e){if(!e)return;const t=Mi(e[0]),n=Mi(e[1]);return null!=t&&null!=n?t>n?[n,t]:[t,n]:void 0}(a),u=d?.[0]??(l.length?Math.min(...l):0),h=d?.[1]??(l.length?Math.max(...l):1),p=h===u?1:h-u,m=gi().domain([0,i]).range([c.plot.x,c.plot.x+c.plot.width]),f=Array.from({length:i},()=>0),y=[];t.forEach((e,t)=>{const r=Mi(ki(e,t,n));if(null==r)return;const s=Math.max(0,Math.min(i-1,Math.floor((r-u)/p*i)));f[s]+=1,y.push({id:(e.id??"galton-"+t)+"",x:m(s+.5),y:c.plot.y+o+2,vx:8*(t%5-2),vy:0,mass:1,shape:{type:"circle",radius:o},datum:{...e,value:r,bin:s}})});const g=c.plot.y+c.plot.height;return{config:wi(r,[...at({x:c.plot.x,y:c.plot.y,width:c.plot.width,height:c.plot.height},{idPrefix:"galton",wallThickness:20,floorThickness:20}),...ct({idPrefix:"galton-bin",count:i,domainStart:0,domainStep:1,xScale:m,yTop:c.plot.y-400,yBottom:g,wallThickness:6})],"GaltonBoardChart"),initialSpawns:y,initialSpawnPacing:{pacing:{ratePerSec:55}},projectionRows:f.map((e,t)=>({label:t+1+"",value:e})),metadata:{kind:"galton-board",bins:i,plot:c.plot,valueExtent:[u,h]}}}import{scaleLinear as Ti}from"d3-scale";function qi(e){const{count:t,idPrefix:n,wallThickness:i,xScale:o,yBottom:r,yTop:s,yTopForIndex:a}=e;return Array.from({length:t+1},(e,t)=>{const c=Math.min(r-1,a?.(t)??s),l=Math.max(1,r-c);return{id:`${n}-wall-${t}`,shape:{type:"aabb",x:o(t),y:c+l/2,width:i,height:l}}})}function Oi(e){const{data:t,timeAccessor:n,arrivalAccessor:i,windows:o,watermark:r,ballRadius:s,seed:a,size:c,timeExtent:l,timeScale:d=1}=e,u=bi(c),h=t.map((e,t)=>Mi(ki(e,t,n))).filter(e=>null!=e),p=Mi(l?.[0]),m=Mi(l?.[1]),f=h.length?Math.min(...h):0,y=h.length?Math.max(...h):f+o.size,g=Math.min(p??f,f),b=Math.max(m??y,y),v=Math.floor(g/o.size)*o.size,x=Math.max(1,Math.ceil((b-v+o.size)/o.size)),w=h.length?Math.max(...h):0,S="function"==typeof r?r(w):Mi(r?.value)??w-(r?.delay??o.size),k=Math.max(0,Math.min(x,Array.from({length:x},(e,t)=>t).reduce((e,t)=>v+(t+1)*o.size>S?e:e+1,0))),M=function(e,t){const n=Math.max(5*t,Math.min(92,.13*e.plot.width));return{gutter:{x:e.plot.x,y:e.plot.y,width:n,height:e.plot.height},windowPlot:{x:e.plot.x+n,y:e.plot.y,width:Math.max(40,e.plot.width-n),height:e.plot.height},wallTop:e.plot.y+.48*e.plot.height}}(u,s),I=v+x*o.size,A=Ti().domain([v,I]).range([M.windowPlot.x,M.windowPlot.x+M.windowPlot.width]),B=Array.from({length:x},()=>({value:0,secondary:0})),R=[];t.forEach((e,t)=>{const r=Mi(ki(e,t,n));if(null==r)return;const a=Mi(ki(e,t,i))??r,c=Math.max(0,Math.min(x-1,Math.floor((r-v)/o.size))),l=S>=v+(c+1)*o.size;B[c].value+=l?0:1,B[c].secondary+=l?1:0,R.push({id:(e.id??"event-"+t)+"",x:Math.max(M.windowPlot.x+s,Math.min(M.windowPlot.x+M.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 C=u.plot.y+u.plot.height,P=function(e,t){const n=Math.max(0,Math.min(e.windowCount,e.closedWindowCount));if(!n)return[];const i=e.windowStart,o=e.windowStart+e.windowCount*e.windowSize,r=Ti().domain([i,o]).range([e.windowPlot.x,e.windowPlot.x+e.windowPlot.width]),s=r(e.windowStart+n*e.windowSize),a=e.windowPlot.x,c=t+Math.max(18,Math.min(.3*e.windowPlot.height,s-a)),l=e=>s===a?t:c+(e-a)/(s-a)*(t-c),d=[];for(let t=0;n>t;t+=1){const n=e.windowStart+t*e.windowSize,i=n+e.windowSize,o=r(n),s=r(i);d.push({id:"eventdrop-lid-"+t,windowIndex:t,x1:o,y1:l(o),x2:s,y2:l(s)})}return d}({closedWindowCount:k,gutter:M.gutter,plot:u.plot,windowCount:x,windowPlot:M.windowPlot,windowSize:o.size,windowStart:v},u.plot.y+.28*u.plot.height);return{config:wi(a,[...at({x:u.plot.x,y:u.plot.y,width:u.plot.width,height:u.plot.height},{idPrefix:"eventdrop",wallThickness:20,floorThickness:20}),...qi({idPrefix:"eventdrop-window",count:x,xScale:e=>A(v+e*o.size),yTop:M.wallTop,yTopForIndex:e=>{const t=(e=>{if(0>e||e>k)return null;const t=0===e?P[0]?.y1:P[e-1]?.y2??P[e]?.y1;return"number"==typeof t&&Number.isFinite(t)?t:null})(e);return null==t?M.wallTop:t+1.25*s},yBottom:C,wallThickness:6}),...P.map(e=>({id:e.id,shape:{type:"segment",x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2,thickness:Math.max(4,.42*s)},friction:.02,restitution:.01}))],"EventDropChart",{friction:.08}),initialSpawns:R,initialSpawnPacing:{pacing:"arrival",timeAccessor:e=>e.datum?.arrivalTime,timeScale:d},projectionRows:B.map((e,t)=>({label:`${v+t*o.size}-${v+(t+1)*o.size}`,value:e.value,secondary:e.secondary})),metadata:{kind:"event-drop",closedWindowCount:k,gutter:M.gutter,lidSegments:P,lateCount:B.reduce((e,t)=>e+t.secondary,0),plot:u.plot,windowPlot:M.windowPlot,watermarkValue:S,windowCount:x,windowSize:o.size,windowStart:v}}}function Ei(e,t,n,i){const o=Mi(ki(e,t,i.timeAccessor));if(null==o)return null;const r=Mi(ki(e,t,i.arrivalAccessor))??o,{windowPlot:s,windowStart:a,windowCount:c,windowSize:l,watermarkValue:d}=n,u=a+c*l,h=Ti().domain([a,u]).range([s.x,s.x+s.width]),p=Math.max(0,Math.min(c-1,Math.floor((o-a)/l))),m=d>=a+(p+1)*l,{ballRadius:f}=i;return{id:(e.id??"event-push-"+t)+"",x:Math.max(s.x+f,Math.min(s.x+s.width-f,h(o))),y:s.y+f+2,vx:8*(t%3-1),vy:0,mass:1,friction:.02,shape:{type:"circle",radius:f},datum:{...e,eventTime:o,arrivalTime:r,windowIndex:p,late:m}}}function Fi(e={}){const t=(e.categories?.length?e.categories:["Intake","Review","Build","Ship"]).map(e=>(e+"").trim()).filter(Boolean),n=t.length?t:["Intake"],i=Math.max(n.length,Math.round(e.count??Math.max(48,12*n.length))),o=Ai(e.unitValue,1),r=Ri(e.seed??1),s=e.idPrefix??"mechanical-pile",a=n.map(()=>.65+.9*r()),c=a.reduce((e,t)=>e+t,0)||1,l=i-n.length,d=a.map(e=>e/c*l),u=d.map(e=>1+Math.floor(e));let h=i-u.reduce((e,t)=>e+t,0);const p=d.map((e,t)=>({index:t,fraction:e-Math.floor(e)})).sort((e,t)=>t.fraction-e.fraction);for(let e=0;h>0;e=(e+1)%p.length)u[p[e].index]+=1,h-=1;return n.map((e,t)=>({id:`${s}-${t}`,category:e,value:u[t]*o,mechanical:!0,unitCount:u[t],unitValue:o,share:u[t]/i}))}function Di(e,t,n){const i=e.width/Math.max(1,t),o=Math.max(2,2*n),r=Math.min(.7*i,Math.max(3.2*o,o+8)),s=Math.max(1,Math.floor(r/o));return{laneWidth:i,tubeWidth:r,ballDiameter:o,perRow:s,centerX:t=>e.x+(t+.5)*i,pileHeight:e=>Math.ceil(Math.max(0,e)/s)*o}}function ji(e){const{data:t,categoryAccessor:n,valueAccessor:i,unitValue:o,ballRadius:r,seed:s,size:a}=e,c=Ai(o,1),l=bi(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((ki(e,t,n)??"unknown")+"")});const f=Math.max(1,d.length),y=Di(l.plot,f,r),g=Math.max(0,y.tubeWidth/2-r-1),b=d.map(()=>[]);t.forEach((e,t)=>{const o=(ki(e,t,n)??"unknown")+"",s=m(o),a=i?Mi(ki(e,t,i)):1,d=Math.max(0,Math.round((a??0)/c)),u=y.centerX(s);for(let n=0;d>n;n+=1){const i=h.get(o)??0,a=y.perRow>1?((y.perRow>1?i%y.perRow:0)/(y.perRow-1)*2-1)*g:0;h.set(o,i+1),b[s].push({id:`${(e.id??"pile-"+t)+""}-${n}`,x:u+a,y:l.plot.y+r+2,vx:(n%3-1)*r/2,vy:0,mass:1,shape:{type:"circle",radius:r},datum:{...e,category:o,unitIndex:n}})}});const v=b.reduce((e,t)=>Math.max(e,t.length),0);for(let e=0;v>e;e+=1)for(const t of b)t.length>e&&p.push(t[e]);const x=l.plot.y+l.plot.height,w=[...at({x:l.plot.x,y:l.plot.y,width:l.plot.width,height:l.plot.height},{idPrefix:"pile",wallThickness:20,floorThickness:20})],S=l.plot.y-400;for(let e=0;f>e;e+=1){const t=y.centerX(e);for(const n of[-1,1])w.push({id:`pile-tube-${e}-${0>n?"l":"r"}`,shape:{type:"aabb",x:t+n*y.tubeWidth/2,y:(S+x)/2,width:6,height:x-S}})}return{config:wi(s,w,"UnitPileChart"),initialSpawns:p,initialSpawnPacing:{pacing:{ratePerSec:20}},projectionRows:d.map(e=>({label:e,value:h.get(e)??0}))}}import{scaleLinear as Ni}from"d3-scale";function zi(e){const{data:t,xAccessor:n,groupAccessor:i,radiusAccessor:o,pointRadius:r,seed:s,size:a,xExtent:c,collisionIterations:l,settle:d}=e,u=bi(a),h=Ri(s),p=[],m=[],f=new Map;t.forEach((e,t)=>{const s=Mi(ki(e,t,n));if(null==s)return;const a=i?(ki(e,t,i)??"All")+"":"All",c=o?Mi(ki(e,t,o)):null,l=Ii(null!=c&&c>0?c:r,2,18);!function(e){let t=f.get(e);null==t&&(t=m.length,m.push(e),f.set(e,t))}(a),p.push({datum:e,index:t,value:s,group:a,radius:l})});const y=p.map(e=>e.value),g=c?Mi(c[0]):null,b=c?Mi(c[1]):null,v=y.length?Math.min(...y):0,x=y.length?Math.max(...y):1;let w=g??v,S=b??x;if(w===S&&(w-=.5,S+=.5),w>S){const e=S;S=w,w=e}const k=Math.max(r,...p.map(e=>e.radius)),M=u.plot.x+k+8,I=u.plot.x+u.plot.width-k-8,A=Ni().domain([w,S]).range([M,I]),B=Math.max(1,m.length),R=Math.min(Math.max(28,3*k),u.plot.height/4),C=u.plot.y+R,P=Math.max(0,u.plot.y+u.plot.height-R-C),T=e=>{const t=f.get(e)??0;return 1===B?u.plot.y+.54*u.plot.height:C+t/(B-1)*P},q=new Map,O=p.map((e,t)=>{q.set(e.group,(q.get(e.group)??0)+1);const n=A(e.value),i=T(e.group),o=(h()-.5)*e.radius*1.6,r=(h()-.5)*e.radius*1.6;return{id:(e.datum.id??"collision-swarm-"+t)+"",x:d?n+o:Ii(n+(t%9-4)*e.radius*2.5,M,I),y:d?i+r:u.plot.y-18-t%12*e.radius,vx:d?0:22*(h()-.5),vy:d?0:24+18*h(),mass:1,shape:{type:"circle",radius:e.radius},datum:{...e.datum,xValue:e.value,group:e.group,radius:e.radius,targetX:n,targetY:i},springs:[{target:{type:"point",x:n,y:i},restLength:0,stiffness:34,damping:5.5}]}});return{config:wi(s,at({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*k),collisionIterations:Math.max(1,Math.round(l??6)),velocityDamping:.992,restitution:.02,friction:.18,sleepSpeed:3,sleepAfter:.5}),initialSpawns:O,projectionRows:m.map(e=>({label:e,value:q.get(e)??0})),metadata:{kind:"collision-swarm",xExtent:[w,S],xRange:[M,I],groups:m.map(e=>({label:e,y:T(e),count:q.get(e)??0})),plot:u.plot}}}function Wi(e){if(Array.isArray(e)&&e.length>=2){const t=Mi(e[0]),n=Mi(e[1]);return null!=t&&null!=n?{x:t,y:n}:null}if(e&&"object"==typeof e){const t=e,n=Mi(t.x),i=Mi(t.y);return null!=n&&null!=i?{x:n,y:i}:null}return null}function $i(e){return Array.isArray(e)?e.map(Wi).filter(e=>null!=e):[]}function Li(e,t,n){return"normalized"===n?{x:t.plot.x+e.x*t.plot.width,y:t.plot.y+e.y*t.plot.height}:{x:Ii(e.x,t.plot.x,t.plot.x+t.plot.width),y:Ii(e.y,t.plot.y,t.plot.y+t.plot.height)}}function Hi(e){let t=0;for(let n=1;e.length>n;n+=1)t+=Math.hypot(e[n].x-e[n-1].x,e[n].y-e[n-1].y);return t}function Yi(e,t){if(0===e.length)return{x:0,y:0};if(1===e.length)return{...e[0]};const n=Ii(t,0,1)*Hi(e);let i=0;for(let t=1;e.length>t;t+=1){const o=e[t-1],r=e[t],s=Math.hypot(r.x-o.x,r.y-o.y);if(s>0){if(i+s>=n){const e=(n-i)/s;return{x:o.x+(r.x-o.x)*e,y:o.y+(r.y-o.y)*e}}i+=s}}return{...e[e.length-1]}}function Xi(e,t){const n=Yi(e,Math.max(0,t-.02)),i=Yi(e,Math.min(1,t+.02)),o=i.x-n.x,r=i.y-n.y,s=Math.hypot(o,r)||1;return{x:o/s,y:r/s}}function Vi(e){const{coordinateMode:t,flowSpeed:n,links:i,maxParticles:o,nodeIdAccessor:r,nodeXAccessor:s,nodeYAccessor:a,nodes:c,particleRadius:l,particleRate:d,pathAccessor:u,pathConstraint:h="path",reducedMotion:p,seed:m,size:f,sourceAccessor:y,targetAccessor:g,throughputAccessor:b}=e,v=bi(f),x=Ri(m),w=new Map,S=new Map,k=[];function M(e){if(e&&"object"==typeof e){const t=e;if("function"==typeof r){const e=r(t,0);if(null!=e)return e+""}if("string"==typeof r&&null!=t[r])return t[r]+"";if(null!=t.id)return t.id+""}return(e??"unknown")+""}c.forEach((e,t)=>{const n=(ki(e,t,r)??e.id??t)+"",i=Mi(ki(e,t,s)),o=Mi(ki(e,t,a));if(null!=i&&null!=o){const e={x:i,y:o};w.set(n,e),k.push(e)}S.set(n,(e.label??e.name??n)+"")});const I=[];i.forEach((e,t)=>{const n=M(ki(e,t,y)),i=M(ki(e,t,g)),o=Math.max(0,Mi(ki(e,t,b))??0),r=$i(u?ki(e,t,u):void 0),s=r.length?r:$i(e.path??e.points??e.route);s.forEach(e=>k.push(e)),I.push({id:(e.id??`physical-flow-${n}-${i}-${t}`)+"",link:e,index:t,source:n,target:i,throughput:o,rawPath:s})});const A=(R=k,"normalized"===(B=t)||"pixels"===B?B:R.length>0&&R.every(e=>!(0>e.x||e.x>1||0>e.y||e.y>1))?"normalized":"pixels");var B,R;const C=new Map;for(const[e,t]of w)C.set(e,Li(t,v,A));const P=[];for(const e of I){let t=e.rawPath.map(e=>Li(e,v,A));if(2>t.length){const n=C.get(e.source),i=C.get(e.target);n&&i&&(t=[n,i])}else C.has(e.source)||C.set(e.source,t[0]),C.has(e.target)||C.set(e.target,t[t.length-1]);t.length>=2&&e.throughput>0&&(S.has(e.source)||S.set(e.source,e.source),S.has(e.target)||S.set(e.target,e.target),P.push({...e,path:t,packetCount:0}))}const T=Ai(d,.12),q=Math.max(1,Math.round(o)),O=P.map(e=>Math.max(1,Math.round(e.throughput*T))),E=O.reduce((e,t)=>e+t,0),F=E>q?q/E:1;P.forEach((e,t)=>{e.packetCount=Math.max(1,Math.floor(O[t]*F))});let D=P.reduce((e,t)=>e+t.packetCount,0);for(;D>q;){const e=P.reduce((e,t,n)=>t.packetCount>1&&(-1===e||t.packetCount>P[e].packetCount)?n:e,-1);if(-1===e)break;P[e].packetCount-=1,D-=1}const j=new Map,N=new Map,z=[],W=Ai(n,90),$=Ai(l,4);P.forEach((e,t)=>{j.set(e.target,(j.get(e.target)??0)+e.throughput),N.set(e.source,(N.get(e.source)??0)+e.throughput);const n=Hi(e.path);for(let i=0;e.packetCount>i;i+=1){const o=(i+.5)/e.packetCount,r=p?o:Ii(.12+.84*o+.04*(x()-.5),.04,.98),s=p?r:Math.max(0,r-(.18+.12*x())),a=Yi(e.path,s),c=Yi(e.path,r),l=Xi(e.path,s),d={x:-l.y,y:l.x},u=(x()-.5)*$*1.5;z.push({id:`${e.id}-packet-${i}`,x:a.x+d.x*u,y:a.y+d.y*u,vx:p?0:l.x*W+10*(x()-.5),vy:p?0:l.y*W+10*(x()-.5),mass:.8,spawnAt:p?0:.04*t+i/32,shape:{type:"circle",radius:$},datum:{...e.link,source:e.source,target:e.target,throughput:e.throughput,packetIndex:i,packetCount:e.packetCount,routeProgress:r,flowPath:e.path,flowPathLength:n,flowRouteId:e.id,flowSpeed:W,sourceLabel:S.get(e.source)??e.source,targetLabel:S.get(e.target)??e.target},springs:"none"!==h&&p?[{target:{type:"point",x:c.x,y:c.y},restLength:.7*$,stiffness:26,damping:4.25}]:void 0})}});const L=Math.max(18,5*$),H=Array.from(C,([e,t])=>({nodeId:e,label:S.get(e)??e,sensorId:"physical-flow-node-"+Bi(e),point:t})),Y=H.map(e=>({id:e.sensorId,sensor:!0,shape:{type:"aabb",x:e.point.x,y:e.point.y,width:L,height:L}})),X=Object.fromEntries(H.map(e=>[e.sensorId,{binId:e.label,enterType:"physics-proximity-enter",exitType:"physics-proximity-exit"}])),V=wi(m,[...at({x:v.plot.x,y:v.plot.y,width:v.plot.width,height:v.plot.height},{idPrefix:"physical-flow",wallThickness:18,floorThickness:18}),...Y],"PacketFlowChart",{gravity:{x:0,y:0},cellSize:Math.max(24,7*$),collisionIterations:3,velocityDamping:.994,restitution:.01,friction:.16,sleepSpeed:2.5,sleepAfter:.7});V.bodyLimit=q,V.eviction="oldest",V.observation={...V.observation,sensors:X};const _=Array.from(C,([e,t])=>({id:e,label:S.get(e)??e,x:t.x,y:t.y,sensorId:"physical-flow-node-"+Bi(e),incoming:j.get(e)??0,outgoing:N.get(e)??0})),K=P.map(e=>({id:e.id,source:e.source,target:e.target,sourceLabel:S.get(e.source)??e.source,targetLabel:S.get(e.target)??e.target,throughput:e.throughput,packetCount:e.packetCount,path:e.path}));return{config:V,initialSpawns:z,projectionRows:_.filter(e=>e.incoming>0||e.outgoing>0).map(e=>({label:e.label,value:e.incoming,secondary:e.outgoing})),metadata:{kind:"physical-flow",coordinateMode:A,particleCount:z.length,totalThroughput:P.reduce((e,t)=>e+t.throughput,0),plot:v.plot,nodes:_,links:K}}}function _i(e,t){if("region-enter"!==t.type)return e;const n=t.region.id,i=e[n]??{id:n,label:t.region.label??n,count:0,bodyIds:[]};if(i.bodyIds.includes(t.bodyId))return e;const o=[...i.bodyIds,t.bodyId];return{...e,[n]:{...i,count:o.length,bodyIds:o}}}function Ki(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 Gi(e,t){const n=t instanceof Set?t:new Set(t);return e.map(e=>{const t=e.bodyIds??[],i=t.filter(e=>!n.has(e)),o=t.length-i.length,r=e.completion?.mode??"allMembersAbsorbed",s=e.completion?.valueByBodyId,a=e=>{const t=s?.[e];return Number.isFinite(t)&&Number(t)>=0?Number(t):1},c=t.reduce((e,t)=>e+a(t),0),l=t.reduce((e,t)=>e+(n.has(t)?a(t):0),0),d=e.completion?.threshold,u="threshold"===r?Number.isFinite(d)&&Number(d)>=0?Number(d):c:void 0;return{id:e.id,label:e.label??e.id,mode:r,complete:t.length>0&&("anyAbsorbed"===r?o>0:"threshold"===r?l>=(u??c):0===i.length),absorbed:o,total:t.length,absorbedValue:l,totalValue:c,threshold:u,missing:i}})}function Ui(e,t,n){return Math.max(t,Math.min(n,e))}function Qi(e,t,n={}){const i=n.random??Math.random,o=e.stages.find(e=>e.id===t)??e.stages[e.stages.length-1],r=Ui(n.along??.5,.05,.95),s=n.jitterX??0,a=n.padY??20,c=o.x0+(o.x1-o.x0)*r+(2*i()-1)*s,l=Math.min(1,o.width/2),d=Ui(c,o.x0+l,o.x1-l),u=e.boundaryY(d,"top")+a,h=e.boundaryY(d,"bottom")-a;return{x:d,y:h>u?u+i()*Math.max(1,h-u):e.midY}}function Zi(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 Ji(e,t,n){return Math.max(t,Math.min(n,e))}function eo(e,t,n,i,o,r={}){return{id:e,friction:r.friction,restitution:r.restitution,bodyFilter:r.bodyFilter,shape:{type:"segment",x1:t,y1:n,x2:i,y2:o,thickness:r.thickness??8}}}function to(e){const t=e.shape??"lane",n=Math.max(1,Math.round(e.width)),i=Math.max(1,Math.round(e.height)),o=e.padX??46,r=e.padY??72,s=o,a=n-o,c=r,l=i-Math.max(24,Math.round(.45*r)),d=(c+l)/2,u=Math.max(1,l-c),h=Ji(e.pinchRatio??.18,.06,.5),p=Number(e.pinchHeightOffset??0),m=Number.isFinite(p)?p:0,f=Ji(u*h+m,.06*u,.5*u),y=f/2,g=d-y,b=d+y,v=e.idPrefix??"process",x=e.friction??.58,w=e.restitution??.18,S=e.wallThickness??8,k=e.stages;if(!k.length)throw Error("processStageLayout requires at least one stage");const M=Ji(e.centerStageIndex??Math.floor(k.length/2),0,k.length-1),I=function(e){const t=e.reduce((e,t)=>e+(t.share??1),0);return t>0?t:e.length}(k),A=a-s;let B=s;const R=k.map((e,t)=>{const n=B,i=t===k.length-1?a:B+(e.share??1)/I*A;return B=i,{id:e.id,label:e.label,description:e.description,kind:e.kind??"stage",index:t,x0:n,x1:i,x:(n+i)/2,width:i-n,y:d,height:u}}),C=R[M],P=C.x0,T=C.x1,q=(e,n)=>{if("lane"===t)return"top"===n?c:l;if("funnel"===t){const t=Ji((e-s)/Math.max(1,a-s),0,1);return"top"===n?c+(g-c)*t:l+(b-l)*t}if(P>=e){const t=Ji((e-s)/Math.max(1,P-s),0,1);return"top"===n?c+(g-c)*t:l+(b-l)*t}if(T>=e)return"top"===n?g:b;const i=Ji((e-T)/Math.max(1,a-T),0,1);return"top"===n?g+(c-g)*i:b+(l-b)*i},O=R.map(e=>{const t=Math.min(q(e.x0,"top"),q(e.x1,"top")),n=Math.max(q(e.x0,"bottom"),q(e.x1,"bottom"));return{...e,y:(t+n)/2,height:Math.max(1,n-t)}}),E={thickness:S,friction:x,restitution:w},F=[];"lane"===t?F.push(eo(v+"-top",s,c,a,c,E),eo(v+"-bottom",s,l,a,l,E),eo(v+"-left",s,c,s,l,{...E,thickness:Math.max(6,S-2)}),eo(v+"-right",a,c,a,l,{...E,thickness:Math.max(6,S)})):"funnel"===t?F.push(eo(v+"-top",s,c,a,g,E),eo(v+"-bottom",s,l,a,b,E),eo(v+"-left",s,c,s,l,{...E,thickness:Math.max(6,S-2)}),eo(v+"-right",a,g,a,b,{...E,thickness:Math.max(6,S)})):F.push(eo(v+"-left-top",s,c,P,g,E),eo(v+"-left-bottom",s,l,P,b,E),eo(v+"-center-top",P,g,T,g,E),eo(v+"-center-bottom",P,b,T,b,E),eo(v+"-right-top",T,g,a,c,E),eo(v+"-right-bottom",T,b,a,l,E),eo(v+"-left",s,c,s,l,{...E,thickness:Math.max(6,S-2)}),eo(v+"-right",a,c,a,l,{...E,thickness:Math.max(6,S)}));const D=e.membraneDampingScale??.5,j=s,N=Math.max(1,("bowtie"===t?P:a)-j),z=(e.membranes??[]).map(e=>{const t=j+Ji(e.offset,0,1)*N,n=e.width??18+18*e.cost,i=u-16,o=d+.25*(e.wobble??0);return{...e,x:t,y:o,width:n,height:i}}),W=!1===e.includeMembraneRegions?[]:z.map(e=>oo({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??D,bodyStyle:e.bodyStyle,metadata:e.metadata,semanticItem:e.semanticItem,color:e.color}));return{shape:t,width:n,height:i,padX:o,padY:r,left:s,right:a,topY:c,bottomY:l,midY:d,centerLeft:P,centerRight:T,pinchHeight:f,pinchTop:g,pinchBottom:b,stages:O,membranes:z,colliders:F,regionEffects:W,boundaryY:q}}function no(e){return{id:e.id,label:e.label,description:e.description,kind:e.kind,shape:(t=e.x,n=e.y,i=e.width,o=e.height,{type:"aabb",x:t,y:n,width:i,height:o}),bodyFilter:e.bodyFilter,collider:e.collider,colliderThickness:e.colliderThickness,friction:e.friction,restitution:e.restitution,semanticItem:e.semanticItem,metadata:e.metadata,bodyStyle:e.bodyStyle,attributes:e.attributes,onEnter:e.onEnter,onExit:e.onExit};var t,n,i,o}function io(e,t={}){const n=t.idPrefix??"stage",i=Math.max(0,t.insetX??0),o=Math.max(0,t.insetY??1);return e.stages.map(e=>{const r="function"==typeof t.metadata?t.metadata(e):t.metadata??{};return{...no({id:n?`${n}:${e.id}`:e.id,label:e.label??e.id,description:e.description,kind:"region",x:e.x,y:e.y,width:Math.max(1,e.width-2*i),height:Math.max(1,e.height-2*o),bodyFilter:t.bodyFilter,semanticItem:t.semanticItem,attributes:{primitive:"processStage",stageId:e.id,stageIndex:e.index},metadata:{...r,primitive:"processStage",stageId:e.id,stageIndex:e.index}})}})}function oo(e){const t=e.dampingScale??.5,n=e.energyScale??1,i=Ji(e.cost,0,2);return{...no({...e,kind:e.kind??"membrane",attributes:{primitive:"membrane",membraneCost:i,..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),damping:i*t,energyDelta:-i*n}}function ro(e){return{...no({...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 so(e){const t="number"==typeof e.force?{x:e.force,y:0}:e.force??{x:12,y:0};return{...no({...e,kind:e.kind??"force-field",attributes:{primitive:"routeSurface",..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),force:t,damping:e.damping??.015}}function ao(e){const t=e.pressure??e.occupancy??0,n=e.baseDamping??.08,i=e.dampingPerUnit??.12,o=e.energyPerUnit??0;return{...no({...e,kind:e.kind??"membrane",attributes:{primitive:"pressureField",pressure:t,..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),damping:n+t*i,energyDelta:o?-t*o:void 0,force:e.force}}function co(e){const t="number"==typeof e.force?{x:e.force,y:0}:e.force;return{...no({...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 lo(e){return{...no({...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 uo(e){const t="number"==typeof e.force?{x:e.force,y:0}:e.force??{x:24,y:0};return{...no({...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 ho(e){return{...no({...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 po(e){const t=e.x??e.anchor?.x??0,n=e.y??e.anchor?.y??0;return{id:e.id,label:e.label,description:e.description,group:e.group,bodyIds:e.bodyIds,datum:e.datum,state:e.state,x:t,y:n,width:e.width,height:e.height,anchor:e.anchor??{x:t,y:n},completion:e.completion,tether:e.tether,semanticItem:e.semanticItem}}function mo(e){const t=e.idPrefix??"lane",n={thickness:e.thickness??8,friction:e.friction??.5,restitution:e.restitution??.16},i=[eo(t+"-top",e.left,e.top,e.right,e.top,n),eo(t+"-bottom",e.left,e.bottom,e.right,e.bottom,n)];return e.openEnds||i.push(eo(t+"-left",e.left,e.top,e.left,e.bottom,n),eo(t+"-right",e.right,e.top,e.right,e.bottom,n)),i}function fo(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 yo(e){const t=e.stages;if(!t.length)throw Error("buildProcessFlowPhysics requires at least one stage");const n=e.size,i=bi(n),o=Ii(e.ballRadius??6,2,18),r=e.seed??1,s=Ri(r),a=e.idAccessor,c=e.stageAccessor??"stage",l=e.groupBy,d=e.groupLabelAccessor,u=e.workAccessor,h=e.radiusAccessor,p=e.groupCompletion??(l?"allAbsorbed":"none"),m=e.springStiffness??.28,f=e.springDamping??.72,y=!0===e.settle,g=t.map(e=>({id:e.id,label:e.label??e.id,description:e.description,share:e.share})),b=to({width:n[0],height:n[1],shape:"lane",padX:Math.max(28,i.plot.x),padY:Math.max(36,i.plot.y+8),stages:g,idPrefix:"process-flow",includeMembraneRegions:!1,friction:.48,restitution:.14}),v=new Map(b.stages.map((e,t)=>[e.id,t])),x=new Map(b.stages.map(e=>[e.id,e])),w=b.stages[0].id,S=b.stages[0],k=new Set(t.filter(e=>e.absorb).map(e=>e.id)),M=t.map(e=>{const t=x.get(e.id)??S;return function(e,t){const n={id:"process-stage-"+e.id,label:e.label??e.id,description:e.description,x:t.x,y:t.y,width:Math.max(12,.92*t.width),height:Math.max(40,.88*t.height),semanticItem:!1,attributes:{stageId:e.id}};if(e.absorb)return uo({...n,kind:e.kind??"sink",force:fo(e.force,28),damping:e.damping??.04,charge:"absorbed",attributes:{...n.attributes,primitive:"absorb"}});if(e.portal){const t=e.portal.force??e.force??{x:-40,y:0};return lo({...n,kind:e.kind??"force-field",force:fo(t,-40),damping:e.damping??.1,targetStage:e.portal.targetStageId,attributes:{...n.attributes,primitive:"portal",targetStage:e.portal.targetStageId}})}if(e.capacity){const t=Math.max(.1,e.capacity.unitsPerSecond);return co({...n,kind:e.kind??"force-field",capacity:t,unitsPerSecond:t,force:fo(e.force,10+.8*t),damping:e.damping??Math.max(.04,.32-.01*t),attributes:{...n.attributes,unitAccessor:e.capacity.unitAccessor,reviewerCapacity:t}})}if(e.pressure){const t="object"==typeof e.pressure&&e.pressure?e.pressure:{};return ao({...n,kind:e.kind??"membrane",pressure:t.pressure,occupancy:t.occupancy,baseDamping:t.baseDamping??e.damping??.1,dampingPerUnit:t.dampingPerUnit??.1,energyPerUnit:t.energyPerUnit??0,force:fo(e.force,8),attributes:{...n.attributes,primitive:"pressureField"}})}return null!=e.force||null!=e.damping?so({...n,kind:e.kind??"force-field",force:fo(e.force,14),damping:e.damping??.02,attributes:{...n.attributes,primitive:"routeSurface"}}):ho({...n,kind:e.kind??"force-field",force:{x:10,y:0},damping:.02,attributes:{...n.attributes,primitive:"forceField"}})}(e,{x:t.x,y:b.midY,width:t.width,height:b.bottomY-b.topY})});M.unshift(so({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 n=(a?ki(e,t,a)??e.id??"process-flow-"+t:e.id??"process-flow-"+t)+"",i=(ki(e,t,c)??w)+"",r=v.has(i)?i:w;I.set(r,(I.get(r)??0)+1);const s=l?(ki(e,t,l)??"")+"":void 0,p=s&&d?(ki(e,t,d)??s)+"":s,m=u?Mi(ki(e,t,u))??1:1,f=h?Mi(ki(e,t,h)):null,y=Ii(null!=f&&f>0?f:o,2,18);A.push({datum:e,id:n,stageId:r,groupId:s||void 0,groupLabel:p||void 0,work:m,radius:y,index:t})});const B=new Map,R=new Map;for(const e of A){if(!e.groupId)continue;const t=B.get(e.groupId)??[];t.push(e.id),B.set(e.groupId,t),e.groupLabel&&R.set(e.groupId,e.groupLabel)}const C=Ii(e.groupAnchorAlong??.55,.15,.9),P=b.left+(b.right-b.left)*C,T=Array.from(B.keys()),q=T.map((e,n)=>{const i=B.get(e)??[],o=T.length>1?b.topY+28+n/Math.max(1,T.length-1)*(b.bottomY-b.topY-56):b.midY;return po({id:e,label:R.get(e)??e,bodyIds:i,anchor:{x:P,y:o},x:P,y:o,completion:"allAbsorbed"===p?{mode:"allMembersAbsorbed",targetZone:t.find(e=>e.absorb)?.id??"merged"}:void 0,tether:{stiffness:.06,visible:!0,restLength:18}})}),O=Gi(q,A.filter(e=>k.has(e.stageId)).map(e=>e.id)),E=new Map(q.map(e=>[e.id,e])),F=A.map((e,t)=>{const n=x.get(e.stageId)??S,i=n.x+(s()-.5)*Math.min(24,.2*n.width),o=b.boundaryY(i,"top")+e.radius+10,r=b.boundaryY(i,"bottom")-e.radius-10,a=r>o?o+s()*Math.max(1,r-o):b.midY,c=y?i:b.left+18+t%7*4,l=y?a:b.midY+(s()-.5)*(b.bottomY-b.topY)*.35,d=[{target:{type:"point",x:i,y:a},restLength:.45*e.radius,stiffness:m,damping:f}];if(e.groupId){const t=E.get(e.groupId);t?.anchor&&!k.has(e.stageId)&&d.push({target:{type:"point",x:t.anchor.x,y:t.anchor.y},restLength:t.tether?.restLength??22,stiffness:t.tether?.stiffness??.05,damping:.8})}return{id:e.id,x:c,y:l,vx:y?0:40+40*s(),vy:y?0:20*(s()-.5),mass:1,shape:{type:"circle",radius:e.radius},spawnAt:y?0:.03*t,springs:d,datum:{...e.datum,id:e.id,stage:e.stageId,groupId:e.groupId,groupLabel:e.groupLabel,work:e.work,__processFlow:!0}}}),D={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},j=b.stages.map(e=>({label:e.label??e.id,value:I.get(e.id)??0})),N=t.map(e=>{const t=x.get(e.id)??S;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:D,initialSpawns:F,initialSpawnPacing:y?void 0:{pacing:"arrival",timeAccessor:"spawnAt",timeScale:1},projectionRows:j,metadata:{kind:"process-flow",plot:i.plot,volume:b,stages:N,groups:q,groupCompletion:O,regionEffects:M}}}import{forwardRef as go,useCallback as bo,useMemo as vo,useRef as xo}from"react";import{useImperativeHandle as wo,useRef as So}from"react";function ko(e,t){if(!t?.length)return[e];const n=t.filter(t=>{if(t.id===e||t.id.startsWith(e+"-"))return!0;const n=t.datum;return!(!n||"object"!=typeof n||null==n.id)&&n.id+""===e}).map(e=>e.id);return n.length?n:[e]}function Mo(e,t,n){if("function"==typeof n)return n(e,t)+"";if("string"==typeof n){const t=e[n];if(null!=t)return t+""}return null!=e&&"object"==typeof e&&"id"in e&&null!=e.id?e.id+"":"physics-row-"+t}function Io(e,t){const n=e?.getData().find(e=>e.id===t),i=n?.datum;if(i&&"object"==typeof i)return i}function Ao(e,t){const{frameRef:n,spawnDatum:i,seedRows:o,idAccessor:r,bodyIdsForSeed:s,seedSpawns:a}=t,c=So(new Map),l=So(new Map),d=So(""),u=o?o.map((e,t)=>Mo(e,t,r)).join("\0"):"";if(u!==d.current&&(d.current=u,o))for(let e=0;o.length>e;e+=1){const t=o[e],n=Mo(t,e,r);c.current.set(n,t),l.current.set(n,s?.(t,n,e)??ko(n,a))}wo(e,()=>{const e=c.current,t=l.current;function o(e,t){const n=i(e,t);return{datumId:n.datumId||Mo(e,t,r),spawns:n.spawns.map(e=>({...e,spawnAt:void 0}))}}function s(i){const o=[];for(const{datum:n,result:r}of i)e.set(r.datumId,n),t.set(r.datumId,r.spawns.map(e=>e.id)),o.push(...r.spawns);if(!o.length)return;const r=n.current;r?(r.pushMany(o),r.step(0)):"production"!==process.env.NODE_ENV&&console.warn("[semiotic/physics] push() called before the physics frame mounted (loading/empty early-return). Omit data for push mode and ensure the chart is mounted.")}function a(i){const o=e.get(i);if(o)return o;const r=t.get(i)??[i];for(const o of r){const r=Io(n.current,o);if(r)return e.set(i,r),t.has(i)||t.set(i,[o]),r}}return{push:t=>{s([{datum:t,result:o(t,e.size)}])},pushMany:t=>{const n=e.size;s(t.map((e,t)=>({datum:e,result:o(e,n+t)})))},remove:i=>{const o=Array.isArray(i)?i:[i],r=[],s=[];for(const n of o){const i=a(n);i&&r.push(i),e.delete(n),s.push(...t.get(n)??[n]),t.delete(n)}return s.length&&n.current?.remove(s),r},update:(i,r)=>{const c=Array.isArray(i)?i:[i],l=[];for(const i of c){const c=a(i);if(!c)continue;l.push(c);const d=t.get(i)??[i];n.current?.remove(d),e.delete(i),t.delete(i);const u=r(c);s([{datum:u,result:o(u,e.size)}])}return l},clear:()=>{e.clear(),t.clear(),d.current="",n.current?.clear()},getData:()=>{const t=n.current;if(!t)return Array.from(e.values());const i=t.getData().map(e=>e.datum).filter(e=>!!e&&"object"==typeof e);return i.length?i:Array.from(e.values())},getScales:()=>null,getCustomLayout:()=>n.current?.snapshot()??null,popBodies:(e,t)=>n.current?.popBodies(e,t)??[]}},[n,r,i])}import{useCallback as Bo,useEffect as Ro,useMemo as Co,useRef as Po,useState as To}from"react";import{Fragment as qo,jsx as Oo,jsxs as Eo}from"react/jsx-runtime";function Fo(e){return!!e&&"string"==typeof e.name}function Do(e,t=!1){if(!e?.datum)return null;const n=e.datum,i=n.sourceDatum;return t&&i&&"object"==typeof i?i:n}function jo(e){const{selection:t,linkedHover:n,colorBy:i,chartType:o,chartId:r,onBodyHover:s,fallbackFields:a,unwrapSourceDatum:c}=e,l="string"==typeof i?i:void 0,d=Fo(t)?t:void 0,{activeSelectionHook:u,customHoverBehavior:h}=T({selection:d,linkedHover:n,fallbackFields:l?[l]:a,onObservation:e.onObservation,onClick:e.onClick,chartType:o,chartId:r,colorByField:l}),p=Fo(t)?null:t??null,m=Co(()=>{if(p)return p;if(!u?.isActive)return null;const e=u.predicate;return{isActive:!0,predicate:t=>{const n=Do(t,c);return null!=n&&e(n)}}},[u?.isActive,u?.predicate,p,c]),f=Co(()=>{if(n||s)return(e,t)=>{if(s?.(e,t),!n)return;const i=Do(e,c);h(i&&t?{...t,data:i}:null)}},[h,s,n,c]);return Co(()=>({selection:m,onBodyHover:f}),[f,m])}var No=new Set(["sample","mechanical"]);function zo(e,t,n,i){const[o,r]=To(0),s=Po(null),a=Po(!1),c=function(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0?e:null}(t),l=Po(c),d=Po(!!n),u=Po(i);l.current=c,d.current=!!n,u.current=i;const h=Bo(()=>{null!=s.current&&(clearTimeout(s.current),s.current=null)},[]),p=Bo(()=>{h();const e=l.current;null!=e&&!d.current&&a.current&&(s.current=setTimeout(()=>{s.current=null,a.current=!1,u.current?.(),r(e=>e+1)},e))},[h]);Ro(()=>{null==c||n?h():a.current&&p()},[h,c,n,p]),Ro(()=>h,[h]);const m=e?.observation?.onSimulationStateChange,f=Bo((e,t)=>{if(m?.(e,t),"running"===e)return a.current=!1,void h();"settled"===e&&"running"===t&&(a.current=!0,p())},[h,m,p]);return{config:Co(()=>null==c?e:{...e,observation:{...e?.observation,onSimulationStateChange:f}},[e,c,f]),rerunKey:o}}function Wo(e,t,n){const i=n?.hasSimulationMode?function(e){const t=e=>"string"==typeof e&&No.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=P(i.chartMode,{width:e.width,height:e.height,enableHover:e.enableHover,title:e.title,description:e.description,summary:e.summary,accessibleTable:e.accessibleTable,mobileInteraction:e.mobileInteraction,mobileSemantics:e.mobileSemantics,responsiveRules:e.responsiveRules},{width:t[0],height:t[1]}),r=e.size?.[0],s=e.size?.[1],a=t[0],c=t[1],l=Co(()=>{return e=[a,c],(null!=r&&null!=s?[r,s]:void 0)??[o.width??e[0],o.height??e[1]];var e},[c,a,o.height,o.width,s,r]),d=o.compactMode?"sparkline"===i.chartMode?{top:2,right:2,bottom:2,left:2}:{top:8,right:8,bottom:8,left:8}:{top:0,right:0,bottom:0,left:0};const u=e.showProjection??!o.compactMode,h=e.showChrome??!o.compactMode,p=Yo(e.tooltip,void 0),m=void 0!==p.enableHover?p.enableHover:o.enableHover,f=o.compactMode?o.title:o.title??e.title,y=[e.className,i.chartMode&&"primary"!==i.chartMode?"semiotic-physics--"+i.chartMode:null].filter(Boolean).join(" ")||void 0;return{chartMode:i.chartMode,simulationMode:i.simulationMode,resolved:o,chartSize:l,margin:d,showProjection:u,showChrome:h,enableHover:m,title:f,description:o.description??e.description,summary:o.summary??e.summary,accessibleTable:o.accessibleTable??e.accessibleTable,className:y,compactMode:o.compactMode,mobileInteraction:o.mobileInteraction,mobileSemantics:o.mobileSemantics}}function $o(e){const[t,n]=e.size;return L(e.loading,t,n,e.loadingContent)||$(e.data,t,n,e.emptyContent)}function Lo(e,t,n){return Oo(W,{componentName:e,width:t[0],height:t[1],children:n})}function Ho(e,t){return e?t?n=>Eo(qo,{children:["function"==typeof e?e(n):e,"function"==typeof t?t(n):t]}):e:t}function Yo(e,t){return!1===e?{enableHover:!1}:{enableHover:t?.enableHover,tooltipContent:k(e)||t?.tooltipContent}}function Xo(e,t,n,i){return{accessibleTable:i?.accessibleTable??e.accessibleTable??t?.accessibleTable,annotations:e.annotations??t?.annotations,autoPlaceAnnotations:e.autoPlaceAnnotations??t?.autoPlaceAnnotations,background:e.background??t?.background,chartId:e.chartId??t?.chartId,chartMode:i?.chartMode??t?.chartMode,className:i?.className??e.className??t?.className,color:e.color??t?.color,description:i?.description??e.description??t?.description,emphasis:e.emphasis??t?.emphasis,enableHover:i?.enableHover??t?.enableHover,hoverRadius:e.hoverRadius??t?.hoverRadius,legend:e.legend??t?.legend,legendLayout:e.legendLayout??t?.legendLayout,legendPosition:e.legendPosition??t?.legendPosition,margin:i?.margin??t?.margin,maxDevicePixelRatio:e.maxDevicePixelRatio??t?.maxDevicePixelRatio,onClick:null!=e.onClick?(t,n)=>{t&&e.onClick?.(t,{x:n.x,y:n.y})}:t?.onClick,onObservation:e.onObservation??t?.onObservation,onAnnotationActivate:t?.onAnnotationActivate,opacity:e.opacity??t?.opacity,selection:i?.selection??t?.selection,semanticItems:t?.semanticItems??n,stroke:e.stroke??t?.stroke,strokeWidth:e.strokeWidth??t?.strokeWidth,summary:i?.summary??e.summary??t?.summary,svgAnnotationRules:e.svgAnnotationRules??t?.svgAnnotationRules,title:i?.title??e.title??t?.title}}import{scaleLinear as Vo}from"d3-scale";function _o(e,t){const n=t.config??{},i=(t.sensors??[]).map(e=>({...e,sensor:!0})),o=[...t.colliders??[],...i],r=[...e.colliders??[],...n.colliders??[],...o];return{...e,...n,observation:{...e.observation,...n.observation},...r.length>0&&{colliders:r}}}function Ko(e){const t=function(e,t,n){const i=e?.observation;return{...e,observation:{...i,chartId:t??i?.chartId??"physics-custom",chartType:i?.chartType??"PhysicsCustomChart",onObservation:n??i?.onObservation}}}(e.config,e.chartId,e.onObservation),n=r(e.colorScheme,e.themeCategorical,R),i=bi(e.size),s={data:e.data,scales:{x:Vo().domain(e.xExtent??[0,1]).range([i.plot.x,i.plot.x+i.plot.width]),y:Vo().domain(e.yExtent??[0,1]).range([i.plot.y+i.plot.height,i.plot.y])},dimensions:i,theme:{semantic:e.semantic,categorical:[...n]},resolveColor:o(n,e.colorScheme),config:e.layoutConfig??{},world:new It(t)},a=e.skipLayout?{}:e.layout(s)??{},c=function(e,t){if(!t?.length)return e;const n=new Map;for(const e of t){const{bodyId:t,...i}=e,o=n.get(t)??[];o.push(i),n.set(t,o)}return e.map(e=>{const t=n.get(e.id);return t?.length?{...e,springs:[...e.springs??[],...t]}:e})}([...a.initialSpawns??a.bodies??[]],a.constraints);return{config:_o(t,a),context:s,initialSpawnPacing:a.initialSpawnPacing,initialSpawns:c,result:a}}import{jsx as Go}from"react/jsx-runtime";var Uo=go(function(e,t){const{chartId:n,color:i,colorBy:o,colorScheme:r,config:s,controllers:a,data:c,emptyContent:l,frameProps:d={},layout:u,layoutConfig:h,loading:p,loadingContent:m,onObservation:f,opacity:y,paused:g,spawnDatum:b,stroke:x,strokeWidth:w,title:S,xExtent:k,yExtent:M}=e,I=Wo(e,[700,380]),{chartSize:A,className:B,title:R,chartMode:C,margin:P,enableHover:T,description:q,summary:O,accessibleTable:E}=I,F=xo(null),D=xo(null),W=xo(""),{selection:$,onBodyHover:L}=jo({selection:e.selection,linkedHover:e.linkedHover,colorBy:o,chartType:"PhysicsCustomChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:d?.onBodyHover}),H=$o({data:c,emptyContent:l,loading:p,loadingContent:m,size:A}),Y=null!=H,X=vo(()=>v(c??[]),[c]),V=z(e=>e.theme),_=vo(()=>N(V)??{},[V]),K=V?.colors?.categorical??j.colors.categorical,G=vo(()=>[A[0],A[1],X.length,X.map((e,t)=>(e.id??t)+"").join("|"),k?.join(",")??"",M?.join(",")??""].join("::"),[A,X,k,M]),U=vo(()=>Ko({chartId:n,colorScheme:r,config:s,data:X,layout:u,layoutConfig:h,onObservation:f,semantic:_,skipLayout:Y,size:A,themeCategorical:K,xExtent:k,yExtent:M}),[n,A,r,s,u,h,f,X,_,Y,K,k,M]);W.current===G&&null!=D.current||(W.current=G,D.current=U.initialSpawns);const Q=D.current,Z=vo(()=>{const e=[...U.result.controllers??[],...a??[],...d.controllers??[]];return e.length?e:void 0},[d.controllers,a,U.result.controllers]),J=vo(()=>{const e=[...U.result.regionEffects??[],...d.regionEffects??[]];return e.length?e:void 0},[d.regionEffects,U.result.regionEffects]),ee=bo(e=>{const t=e.datum,n=t&&o?function(e,t,n){return"function"==typeof n?n(e,0):e[n]}(t,0,o)+"":e.id;return{fill:i??U.context.resolveColor(n,t),stroke:x??"#111827",strokeWidth:w??1,opacity:y??.9}},[i,o,y,U.context,x,w]);Ao(t,{frameRef:F,spawnDatum:bo((e,t)=>{const i=e;if(b)return function(e,t,n){return Array.isArray(n)?{datumId:(e.id??n[0]?.id??"physics-custom-"+t)+"",spawns:n}:"spawns"in n?n:{datumId:(e.id??n.id??"physics-custom-"+t)+"",spawns:[n]}}(e,t,b(i,t,U.context));const o=Ko({chartId:n,colorScheme:r,config:s,data:[i],layout:u,layoutConfig:h,onObservation:f,semantic:_,size:A,themeCategorical:K,xExtent:k,yExtent:M}),a=o.initialSpawns.length?o.initialSpawns:[{id:(e.id??"physics-custom-"+t)+"",x:o.context.dimensions.plot.x+o.context.dimensions.plot.width/2,y:o.context.dimensions.plot.y+12,mass:1,shape:{type:"circle",radius:5},datum:e}];return{datumId:(e.id??a[0].id)+"",spawns:a}},[n,A,r,s,b,u,h,f,U.context,_,K,k,M]),seedRows:X,seedSpawns:Q});const te=bo((e,t)=>{d.onBodyPointerDown?.(e,t)},[d]);if(H)return H;const ne=Yo(e.tooltip,d),ie=Xo(e,d,U.result.semanticItems,{selection:$,chartMode:C,className:B,title:R??S,description:q,summary:O,accessibleTable:E,enableHover:T,margin:P});return Lo("PhysicsCustomChart",A,Go(yi,{...d,...ne,...ie,ref:F,onBodyHover:L,backgroundGraphics:Ho(d.backgroundGraphics,U.result.backgroundOverlays),bodyForces:U.result.bodyForces??d.bodyForces,bodyStyle:U.result.bodyStyle??d.bodyStyle??ee,config:U.config,controllers:Z,foregroundGraphics:Ho(d.foregroundGraphics,U.result.overlays),initialSpawnPacing:U.initialSpawnPacing,initialSpawns:Q,onBodyPointerDown:te,paused:g,regionEffects:J,responsiveHeight:e.responsiveHeight,responsiveWidth:e.responsiveWidth,selectedBodyStyle:U.result.selectedBodyStyle??d.selectedBodyStyle,size:A}))});Uo.displayName="PhysicsCustomChart";export{X as DEFAULT_PHYSICS_CANVAS_THEME,K as physicsCanvasColorWithAlpha,G as resolvePhysicsCanvasTheme,ne as bodiesToAnnotationAnchors,ie as buildPhysicsAnnotationContext,oe as normalizePhysicsAnnotations,re as PhysicsSVGOverlay,qe as BuiltInPhysicsEngineAdapter,Oe as createDefaultPhysicsEngineAdapter,He as PhysicsSedimentAccumulator,Ye as sedimentHeightfield,Ve as evaluatePhysicsBodyBudget,Je as schedulePhysicsSpawns,at as collidersFromPlotBounds,ct as collidersFromXScaleBins,It as PhysicsPipelineStore,Bt as buildPhysicsSettledEvidence,Tt as physicsBodyToXYSceneNode,qt as physicsBodiesToXYSceneNodes,Ot as buildPhysicsSettledScene,zt as renderPhysicsSettledSVG,Ht as createCapacityQueueController,Yt as createServiceResourcePoolController,Vt as createServiceLevelController,_t as createDependencyGateController,Gt as composePhysicsControllers,Ut as createPortalController,Jt as collidersFromPhysicsAnnotations,en as resolvePhysicsBodyAnnotations,tn as summarizePhysicsAnnotations,fi as StreamPhysicsFrame,yi as StreamPhysicsFrame_default,bi as physicsChartArea,xi as styleFromColorAccessor,Si as projectionRowsToSemanticItems,Ci as generateGaltonMechanicalSamples,Pi as buildGaltonBoardPhysics,Oi as buildEventDropPhysics,Ei as placeEventDropSpawn,Fi as generatePhysicsPileMechanicalSamples,Di as pileTubeGeometry,ji as buildPhysicsPile,zi as buildCollisionSwarmPhysics,Vi as buildPhysicalFlowPhysics,_i as aggregateRegionCounts,Ki as regionCountsToProjectionRows,Gi as groupCompletionRows,Qi as stageTargetInVolume,Zi as processVolumePolygons,to as processStageLayout,io as processStageRegions,oo as membraneRegion,ro as chargeGateRegion,so as routeSurfaceRegion,ao as pressureFieldRegion,co as capacitatedRegion,lo as portalRegion,uo as absorbRegion,ho as forceFieldRegion,po as bodyGroupSpec,mo as processLaneWalls,yo as buildProcessFlowPhysics,Ao as usePhysicsHocHandle,jo as usePhysicsSelection,zo as usePhysicsRerun,Wo as usePhysicsChartMode,$o as renderPhysicsChartState,Lo as renderPhysicsFrame,Ho as composePhysicsFrameGraphics,Yo as resolvePhysicsTooltipProps,Xo as resolvePhysicsFrameSharedProps,Uo as PhysicsCustomChart};