@simten/embed 0.1.12 → 0.1.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/circuit-embed.js +1 -1
- package/package.json +3 -3
package/dist/circuit-embed.js
CHANGED
|
@@ -76,4 +76,4 @@ main:
|
|
|
76
76
|
`),()=>{R.contains(E)&&R.removeChild(E)}},[e]),M.jsx(CH,{isPresent:e,childRef:u,sizeRef:d,pop:a,children:a===!1?t:N.cloneElement(t,{ref:m})})}const NH=({children:t,initial:e,isPresent:n,onExitComplete:o,custom:s,presenceAffectsLayout:a,mode:l,anchorX:u,anchorY:d,root:h})=>{const p=Yh(AH),m=N.useId();let y=!0,b=N.useMemo(()=>(y=!1,{id:m,initial:e,isPresent:n,custom:s,onExitComplete:x=>{p.set(x,!0);for(const w of p.values())if(!w)return;o&&o()},register:x=>(p.set(x,!1),()=>p.delete(x))}),[n,p,o]);return a&&y&&(b={...b}),N.useMemo(()=>{p.forEach((x,w)=>p.set(w,!1))},[n]),N.useEffect(()=>{!n&&!p.size&&o&&o()},[n]),t=M.jsx(TH,{pop:l==="popLayout",isPresent:n,anchorX:u,anchorY:d,root:h,children:t}),M.jsx(Yc.Provider,{value:b,children:t})};function AH(){return new Map}function qS(t=!0){const e=N.useContext(Yc);if(e===null)return[!0,null];const{isPresent:n,onExitComplete:o,register:s}=e,a=N.useId();N.useEffect(()=>{if(t)return s(a)},[t]);const l=N.useCallback(()=>t&&o&&o(a),[a,o,t]);return!n&&o?[!1,l]:[!0]}const cu=t=>t.key||"";function GS(t){const e=[];return N.Children.forEach(t,n=>{N.isValidElement(n)&&e.push(n)}),e}const FS=({children:t,custom:e,initial:n=!0,onExitComplete:o,presenceAffectsLayout:s=!0,mode:a="sync",propagate:l=!1,anchorX:u="left",anchorY:d="top",root:h})=>{const[p,m]=qS(l),y=N.useMemo(()=>GS(t),[t]),b=l&&!p?[]:y.map(cu),x=N.useRef(!0),w=N.useRef(y),_=Yh(()=>new Map),S=N.useRef(new Set),[k,C]=N.useState(y),[E,R]=N.useState(y);y1(()=>{x.current=!1,w.current=y;for(let D=0;D<E.length;D++){const $=cu(E[D]);b.includes($)?(_.delete($),S.current.delete($)):_.get($)!==!0&&_.set($,!1)}},[E,b.length,b.join("-")]);const A=[];if(y!==k){let D=[...y];for(let $=0;$<E.length;$++){const q=E[$],Y=cu(q);b.includes(Y)||(D.splice($,0,q),A.push(q))}return a==="wait"&&A.length&&(D=A),R(GS(D)),C(y),null}const{forceRender:O}=N.useContext(Uh);return M.jsx(M.Fragment,{children:E.map(D=>{const $=cu(D),q=l&&!p?!1:y===E||b.includes($),Y=()=>{if(S.current.has($))return;if(S.current.add($),_.has($))_.set($,!0);else return;let K=!0;_.forEach(W=>{W||(K=!1)}),K&&(O?.(),R(w.current),l&&m?.(),o&&o())};return M.jsx(NH,{isPresent:q,initial:!x.current||n?void 0:!1,custom:e,presenceAffectsLayout:s,mode:a,root:h,onExitComplete:q?void 0:Y,anchorX:u,anchorY:d,children:D},$)})})},XS=N.createContext({strict:!1}),ZS={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]};let KS=!1;function MH(){if(KS)return;const t={};for(const e in ZS)t[e]={isEnabled:n=>ZS[e].some(o=>!!n[o])};U_(t),KS=!0}function QS(){return MH(),mB()}function RH(t){const e=QS();for(const n in t)e[n]={...e[n],...t[n]};U_(e)}const kH=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","propagate","ignoreStrict","viewport"]);function uu(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||kH.has(t)}let WS=t=>!uu(t);function OH(t){typeof t=="function"&&(WS=e=>e.startsWith("on")?!uu(e):t(e))}try{OH(require("@emotion/is-prop-valid").default)}catch{}function DH(t,e,n){const o={};for(const s in t)s==="values"&&typeof t.values=="object"||(WS(s)||n===!0&&uu(s)||!e&&!uu(s)||t.draggable&&s.startsWith("onDrag"))&&(o[s]=t[s]);return o}const fu=N.createContext({});function jH(t,e){if(iu(t)){const{initial:n,animate:o}=t;return{initial:n===!1||Ra(n)?n:void 0,animate:Ra(o)?o:void 0}}return t.inherit!==!1?e:{}}function zH(t){const{initial:e,animate:n}=jH(t,N.useContext(fu));return N.useMemo(()=>({initial:e,animate:n}),[JS(e),JS(n)])}function JS(t){return Array.isArray(t)?t.join(" "):t}const Qp=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function t2(t,e,n){for(const o in e)!Ue(e[o])&&!nS(o,n)&&(t[o]=e[o])}function VH({transformTemplate:t},e){return N.useMemo(()=>{const n=Qp();return Yp(n,e,t),Object.assign({},n.vars,n.style)},[e])}function LH(t,e){const n=t.style||{},o={};return t2(o,n,t),Object.assign(o,VH(t,e)),o}function IH(t,e){const n={},o=LH(t,e);return t.drag&&t.dragListener!==!1&&(n.draggable=!1,o.userSelect=o.WebkitUserSelect=o.WebkitTouchCallout="none",o.touchAction=t.drag===!0?"none":`pan-${t.drag==="x"?"y":"x"}`),t.tabIndex===void 0&&(t.onTap||t.onTapStart||t.whileTap)&&(n.tabIndex=0),n.style=o,n}const e2=()=>({...Qp(),attrs:{}});function PH(t,e,n,o){const s=N.useMemo(()=>{const a=e2();return iS(a,e,rS(o),t.transformTemplate,t.style),{...a.attrs,style:{...a.style}}},[e]);if(t.style){const a={};t2(a,t.style,t),s.style={...a,...s.style}}return s}const BH=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function Wp(t){return typeof t!="string"||t.includes("-")?!1:!!(BH.indexOf(t)>-1||/[A-Z]/u.test(t))}function HH(t,e,n,{latestValues:o},s,a=!1,l){const d=(l??Wp(t)?PH:IH)(e,o,s,t),h=DH(e,typeof t=="string",a),p=t!==N.Fragment?{...h,...d,ref:n}:{},{children:m}=e,y=N.useMemo(()=>Ue(m)?m.get():m,[m]);return N.createElement(t,{...p,children:y})}function $H({scrapeMotionValuesFromProps:t,createRenderState:e},n,o,s){return{latestValues:UH(n,o,s,t),renderState:e()}}function UH(t,e,n,o){const s={},a=o(t,{});for(const y in a)s[y]=au(a[y]);let{initial:l,animate:u}=t;const d=iu(t),h=B_(t);e&&h&&!d&&t.inherit!==!1&&(l===void 0&&(l=e.initial),u===void 0&&(u=e.animate));let p=n?n.initial===!1:!1;p=p||l===!1;const m=p?u:l;if(m&&typeof m!="boolean"&&!nu(m)){const y=Array.isArray(m)?m:[m];for(let b=0;b<y.length;b++){const x=Cp(t,y[b]);if(x){const{transitionEnd:w,transition:_,...S}=x;for(const k in S){let C=S[k];if(Array.isArray(C)){const E=p?C.length-1:0;C=C[E]}C!==null&&(s[k]=C)}for(const k in w)s[k]=w[k]}}}return s}const n2=t=>(e,n)=>{const o=N.useContext(fu),s=N.useContext(Yc),a=()=>$H(t,e,o,s);return n?a():Yh(a)},YH=n2({scrapeMotionValuesFromProps:Gp,createRenderState:Qp}),qH=n2({scrapeMotionValuesFromProps:sS,createRenderState:e2}),GH=Symbol.for("motionComponentSymbol");function FH(t,e,n){const o=N.useRef(n);N.useInsertionEffect(()=>{o.current=n});const s=N.useRef(null);return N.useCallback(a=>{a&&t.onMount?.(a),e&&(a?e.mount(a):e.unmount());const l=o.current;if(typeof l=="function")if(a){const u=l(a);typeof u=="function"&&(s.current=u)}else s.current?(s.current(),s.current=null):l(a);else l&&(l.current=a)},[e])}const i2=N.createContext({});function Jr(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function XH(t,e,n,o,s,a){const{visualElement:l}=N.useContext(fu),u=N.useContext(XS),d=N.useContext(Yc),h=N.useContext(Kp),p=h.reducedMotion,m=h.skipAnimations,y=N.useRef(null),b=N.useRef(!1);o=o||u.renderer,!y.current&&o&&(y.current=o(t,{visualState:e,parent:l,props:n,presenceContext:d,blockInitialAnimation:d?d.initial===!1:!1,reducedMotionConfig:p,skipAnimations:m,isSVG:a}),b.current&&y.current&&(y.current.manuallyAnimateOnMount=!0));const x=y.current,w=N.useContext(i2);x&&!x.projection&&s&&(x.type==="html"||x.type==="svg")&&ZH(y.current,n,s,w);const _=N.useRef(!1);N.useInsertionEffect(()=>{x&&_.current&&x.update(n,d)});const S=n[b_],k=N.useRef(!!S&&!window.MotionHandoffIsComplete?.(S)&&window.MotionHasOptimisedAnimation?.(S));return y1(()=>{b.current=!0,x&&(_.current=!0,window.MotionIsMounted=!0,x.updateFeatures(),x.scheduleRenderMicrotask(),k.current&&x.animationState&&x.animationState.animateChanges())}),N.useEffect(()=>{x&&(!k.current&&x.animationState&&x.animationState.animateChanges(),k.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(S)}),k.current=!1),x.enteringChildren=void 0)}),x}function ZH(t,e,n,o){const{layoutId:s,layout:a,drag:l,dragConstraints:u,layoutScroll:d,layoutRoot:h,layoutCrossfade:p}=e;t.projection=new n(t.latestValues,e["data-framer-portal-id"]?void 0:o2(t.parent)),t.projection.setOptions({layoutId:s,layout:a,alwaysMeasureLayout:!!l||u&&Jr(u),visualElement:t,animationType:typeof a=="string"?a:"both",initialPromotionConfig:o,crossfade:p,layoutScroll:d,layoutRoot:h})}function o2(t){if(t)return t.options.allowProjection!==!1?t.projection:o2(t.parent)}function Jp(t,{forwardMotionProps:e=!1,type:n}={},o,s){o&&RH(o);const a=n?n==="svg":Wp(t),l=a?qH:YH;function u(h,p){let m;const y={...N.useContext(Kp),...h,layoutId:KH(h)},{isStatic:b}=y,x=zH(h),w=l(h,b);if(!b&&g1){QH();const _=WH(y);m=_.MeasureLayout,x.visualElement=XH(t,w,y,s,_.ProjectionNode,a)}return M.jsxs(fu.Provider,{value:x,children:[m&&x.visualElement?M.jsx(m,{visualElement:x.visualElement,...y}):null,HH(t,h,FH(w,x.visualElement,p),w,b,e,a)]})}u.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const d=N.forwardRef(u);return d[GH]=t,d}function KH({layoutId:t}){const e=N.useContext(Uh).id;return e&&t!==void 0?e+"-"+t:t}function QH(t,e){N.useContext(XS).strict}function WH(t){const e=QS(),{drag:n,layout:o}=e;if(!n&&!o)return{};const s={...n,...o};return{MeasureLayout:n?.isEnabled(t)||o?.isEnabled(t)?s.MeasureLayout:void 0,ProjectionNode:s.ProjectionNode}}function JH(t,e){if(typeof Proxy>"u")return Jp;const n=new Map,o=(a,l)=>Jp(a,l,t,e),s=(a,l)=>o(a,l);return new Proxy(s,{get:(a,l)=>l==="create"?o:(n.has(l)||n.set(l,Jp(l,void 0,t,e)),n.get(l))})}const t$=(t,e)=>e.isSVG??Wp(t)?new OB(e):new TB(e,{allowProjection:t!==N.Fragment});class e$ extends to{constructor(e){super(e),e.animationState||(e.animationState=LB(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();nu(e)&&(this.unmountControls=e.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:e}=this.node.getProps(),{animate:n}=this.node.prevProps||{};e!==n&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}}let n$=0;class i$ extends to{constructor(){super(...arguments),this.id=n$++}update(){if(!this.node.presenceContext)return;const{isPresent:e,onExitComplete:n}=this.node.presenceContext,{isPresent:o}=this.node.prevPresenceContext||{};if(!this.node.animationState||e===o)return;const s=this.node.animationState.setActive("exit",!e);n&&!e&&s.then(()=>{n(this.id)})}mount(){const{register:e,onExitComplete:n}=this.node.presenceContext||{};n&&n(this.id),e&&(this.unmount=e(this.id))}unmount(){}}const o$={animation:{Feature:e$},exit:{Feature:i$}};function ja(t){return{point:{x:t.pageX,y:t.pageY}}}const r$=t=>e=>zp(e)&&t(e,ja(e));function za(t,e,n,o){return Da(t,e,r$(n),o)}const r2=({current:t})=>t?t.ownerDocument.defaultView:null,s2=(t,e)=>Math.abs(t-e);function s$(t,e){const n=s2(t.x,e.x),o=s2(t.y,e.y);return Math.sqrt(n**2+o**2)}const a2=new Set(["auto","scroll"]);class l2{constructor(e,n,{transformPagePoint:o,contextWindow:s=window,dragSnapToOrigin:a=!1,distanceThreshold:l=3,element:u}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=b=>{this.handleScroll(b.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const b=em(this.lastMoveEventInfo,this.history),x=this.startEvent!==null,w=s$(b.offset,{x:0,y:0})>=this.distanceThreshold;if(!x&&!w)return;const{point:_}=b,{timestamp:S}=Le;this.history.push({..._,timestamp:S});const{onStart:k,onMove:C}=this.handlers;x||(k&&k(this.lastMoveEvent,b),this.startEvent=this.lastMoveEvent),C&&C(this.lastMoveEvent,b)},this.handlePointerMove=(b,x)=>{this.lastMoveEvent=b,this.lastMoveEventInfo=tm(x,this.transformPagePoint),re.update(this.updatePoint,!0)},this.handlePointerUp=(b,x)=>{this.end();const{onEnd:w,onSessionEnd:_,resumeAnimation:S}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&S&&S(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const k=em(b.type==="pointercancel"?this.lastMoveEventInfo:tm(x,this.transformPagePoint),this.history);this.startEvent&&w&&w(b,k),_&&_(b,k)},!zp(e))return;this.dragSnapToOrigin=a,this.handlers=n,this.transformPagePoint=o,this.distanceThreshold=l,this.contextWindow=s||window;const d=ja(e),h=tm(d,this.transformPagePoint),{point:p}=h,{timestamp:m}=Le;this.history=[{...p,timestamp:m}];const{onSessionStart:y}=n;y&&y(e,em(h,this.history)),this.removeListeners=wa(za(this.contextWindow,"pointermove",this.handlePointerMove),za(this.contextWindow,"pointerup",this.handlePointerUp),za(this.contextWindow,"pointercancel",this.handlePointerUp)),u&&this.startScrollTracking(u)}startScrollTracking(e){let n=e.parentElement;for(;n;){const o=getComputedStyle(n);(a2.has(o.overflowX)||a2.has(o.overflowY))&&this.scrollPositions.set(n,{x:n.scrollLeft,y:n.scrollTop}),n=n.parentElement}this.scrollPositions.set(window,{x:window.scrollX,y:window.scrollY}),window.addEventListener("scroll",this.onElementScroll,{capture:!0}),window.addEventListener("scroll",this.onWindowScroll),this.removeScrollListeners=()=>{window.removeEventListener("scroll",this.onElementScroll,{capture:!0}),window.removeEventListener("scroll",this.onWindowScroll)}}handleScroll(e){const n=this.scrollPositions.get(e);if(!n)return;const o=e===window,s=o?{x:window.scrollX,y:window.scrollY}:{x:e.scrollLeft,y:e.scrollTop},a={x:s.x-n.x,y:s.y-n.y};a.x===0&&a.y===0||(o?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=a.x,this.lastMoveEventInfo.point.y+=a.y):this.history.length>0&&(this.history[0].x-=a.x,this.history[0].y-=a.y),this.scrollPositions.set(e,s),re.update(this.updatePoint,!0))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),Qi(this.updatePoint)}}function tm(t,e){return e?{point:e(t.point)}:t}function c2(t,e){return{x:t.x-e.x,y:t.y-e.y}}function em({point:t},e){return{point:t,delta:c2(t,u2(e)),offset:c2(t,a$(e)),velocity:l$(e,.1)}}function a$(t){return t[0]}function u2(t){return t[t.length-1]}function l$(t,e){if(t.length<2)return{x:0,y:0};let n=t.length-1,o=null;const s=u2(t);for(;n>=0&&(o=t[n],!(s.timestamp-o.timestamp>Ln(e)));)n--;if(!o)return{x:0,y:0};o===t[0]&&t.length>2&&s.timestamp-o.timestamp>Ln(e)*2&&(o=t[1]);const a=bn(s.timestamp-o.timestamp);if(a===0)return{x:0,y:0};const l={x:(s.x-o.x)/a,y:(s.y-o.y)/a};return l.x===1/0&&(l.x=0),l.y===1/0&&(l.y=0),l}function c$(t,{min:e,max:n},o){return e!==void 0&&t<e?t=o?he(e,t,o.min):Math.max(t,e):n!==void 0&&t>n&&(t=o?he(n,t,o.max):Math.min(t,n)),t}function f2(t,e,n){return{min:e!==void 0?t.min+e:void 0,max:n!==void 0?t.max+n-(t.max-t.min):void 0}}function u$(t,{top:e,left:n,bottom:o,right:s}){return{x:f2(t.x,n,s),y:f2(t.y,e,o)}}function d2(t,e){let n=e.min-t.min,o=e.max-t.max;return e.max-e.min<t.max-t.min&&([n,o]=[o,n]),{min:n,max:o}}function f$(t,e){return{x:d2(t.x,e.x),y:d2(t.y,e.y)}}function d$(t,e){let n=.5;const o=Ge(t),s=Ge(e);return s>o?n=_a(e.min,e.max-o,t.min):o>s&&(n=_a(t.min,t.max-s,e.min)),ni(0,1,n)}function h$(t,e){const n={};return e.min!==void 0&&(n.min=e.min-t.min),e.max!==void 0&&(n.max=e.max-t.min),n}const nm=.35;function p$(t=nm){return t===!1?t=0:t===!0&&(t=nm),{x:h2(t,"left","right"),y:h2(t,"top","bottom")}}function h2(t,e,n){return{min:p2(t,e),max:p2(t,n)}}function p2(t,e){return typeof t=="number"?t:t[e]||0}const m$=new WeakMap;class g${constructor(e){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=Me(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=e}start(e,{snapToCursor:n=!1,distanceThreshold:o}={}){const{presenceContext:s}=this.visualElement;if(s&&s.isPresent===!1)return;const a=m=>{n&&this.snapToCursor(ja(m).point),this.stopAnimation()},l=(m,y)=>{const{drag:b,dragPropagation:x,onDragStart:w}=this.getProps();if(b&&!x&&(this.openDragLock&&this.openDragLock(),this.openDragLock=qP(b),!this.openDragLock))return;this.latestPointerEvent=m,this.latestPanInfo=y,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),oi(S=>{let k=this.getAxisMotionValue(S).get()||0;if(ii.test(k)){const{projection:C}=this.visualElement;if(C&&C.layout){const E=C.layout.layoutBox[S];E&&(k=Ge(E)*(parseFloat(k)/100))}}this.originPoint[S]=k}),w&&re.update(()=>w(m,y),!1,!0),Np(this.visualElement,"transform");const{animationState:_}=this.visualElement;_&&_.setActive("whileDrag",!0)},u=(m,y)=>{this.latestPointerEvent=m,this.latestPanInfo=y;const{dragPropagation:b,dragDirectionLock:x,onDirectionLock:w,onDrag:_}=this.getProps();if(!b&&!this.openDragLock)return;const{offset:S}=y;if(x&&this.currentDirection===null){this.currentDirection=v$(S),this.currentDirection!==null&&w&&w(this.currentDirection);return}this.updateAxis("x",y.point,S),this.updateAxis("y",y.point,S),this.visualElement.render(),_&&re.update(()=>_(m,y),!1,!0)},d=(m,y)=>{this.latestPointerEvent=m,this.latestPanInfo=y,this.stop(m,y),this.latestPointerEvent=null,this.latestPanInfo=null},h=()=>{const{dragSnapToOrigin:m}=this.getProps();(m||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:p}=this.getProps();this.panSession=new l2(e,{onSessionStart:a,onStart:l,onMove:u,onSessionEnd:d,resumeAnimation:h},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:p,distanceThreshold:o,contextWindow:r2(this.visualElement),element:this.visualElement.current})}stop(e,n){const o=e||this.latestPointerEvent,s=n||this.latestPanInfo,a=this.isDragging;if(this.cancel(),!a||!s||!o)return;const{velocity:l}=s;this.startAnimation(l);const{onDragEnd:u}=this.getProps();u&&re.postRender(()=>u(o,s))}cancel(){this.isDragging=!1;const{projection:e,animationState:n}=this.visualElement;e&&(e.isAnimationBlocked=!1),this.endPanSession();const{dragPropagation:o}=this.getProps();!o&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),n&&n.setActive("whileDrag",!1)}endPanSession(){this.panSession&&this.panSession.end(),this.panSession=void 0}updateAxis(e,n,o){const{drag:s}=this.getProps();if(!o||!du(e,s,this.currentDirection))return;const a=this.getAxisMotionValue(e);let l=this.originPoint[e]+o[e];this.constraints&&this.constraints[e]&&(l=c$(l,this.constraints[e],this.elastic[e])),a.set(l)}resolveConstraints(){const{dragConstraints:e,dragElastic:n}=this.getProps(),o=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,s=this.constraints;e&&Jr(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&o?this.constraints=u$(o.layoutBox,e):this.constraints=!1,this.elastic=p$(n),s!==this.constraints&&!Jr(e)&&o&&this.constraints&&!this.hasMutatedConstraints&&oi(a=>{this.constraints!==!1&&this.getAxisMotionValue(a)&&(this.constraints[a]=h$(o.layoutBox[a],this.constraints[a]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:n}=this.getProps();if(!e||!Jr(e))return!1;const o=e.current,{projection:s}=this.visualElement;if(!s||!s.layout)return!1;const a=xB(o,s.root,this.visualElement.getTransformPagePoint());let l=f$(s.layout.layoutBox,a);if(n){const u=n(yB(l));this.hasMutatedConstraints=!!u,u&&(l=q_(u))}return l}startAnimation(e){const{drag:n,dragMomentum:o,dragElastic:s,dragTransition:a,dragSnapToOrigin:l,onDragTransitionEnd:u}=this.getProps(),d=this.constraints||{},h=oi(p=>{if(!du(p,n,this.currentDirection))return;let m=d&&d[p]||{};l&&(m={min:0,max:0});const y=s?200:1e6,b=s?40:1e7,x={type:"inertia",velocity:o?e[p]:0,bounceStiffness:y,bounceDamping:b,timeConstant:750,restDelta:1,restSpeed:10,...a,...m};return this.startAxisValueAnimation(p,x)});return Promise.all(h).then(u)}startAxisValueAnimation(e,n){const o=this.getAxisMotionValue(e);return Np(this.visualElement,e),o.start(Ep(e,o,0,n,this.visualElement,!1))}stopAnimation(){oi(e=>this.getAxisMotionValue(e).stop())}getAxisMotionValue(e){const n=`_drag${e.toUpperCase()}`,o=this.visualElement.getProps(),s=o[n];return s||this.visualElement.getValue(e,(o.initial?o.initial[e]:void 0)||0)}snapToCursor(e){oi(n=>{const{drag:o}=this.getProps();if(!du(n,o,this.currentDirection))return;const{projection:s}=this.visualElement,a=this.getAxisMotionValue(n);if(s&&s.layout){const{min:l,max:u}=s.layout.layoutBox[n],d=a.get()||0;a.set(e[n]-he(l,u,.5)+d)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:n}=this.getProps(),{projection:o}=this.visualElement;if(!Jr(n)||!o||!this.constraints)return;this.stopAnimation();const s={x:0,y:0};oi(l=>{const u=this.getAxisMotionValue(l);if(u&&this.constraints!==!1){const d=u.get();s[l]=d$({min:d,max:d},this.constraints[l])}});const{transformTemplate:a}=this.visualElement.getProps();this.visualElement.current.style.transform=a?a({},""):"none",o.root&&o.root.updateScroll(),o.updateLayout(),this.constraints=!1,this.resolveConstraints(),oi(l=>{if(!du(l,e,null))return;const u=this.getAxisMotionValue(l),{min:d,max:h}=this.constraints[l];u.set(he(d,h,s[l]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;m$.set(this.visualElement,this);const e=this.visualElement.current,n=za(e,"pointerdown",h=>{const{drag:p,dragListener:m=!0}=this.getProps(),y=h.target,b=y!==e&&QP(y);p&&m&&!b&&this.start(h)});let o;const s=()=>{const{dragConstraints:h}=this.getProps();Jr(h)&&h.current&&(this.constraints=this.resolveRefConstraints(),o||(o=y$(e,h.current,()=>this.scalePositionWithinConstraints())))},{projection:a}=this.visualElement,l=a.addEventListener("measure",s);a&&!a.layout&&(a.root&&a.root.updateScroll(),a.updateLayout()),re.read(s);const u=Da(window,"resize",()=>this.scalePositionWithinConstraints()),d=a.addEventListener("didUpdate",(({delta:h,hasLayoutChanged:p})=>{this.isDragging&&p&&(oi(m=>{const y=this.getAxisMotionValue(m);y&&(this.originPoint[m]+=h[m].translate,y.set(y.get()+h[m].translate))}),this.visualElement.render())}));return()=>{u(),n(),l(),d&&d(),o&&o()}}getProps(){const e=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:o=!1,dragPropagation:s=!1,dragConstraints:a=!1,dragElastic:l=nm,dragMomentum:u=!0}=e;return{...e,drag:n,dragDirectionLock:o,dragPropagation:s,dragConstraints:a,dragElastic:l,dragMomentum:u}}}function m2(t){let e=!0;return()=>{if(e){e=!1;return}t()}}function y$(t,e,n){const o=L_(t,m2(n)),s=L_(e,m2(n));return()=>{o(),s()}}function du(t,e,n){return(e===!0||e===t)&&(n===null||n===t)}function v$(t,e=10){let n=null;return Math.abs(t.y)>e?n="y":Math.abs(t.x)>e&&(n="x"),n}class b$ extends to{constructor(e){super(e),this.removeGroupControls=vn,this.removeListeners=vn,this.controls=new g$(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||vn}update(){const{dragControls:e}=this.node.getProps(),{dragControls:n}=this.node.prevProps||{};e!==n&&(this.removeGroupControls(),e&&(this.removeGroupControls=e.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners(),this.controls.isDragging||this.controls.endPanSession()}}const im=t=>(e,n)=>{t&&re.update(()=>t(e,n),!1,!0)};class x$ extends to{constructor(){super(...arguments),this.removePointerDownListener=vn}onPointerDown(e){this.session=new l2(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:r2(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:n,onPan:o,onPanEnd:s}=this.node.getProps();return{onSessionStart:im(e),onStart:im(n),onMove:im(o),onEnd:(a,l)=>{delete this.session,s&&re.postRender(()=>s(a,l))}}}mount(){this.removePointerDownListener=za(this.node.current,"pointerdown",e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}let om=!1;class w$ extends N.Component{componentDidMount(){const{visualElement:e,layoutGroup:n,switchLayoutGroup:o,layoutId:s}=this.props,{projection:a}=e;a&&(n.group&&n.group.add(a),o&&o.register&&s&&o.register(a),om&&a.root.didUpdate(),a.addEventListener("animationComplete",()=>{this.safeToRemove()}),a.setOptions({...a.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),lu.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:n,visualElement:o,drag:s,isPresent:a}=this.props,{projection:l}=o;return l&&(l.isPresent=a,e.layoutDependency!==n&&l.setOptions({...l.options,layoutDependency:n}),om=!0,s||e.layoutDependency!==n||n===void 0||e.isPresent!==a?l.willUpdate():this.safeToRemove(),e.isPresent!==a&&(a?l.promote():l.relegate()||re.postRender(()=>{const u=l.getStack();(!u||!u.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:e}=this.props.visualElement;e&&(e.root.didUpdate(),jp.postRender(()=>{!e.currentAnimation&&e.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:e,layoutGroup:n,switchLayoutGroup:o}=this.props,{projection:s}=e;om=!0,s&&(s.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(s),o&&o.deregister&&o.deregister(s))}safeToRemove(){const{safeToRemove:e}=this.props;e&&e()}render(){return null}}function g2(t){const[e,n]=qS(),o=N.useContext(Uh);return M.jsx(w$,{...t,layoutGroup:o,switchLayoutGroup:N.useContext(i2),isPresent:e,safeToRemove:n})}const _$={pan:{Feature:x$},drag:{Feature:b$,ProjectionNode:US,MeasureLayout:g2}};function y2(t,e,n){const{props:o}=t;t.animationState&&o.whileHover&&t.animationState.setActive("whileHover",n==="Start");const s="onHover"+n,a=o[s];a&&re.postRender(()=>a(e,ja(e)))}class S$ extends to{mount(){const{current:e}=this.node;e&&(this.unmount=FP(e,(n,o)=>(y2(this.node,o,"Start"),s=>y2(this.node,s,"End"))))}unmount(){}}class E$ extends to{constructor(){super(...arguments),this.isActive=!1}onFocus(){let e=!1;try{e=this.node.current.matches(":focus-visible")}catch{e=!0}!e||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=wa(Da(this.node.current,"focus",()=>this.onFocus()),Da(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function v2(t,e,n){const{props:o}=t;if(t.current instanceof HTMLButtonElement&&t.current.disabled)return;t.animationState&&o.whileTap&&t.animationState.setActive("whileTap",n==="Start");const s="onTap"+(n==="End"?"":n),a=o[s];a&&re.postRender(()=>a(e,ja(e)))}class C$ extends to{mount(){const{current:e}=this.node;if(!e)return;const{globalTapTarget:n,propagate:o}=this.node.props;this.unmount=JP(e,(s,a)=>(v2(this.node,a,"Start"),(l,{success:u})=>v2(this.node,l,u?"End":"Cancel")),{useGlobalTarget:n,stopPropagation:o?.tap===!1})}unmount(){}}const rm=new WeakMap,sm=new WeakMap,T$=t=>{const e=rm.get(t.target);e&&e(t)},N$=t=>{t.forEach(T$)};function A$({root:t,...e}){const n=t||document;sm.has(n)||sm.set(n,{});const o=sm.get(n),s=JSON.stringify(e);return o[s]||(o[s]=new IntersectionObserver(N$,{root:t,...e})),o[s]}function M$(t,e,n){const o=A$(e);return rm.set(t,n),o.observe(t),()=>{rm.delete(t),o.unobserve(t)}}const R$={some:0,all:1};class k$ extends to{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:e={}}=this.node.getProps(),{root:n,margin:o,amount:s="some",once:a}=e,l={root:n?n.current:void 0,rootMargin:o,threshold:typeof s=="number"?s:R$[s]},u=d=>{const{isIntersecting:h}=d;if(this.isInView===h||(this.isInView=h,a&&!h&&this.hasEnteredView))return;h&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",h);const{onViewportEnter:p,onViewportLeave:m}=this.node.getProps(),y=h?p:m;y&&y(d)};return M$(this.node.current,l,u)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:e,prevProps:n}=this.node;["amount","margin","root"].some(O$(e,n))&&this.startObserver()}unmount(){}}function O$({viewport:t={}},{viewport:e={}}={}){return n=>t[n]!==e[n]}const D$={...o$,...{inView:{Feature:k$},tap:{Feature:C$},focus:{Feature:E$},hover:{Feature:S$}},..._$,...{layout:{ProjectionNode:US,MeasureLayout:g2}}},hu=JH(D$,t$),b2="__boundary_in_",x2="__boundary_out_";function j$(t){const e=[],n=[];for(const o of t.inputs){const s=`${b2}${o.name}`,a=o.portType.kind==="bus";e.push({id:s,label:o.name,componentRef:a?"Input":"Switch",arguments:a?{value:0,width:o.portType.width}:{value:!1},inputs:[],outputs:[{id:`${s}_out`,name:"out",portType:o.portType}],clocks:[]})}for(const o of t.outputs){const s=`${x2}${o.name}`,a=o.portType.kind==="bus";e.push({id:s,label:o.name,componentRef:a?"HexDisplay":"Led",arguments:{},inputs:[{id:`${s}_in`,name:"in",portType:o.portType}],outputs:[],clocks:[]})}for(const o of t.connections){const s={...o.source},a={...o.target};o.source.nodeId===""&&(s.nodeId=`${b2}${o.source.portName}`,s.portName="out"),o.target.nodeId===""&&(a.nodeId=`${x2}${o.target.portName}`,a.portName="in"),n.push({...o,source:s,target:a})}return{...t,name:`__drilldown_${t.name}`,nodes:[...e,...t.nodes],connections:n,implementation:{kind:"primitive"}}}const De="__top__";function z$(t,e,n=!1,o){const s=[],a=[],l={path:"",componentName:t.name,children:[],primitives:[]};function u(p,m,y,b=new Set){for(const x of p.nodes){const w=m+x.id,_=e.resolveCircuit(x.componentRef);if(!_)throw new Error(`Unknown component: ${x.componentRef} (referenced by node ${w})`);if(_.implementation.kind==="primitive")s.push({id:w,primitiveType:x.componentRef,arguments:x.arguments,inputs:x.inputs.map(S=>({...S,nodeId:w})),outputs:x.outputs.map(S=>({...S,nodeId:w})),clocks:x.clocks.map(S=>({...S,nodeId:w})),dependents:[],inputSources:[]}),y.primitives.push(w);else if(_.implementation.kind==="composite"){if(b.has(x.componentRef))throw new Error(`Recursive circuit definition detected: '${x.componentRef}' references itself (cycle: ${[...b,x.componentRef].join(" → ")})`);const S={path:w,componentName:x.componentRef,children:[],primitives:[]};y.children.push(S);const k=new Set(b);k.add(x.componentRef),u(_,w+".",S,k)}else console.warn(`Intrinsic component ${x.componentRef} treated as primitive during elaboration`),s.push({id:w,primitiveType:x.componentRef,arguments:x.arguments,inputs:x.inputs.map(S=>({...S,nodeId:w})),outputs:x.outputs.map(S=>({...S,nodeId:w})),clocks:x.clocks.map(S=>({...S,nodeId:w})),dependents:[],inputSources:[]}),y.primitives.push(w)}for(const x of p.connections){const w=x.source.nodeId===""?m===""?De:m.slice(0,-1):m+x.source.nodeId,_=x.target.nodeId===""?m===""?De:m.slice(0,-1):m+x.target.nodeId;a.push({id:`${w}.${x.source.portName}->${_}.${x.target.portName}`,source:{nodeId:w,portName:x.source.portName},target:{nodeId:_,portName:x.target.portName},portType:x.portType})}}if(t.implementation.kind==="primitive"&&t.nodes.length===0){const p=t.name;s.push({id:p,primitiveType:t.name,arguments:{},inputs:t.inputs.map(m=>({id:`${p}.${m.name}`,name:m.name,portType:m.portType,nodeId:p})),outputs:t.outputs.map(m=>({id:`${p}.${m.name}`,name:m.name,portType:m.portType,nodeId:p})),clocks:t.clocks.map(m=>({id:`${p}.${m.name}`,name:m.name,nodeId:p})),dependents:[],inputSources:[]}),l.primitives.push(p);for(const m of t.inputs)a.push({id:`${De}.${m.name}->${p}.${m.name}`,source:{nodeId:De,portName:m.name},target:{nodeId:p,portName:m.name},portType:m.portType});for(const m of t.outputs)a.push({id:`${p}.${m.name}->${De}.${m.name}`,source:{nodeId:p,portName:m.name},target:{nodeId:De,portName:m.name},portType:m.portType})}else u(t,"",l,new Set([t.name]));const d=V$(t,a,s,e,"",n),h={nodes:s,connections:d,hierarchy:l,topLevelInputs:t.inputs,topLevelOutputs:t.outputs,nodeMap:new Map};return I$(h),h}function V$(t,e,n,o,s,a=!1){const l=new Map,u=new Set;function d(m,y,b=new Set){for(const x of m.nodes){const w=y+x.id,_=o.resolveCircuit(x.componentRef);if(_&&_.implementation.kind==="composite"){if(b.has(x.componentRef))continue;u.add(w),a&&console.log(`
|
|
77
77
|
=== Tracing composite: ${w} (${x.componentRef}) ===`),L$(_,w,l,o,a);const S=new Set(b);S.add(x.componentRef),d(_,w+".",S)}}}if(d(t,s,new Set([t.name])),a){console.log(`
|
|
78
78
|
=== Port Forwarding Map (${l.size} rules) ===`);for(const[m,y]of l.entries())for(const b of y)console.log(` ${m} -> ${b.nodeId}.${b.portName}`)}const h=[];for(const m of e){const y=u.has(m.source.nodeId),b=u.has(m.target.nodeId),x=b&&m.source.nodeId.startsWith(m.target.nodeId+"."),w=y&&m.target.nodeId.startsWith(m.source.nodeId+".");if(x||w){a&&console.log(` SKIP PORT FORWARDING: ${m.source.nodeId}.${m.source.portName} -> ${m.target.nodeId}.${m.target.portName}`);continue}const _=y&&b&&m.source.nodeId===m.target.nodeId,S=R=>R.nodeId===De||n.some(A=>A.id===R.nodeId),k=R=>{const A=[],O=new Set,D=[R];for(;D.length>0;){const $=D.shift(),q=`${$.nodeId}.${$.portName}`;if(!O.has(q)){if(O.add(q),S($)){A.push($);continue}if(u.has($.nodeId)&&l.has(q)){const Y=l.get(q);for(const K of Y)D.push(K)}else A.push($)}}return A.length>0?A:[R]};let C=[m.source];if(y&&!_&&(C=k(m.source),a&&C.length>0))for(const R of C)console.log(` FORWARD SOURCE: ${m.source.nodeId}.${m.source.portName} -> ${R.nodeId}.${R.portName}`);let E=[m.target];if(b&&!_&&(E=k(m.target),a&&E.length>0))for(const R of E)console.log(` FORWARD TARGET: ${m.target.nodeId}.${m.target.portName} -> ${R.nodeId}.${R.portName}`);for(const R of C)for(const A of E)R.nodeId===A.nodeId&&R.portName===A.portName||h.push({id:`${R.nodeId}.${R.portName}->${A.nodeId}.${A.portName}`,source:R,target:A,portType:m.portType})}const p=h.filter(m=>u.has(m.source.nodeId)&&m.source.nodeId===m.target.nodeId);if(p.length>0){a&&console.log(`
|
|
79
|
-
=== Eliminating ${p.length} passthrough connections ===`);const m=[],y=new Set;for(const b of h)if(u.has(b.source.nodeId)&&b.source.nodeId===b.target.nodeId){y.add(b.id),a&&console.log(` PASSTHROUGH: ${b.source.nodeId}.${b.source.portName} -> ${b.target.portName}`);const w=h.filter(S=>S.target.nodeId===b.source.nodeId&&S.target.portName===b.source.portName&&!y.has(S.id)),_=h.filter(S=>S.source.nodeId===b.target.nodeId&&S.source.portName===b.target.portName&&!y.has(S.id));for(const S of w)for(const k of _){const C={id:`${S.source.nodeId}.${S.source.portName}->${k.target.nodeId}.${k.target.portName}`,source:S.source,target:k.target,portType:b.portType};m.push(C),y.add(S.id),y.add(k.id),a&&console.log(` DIRECT: ${C.source.nodeId}.${C.source.portName} -> ${C.target.nodeId}.${C.target.portName}`)}}else y.has(b.id)||m.push(b);return w2(m,n,u,a)}return w2(h,n,u,a)}function w2(t,e,n,o){const s=new Set(e.map(p=>p.id)),a=p=>p.nodeId===De||s.has(p.nodeId),l=new Map;for(const p of t){const m=`${p.source.nodeId}.${p.source.portName}`;l.has(m)||l.set(m,[]),l.get(m).push(p)}const u=p=>{const m=[],y=new Set,b=[p];for(;b.length>0;){const x=b.pop(),w=`${x.nodeId}.${x.portName}`;if(!y.has(w)){if(y.add(w),a(x)){m.push(x);continue}for(const _ of l.get(w)??[])b.push(_.target)}}return m},d=[],h=new Set;for(const p of t){if(!a(p.source))continue;const m=a(p.target)?[p.target]:u(p.target);for(const y of m){if(p.source.nodeId===y.nodeId&&p.source.portName===y.portName)continue;const x=`${p.source.nodeId}.${p.source.portName}->${y.nodeId}.${y.portName}`;h.has(x)||(h.add(x),o&&console.log(` RESOLVED: ${p.source.nodeId}.${p.source.portName} -> ${y.nodeId}.${y.portName}`),d.push({id:x,source:p.source,target:y,portType:p.portType}))}}return d}function L$(t,e,n,o,s=!1){for(const a of t.connections){if(a.source.nodeId===""&&a.target.nodeId!==""){const l=`${e}.${a.source.portName}`,u=pu(e,a.target,t,o);n.has(l)||n.set(l,[]);for(const d of u)n.get(l).push(d),s&&console.log(` INPUT: ${a.source.portName} -> ${d.nodeId}.${d.portName}`)}if(a.source.nodeId!==""&&a.target.nodeId===""){const l=`${e}.${a.target.portName}`,u=pu(e,a.source,t,o);n.has(l)||n.set(l,[]);for(const d of u)n.get(l).push(d),s&&console.log(` OUTPUT: ${a.target.portName} <- ${d.nodeId}.${d.portName}`)}if(a.source.nodeId===""&&a.target.nodeId===""){s&&console.log(` PASSTHROUGH: ${a.source.portName} -> ${a.target.portName}`);const l=`${e}.${a.source.portName}`;n.has(l)||n.set(l,[]),n.get(l).push({nodeId:e,portName:a.target.portName}),s&&console.log(` -> Added passthrough forwarding: ${l} -> ${e}.${a.target.portName}`)}}}function pu(t,e,n,o,s=new Set){if(e.nodeId==="")return[{nodeId:t,portName:e.portName}];const a=t+"."+e.nodeId,l=n.nodes.find(p=>p.id===e.nodeId);if(!l)return[{nodeId:a,portName:e.portName}];const u=o.resolveCircuit(l.componentRef);if(!u||u.implementation.kind!=="composite")return[{nodeId:a,portName:e.portName}];if(s.has(l.componentRef))return[{nodeId:a,portName:e.portName}];const d=new Set(s);d.add(l.componentRef);const h=[];for(const p of u.connections){if(p.target.nodeId===""&&p.target.portName===e.portName){const m=pu(a,p.source,u,o,d);h.push(...m)}if(p.source.nodeId===""&&p.source.portName===e.portName){const m=pu(a,p.target,u,o,d);h.push(...m)}}return h.length>0?h:[{nodeId:a,portName:e.portName}]}function I$(t){t.nodeMap=new Map(t.nodes.map(e=>[e.id,e]));for(const e of t.nodes)e.dependents=[],e.inputSources=[];for(const e of t.connections){const n=e.source.nodeId,o=e.target.nodeId;if(o===De)continue;const s=t.nodeMap.get(n);s&&!s.dependents.includes(o)&&s.dependents.push(o);const a=t.nodeMap.get(o);a&&a.inputSources.push({portName:e.target.portName,sourceNodeId:n,sourcePortName:e.source.portName})}}function P$(t,e){return`${t}.${e}`}function _2(t,e,n){const o=new Map,s=new Map,a=new Map;for(const l of t.nodes){const u=e.resolveCircuit(l.primitiveType);if(u){if(u.implementation.kind==="primitive"&&u.state.length>0){const d=u.state.map(p=>B$(p,l.id,l.arguments,l.primitiveType,n)),h=u.state.length===1?d[0]:Object.fromEntries(u.state.map((p,m)=>[p.name,d[m]]));o.set(l.id,h),s.set(l.id,h)}for(const d of l.clocks)a.set(P$(l.id,d.name),{value:!1,edge:"none"})}}return{currentState:o,nextState:s,clocks:a,cycleCount:0}}function B$(t,e,n,o,s){const a=t.stateType.kind,l=n[t.name];if(a==="memory"){const d=new Map,h=t.initialValue;if(h?.data){if(h.data instanceof Map)for(const[p,m]of h.data)d.set(p,m);else if(typeof h.data=="object")for(const[p,m]of Object.entries(h.data)){const y=parseInt(p,10);!isNaN(y)&&typeof m=="number"&&d.set(y,m)}}if(l!==void 0){if(Array.isArray(l))l.forEach((p,m)=>{typeof p=="number"&&d.set(m,p)});else if(l instanceof Map)for(const[p,m]of l)d.set(p,m);else if(typeof l=="object"&&l!==null)for(const[p,m]of Object.entries(l)){const y=parseInt(p,10);!isNaN(y)&&typeof m=="number"&&d.set(y,m)}}if(s){const p=$$(e,s,o);if(p)for(const[m,y]of p.entries())d.set(m,y)}return d}if(l!==void 0&&(typeof l=="number"||typeof l=="boolean"))return l;const u=t.initialValue;return u}function H$(t){const n=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(n,"i")}function $$(t,e,n){for(const[o,s]of e){const a=H$(o);if(a.test(t)||n&&a.test(n))return s}}const am={And:0,Or:1,Not:2,Nand:3,Nor:4,Xor:5,Xnor:6,Buffer:7,Switch:10,Led:11,Output:12,Button:13,Input:14,Constant:15,Splitter:20,Splitter8to8:21,Combiner8to8:22,Probe:23,BitSlice:24,AddressCombiner:25,Concat:26,BusAnd:40,BusOr:41,BusNot:42,BusXor:43,Incrementer:50,Adder:51,Multiplier:52,Comparator:53,LeftShifter:54,RightShifter:55,Subtractor:56,SignedAdder:57,SignedComparator:58,SignedMultiplier:59,Mux:70,Decoder:71,SevenSegment:80,HexDisplay:81,Screen:82,RasterDisplay:83,DFlipFlop:90,Register:91,ROM:100,RAM:101,DualPortRAM:102,Console:110},U$=Object.entries(am).reduce((t,[e,n])=>(t[n]=e,t),[]);class Y${queue;pending;head=0;tail=0;capacity;constructor(e){this.capacity=e,this.queue=new Uint32Array(e),this.pending=new Uint8Array(e)}enqueue(e){this.pending[e]||(this.pending[e]=1,this.queue[this.tail%this.capacity]=e,this.tail++)}enqueueAll(e){for(let n=0;n<e.length;n++)this.enqueue(e[n])}dequeue(){const e=this.queue[this.head%this.capacity];return this.pending[e]=0,this.head++,e}isEmpty(){return this.head===this.tail}size(){return this.tail-this.head}toArray(){const e=[];for(let n=this.head;n<this.tail;n++)e.push(this.queue[n%this.capacity]);return e}clear(){this.head=0,this.tail=0,this.pending.fill(0)}}function S2(t){return{values:new Int32Array(t),changed:new Uint8Array(t),initialized:new Uint8Array(t)}}function E2(t,e){const n=t.circuit.inputSourcePort[t.portStart+e];return n>=0?t.values.values[n]:0}function C2(t,e,n){const o=t.portStart+t.inputCount+e;t.values.values[o]=n,t.values.initialized[o]=1}const q$=Math.max(...Object.values(am))+1,Va=new Array(q$).fill(null);function T2(t){return new Proxy(t,{get(e,n){if(typeof n=="string"&&/^\d+$/.test(n))return e.get(Number(n))??0;const o=e[n];return typeof o=="function"?o.bind(e):o},set(e,n,o){return typeof n=="string"&&/^\d+$/.test(n)?(e.set(Number(n),o),!0):!1}})}let G$=200;const N2=new Map;function F$(t){const e=am[t];if(e!==void 0)return e;const n=N2.get(t);if(n!==void 0)return n;const o=G$++;return N2.set(t,o),U$[o]=t,o}function X$(t,e,n,o){const s=t.length,a=e.length;return!o||o.length===0?function(u){const d={},h=u.circuit.flatCircuit.nodes[u.nodeIndex]?.arguments;if(h)for(const m in h)d[m]=h[m];for(let m=0;m<s;m++)d[t[m]]=E2(u,m);const p=n(d);for(let m=0;m<a;m++){const y=p[e[m]];y!==void 0&&C2(u,m,y)}}:function(u){const d={},h=u.circuit.flatCircuit.nodes[u.nodeIndex]?.arguments;if(h)for(const m in h)d[m]=h[m];for(let m=0;m<s;m++)d[t[m]]=E2(u,m);if(u.state){const m=u.state.currentState[u.nodeIndex];if(m!=null&&typeof m=="object"&&!Array.isArray(m)&&!(m instanceof Map)){const y=m;for(const b of o){const x=y[b];d[b]=x instanceof Map?T2(x):x}}else m!=null&&(d[o[0]]=m instanceof Map?T2(m):m)}const p=n(d);for(let m=0;m<a;m++){const y=p[e[m]];y!==void 0&&C2(u,m,y)}}}function Z$(t){const e=F$(t);if(Va[e]!=null)return e;const n=Ll(t);if(!n)return console.warn(`[eval-bridge] No eval-registry entry for '${t}' — getAllCircuitEvals:`,[...JN().keys()]),e;for(;Va.length<=e;)Va.push(null);return Va[e]=X$(n.inputNames,n.outputNames,n.evalFn,n.stateKeys),e}const lm=new Map;function K$(t){if(lm.has(t))return lm.get(t);const e=Ll(t);if(!e?.onTickFn)return;const n={inputNames:e.inputNames,stateKeys:e.stateKeys??[],fn:e.onTickFn};return lm.set(t,n),n}function Q$(t,e){const n=t.nodes.length,o=new Map,s=new Array(n);for(let q=0;q<n;q++){const Y=t.nodes[q];o.set(Y.id,q),s[q]=Y.id}let a=0;const l=new Uint32Array(n),u=new Uint8Array(n),d=new Uint8Array(n);for(let q=0;q<n;q++){const Y=t.nodes[q];l[q]=a,u[q]=Y.inputs.length,d[q]=Y.outputs.length,a+=Y.inputs.length+Y.outputs.length}const h=t.topLevelInputs.length,p=t.topLevelOutputs.length,m=a+h+p,y=new Map,b=new Array(m),x=new Uint8Array(m),w=new Uint8Array(m),_=new Array(m);let S=a;for(const q of t.topLevelInputs){const Y=`${De}.${q.name}`;y.set(Y,S),b[S]=Y,x[S]=1,w[S]=q.portType.kind==="bus"?1:0,S++}for(const q of t.topLevelOutputs){const Y=`${De}.${q.name}`;y.set(Y,S),b[S]=Y,x[S]=0,w[S]=q.portType.kind==="bus"?1:0,S++}for(let q=0;q<n;q++){const Y=t.nodes[q];let K=l[q];for(const W of Y.inputs){const B=`${Y.id}.${W.name}`;y.set(B,K),b[K]=B,x[K]=0,w[K]=W.portType.kind==="bus"?1:0,_[K]=W.name,K++}for(const W of Y.outputs){const B=`${Y.id}.${W.name}`;y.set(B,K),b[K]=B,x[K]=1;let H=W.portType.kind==="bus";if(!H){const j=Y.arguments.width;if(typeof j=="number"&&j>1&&(H=!0),!H&&Y.primitiveType==="Mux"){for(const I of Y.inputs)if(I.name!=="sel"&&I.portType.kind==="bus"){H=!0;break}}}w[K]=H?1:0,K++}}const k=new Uint16Array(n);for(let q=0;q<n;q++){const Y=t.nodes[q];k[q]=Z$(Y.primitiveType)}const C=new Array(n);for(let q=0;q<n;q++){const K=t.nodes[q].dependents.map(W=>o.get(W)).filter(W=>W!==void 0);C[q]=new Uint32Array(K)}const E=new Int32Array(a),R=new Int32Array(a);E.fill(-1),R.fill(-1);for(let q=0;q<n;q++){const Y=t.nodes[q],K=l[q];for(let W=0;W<Y.inputSources.length;W++){const B=Y.inputSources[W],H=Y.inputs.findIndex(I=>I.name===B.portName);if(H===-1)continue;const j=K+H;if(B.sourceNodeId===De){E[j]=-1;const I=`${De}.${B.sourcePortName}`;R[j]=y.get(I)??-1}else{const I=o.get(B.sourceNodeId);if(I===void 0)continue;const z=t.nodes[I],U=z.outputs.findIndex(G=>G.name===B.sourcePortName);if(U===-1)continue;E[j]=I,R[j]=l[I]+z.inputs.length+U}}}const A=new Uint8Array(n),O=new Uint8Array(n),D=new Uint8Array(n),$=new Uint8Array(n);for(let q=0;q<n;q++){const Y=t.nodes[q];A[q]=Y.inputs.length===0?1:0;const K=e.resolveCircuit(Y.primitiveType);K?.state&&K.state.length>0&&(D[q]=1,O[q]=1);for(const W of Y.inputSources)if(W.sourceNodeId===De){$[q]=1;break}}return{nodeCount:n,portCount:m,nodeIdToIndex:o,indexToNodeId:s,portKeyToIndex:y,indexToPortKey:b,primitiveTypeIndex:k,nodePortStart:l,nodeInputCount:u,nodeOutputCount:d,dependents:C,inputSourceNode:E,inputSourcePort:R,inputPortNames:_,portIsOutput:x,portIsBus:w,isSourceNode:A,isStateOutputNode:O,hasState:D,readsTopLevelInput:$,flatCircuit:t}}function cm(t,e){const n=new Array(t.nodeCount),o=new Array(t.nodeCount);for(const[s,a]of e.currentState){const l=t.nodeIdToIndex.get(s);l!==void 0&&(n[l]=a)}for(const[s,a]of e.nextState){const l=t.nodeIdToIndex.get(s);l!==void 0&&(o[l]=a)}return{currentState:n,nextState:o,clocks:e.clocks,cycleCount:e.cycleCount}}function um(t,e){const n=new Map,o=new Map;for(let s=0;s<t.nodeCount;s++){const a=t.indexToNodeId[s];e.currentState[s]!==void 0&&n.set(a,e.currentState[s]),e.nextState[s]!==void 0&&o.set(a,e.nextState[s])}return{currentState:n,nextState:o,clocks:e.clocks,cycleCount:e.cycleCount}}const A2=1e4,fm=new WeakMap;function W$(t){const e=new Map(t),n=new Proxy(e,{get(o,s){if(typeof s=="string"&&/^\d+$/.test(s))return o.get(Number(s))??0;const a=o[s];return typeof a=="function"?a.bind(o):a},set(o,s,a){return typeof s=="string"&&/^\d+$/.test(s)?(o.set(Number(s),a),!0):!1}});return fm.set(n,e),n}const J$=new Int32Array(64),tU=new Uint8Array(64);function La(t,e,n,o,s){let a=0;if(s)for(const[u,d]of s){const h=t.portKeyToIndex.get(u);h!==void 0&&(n.values[h]=typeof d=="boolean"?d?1:0:d,n.initialized[h]=1)}const l={circuit:t,values:n,state:o,queue:e,nodeIndex:0,portStart:0,inputCount:0,outputCount:0};for(;!e.isEmpty();){if(++a>A2)throw new Error(`Propagation did not stabilize after ${A2} iterations. Possible unstable feedback loop in circuit.`);const u=e.dequeue(),d=t.nodePortStart[u],h=t.nodeInputCount[u],p=t.nodeOutputCount[u],m=d+h;l.nodeIndex=u,l.portStart=d,l.inputCount=h,l.outputCount=p;const y=p<=64?J$:new Int32Array(p),b=p<=64?tU:new Uint8Array(p);for(let S=0;S<p;S++)y[S]=n.values[m+S],b[S]=n.initialized[m+S];const x=t.primitiveTypeIndex[u],w=Va[x];w?w(l):eU(t,u);let _=!1;for(let S=0;S<p;S++){const k=m+S;if(n.values[k]!==y[S]||n.initialized[k]&&!b[S]){_=!0;break}}_&&e.enqueueAll(t.dependents[u])}return a}function eU(t,e,n,o,s){const a=t.flatCircuit.nodes[e];throw new Error(`Primitive '${a.primitiveType}' has no registered evaluator. Either import '@simten/core/std' to register the standard library, or register the primitive's eval lambda explicitly via registerEvalFunction(). If you constructed a Circuit IR by hand (rather than via circuit()), you must register its evaluator yourself.`)}function mu(t,e){for(let n=0;n<t.nodeCount;n++)(t.isSourceNode[n]||t.isStateOutputNode[n]||t.readsTopLevelInput[n])&&(e.enqueue(n),t.isSourceNode[n],t.isStateOutputNode[n],t.readsTopLevelInput[n])}function nU(t,e){for(let n=0;n<t.nodeCount;n++)t.isStateOutputNode[n]&&e.enqueue(n)}function iU(t,e){for(const[n,o]of e.clocks)o.edge="rising",o.value=!0}function oU(t,e,n,o){for(let s=0;s<t.nodeCount;s++){if(!t.hasState[s])continue;const a=t.flatCircuit.nodes[s],l=K$(a.primitiveType);if(!l)continue;const u=new Map,d=t.nodePortStart[s],h=t.nodeInputCount[s];for(let w=0;w<h;w++){const _=d+w,S=t.inputSourceNode[_],k=t.inputSourcePort[_],C=t.inputPortNames[_];if(S===-1){if(o&&k>=0){const E=t.indexToPortKey[k],R=o.get(E);R!==void 0&&u.set(C,R)}}else if(k>=0){const E=e.values[k];u.set(C,E)}}if(a.arguments)for(const[w,_]of Object.entries(a.arguments))u.set(`__${w}`,_);const p={};for(const w of a.clocks){const _=`${a.id}.${w.name}`,S=n.clocks.get(_);S&&(p[w.name]=S.edge)}const m=n.currentState[s],y={};for(const[w,_]of u)y[w]=_;if(m!=null&&typeof m=="object"&&!(m instanceof Map))for(const w of l.stateKeys)y[w]=m[w];else m!=null&&l.stateKeys.length===1&&(m instanceof Map?y[l.stateKeys[0]]=W$(m):y[l.stateKeys[0]]=m);const b=l.fn(y);let x=l.stateKeys.length===1?b[l.stateKeys[0]]:b;x!=null&&typeof x=="object"&&fm.has(x)&&(x=fm.get(x)),n.nextState[s]=x}}function rU(t){for(let e=0;e<t.currentState.length;e++){const n=t.nextState[e];n!==void 0&&(n instanceof Map?(t.currentState[e]=new Map(n),t.nextState[e]=new Map(n)):(t.currentState[e]=n,t.nextState[e]=n))}t.cycleCount++}function Ia(t,e,n){const o=new Map;if(n)for(const[s,a]of n)o.set(s,a);for(let s=0;s<t.portCount;s++){const a=t.indexToPortKey[s],l=t.portIsOutput[s]===1,u=t.portIsBus[s]===0;let d,h;if(l)d=e.values[s],h=e.initialized[s]!==0;else{const m=t.inputSourcePort[s];m>=0?(d=e.values[m],h=e.initialized[m]!==0):(d=0,h=!1)}h||(d=0);const p=d>1||d<0;o.set(a,u&&!p?d!==0:d)}return o}function sU(t,e,n){for(const[o,s]of n){const a=t.portKeyToIndex.get(o);a!==void 0&&(e.values[a]=typeof s=="boolean"?s?1:0:s,e.initialized[a]=1)}}function gu(t,e,n){for(const o of t.flatCircuit.connections)if(o.target.nodeId===De||o.target.nodeId===""){const s=`${o.source.nodeId}.${o.source.portName}`,a=t.portKeyToIndex.get(s);if(a!==void 0){const l=`${o.target.nodeId||De}.${o.target.portName}`,u=t.portIsBus[a]===0,d=e.values[a];n.set(l,u?d!==0:d)}}}class aU{flatCircuit=null;options=null;numericCircuit=null;numericSeqState=null;numericValues=null;eventQueue=null;topLevelInputs=new Map;cachedFlatSeqState=null;cachedPortValues=null;cacheValid=!1;totalTicks=0;totalEvaluations=0;initialize(e,n){this.flatCircuit=e,this.options=n,this.numericCircuit=Q$(e,n.componentLibrary);const o=_2(e,n.componentLibrary);this.numericSeqState=cm(this.numericCircuit,o),this.numericValues=S2(this.numericCircuit.portCount),this.eventQueue=new Y$(this.numericCircuit.nodeCount),this.topLevelInputs=new Map;for(const s of e.topLevelInputs){const a=`${De}.${s.name}`,l=s.portType.kind==="bit"?!1:0;this.topLevelInputs.set(a,l)}this.eventQueue.clear(),mu(this.numericCircuit,this.eventQueue),La(this.numericCircuit,this.eventQueue,this.numericValues,this.numericSeqState,this.topLevelInputs),this.totalTicks=0,this.totalEvaluations=0,this.cacheValid=!1}setNode(e,n){if(!this.flatCircuit||!this.numericCircuit)return;const o=`${De}.${e}`;if(this.topLevelInputs.has(o)){this.topLevelInputs.set(o,n),this.cacheValid=!1;return}const s=this.flatCircuit.nodes.find(l=>l.id===e)??this.flatCircuit.nodes.find(l=>l.id.endsWith("."+e));if(!s)return;const a=this.numericCircuit.nodeIdToIndex.get(s.id);if(a!==void 0&&this.numericSeqState&&this.numericSeqState.currentState[a]!==void 0){this.numericSeqState.currentState[a]=n,this.cacheValid=!1,this.cachedFlatSeqState=null,n instanceof Map&&this.options&&(this.options.initialMemory||(this.options.initialMemory=new Map),this.options.initialMemory.set(s.id,n));return}(typeof n=="boolean"||typeof n=="number"||typeof n=="string")&&(s.arguments={...s.arguments,value:n},this.cacheValid=!1)}tick(){if(!this.numericCircuit||!this.numericSeqState||!this.numericValues||!this.eventQueue)throw new Error("Simulator not initialized");this.eventQueue.clear(),mu(this.numericCircuit,this.eventQueue);const e=La(this.numericCircuit,this.eventQueue,this.numericValues,this.numericSeqState,this.topLevelInputs);iU(this.numericCircuit,this.numericSeqState),oU(this.numericCircuit,this.numericValues,this.numericSeqState,this.topLevelInputs),rU(this.numericSeqState),this.eventQueue.clear(),nU(this.numericCircuit,this.eventQueue);const n=La(this.numericCircuit,this.eventQueue,this.numericValues,this.numericSeqState,this.topLevelInputs),o=Ia(this.numericCircuit,this.numericValues,this.topLevelInputs);gu(this.numericCircuit,this.numericValues,o),this.cachedPortValues=o,this.cachedFlatSeqState=null,this.cacheValid=!0;const s=e+n;this.totalTicks++,this.totalEvaluations+=s;const a=um(this.numericCircuit,this.numericSeqState);return{portValues:o,sequentialState:a,metrics:{phase1Evals:e,phase2Evals:n,totalEvals:s}}}runCombinational(){if(!this.numericCircuit||!this.numericValues||!this.eventQueue)throw new Error("Simulator not initialized");if(this.cacheValid&&this.cachedPortValues)return{portValues:this.cachedPortValues,metrics:{totalEvals:0}};this.eventQueue.clear(),mu(this.numericCircuit,this.eventQueue);try{La(this.numericCircuit,this.eventQueue,this.numericValues,this.numericSeqState??void 0,this.topLevelInputs)}catch(n){return{portValues:Ia(this.numericCircuit,this.numericValues,this.topLevelInputs),metrics:{totalEvals:0},error:n instanceof Error?n.message:"Unknown error"}}const e=Ia(this.numericCircuit,this.numericValues,this.topLevelInputs);return gu(this.numericCircuit,this.numericValues,e),this.cachedPortValues=e,this.cacheValid=!0,{portValues:e,metrics:{totalEvals:0}}}getOutput(e,n){if(!this.numericCircuit||!this.numericValues)return;const o=this.getPortValues(),s=`${e}.${n}`;return o.get(s)}getPortValues(){return!this.numericCircuit||!this.numericValues?new Map:(this.cacheValid||(this.cachedPortValues=Ia(this.numericCircuit,this.numericValues,this.topLevelInputs),gu(this.numericCircuit,this.numericValues,this.cachedPortValues),this.cacheValid=!0),this.cachedPortValues)}getState(){return!this.numericCircuit||!this.numericSeqState?null:((!this.cacheValid||!this.cachedFlatSeqState)&&(this.cachedFlatSeqState=um(this.numericCircuit,this.numericSeqState)),this.cachedFlatSeqState)}snapshot(){if(!this.numericSeqState||!this.numericCircuit||!this.numericValues)throw new Error("No sequential state to snapshot");const e=Ia(this.numericCircuit,this.numericValues,this.topLevelInputs);gu(this.numericCircuit,this.numericValues,e);const n=um(this.numericCircuit,this.numericSeqState);return{portValues:e,sequentialState:n,cycleCount:this.numericSeqState.cycleCount}}restore(e){!this.numericCircuit||!this.numericValues||(this.numericSeqState=cm(this.numericCircuit,e.sequentialState),sU(this.numericCircuit,this.numericValues,e.portValues),this.cacheValid=!1)}reset(){if(!this.flatCircuit||!this.options||!this.numericCircuit)return;const e=_2(this.flatCircuit,this.options.componentLibrary,this.options.initialMemory);this.numericSeqState=cm(this.numericCircuit,e),this.numericValues=S2(this.numericCircuit.portCount),this.eventQueue.clear(),mu(this.numericCircuit,this.eventQueue),La(this.numericCircuit,this.eventQueue,this.numericValues,this.numericSeqState,this.topLevelInputs),this.totalTicks=0,this.totalEvaluations=0,this.cacheValid=!1}getMetrics(){return{totalTicks:this.totalTicks,totalEvaluations:this.totalEvaluations,avgEvalsPerTick:this.totalTicks>0?this.totalEvaluations/this.totalTicks:0,nodeCount:this.flatCircuit?.nodes.length??0}}}function lU(t,e){const n=new aU;return n.initialize(t,e),n}function cU(t,e){const n=z$(t,e);return lU(n,{componentLibrary:e})}const uU=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),fU=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,n,o)=>o?o.toUpperCase():n.toLowerCase()),M2=t=>{const e=fU(t);return e.charAt(0).toUpperCase()+e.slice(1)},R2=(...t)=>t.filter((e,n,o)=>!!e&&e.trim()!==""&&o.indexOf(e)===n).join(" ").trim(),dU=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0};var hU={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const pU=N.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:n=2,absoluteStrokeWidth:o,className:s="",children:a,iconNode:l,...u},d)=>N.createElement("svg",{ref:d,...hU,width:e,height:e,stroke:t,strokeWidth:o?Number(n)*24/Number(e):n,className:R2("lucide",s),...!a&&!dU(u)&&{"aria-hidden":"true"},...u},[...l.map(([h,p])=>N.createElement(h,p)),...Array.isArray(a)?a:[a]]));const eo=(t,e)=>{const n=N.forwardRef(({className:o,...s},a)=>N.createElement(pU,{ref:a,iconNode:e,className:R2(`lucide-${uU(M2(t))}`,`lucide-${t}`,o),...s}));return n.displayName=M2(t),n};const mU=eo("chevron-left",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]);const gU=eo("chevron-right",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);const yU=eo("gauge",[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]]);const vU=eo("history",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]]);const bU=eo("pause",[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1",key:"kaeet6"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1",key:"1wsw3u"}]]);const xU=eo("play",[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]]);const wU=eo("rotate-ccw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);const _U=eo("skip-forward",[["path",{d:"M21 4v16",key:"7j8fe9"}],["path",{d:"M6.029 4.285A2 2 0 0 0 3 6v12a2 2 0 0 0 3.029 1.715l9.997-5.998a2 2 0 0 0 .003-3.432z",key:"zs4d6"}]]),k2=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,O2=rx,SU=((t,e)=>n=>{var o;if(e?.variants==null)return O2(t,n?.class,n?.className);const{variants:s,defaultVariants:a}=e,l=Object.keys(s).map(h=>{const p=n?.[h],m=a?.[h];if(p===null)return null;const y=k2(p)||k2(m);return s[h][y]}),u=n&&Object.entries(n).reduce((h,p)=>{let[m,y]=p;return y===void 0||(h[m]=y),h},{}),d=e==null||(o=e.compoundVariants)===null||o===void 0?void 0:o.reduce((h,p)=>{let{class:m,className:y,...b}=p;return Object.entries(b).every(x=>{let[w,_]=x;return Array.isArray(_)?_.includes({...a,...u}[w]):{...a,...u}[w]===_})?[...h,m,y]:h},[]);return O2(t,l,d,n?.class,n?.className)})("inline-flex items-center justify-center gap-2 cursor-pointer whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),D2=N.forwardRef(({className:t,variant:e,size:n,...o},s)=>M.jsx("button",{className:jn(SU({variant:e,size:n,className:t})),ref:s,...o}));D2.displayName="Button";function ts({label:t,icon:e,onClick:n,disabled:o,pulse:s}){return M.jsxs(Nh,{children:[M.jsx(Ah,{asChild:!0,children:M.jsx(D2,{variant:"ghost",size:"icon",onClick:n,disabled:o,"aria-label":t,className:`h-7 w-7 text-muted-foreground disabled:opacity-40 [&_svg]:size-3.5${s?" animate-pulse text-blue-600 dark:text-blue-400 bg-blue-50 dark:bg-blue-950/40 ring-2 ring-blue-500/40":""}`,children:M.jsx(e,{})})}),M.jsx(Mh,{side:"bottom",children:t})]})}function j2({cycle:t,historyLength:e,historyIndex:n,isRunning:o,isViewingPast:s,onStep:a,onRun:l,onPause:u,onReset:d,onStepBack:h,onStepForward:p,onSeek:m,onSpeedChange:y,speed:b=1,maxSpeed:x=100,showScrubber:w,floating:_,chromeless:S,pulseRun:k}){const C=_?"absolute top-3 left-1/2 -translate-x-1/2 z-10":"",E=S?"flex items-center gap-1.5":"flex items-center gap-1.5 border-t border-border bg-card/95 px-3 py-1.5";return M.jsx(Th,{children:M.jsx("div",{className:C,children:M.jsxs("div",{className:E,children:[M.jsx(ts,{label:"Tick",icon:_U,onClick:a,disabled:o||s}),o?M.jsx(ts,{label:"Pause",icon:bU,onClick:u}):M.jsx(ts,{label:"Run",icon:xU,onClick:l,disabled:s,pulse:k&&!s}),M.jsx(ts,{label:"Reset",icon:wU,onClick:d}),y&&M.jsxs("div",{className:"flex items-center gap-2 border-l border-border pl-2 ml-0.5",children:[M.jsx(yU,{className:"h-3.5 w-3.5 text-muted-foreground/70","aria-hidden":!0}),M.jsx("input",{type:"range",min:"1",max:x,value:b,onChange:R=>y(Number(R.target.value)),className:"w-20 h-1 rounded-lg appearance-none cursor-pointer accent-blue-600",disabled:s,"aria-label":"Simulation speed"}),M.jsxs("span",{className:"min-w-[55px] text-[10px] text-muted-foreground font-mono tabular-nums",children:[b," tick/s"]})]}),M.jsx("div",{className:"border-l border-border pl-1.5 ml-0.5",children:M.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["Cycle ",M.jsx("span",{className:"font-mono font-semibold text-foreground",children:t})]})}),e>1&&M.jsxs("div",{className:"flex items-center gap-0.5 border-l border-border pl-1.5 ml-0.5",children:[M.jsx(ts,{label:"Step back",icon:mU,onClick:h,disabled:n<=0||o}),M.jsx("span",{className:"min-w-[40px] text-center text-[11px] text-muted-foreground",children:s?M.jsxs("span",{className:"font-mono text-amber-600 dark:text-amber-400",children:[n+1,"/",e]}):M.jsxs("span",{className:"font-mono",children:[e,"/",e]})}),M.jsx(ts,{label:"Step forward",icon:gU,onClick:p,disabled:!s||o})]}),w&&m&&e>1&&M.jsxs("div",{className:"flex items-center gap-2 border-l border-border pl-2 ml-0.5",children:[M.jsx(vU,{className:"h-3.5 w-3.5 text-muted-foreground/70","aria-hidden":!0}),M.jsx("input",{type:"range",min:"0",max:e-1,value:n,onChange:R=>m(Number(R.target.value)),className:"w-24 h-1 rounded-lg appearance-none cursor-pointer accent-blue-600",disabled:o,"aria-label":"Cycle scrubber"})]})]})})})}function EU({frame:t,componentLibrary:e,onPushLevel:n,theme:o="dark"}){const s=N.useMemo(()=>j$(t.componentDef),[t.componentDef]),a=N.useMemo(()=>ud(s,e.resolveCircuit),[s,e]),l=N.useCallback(H=>{if(!H.isComposite)return;const j=e.resolveCircuit(H.componentRef);j&&j.implementation.kind==="composite"&&j.nodes.length>0&&n(H.componentRef,j,H.label??H.componentRef)},[e,n]),u=Wf(),[d,h]=N.useState(new Map),[p,m]=N.useState(!1),y=N.useRef(null),[b,x]=N.useState(0),[w,_]=N.useState(!1),S=N.useRef([]),[k,C]=N.useState(0),[E,R]=N.useState(-1),A=N.useRef("");A.current||(A.current=`drill-${typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():Math.random().toString(36).slice(2)}`);const O=A.current;N.useEffect(()=>()=>{p&&u.dispose(O).catch(()=>{})},[u,O,p]),N.useEffect(()=>{const H=[],j=new Set;for(const z of e.getAllPrimitiveNames()){const U=e.resolveCircuit(z);U&&!j.has(z)&&(j.add(z),H.push(U))}const I=z=>{for(const U of z.nodes){if(j.has(U.componentRef))continue;const G=e.resolveCircuit(U.componentRef);G&&(j.add(U.componentRef),H.push(G),G.implementation.kind==="composite"&&I(G))}};I(s),u.compileIR(s,H,O,{snapshot:a}).then(z=>{if("error"in z){try{const G=cU(s,e);G.runCombinational(),y.current=G,m(!1);const L=new Map;for(const[F,et]of G.getPortValues())L.set(F,et);h(L)}catch(G){console.warn("[InspectorCanvas] Both sandbox and local failed:",G)}return}m(!0);const U=new Map;for(const[G,L]of Object.entries(z.portValues))U.set(G,L);h(U),S.current=z.snapshotId!==void 0?[{snapshotId:z.snapshotId,cycle:0}]:[],C(S.current.length),R(S.current.length===0?-1:0),x(0)})},[s,e,u,O,a]);const D=N.useCallback(H=>{const j=`${H}.out`,I=d.get(j);u.setNode(H,!I,O).then(z=>{if("error"in z)return;const U=new Map;for(const[G,L]of Object.entries(z.portValues))U.set(G,L);h(U)})},[u,d]),$=N.useCallback((H,j)=>{u.setNode(H,j,O).then(I=>{if("error"in I)return;const z=new Map;for(const[U,G]of Object.entries(I.portValues))z.set(U,G);h(z)})},[u]),q=N.useCallback(()=>{u.tick(void 0,O,{snapshot:a}).then(H=>{if("error"in H)return;const j=new Map;for(const[I,z]of Object.entries(H.portValues))j.set(I,z);if(h(j),x(H.cycle),H.snapshotId!==void 0){const I=S.current.slice(0,E+1);I.push({snapshotId:H.snapshotId,cycle:H.cycle}),S.current=I,C(I.length),R(I.length-1)}})},[u,O,a,E]),Y=N.useCallback(()=>{_(!1),u.reset(O).then(H=>{if("error"in H)return;const j=new Map;for(const[I,z]of Object.entries(H.portValues))j.set(I,z);h(j),x(0),S.current=[],C(0),R(-1),a&&u.snapshot(O).then(I=>{"error"in I||I.snapshotId===void 0||(S.current=[{snapshotId:I.snapshotId,cycle:0}],C(1),R(0))})})},[u,O,a]),K=N.useCallback(H=>{const j=S.current[H];j&&u.restore(j.snapshotId,O).then(I=>{if("error"in I)return;const z=new Map;for(const[U,G]of Object.entries(I.portValues))z.set(U,G);h(z),x(j.cycle),R(H)})},[u,O]),W=N.useCallback(()=>{_(!1),E>0&&K(E-1)},[E,K]),B=N.useCallback(()=>{E<k-1?K(E+1):q()},[E,k,K,q]);return N.useEffect(()=>{if(!w)return;const H=window.setInterval(()=>{q()},200);return()=>window.clearInterval(H)},[w,q]),M.jsxs("div",{className:"relative h-full w-full",children:[a&&M.jsx(j2,{floating:!0,cycle:b,historyLength:k,historyIndex:E,isRunning:w,isViewingPast:E>=0&&E<k-1,onStep:q,onRun:()=>_(!0),onPause:()=>_(!1),onReset:Y,onStepBack:W,onStepForward:B}),M.jsx(z2,{circuit:s,componentLibrary:e,portValues:d,sequentialState:null,onToggleNode:D,onSetNodeValue:$,onNodeDoubleClick:l,nodeTypes:Tw,edgeTypes:Nw,theme:o,showControls:!0,height:"100%",panOnMobile:!0})]})}function CU({stack:t,onNavigate:e,theme:n="dark"}){const s=t[t.length-1]?.componentDef.metadata?.description,a=n==="dark";return M.jsxs("div",{className:"flex items-center gap-1 text-sm min-w-0",children:[t.map((l,u)=>M.jsxs(ko.Fragment,{children:[u>0&&M.jsx("span",{className:`${a?"text-gray-500":"text-gray-400"} shrink-0`,children:">"}),u<t.length-1?M.jsxs("button",{onClick:()=>e(u),className:`${a?"text-blue-400 hover:text-blue-300":"text-blue-600 hover:text-blue-800"} hover:underline font-medium shrink-0`,children:[l.nodeLabel," (",l.componentName,")"]}):M.jsxs("span",{className:`font-semibold shrink-0 ${a?"text-gray-100":"text-gray-900"}`,children:[l.nodeLabel," (",l.componentName,")"]})]},u)),s&&M.jsxs(M.Fragment,{children:[M.jsx("span",{className:`${a?"text-gray-600":"text-gray-300"} shrink-0`,children:"—"}),M.jsx("span",{className:`${a?"text-gray-400":"text-gray-500"} text-xs italic truncate`,children:s})]})]})}const TU={enterIn:{opacity:0},enterOut:{opacity:0},center:{opacity:1},exitIn:{opacity:0},exitOut:{opacity:0}};function NU({stack:t,componentLibrary:e,theme:n="dark",onClose:o,onPopLevel:s,onPushLevel:a,onNavigate:l}){const u=t.length>0,d=N.useRef(0),[h,p]=N.useState("in");N.useEffect(()=>{t.length>d.current?p("in"):t.length<d.current&&p("out"),d.current=t.length},[t.length]),N.useEffect(()=>{if(!u)return;const x=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=x}},[u]);const m=N.useCallback(x=>{x.target===x.currentTarget&&o()},[o]),y=N.useCallback(x=>{x.key==="Escape"&&(x.stopPropagation(),t.length>1?s():o())},[t.length,s,o]),b=u?t[t.length-1]:null;return M.jsx(FS,{children:u&&b&&M.jsxs(M.Fragment,{children:[M.jsx(hu.div,{className:"fixed inset-0 z-50 bg-black/50",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.25},onClick:m,onKeyDown:y,tabIndex:-1},"inspector-backdrop"),M.jsx(hu.div,{className:"fixed inset-0 z-50 flex items-center justify-center p-8 pointer-events-none",children:M.jsxs(hu.div,{className:`flex h-[80vh] w-full max-w-5xl flex-col rounded-lg shadow-xl pointer-events-auto overflow-hidden ${n==="dark"?"bg-gray-900":"bg-white"}`,initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.15},children:[M.jsxs("div",{className:`flex items-center justify-between border-b px-4 py-3 ${n==="dark"?"border-gray-700":"border-gray-200"}`,children:[M.jsx(CU,{stack:t,onNavigate:l,theme:n}),M.jsx("button",{onClick:o,className:`rounded p-1 ${n==="dark"?"text-gray-400 hover:bg-gray-800 hover:text-gray-300":"text-gray-400 hover:bg-gray-100 hover:text-gray-600"}`,"aria-label":"Close inspector",children:M.jsx("svg",{className:"h-5 w-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:M.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),M.jsx("div",{className:"relative flex-1 overflow-hidden",children:M.jsx(FS,{mode:"wait",initial:!1,children:M.jsx(hu.div,{className:"absolute inset-0",initial:h==="in"?"enterIn":"enterOut",animate:"center",exit:h==="in"?"exitIn":"exitOut",variants:TU,transition:{duration:.2,ease:"easeInOut"},children:M.jsx(EU,{frame:b,componentLibrary:e,onPushLevel:a,theme:n})},`${t.length}-${b.componentName}`)})})]})},"inspector-dialog")]})})}function AU(){const{fitView:t,zoomIn:e,zoomOut:n}=da(),o="bg-[var(--embed-bg-tertiary)] hover:opacity-80 text-[var(--embed-text-secondary)] p-1.5 rounded border border-[var(--embed-border)] transition-colors";return M.jsxs("div",{className:"flex items-center gap-1",children:[M.jsx("button",{onClick:()=>n(),className:o,title:"Zoom out","aria-label":"Zoom out",children:M.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",strokeWidth:1.5,children:M.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 12h14"})})}),M.jsx("button",{onClick:()=>e(),className:o,title:"Zoom in","aria-label":"Zoom in",children:M.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",strokeWidth:1.5,children:M.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 5v14M5 12h14"})})}),M.jsx("button",{onClick:()=>t({padding:.3}),className:o,title:"Fit view","aria-label":"Fit view",children:M.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",strokeWidth:1.5,children:M.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.75 3.75v4.5m0-4.5h4.5m-4.5 0L9 9M3.75 20.25v-4.5m0 4.5h4.5m-4.5 0L9 15M20.25 3.75h-4.5m4.5 0v4.5m0-4.5L15 9m5.25 11.25h-4.5m4.5 0v-4.5m0 4.5L15 15"})})})]})}let dm=null;function MU(){if(!dm){const t=new Map;dm={resolveCircuit:e=>t.get(e),getAllPrimitiveNames:()=>[...t.entries()].filter(([,e])=>e.implementation.kind==="primitive").map(([e])=>e),addCircuit:e=>{t.set(e.name,e)}}}return dm}function RU({circuit:t,componentLibrary:e,portValues:n,sequentialState:o,draggable:s=!0,layout:a,onToggleNode:l,onSetNodeValue:u,onLoadMemory:d,onNodeDoubleClick:h,height:p="100%",focus:m,className:y,renderEmptyState:b,renderOverlay:x,nodeTypes:w,edgeTypes:_,showControls:S=!0,showPortLabels:k,onPortClick:C,glowUnconnected:E,theme:R,panOnMobile:A=!1,onRequestRemount:O}){const D=m1(),$=R??D,q=Y8(),Y=w??Tw,K=_??Nw,W=e??MU(),B=N.useMemo(()=>m?new Set(Array.isArray(m)?m:[m]):null,[m]),H=N.useMemo(()=>t?Vj(t):null,[t]),{metadata:j}=U8(a?null:H),I=N.useMemo(()=>{if(!H)return{components:{},connections:{}};if(!a)return j;const mt={};for(const Ct of H.nodes){const It=Ct.label||Ct.id,zt=a[It]??a[Ct.id];zt&&(mt[Ct.id]={id:Ct.id,position:zt})}return{components:mt,connections:{}}},[H,j,a]),{projectedNodes:z,projectedEdges:U}=N.useMemo(()=>{if(!H)return{projectedNodes:[],projectedEdges:[]};const mt=pL(H,I,W,n??void 0,o??void 0),Ct=mt.nodes.map(It=>{const zt=It.data,Vt=zt?.componentRef,ve={...It.data};if(k&&(ve.showPortLabels=!0),E&&(ve.glowUnconnected=!0),C){const Wt=zt.label||zt.componentRef;ve.onPortClick=(je,xn)=>C(Wt,je,xn)}return Vt==="Input"&&u&&(ve.onValueChange=Wt=>u(It.id,Wt)),l&&(Vt==="Switch"||Vt==="Button")&&(ve.onToggle=()=>l(It.id)),d&&(Vt==="RV32I_InstrMem"||Vt==="DualPortROM")&&(ve.onLoadMemory=Wt=>d(It.id,Wt)),{...It,data:ve}});if(B){const It=new Set;for(const zt of Ct){const Vt=zt.data?.label??zt.id;B.has(Vt)&&It.add(zt.id)}return{projectedNodes:Ct.map(zt=>{const Vt=zt.data?.label??zt.id;return{...zt,style:{...zt.style,opacity:B.has(Vt)?1:.15,transition:"opacity 0.2s"}}}),projectedEdges:mt.edges.map(zt=>({...zt,style:{...zt.style,opacity:It.has(zt.source)||It.has(zt.target)?1:.15,transition:"opacity 0.2s"}}))}}return{projectedNodes:Ct,projectedEdges:mt.edges}},[H,I,W,n,o,l,u,d,B,k,C,E]),[G,L]=N.useState([]),[F,et]=N.useState([]),{fitView:rt}=da(),ct=cj(),ht=N.useRef(null),ft=N.useRef(new Set),ut=N.useRef(new Map),dt=N.useRef(0);N.useLayoutEffect(()=>{const mt=ht.current,Ct=ft.current,It=ut.current,zt=H?.name??null,Vt=new Set(z.map(Re=>Re.id)),ve=new Map;for(const Re of z){const me=Re.data,le=`${(me.inputNames??[]).join("|")}>${(me.outputNames??[]).join("|")}`;ve.set(Re.id,le)}ht.current=zt,ft.current=Vt,ut.current=ve;const Wt=zt!==mt;let je=0;for(const Re of Vt)Ct.has(Re)&&je++;const xn=Math.max(Ct.size,Vt.size),Pa=xn>0&&je/xn<.5,Hn=Wt||Pa,tr=[];if(!Hn)for(const[Re,me]of ve){const le=It.get(Re);le!==void 0&&le!==me&&tr.push(Re)}const Ba=dt.current===0;dt.current=z.length,L(Re=>{const me=new Map(Re.map(le=>[le.id,le]));return z.map(le=>{const ze=me.get(le.id);return ze&&!Hn?{...ze,type:le.type,data:le.data,selectable:le.selectable,deletable:le.deletable}:le})}),et(U),Hn&&Ct.size>0?O?.():tr.length>0&&requestAnimationFrame(()=>ct(tr)),z.length>0&&Ba&&!Hn&&requestAnimationFrame(()=>rt({padding:.3}))},[z,U]);const Ot=N.useCallback(mt=>{L(Ct=>pb(mt,Ct))},[]),[At,bt]=N.useState([]),Tt=N.useCallback((mt,Ct,It)=>{bt(zt=>[...zt,{componentName:mt,componentDef:Ct,nodeLabel:It}])},[]),Dt=N.useCallback(()=>{bt(mt=>mt.slice(0,-1))},[]),Xt=N.useCallback(()=>{bt([])},[]),Ft=N.useCallback(mt=>{bt(Ct=>Ct.slice(0,mt+1))},[]),pt=N.useCallback(mt=>{if(!mt.isComposite)return;const Ct=W.resolveCircuit(mt.componentRef);Ct&&Ct.implementation.kind==="composite"&&Ct.nodes.length>0&&bt([{componentName:mt.componentRef,componentDef:Ct,nodeLabel:mt.label??mt.componentRef}])},[W]),yt=h??pt,vt=N.useCallback((mt,Ct)=>{yt(Ct.data)},[yt]);return M.jsxs("div",{"data-embed-theme":$,className:`bg-[var(--embed-bg-primary)] overflow-hidden relative ${y??""}`,style:{height:p},"aria-label":"Circuit diagram",children:[M.jsxs(lj,{nodes:G,edges:F,nodeTypes:Y,edgeTypes:K,onNodesChange:Ot,onNodeDoubleClick:vt,fitView:!0,minZoom:.1,maxZoom:3,fitViewOptions:{padding:.3,...B&&{nodes:G.filter(mt=>{const Ct=mt.data?.label??mt.id;return B.has(Ct)})}},nodesDraggable:s&&!q,nodesConnectable:!1,elementsSelectable:!0,selectionOnDrag:!1,panOnDrag:q&&!A?!1:[1,2],zoomOnScroll:!0,zoomOnPinch:!0,zoomOnDoubleClick:!1,preventScrolling:!1,proOptions:{hideAttribution:!0},deleteKeyCode:null,panActivationKeyCode:null,children:[M.jsx(pj,{variant:pi.Dots,gap:20,size:1,color:"var(--embed-dot-color)"}),S&&M.jsx(ua,{position:"bottom-left",children:M.jsx(AU,{})})]}),x?.(),!t&&(b?b():M.jsx("div",{className:"absolute inset-0 flex items-center justify-center text-[var(--embed-text-muted)]",children:"No circuit"})),!h&&At.length>0&&M.jsx(NU,{stack:At,componentLibrary:W,theme:$,onClose:Xt,onPopLevel:Dt,onPushLevel:Tt,onNavigate:Ft})]})}function z2(t){const[e,n]=N.useState(0),o=N.useCallback(()=>{n(s=>s+1)},[]);return M.jsx(Jb,{children:M.jsx(RU,{...t,onRequestRemount:o})},e)}const kU=N.forwardRef(function({circuit:e,height:n=300,showControls:o=!0,autoHarness:s=!1,initialInputs:a,layout:l,theme:u,focus:d,showPortLabels:h,onPortClick:p,glowUnconnected:m,renderEmptyState:y,renderOverlay:b,onPortValuesChange:x},w){const _=kM(e,{autoHarness:s,initialInputs:a}),S=m1(),k=u??S,C=N.useRef(x);N.useEffect(()=>{C.current=x}),N.useEffect(()=>{!_.ready||!_.portValues||_.portValues.size===0||C.current?.(_.portValues)},[_.ready,_.portValues]);const E=N.useCallback(()=>{_.tick()},[_.tick]),R=N.useCallback(()=>{_.reset()},[_.reset]);if(N.useImperativeHandle(w,()=>({tick:E,reset:R,setNodeValue:_.setNodeValue,startAutoRun:_.startAutoRun,stopAutoRun:_.stopAutoRun}),[E,R,_.setNodeValue,_.startAutoRun,_.stopAutoRun]),_.error)return M.jsx("div",{style:{height:n},className:"flex items-center justify-center p-4",children:M.jsxs("div",{className:"text-sm text-red-400 bg-red-500/10 rounded p-3 border border-red-500/20",children:[M.jsx("div",{className:"font-medium mb-1",children:"Compilation Error"}),M.jsx("div",{className:"font-mono text-xs",children:_.error})]})});if(!_.ready)return M.jsx("div",{style:{height:n},className:"flex items-center justify-center text-muted-foreground/60 text-sm",children:"Compiling..."});const A=_.isSequential&&o?40:0,O=typeof n=="number"?n-A:n;return M.jsxs("div",{style:{height:n},className:"flex flex-col","data-embed-theme":k,children:[M.jsx("div",{className:"flex-1 min-h-0",children:M.jsx(z2,{circuit:_.circuit,componentLibrary:_.componentLibrary??void 0,portValues:_.portValues,sequentialState:_.sequentialState,onToggleNode:_.toggleNode,onSetNodeValue:_.setNodeValue,onLoadMemory:(D,$)=>{const q=_.getSimulator();q&&(q.setNode(D,$),_.runCombinational())},height:O,focus:d,showPortLabels:h,onPortClick:p,glowUnconnected:m,renderEmptyState:y,renderOverlay:b,...l?{layout:l}:{},...u?{theme:u}:{}})}),_.isSequential&&o&&M.jsx(j2,{cycle:_.cycleCount,historyLength:_.history?.length??0,historyIndex:_.historyIndex??-1,isRunning:_.isRunning,isViewingPast:_.isViewingPast??!1,onStep:E,onRun:()=>_.startAutoRun(15),onPause:()=>_.stopAutoRun(),onReset:R,onStepBack:()=>_.stepBack(),onStepForward:()=>{_.isViewingPast?_.stepForward():E()},speed:5})]})});var hm={exports:{}},V2;function OU(){return V2||(V2=1,(function(t){var e=(function(){var n=String.fromCharCode,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",a={};function l(d,h){if(!a[d]){a[d]={};for(var p=0;p<d.length;p++)a[d][d.charAt(p)]=p}return a[d][h]}var u={compressToBase64:function(d){if(d==null)return"";var h=u._compress(d,6,function(p){return o.charAt(p)});switch(h.length%4){default:case 0:return h;case 1:return h+"===";case 2:return h+"==";case 3:return h+"="}},decompressFromBase64:function(d){return d==null?"":d==""?null:u._decompress(d.length,32,function(h){return l(o,d.charAt(h))})},compressToUTF16:function(d){return d==null?"":u._compress(d,15,function(h){return n(h+32)})+" "},decompressFromUTF16:function(d){return d==null?"":d==""?null:u._decompress(d.length,16384,function(h){return d.charCodeAt(h)-32})},compressToUint8Array:function(d){for(var h=u.compress(d),p=new Uint8Array(h.length*2),m=0,y=h.length;m<y;m++){var b=h.charCodeAt(m);p[m*2]=b>>>8,p[m*2+1]=b%256}return p},decompressFromUint8Array:function(d){if(d==null)return u.decompress(d);for(var h=new Array(d.length/2),p=0,m=h.length;p<m;p++)h[p]=d[p*2]*256+d[p*2+1];var y=[];return h.forEach(function(b){y.push(n(b))}),u.decompress(y.join(""))},compressToEncodedURIComponent:function(d){return d==null?"":u._compress(d,6,function(h){return s.charAt(h)})},decompressFromEncodedURIComponent:function(d){return d==null?"":d==""?null:(d=d.replace(/ /g,"+"),u._decompress(d.length,32,function(h){return l(s,d.charAt(h))}))},compress:function(d){return u._compress(d,16,function(h){return n(h)})},_compress:function(d,h,p){if(d==null)return"";var m,y,b={},x={},w="",_="",S="",k=2,C=3,E=2,R=[],A=0,O=0,D;for(D=0;D<d.length;D+=1)if(w=d.charAt(D),Object.prototype.hasOwnProperty.call(b,w)||(b[w]=C++,x[w]=!0),_=S+w,Object.prototype.hasOwnProperty.call(b,_))S=_;else{if(Object.prototype.hasOwnProperty.call(x,S)){if(S.charCodeAt(0)<256){for(m=0;m<E;m++)A=A<<1,O==h-1?(O=0,R.push(p(A)),A=0):O++;for(y=S.charCodeAt(0),m=0;m<8;m++)A=A<<1|y&1,O==h-1?(O=0,R.push(p(A)),A=0):O++,y=y>>1}else{for(y=1,m=0;m<E;m++)A=A<<1|y,O==h-1?(O=0,R.push(p(A)),A=0):O++,y=0;for(y=S.charCodeAt(0),m=0;m<16;m++)A=A<<1|y&1,O==h-1?(O=0,R.push(p(A)),A=0):O++,y=y>>1}k--,k==0&&(k=Math.pow(2,E),E++),delete x[S]}else for(y=b[S],m=0;m<E;m++)A=A<<1|y&1,O==h-1?(O=0,R.push(p(A)),A=0):O++,y=y>>1;k--,k==0&&(k=Math.pow(2,E),E++),b[_]=C++,S=String(w)}if(S!==""){if(Object.prototype.hasOwnProperty.call(x,S)){if(S.charCodeAt(0)<256){for(m=0;m<E;m++)A=A<<1,O==h-1?(O=0,R.push(p(A)),A=0):O++;for(y=S.charCodeAt(0),m=0;m<8;m++)A=A<<1|y&1,O==h-1?(O=0,R.push(p(A)),A=0):O++,y=y>>1}else{for(y=1,m=0;m<E;m++)A=A<<1|y,O==h-1?(O=0,R.push(p(A)),A=0):O++,y=0;for(y=S.charCodeAt(0),m=0;m<16;m++)A=A<<1|y&1,O==h-1?(O=0,R.push(p(A)),A=0):O++,y=y>>1}k--,k==0&&(k=Math.pow(2,E),E++),delete x[S]}else for(y=b[S],m=0;m<E;m++)A=A<<1|y&1,O==h-1?(O=0,R.push(p(A)),A=0):O++,y=y>>1;k--,k==0&&(k=Math.pow(2,E),E++)}for(y=2,m=0;m<E;m++)A=A<<1|y&1,O==h-1?(O=0,R.push(p(A)),A=0):O++,y=y>>1;for(;;)if(A=A<<1,O==h-1){R.push(p(A));break}else O++;return R.join("")},decompress:function(d){return d==null?"":d==""?null:u._decompress(d.length,32768,function(h){return d.charCodeAt(h)})},_decompress:function(d,h,p){var m=[],y=4,b=4,x=3,w="",_=[],S,k,C,E,R,A,O,D={val:p(0),position:h,index:1};for(S=0;S<3;S+=1)m[S]=S;for(C=0,R=Math.pow(2,2),A=1;A!=R;)E=D.val&D.position,D.position>>=1,D.position==0&&(D.position=h,D.val=p(D.index++)),C|=(E>0?1:0)*A,A<<=1;switch(C){case 0:for(C=0,R=Math.pow(2,8),A=1;A!=R;)E=D.val&D.position,D.position>>=1,D.position==0&&(D.position=h,D.val=p(D.index++)),C|=(E>0?1:0)*A,A<<=1;O=n(C);break;case 1:for(C=0,R=Math.pow(2,16),A=1;A!=R;)E=D.val&D.position,D.position>>=1,D.position==0&&(D.position=h,D.val=p(D.index++)),C|=(E>0?1:0)*A,A<<=1;O=n(C);break;case 2:return""}for(m[3]=O,k=O,_.push(O);;){if(D.index>d)return"";for(C=0,R=Math.pow(2,x),A=1;A!=R;)E=D.val&D.position,D.position>>=1,D.position==0&&(D.position=h,D.val=p(D.index++)),C|=(E>0?1:0)*A,A<<=1;switch(O=C){case 0:for(C=0,R=Math.pow(2,8),A=1;A!=R;)E=D.val&D.position,D.position>>=1,D.position==0&&(D.position=h,D.val=p(D.index++)),C|=(E>0?1:0)*A,A<<=1;m[b++]=n(C),O=b-1,y--;break;case 1:for(C=0,R=Math.pow(2,16),A=1;A!=R;)E=D.val&D.position,D.position>>=1,D.position==0&&(D.position=h,D.val=p(D.index++)),C|=(E>0?1:0)*A,A<<=1;m[b++]=n(C),O=b-1,y--;break;case 2:return _.join("")}if(y==0&&(y=Math.pow(2,x),x++),m[O])w=m[O];else if(O===b)w=k+k.charAt(0);else return null;_.push(w),m[b++]=k+w.charAt(0),y--,k=w,y==0&&(y=Math.pow(2,x),x++)}}};return u})();t!=null?t.exports=e:typeof angular<"u"&&angular!=null&&angular.module("LZString",[]).factory("LZString",function(){return e})})(hm)),hm.exports}var DU=OU();function jU(t){return DU.compressToEncodedURIComponent(t)}const zU=N.createContext(null);function VU(){return N.useContext(zU)}function L2(){return typeof window>"u"?"https://simten.dev":window.location.hostname==="localhost"?window.location.origin:"https://simten.dev"}const LU=160,IU=90;function PU(t){if(!t)return 1.5;const e=Object.values(t);if(e.length===0)return 1.5;const n=Math.max(...e.map(s=>s.x))+LU,o=Math.max(...e.map(s=>s.y))+IU;return n<=0||o<=0?1.5:n/o}function I2({onFork:t,forkError:e,forkPending:n,className:o,tooltipSide:s="top"}){return M.jsx(Th,{delayDuration:300,children:M.jsxs(Nh,{children:[M.jsx(Ah,{asChild:!0,children:M.jsx("button",{type:"button",onClick:t,className:`cursor-pointer ${o}`,children:e?"Fork failed":n?"Forking…":"Fork →"})}),M.jsx(Mh,{side:s,children:e??"Open and modify this circuit in the Simten editor"})]})})}const BU=N.forwardRef(function({circuit:e,height:n,aspectRatio:o,showControls:s=!0,layout:a,theme:l,title:u,subtitle:d,description:h,href:p,focus:m,showPortLabels:y,onPortClick:b,glowUnconnected:x,autoRunSpeed:w=500,initialInputs:_,forkSource:S,onPortValuesChange:k},C){const E=u||h,[R,A]=N.useState(null),[O,D]=N.useState(!1),$=VU(),q=async()=>{if(!O)try{const j=S??xM(e);if($){D(!0);const{hash:I}=await $(j);window.open(`${L2()}/circuit/s/${I}`,"_blank","noopener")}else{const I=jU(j);window.open(`${L2()}/circuit/${I}`,"_blank","noopener")}}catch(j){A(j instanceof Error?j.message:"Couldn't fork this circuit"),setTimeout(()=>A(null),3e3)}finally{D(!1)}},Y=n===void 0,K=o??PU(a),W={width:"100%",aspectRatio:String(K),minHeight:240,maxHeight:"70vh"},B=E?void 0:Y?W:{height:n},H=E?Y?W:{height:n}:{height:"100%"};return M.jsxs("div",{style:B,className:`relative flex flex-col ${E?"rounded-xl border border-[var(--embed-border)] overflow-hidden bg-[var(--embed-bg-secondary)]":""}`,children:[!E&&!p&&M.jsx(I2,{onFork:q,forkError:R,forkPending:O,tooltipSide:"bottom",className:"absolute top-2 right-2 z-10 hidden md:flex items-center px-2.5 py-1 rounded border border-[var(--embed-border)] bg-[var(--embed-bg-secondary)] text-[11px] text-[var(--embed-text-primary)] hover:opacity-80 transition-colors shadow-sm"}),M.jsx("div",{style:H,className:"min-h-0",children:M.jsx(kU,{ref:C,circuit:e,height:"100%",showControls:s,autoHarness:!0,initialInputs:_,layout:a,theme:l,focus:m,showPortLabels:y,onPortClick:b,glowUnconnected:x,autoRunSpeed:w,onPortValuesChange:k})}),E&&M.jsxs("div",{className:"border-t border-[var(--embed-border)] px-4 py-3 flex items-end justify-between gap-4",children:[M.jsxs("div",{children:[M.jsx("div",{className:"text-base font-semibold text-[var(--embed-text-primary)]",children:u}),d&&M.jsx("div",{className:"text-xs text-[var(--embed-text-muted)] font-mono mt-0.5",children:d}),h&&M.jsx("div",{className:"text-sm text-[var(--embed-text-secondary)] mt-1.5 leading-relaxed",children:h})]}),p?M.jsx("a",{href:p,className:"shrink-0 px-3 py-1.5 rounded border border-[var(--embed-border)] text-xs text-[var(--embed-text-primary)] hover:opacity-80 transition-colors",children:"Open →"}):M.jsx(I2,{onFork:q,forkError:R,forkPending:O,tooltipSide:"top",className:"hidden md:flex items-center shrink-0 px-3 py-1.5 rounded border border-[var(--embed-border)] text-xs text-[var(--embed-text-primary)] hover:opacity-80 transition-colors"})]})]})});function HU({code:t,height:e,showControls:n,title:o,subtitle:s,description:a,href:l,autoRunSpeed:u,theme:d}){const h=Wf(),[p,m]=N.useState(null),[y,b]=N.useState(null);return N.useEffect(()=>{if(!t){m(null),b(null);return}let x=!1;return h.compile(t).then(w=>{if(x)return;if("error"in w){b(w.error),m(null);return}const _=w.circuits[w.circuits.length-1];if(!_){b("No circuit found in code"),m(null);return}b(null),m(vM(_,w.libraryCircuits))}),()=>{x=!0}},[t,h]),t?y?M.jsx("div",{style:{height:e},className:"flex items-center justify-center p-4",children:M.jsxs("div",{className:"text-sm text-red-400 bg-red-500/10 rounded p-3 border border-red-500/20",children:[M.jsx("div",{className:"font-medium mb-1",children:"Error"}),M.jsx("div",{className:"font-mono text-xs whitespace-pre-wrap",children:y})]})}):p?M.jsx("div",{"data-embed-theme":d??"dark",children:M.jsx(BU,{circuit:p,height:e,showControls:n,title:o,subtitle:s,description:a,href:l,forkSource:t,autoRunSpeed:u,theme:d})}):M.jsx("div",{style:{height:e},className:"flex items-center justify-center text-sm text-gray-500",children:"Compiling..."}):M.jsx("div",{style:{height:e},className:"flex items-center justify-center text-sm text-gray-500",children:"No circuit code provided"})}function $U(t){return M.jsx(XN,{children:M.jsx(HU,{...t})})}const P2=$N($U,{props:{code:"string",height:"number",showControls:"boolean",title:"string",subtitle:"string",description:"string",href:"string",autoRunSpeed:"number",theme:"string"}});return customElements.get("circuit-embed")||customElements.define("circuit-embed",P2),Hf.CircuitEmbedWC=P2,Object.defineProperty(Hf,Symbol.toStringTag,{value:"Module"}),Hf})({});
|
|
79
|
+
=== Eliminating ${p.length} passthrough connections ===`);const m=[],y=new Set;for(const b of h)if(u.has(b.source.nodeId)&&b.source.nodeId===b.target.nodeId){y.add(b.id),a&&console.log(` PASSTHROUGH: ${b.source.nodeId}.${b.source.portName} -> ${b.target.portName}`);const w=h.filter(S=>S.target.nodeId===b.source.nodeId&&S.target.portName===b.source.portName&&!y.has(S.id)),_=h.filter(S=>S.source.nodeId===b.target.nodeId&&S.source.portName===b.target.portName&&!y.has(S.id));for(const S of w)for(const k of _){const C={id:`${S.source.nodeId}.${S.source.portName}->${k.target.nodeId}.${k.target.portName}`,source:S.source,target:k.target,portType:b.portType};m.push(C),y.add(S.id),y.add(k.id),a&&console.log(` DIRECT: ${C.source.nodeId}.${C.source.portName} -> ${C.target.nodeId}.${C.target.portName}`)}}else y.has(b.id)||m.push(b);return w2(m,n,u,a)}return w2(h,n,u,a)}function w2(t,e,n,o){const s=new Set(e.map(p=>p.id)),a=p=>p.nodeId===De||s.has(p.nodeId),l=new Map;for(const p of t){const m=`${p.source.nodeId}.${p.source.portName}`;l.has(m)||l.set(m,[]),l.get(m).push(p)}const u=p=>{const m=[],y=new Set,b=[p];for(;b.length>0;){const x=b.pop(),w=`${x.nodeId}.${x.portName}`;if(!y.has(w)){if(y.add(w),a(x)){m.push(x);continue}for(const _ of l.get(w)??[])b.push(_.target)}}return m},d=[],h=new Set;for(const p of t){if(!a(p.source))continue;const m=a(p.target)?[p.target]:u(p.target);for(const y of m){if(p.source.nodeId===y.nodeId&&p.source.portName===y.portName)continue;const x=`${p.source.nodeId}.${p.source.portName}->${y.nodeId}.${y.portName}`;h.has(x)||(h.add(x),o&&console.log(` RESOLVED: ${p.source.nodeId}.${p.source.portName} -> ${y.nodeId}.${y.portName}`),d.push({id:x,source:p.source,target:y,portType:p.portType}))}}return d}function L$(t,e,n,o,s=!1){for(const a of t.connections){if(a.source.nodeId===""&&a.target.nodeId!==""){const l=`${e}.${a.source.portName}`,u=pu(e,a.target,t,o);n.has(l)||n.set(l,[]);for(const d of u)n.get(l).push(d),s&&console.log(` INPUT: ${a.source.portName} -> ${d.nodeId}.${d.portName}`)}if(a.source.nodeId!==""&&a.target.nodeId===""){const l=`${e}.${a.target.portName}`,u=pu(e,a.source,t,o);n.has(l)||n.set(l,[]);for(const d of u)n.get(l).push(d),s&&console.log(` OUTPUT: ${a.target.portName} <- ${d.nodeId}.${d.portName}`)}if(a.source.nodeId===""&&a.target.nodeId===""){s&&console.log(` PASSTHROUGH: ${a.source.portName} -> ${a.target.portName}`);const l=`${e}.${a.source.portName}`;n.has(l)||n.set(l,[]),n.get(l).push({nodeId:e,portName:a.target.portName}),s&&console.log(` -> Added passthrough forwarding: ${l} -> ${e}.${a.target.portName}`)}}}function pu(t,e,n,o,s=new Set){if(e.nodeId==="")return[{nodeId:t,portName:e.portName}];const a=t+"."+e.nodeId,l=n.nodes.find(p=>p.id===e.nodeId);if(!l)return[{nodeId:a,portName:e.portName}];const u=o.resolveCircuit(l.componentRef);if(!u||u.implementation.kind!=="composite")return[{nodeId:a,portName:e.portName}];if(s.has(l.componentRef))return[{nodeId:a,portName:e.portName}];const d=new Set(s);d.add(l.componentRef);const h=[];for(const p of u.connections){if(p.target.nodeId===""&&p.target.portName===e.portName){const m=pu(a,p.source,u,o,d);h.push(...m)}if(p.source.nodeId===""&&p.source.portName===e.portName){const m=pu(a,p.target,u,o,d);h.push(...m)}}return h.length>0?h:[{nodeId:a,portName:e.portName}]}function I$(t){t.nodeMap=new Map(t.nodes.map(e=>[e.id,e]));for(const e of t.nodes)e.dependents=[],e.inputSources=[];for(const e of t.connections){const n=e.source.nodeId,o=e.target.nodeId;if(o===De)continue;const s=t.nodeMap.get(n);s&&!s.dependents.includes(o)&&s.dependents.push(o);const a=t.nodeMap.get(o);a&&a.inputSources.push({portName:e.target.portName,sourceNodeId:n,sourcePortName:e.source.portName})}}function P$(t,e){return`${t}.${e}`}function _2(t,e,n){const o=new Map,s=new Map,a=new Map;for(const l of t.nodes){const u=e.resolveCircuit(l.primitiveType);if(u){if(u.implementation.kind==="primitive"&&u.state.length>0){const d=u.state.map(p=>B$(p,l.id,l.arguments,l.primitiveType,n)),h=u.state.length===1?d[0]:Object.fromEntries(u.state.map((p,m)=>[p.name,d[m]]));o.set(l.id,h),s.set(l.id,h)}for(const d of l.clocks)a.set(P$(l.id,d.name),{value:!1,edge:"none"})}}return{currentState:o,nextState:s,clocks:a,cycleCount:0}}function B$(t,e,n,o,s){const a=t.stateType.kind,l=n[t.name];if(a==="memory"){const d=new Map,h=t.initialValue;if(h?.data){if(h.data instanceof Map)for(const[p,m]of h.data)d.set(p,m);else if(typeof h.data=="object")for(const[p,m]of Object.entries(h.data)){const y=parseInt(p,10);!isNaN(y)&&typeof m=="number"&&d.set(y,m)}}if(l!==void 0){if(Array.isArray(l))l.forEach((p,m)=>{typeof p=="number"&&d.set(m,p)});else if(l instanceof Map)for(const[p,m]of l)d.set(p,m);else if(typeof l=="object"&&l!==null)for(const[p,m]of Object.entries(l)){const y=parseInt(p,10);!isNaN(y)&&typeof m=="number"&&d.set(y,m)}}if(s){const p=$$(e,s,o);if(p)for(const[m,y]of p.entries())d.set(m,y)}return d}if(l!==void 0&&(typeof l=="number"||typeof l=="boolean"))return l;const u=t.initialValue;return u}function H$(t){const n=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(n,"i")}function $$(t,e,n){for(const[o,s]of e){const a=H$(o);if(a.test(t)||n&&a.test(n))return s}}const am={And:0,Or:1,Not:2,Nand:3,Nor:4,Xor:5,Xnor:6,Buffer:7,Switch:10,Led:11,Output:12,Button:13,Input:14,Constant:15,Splitter:20,Splitter8to8:21,Combiner8to8:22,Probe:23,BitSlice:24,AddressCombiner:25,Concat:26,BusAnd:40,BusOr:41,BusNot:42,BusXor:43,Incrementer:50,Adder:51,Multiplier:52,Comparator:53,LeftShifter:54,RightShifter:55,Subtractor:56,SignedAdder:57,SignedComparator:58,SignedMultiplier:59,Mux:70,Decoder:71,SevenSegment:80,HexDisplay:81,Screen:82,RasterDisplay:83,DFlipFlop:90,Register:91,ROM:100,RAM:101,DualPortRAM:102,Console:110},U$=Object.entries(am).reduce((t,[e,n])=>(t[n]=e,t),[]);class Y${queue;pending;head=0;tail=0;capacity;constructor(e){this.capacity=e,this.queue=new Uint32Array(e),this.pending=new Uint8Array(e)}enqueue(e){this.pending[e]||(this.pending[e]=1,this.queue[this.tail%this.capacity]=e,this.tail++)}enqueueAll(e){for(let n=0;n<e.length;n++)this.enqueue(e[n])}dequeue(){const e=this.queue[this.head%this.capacity];return this.pending[e]=0,this.head++,e}isEmpty(){return this.head===this.tail}size(){return this.tail-this.head}toArray(){const e=[];for(let n=this.head;n<this.tail;n++)e.push(this.queue[n%this.capacity]);return e}clear(){this.head=0,this.tail=0,this.pending.fill(0)}}function S2(t){return{values:new Int32Array(t),changed:new Uint8Array(t),initialized:new Uint8Array(t)}}function E2(t,e){const n=t.circuit.inputSourcePort[t.portStart+e];return n>=0?t.values.values[n]:0}function C2(t,e,n){const o=t.portStart+t.inputCount+e;t.values.values[o]=n,t.values.initialized[o]=1}const q$=Math.max(...Object.values(am))+1,Va=new Array(q$).fill(null);function T2(t){return new Proxy(t,{get(e,n){if(typeof n=="string"&&/^\d+$/.test(n))return e.get(Number(n))??0;const o=e[n];return typeof o=="function"?o.bind(e):o},set(e,n,o){return typeof n=="string"&&/^\d+$/.test(n)?(e.set(Number(n),o),!0):!1}})}let G$=200;const N2=new Map;function F$(t){const e=am[t];if(e!==void 0)return e;const n=N2.get(t);if(n!==void 0)return n;const o=G$++;return N2.set(t,o),U$[o]=t,o}function X$(t,e,n,o){const s=t.length,a=e.length;return!o||o.length===0?function(u){const d={},h=u.circuit.flatCircuit.nodes[u.nodeIndex]?.arguments;if(h)for(const m in h)d[m]=h[m];for(let m=0;m<s;m++)d[t[m]]=E2(u,m);const p=n(d);for(let m=0;m<a;m++){const y=p[e[m]];y!==void 0&&C2(u,m,y)}}:function(u){const d={},h=u.circuit.flatCircuit.nodes[u.nodeIndex]?.arguments;if(h)for(const m in h)d[m]=h[m];for(let m=0;m<s;m++)d[t[m]]=E2(u,m);if(u.state){const m=u.state.currentState[u.nodeIndex];if(m!=null&&typeof m=="object"&&!Array.isArray(m)&&!(m instanceof Map)){const y=m;for(const b of o){const x=y[b];d[b]=x instanceof Map?T2(x):x}}else m!=null&&(d[o[0]]=m instanceof Map?T2(m):m)}const p=n(d);for(let m=0;m<a;m++){const y=p[e[m]];y!==void 0&&C2(u,m,y)}}}function Z$(t){const e=F$(t);if(Va[e]!=null)return e;const n=Ll(t);if(!n)return console.warn(`[eval-bridge] No eval-registry entry for '${t}' — getAllCircuitEvals:`,[...JN().keys()]),e;for(;Va.length<=e;)Va.push(null);return Va[e]=X$(n.inputNames,n.outputNames,n.evalFn,n.stateKeys),e}const lm=new Map;function K$(t){if(lm.has(t))return lm.get(t);const e=Ll(t);if(!e?.onTickFn)return;const n={inputNames:e.inputNames,stateKeys:e.stateKeys??[],fn:e.onTickFn};return lm.set(t,n),n}function Q$(t,e){const n=t.nodes.length,o=new Map,s=new Array(n);for(let q=0;q<n;q++){const Y=t.nodes[q];o.set(Y.id,q),s[q]=Y.id}let a=0;const l=new Uint32Array(n),u=new Uint8Array(n),d=new Uint8Array(n);for(let q=0;q<n;q++){const Y=t.nodes[q];l[q]=a,u[q]=Y.inputs.length,d[q]=Y.outputs.length,a+=Y.inputs.length+Y.outputs.length}const h=t.topLevelInputs.length,p=t.topLevelOutputs.length,m=a+h+p,y=new Map,b=new Array(m),x=new Uint8Array(m),w=new Uint8Array(m),_=new Array(m);let S=a;for(const q of t.topLevelInputs){const Y=`${De}.${q.name}`;y.set(Y,S),b[S]=Y,x[S]=1,w[S]=q.portType.kind==="bus"?1:0,S++}for(const q of t.topLevelOutputs){const Y=`${De}.${q.name}`;y.set(Y,S),b[S]=Y,x[S]=0,w[S]=q.portType.kind==="bus"?1:0,S++}for(let q=0;q<n;q++){const Y=t.nodes[q];let K=l[q];for(const W of Y.inputs){const B=`${Y.id}.${W.name}`;y.set(B,K),b[K]=B,x[K]=0,w[K]=W.portType.kind==="bus"?1:0,_[K]=W.name,K++}for(const W of Y.outputs){const B=`${Y.id}.${W.name}`;y.set(B,K),b[K]=B,x[K]=1;let H=W.portType.kind==="bus";if(!H){const j=Y.arguments.width;if(typeof j=="number"&&j>1&&(H=!0),!H&&Y.primitiveType==="Mux"){for(const I of Y.inputs)if(I.name!=="sel"&&I.portType.kind==="bus"){H=!0;break}}}w[K]=H?1:0,K++}}const k=new Uint16Array(n);for(let q=0;q<n;q++){const Y=t.nodes[q];k[q]=Z$(Y.primitiveType)}const C=new Array(n);for(let q=0;q<n;q++){const K=t.nodes[q].dependents.map(W=>o.get(W)).filter(W=>W!==void 0);C[q]=new Uint32Array(K)}const E=new Int32Array(a),R=new Int32Array(a);E.fill(-1),R.fill(-1);for(let q=0;q<n;q++){const Y=t.nodes[q],K=l[q];for(let W=0;W<Y.inputSources.length;W++){const B=Y.inputSources[W],H=Y.inputs.findIndex(I=>I.name===B.portName);if(H===-1)continue;const j=K+H;if(B.sourceNodeId===De){E[j]=-1;const I=`${De}.${B.sourcePortName}`;R[j]=y.get(I)??-1}else{const I=o.get(B.sourceNodeId);if(I===void 0)continue;const z=t.nodes[I],U=z.outputs.findIndex(G=>G.name===B.sourcePortName);if(U===-1)continue;E[j]=I,R[j]=l[I]+z.inputs.length+U}}}const A=new Uint8Array(n),O=new Uint8Array(n),D=new Uint8Array(n),$=new Uint8Array(n);for(let q=0;q<n;q++){const Y=t.nodes[q];A[q]=Y.inputs.length===0?1:0;const K=e.resolveCircuit(Y.primitiveType);K?.state&&K.state.length>0&&(D[q]=1,O[q]=1);for(const W of Y.inputSources)if(W.sourceNodeId===De){$[q]=1;break}}return{nodeCount:n,portCount:m,nodeIdToIndex:o,indexToNodeId:s,portKeyToIndex:y,indexToPortKey:b,primitiveTypeIndex:k,nodePortStart:l,nodeInputCount:u,nodeOutputCount:d,dependents:C,inputSourceNode:E,inputSourcePort:R,inputPortNames:_,portIsOutput:x,portIsBus:w,isSourceNode:A,isStateOutputNode:O,hasState:D,readsTopLevelInput:$,flatCircuit:t}}function cm(t,e){const n=new Array(t.nodeCount),o=new Array(t.nodeCount);for(const[s,a]of e.currentState){const l=t.nodeIdToIndex.get(s);l!==void 0&&(n[l]=a)}for(const[s,a]of e.nextState){const l=t.nodeIdToIndex.get(s);l!==void 0&&(o[l]=a)}return{currentState:n,nextState:o,clocks:e.clocks,cycleCount:e.cycleCount}}function um(t,e){const n=new Map,o=new Map;for(let s=0;s<t.nodeCount;s++){const a=t.indexToNodeId[s];e.currentState[s]!==void 0&&n.set(a,e.currentState[s]),e.nextState[s]!==void 0&&o.set(a,e.nextState[s])}return{currentState:n,nextState:o,clocks:e.clocks,cycleCount:e.cycleCount}}const A2=1e4,fm=new WeakMap;function W$(t){const e=new Map(t),n=new Proxy(e,{get(o,s){if(typeof s=="string"&&/^\d+$/.test(s))return o.get(Number(s))??0;const a=o[s];return typeof a=="function"?a.bind(o):a},set(o,s,a){return typeof s=="string"&&/^\d+$/.test(s)?(o.set(Number(s),a),!0):!1}});return fm.set(n,e),n}const J$=new Int32Array(64),tU=new Uint8Array(64);function La(t,e,n,o,s){let a=0;if(s)for(const[u,d]of s){const h=t.portKeyToIndex.get(u);h!==void 0&&(n.values[h]=typeof d=="boolean"?d?1:0:d,n.initialized[h]=1)}const l={circuit:t,values:n,state:o,queue:e,nodeIndex:0,portStart:0,inputCount:0,outputCount:0};for(;!e.isEmpty();){if(++a>A2)throw new Error(`Propagation did not stabilize after ${A2} iterations. Possible unstable feedback loop in circuit.`);const u=e.dequeue(),d=t.nodePortStart[u],h=t.nodeInputCount[u],p=t.nodeOutputCount[u],m=d+h;l.nodeIndex=u,l.portStart=d,l.inputCount=h,l.outputCount=p;const y=p<=64?J$:new Int32Array(p),b=p<=64?tU:new Uint8Array(p);for(let S=0;S<p;S++)y[S]=n.values[m+S],b[S]=n.initialized[m+S];const x=t.primitiveTypeIndex[u],w=Va[x];w?w(l):eU(t,u);let _=!1;for(let S=0;S<p;S++){const k=m+S;if(n.values[k]!==y[S]||n.initialized[k]&&!b[S]){_=!0;break}}_&&e.enqueueAll(t.dependents[u])}return a}function eU(t,e,n,o,s){const a=t.flatCircuit.nodes[e];throw new Error(`Primitive '${a.primitiveType}' has no registered evaluator. Either import '@simten/core/std' to register the standard library, or register the primitive's eval lambda explicitly via registerEvalFunction(). If you constructed a Circuit IR by hand (rather than via circuit()), you must register its evaluator yourself.`)}function mu(t,e){for(let n=0;n<t.nodeCount;n++)(t.isSourceNode[n]||t.isStateOutputNode[n]||t.readsTopLevelInput[n])&&(e.enqueue(n),t.isSourceNode[n],t.isStateOutputNode[n],t.readsTopLevelInput[n])}function nU(t,e){for(let n=0;n<t.nodeCount;n++)t.isStateOutputNode[n]&&e.enqueue(n)}function iU(t,e){for(const[n,o]of e.clocks)o.edge="rising",o.value=!0}function oU(t,e,n,o){for(let s=0;s<t.nodeCount;s++){if(!t.hasState[s])continue;const a=t.flatCircuit.nodes[s],l=K$(a.primitiveType);if(!l)continue;const u=new Map,d=t.nodePortStart[s],h=t.nodeInputCount[s];for(let w=0;w<h;w++){const _=d+w,S=t.inputSourceNode[_],k=t.inputSourcePort[_],C=t.inputPortNames[_];if(S===-1){if(o&&k>=0){const E=t.indexToPortKey[k],R=o.get(E);R!==void 0&&u.set(C,R)}}else if(k>=0){const E=e.values[k];u.set(C,E)}}if(a.arguments)for(const[w,_]of Object.entries(a.arguments))u.set(`__${w}`,_);const p={};for(const w of a.clocks){const _=`${a.id}.${w.name}`,S=n.clocks.get(_);S&&(p[w.name]=S.edge)}const m=n.currentState[s],y={};for(const[w,_]of u)y[w]=_;if(m!=null&&typeof m=="object"&&!(m instanceof Map))for(const w of l.stateKeys)y[w]=m[w];else m!=null&&l.stateKeys.length===1&&(m instanceof Map?y[l.stateKeys[0]]=W$(m):y[l.stateKeys[0]]=m);const b=l.fn(y);let x=l.stateKeys.length===1?b[l.stateKeys[0]]:b;x!=null&&typeof x=="object"&&fm.has(x)&&(x=fm.get(x)),n.nextState[s]=x}}function rU(t){for(let e=0;e<t.currentState.length;e++){const n=t.nextState[e];n!==void 0&&(n instanceof Map?(t.currentState[e]=new Map(n),t.nextState[e]=new Map(n)):(t.currentState[e]=n,t.nextState[e]=n))}t.cycleCount++}function Ia(t,e,n){const o=new Map;if(n)for(const[s,a]of n)o.set(s,a);for(let s=0;s<t.portCount;s++){const a=t.indexToPortKey[s],l=t.portIsOutput[s]===1,u=t.portIsBus[s]===0;let d,h;if(l)d=e.values[s],h=e.initialized[s]!==0;else{const m=t.inputSourcePort[s];m>=0?(d=e.values[m],h=e.initialized[m]!==0):(d=0,h=!1)}h||(d=0);const p=d>1||d<0;o.set(a,u&&!p?d!==0:d)}return o}function sU(t,e,n){for(const[o,s]of n){const a=t.portKeyToIndex.get(o);a!==void 0&&(e.values[a]=typeof s=="boolean"?s?1:0:s,e.initialized[a]=1)}}function gu(t,e,n){for(const o of t.flatCircuit.connections)if(o.target.nodeId===De||o.target.nodeId===""){const s=`${o.source.nodeId}.${o.source.portName}`,a=t.portKeyToIndex.get(s);if(a!==void 0){const l=`${o.target.nodeId||De}.${o.target.portName}`,u=t.portIsBus[a]===0,d=e.values[a];n.set(l,u?d!==0:d)}}}class aU{flatCircuit=null;options=null;numericCircuit=null;numericSeqState=null;numericValues=null;eventQueue=null;topLevelInputs=new Map;cachedFlatSeqState=null;cachedPortValues=null;cacheValid=!1;totalTicks=0;totalEvaluations=0;initialize(e,n){this.flatCircuit=e,this.options=n,this.numericCircuit=Q$(e,n.componentLibrary);const o=_2(e,n.componentLibrary);this.numericSeqState=cm(this.numericCircuit,o),this.numericValues=S2(this.numericCircuit.portCount),this.eventQueue=new Y$(this.numericCircuit.nodeCount),this.topLevelInputs=new Map;for(const s of e.topLevelInputs){const a=`${De}.${s.name}`,l=s.portType.kind==="bit"?!1:0;this.topLevelInputs.set(a,l)}this.eventQueue.clear(),mu(this.numericCircuit,this.eventQueue),La(this.numericCircuit,this.eventQueue,this.numericValues,this.numericSeqState,this.topLevelInputs),this.totalTicks=0,this.totalEvaluations=0,this.cacheValid=!1}setNode(e,n){if(!this.flatCircuit||!this.numericCircuit)return;const o=`${De}.${e}`;if(this.topLevelInputs.has(o)){this.topLevelInputs.set(o,n),this.cacheValid=!1;return}const s=this.flatCircuit.nodes.find(l=>l.id===e)??this.flatCircuit.nodes.find(l=>l.id.endsWith("."+e));if(!s)return;const a=this.numericCircuit.nodeIdToIndex.get(s.id);if(a!==void 0&&this.numericSeqState&&this.numericSeqState.currentState[a]!==void 0){this.numericSeqState.currentState[a]=n,this.cacheValid=!1,this.cachedFlatSeqState=null,n instanceof Map&&this.options&&(this.options.initialMemory||(this.options.initialMemory=new Map),this.options.initialMemory.set(s.id,n));return}(typeof n=="boolean"||typeof n=="number"||typeof n=="string")&&(s.arguments={...s.arguments,value:n},this.cacheValid=!1)}tick(){if(!this.numericCircuit||!this.numericSeqState||!this.numericValues||!this.eventQueue)throw new Error("Simulator not initialized");this.eventQueue.clear(),mu(this.numericCircuit,this.eventQueue);const e=La(this.numericCircuit,this.eventQueue,this.numericValues,this.numericSeqState,this.topLevelInputs);iU(this.numericCircuit,this.numericSeqState),oU(this.numericCircuit,this.numericValues,this.numericSeqState,this.topLevelInputs),rU(this.numericSeqState),this.eventQueue.clear(),nU(this.numericCircuit,this.eventQueue);const n=La(this.numericCircuit,this.eventQueue,this.numericValues,this.numericSeqState,this.topLevelInputs),o=Ia(this.numericCircuit,this.numericValues,this.topLevelInputs);gu(this.numericCircuit,this.numericValues,o),this.cachedPortValues=o,this.cachedFlatSeqState=null,this.cacheValid=!0;const s=e+n;this.totalTicks++,this.totalEvaluations+=s;const a=um(this.numericCircuit,this.numericSeqState);return{portValues:o,sequentialState:a,metrics:{phase1Evals:e,phase2Evals:n,totalEvals:s}}}runCombinational(){if(!this.numericCircuit||!this.numericValues||!this.eventQueue)throw new Error("Simulator not initialized");if(this.cacheValid&&this.cachedPortValues)return{portValues:this.cachedPortValues,metrics:{totalEvals:0}};this.eventQueue.clear(),mu(this.numericCircuit,this.eventQueue);try{La(this.numericCircuit,this.eventQueue,this.numericValues,this.numericSeqState??void 0,this.topLevelInputs)}catch(n){return{portValues:Ia(this.numericCircuit,this.numericValues,this.topLevelInputs),metrics:{totalEvals:0},error:n instanceof Error?n.message:"Unknown error"}}const e=Ia(this.numericCircuit,this.numericValues,this.topLevelInputs);return gu(this.numericCircuit,this.numericValues,e),this.cachedPortValues=e,this.cacheValid=!0,{portValues:e,metrics:{totalEvals:0}}}getOutput(e,n){if(!this.numericCircuit||!this.numericValues)return;const o=this.getPortValues(),s=`${e}.${n}`;return o.get(s)}getPortValues(){return!this.numericCircuit||!this.numericValues?new Map:(this.cacheValid||(this.cachedPortValues=Ia(this.numericCircuit,this.numericValues,this.topLevelInputs),gu(this.numericCircuit,this.numericValues,this.cachedPortValues),this.cacheValid=!0),this.cachedPortValues)}getState(){return!this.numericCircuit||!this.numericSeqState?null:((!this.cacheValid||!this.cachedFlatSeqState)&&(this.cachedFlatSeqState=um(this.numericCircuit,this.numericSeqState)),this.cachedFlatSeqState)}snapshot(){if(!this.numericSeqState||!this.numericCircuit||!this.numericValues)throw new Error("No sequential state to snapshot");const e=Ia(this.numericCircuit,this.numericValues,this.topLevelInputs);gu(this.numericCircuit,this.numericValues,e);const n=um(this.numericCircuit,this.numericSeqState);return{portValues:e,sequentialState:n,cycleCount:this.numericSeqState.cycleCount}}restore(e){!this.numericCircuit||!this.numericValues||(this.numericSeqState=cm(this.numericCircuit,e.sequentialState),sU(this.numericCircuit,this.numericValues,e.portValues),this.cacheValid=!1,this.cachedFlatSeqState=null)}reset(){if(!this.flatCircuit||!this.options||!this.numericCircuit)return;const e=_2(this.flatCircuit,this.options.componentLibrary,this.options.initialMemory);this.numericSeqState=cm(this.numericCircuit,e),this.numericValues=S2(this.numericCircuit.portCount),this.eventQueue.clear(),mu(this.numericCircuit,this.eventQueue),La(this.numericCircuit,this.eventQueue,this.numericValues,this.numericSeqState,this.topLevelInputs),this.totalTicks=0,this.totalEvaluations=0,this.cacheValid=!1}getMetrics(){return{totalTicks:this.totalTicks,totalEvaluations:this.totalEvaluations,avgEvalsPerTick:this.totalTicks>0?this.totalEvaluations/this.totalTicks:0,nodeCount:this.flatCircuit?.nodes.length??0}}}function lU(t,e){const n=new aU;return n.initialize(t,e),n}function cU(t,e){const n=z$(t,e);return lU(n,{componentLibrary:e})}const uU=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),fU=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,n,o)=>o?o.toUpperCase():n.toLowerCase()),M2=t=>{const e=fU(t);return e.charAt(0).toUpperCase()+e.slice(1)},R2=(...t)=>t.filter((e,n,o)=>!!e&&e.trim()!==""&&o.indexOf(e)===n).join(" ").trim(),dU=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0};var hU={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const pU=N.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:n=2,absoluteStrokeWidth:o,className:s="",children:a,iconNode:l,...u},d)=>N.createElement("svg",{ref:d,...hU,width:e,height:e,stroke:t,strokeWidth:o?Number(n)*24/Number(e):n,className:R2("lucide",s),...!a&&!dU(u)&&{"aria-hidden":"true"},...u},[...l.map(([h,p])=>N.createElement(h,p)),...Array.isArray(a)?a:[a]]));const eo=(t,e)=>{const n=N.forwardRef(({className:o,...s},a)=>N.createElement(pU,{ref:a,iconNode:e,className:R2(`lucide-${uU(M2(t))}`,`lucide-${t}`,o),...s}));return n.displayName=M2(t),n};const mU=eo("chevron-left",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]);const gU=eo("chevron-right",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);const yU=eo("gauge",[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]]);const vU=eo("history",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]]);const bU=eo("pause",[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1",key:"kaeet6"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1",key:"1wsw3u"}]]);const xU=eo("play",[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]]);const wU=eo("rotate-ccw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);const _U=eo("skip-forward",[["path",{d:"M21 4v16",key:"7j8fe9"}],["path",{d:"M6.029 4.285A2 2 0 0 0 3 6v12a2 2 0 0 0 3.029 1.715l9.997-5.998a2 2 0 0 0 .003-3.432z",key:"zs4d6"}]]),k2=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,O2=rx,SU=((t,e)=>n=>{var o;if(e?.variants==null)return O2(t,n?.class,n?.className);const{variants:s,defaultVariants:a}=e,l=Object.keys(s).map(h=>{const p=n?.[h],m=a?.[h];if(p===null)return null;const y=k2(p)||k2(m);return s[h][y]}),u=n&&Object.entries(n).reduce((h,p)=>{let[m,y]=p;return y===void 0||(h[m]=y),h},{}),d=e==null||(o=e.compoundVariants)===null||o===void 0?void 0:o.reduce((h,p)=>{let{class:m,className:y,...b}=p;return Object.entries(b).every(x=>{let[w,_]=x;return Array.isArray(_)?_.includes({...a,...u}[w]):{...a,...u}[w]===_})?[...h,m,y]:h},[]);return O2(t,l,d,n?.class,n?.className)})("inline-flex items-center justify-center gap-2 cursor-pointer whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),D2=N.forwardRef(({className:t,variant:e,size:n,...o},s)=>M.jsx("button",{className:jn(SU({variant:e,size:n,className:t})),ref:s,...o}));D2.displayName="Button";function ts({label:t,icon:e,onClick:n,disabled:o,pulse:s}){return M.jsxs(Nh,{children:[M.jsx(Ah,{asChild:!0,children:M.jsx(D2,{variant:"ghost",size:"icon",onClick:n,disabled:o,"aria-label":t,className:`h-7 w-7 text-muted-foreground disabled:opacity-40 [&_svg]:size-3.5${s?" animate-pulse text-blue-600 dark:text-blue-400 bg-blue-50 dark:bg-blue-950/40 ring-2 ring-blue-500/40":""}`,children:M.jsx(e,{})})}),M.jsx(Mh,{side:"bottom",children:t})]})}function j2({cycle:t,historyLength:e,historyIndex:n,isRunning:o,isViewingPast:s,onStep:a,onRun:l,onPause:u,onReset:d,onStepBack:h,onStepForward:p,onSeek:m,onSpeedChange:y,speed:b=1,maxSpeed:x=100,showScrubber:w,floating:_,chromeless:S,pulseRun:k}){const C=_?"absolute top-3 left-1/2 -translate-x-1/2 z-10":"",E=S?"flex items-center gap-1.5":"flex items-center gap-1.5 border-t border-border bg-card/95 px-3 py-1.5";return M.jsx(Th,{children:M.jsx("div",{className:C,children:M.jsxs("div",{className:E,children:[M.jsx(ts,{label:"Tick",icon:_U,onClick:a,disabled:o||s}),o?M.jsx(ts,{label:"Pause",icon:bU,onClick:u}):M.jsx(ts,{label:"Run",icon:xU,onClick:l,disabled:s,pulse:k&&!s}),M.jsx(ts,{label:"Reset",icon:wU,onClick:d}),y&&M.jsxs("div",{className:"flex items-center gap-2 border-l border-border pl-2 ml-0.5",children:[M.jsx(yU,{className:"h-3.5 w-3.5 text-muted-foreground/70","aria-hidden":!0}),M.jsx("input",{type:"range",min:"1",max:x,value:b,onChange:R=>y(Number(R.target.value)),className:"w-20 h-1 rounded-lg appearance-none cursor-pointer accent-blue-600",disabled:s,"aria-label":"Simulation speed"}),M.jsxs("span",{className:"min-w-[55px] text-[10px] text-muted-foreground font-mono tabular-nums",children:[b," tick/s"]})]}),M.jsx("div",{className:"border-l border-border pl-1.5 ml-0.5",children:M.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["Cycle ",M.jsx("span",{className:"font-mono font-semibold text-foreground",children:t})]})}),e>1&&M.jsxs("div",{className:"flex items-center gap-0.5 border-l border-border pl-1.5 ml-0.5",children:[M.jsx(ts,{label:"Step back",icon:mU,onClick:h,disabled:n<=0||o}),M.jsx("span",{className:"min-w-[40px] text-center text-[11px] text-muted-foreground",children:s?M.jsxs("span",{className:"font-mono text-amber-600 dark:text-amber-400",children:[n+1,"/",e]}):M.jsxs("span",{className:"font-mono",children:[e,"/",e]})}),M.jsx(ts,{label:"Step forward",icon:gU,onClick:p,disabled:!s||o})]}),w&&m&&e>1&&M.jsxs("div",{className:"flex items-center gap-2 border-l border-border pl-2 ml-0.5",children:[M.jsx(vU,{className:"h-3.5 w-3.5 text-muted-foreground/70","aria-hidden":!0}),M.jsx("input",{type:"range",min:"0",max:e-1,value:n,onChange:R=>m(Number(R.target.value)),className:"w-24 h-1 rounded-lg appearance-none cursor-pointer accent-blue-600",disabled:o,"aria-label":"Cycle scrubber"})]})]})})})}function EU({frame:t,componentLibrary:e,onPushLevel:n,theme:o="dark"}){const s=N.useMemo(()=>j$(t.componentDef),[t.componentDef]),a=N.useMemo(()=>ud(s,e.resolveCircuit),[s,e]),l=N.useCallback(H=>{if(!H.isComposite)return;const j=e.resolveCircuit(H.componentRef);j&&j.implementation.kind==="composite"&&j.nodes.length>0&&n(H.componentRef,j,H.label??H.componentRef)},[e,n]),u=Wf(),[d,h]=N.useState(new Map),[p,m]=N.useState(!1),y=N.useRef(null),[b,x]=N.useState(0),[w,_]=N.useState(!1),S=N.useRef([]),[k,C]=N.useState(0),[E,R]=N.useState(-1),A=N.useRef("");A.current||(A.current=`drill-${typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():Math.random().toString(36).slice(2)}`);const O=A.current;N.useEffect(()=>()=>{p&&u.dispose(O).catch(()=>{})},[u,O,p]),N.useEffect(()=>{const H=[],j=new Set;for(const z of e.getAllPrimitiveNames()){const U=e.resolveCircuit(z);U&&!j.has(z)&&(j.add(z),H.push(U))}const I=z=>{for(const U of z.nodes){if(j.has(U.componentRef))continue;const G=e.resolveCircuit(U.componentRef);G&&(j.add(U.componentRef),H.push(G),G.implementation.kind==="composite"&&I(G))}};I(s),u.compileIR(s,H,O,{snapshot:a}).then(z=>{if("error"in z){try{const G=cU(s,e);G.runCombinational(),y.current=G,m(!1);const L=new Map;for(const[F,et]of G.getPortValues())L.set(F,et);h(L)}catch(G){console.warn("[InspectorCanvas] Both sandbox and local failed:",G)}return}m(!0);const U=new Map;for(const[G,L]of Object.entries(z.portValues))U.set(G,L);h(U),S.current=z.snapshotId!==void 0?[{snapshotId:z.snapshotId,cycle:0}]:[],C(S.current.length),R(S.current.length===0?-1:0),x(0)})},[s,e,u,O,a]);const D=N.useCallback(H=>{const j=`${H}.out`,I=d.get(j);u.setNode(H,!I,O).then(z=>{if("error"in z)return;const U=new Map;for(const[G,L]of Object.entries(z.portValues))U.set(G,L);h(U)})},[u,d]),$=N.useCallback((H,j)=>{u.setNode(H,j,O).then(I=>{if("error"in I)return;const z=new Map;for(const[U,G]of Object.entries(I.portValues))z.set(U,G);h(z)})},[u]),q=N.useCallback(()=>{u.tick(void 0,O,{snapshot:a}).then(H=>{if("error"in H)return;const j=new Map;for(const[I,z]of Object.entries(H.portValues))j.set(I,z);if(h(j),x(H.cycle),H.snapshotId!==void 0){const I=S.current.slice(0,E+1);I.push({snapshotId:H.snapshotId,cycle:H.cycle}),S.current=I,C(I.length),R(I.length-1)}})},[u,O,a,E]),Y=N.useCallback(()=>{_(!1),u.reset(O).then(H=>{if("error"in H)return;const j=new Map;for(const[I,z]of Object.entries(H.portValues))j.set(I,z);h(j),x(0),S.current=[],C(0),R(-1),a&&u.snapshot(O).then(I=>{"error"in I||I.snapshotId===void 0||(S.current=[{snapshotId:I.snapshotId,cycle:0}],C(1),R(0))})})},[u,O,a]),K=N.useCallback(H=>{const j=S.current[H];j&&u.restore(j.snapshotId,O).then(I=>{if("error"in I)return;const z=new Map;for(const[U,G]of Object.entries(I.portValues))z.set(U,G);h(z),x(j.cycle),R(H)})},[u,O]),W=N.useCallback(()=>{_(!1),E>0&&K(E-1)},[E,K]),B=N.useCallback(()=>{E<k-1?K(E+1):q()},[E,k,K,q]);return N.useEffect(()=>{if(!w)return;const H=window.setInterval(()=>{q()},200);return()=>window.clearInterval(H)},[w,q]),M.jsxs("div",{className:"relative h-full w-full",children:[a&&M.jsx(j2,{floating:!0,cycle:b,historyLength:k,historyIndex:E,isRunning:w,isViewingPast:E>=0&&E<k-1,onStep:q,onRun:()=>_(!0),onPause:()=>_(!1),onReset:Y,onStepBack:W,onStepForward:B}),M.jsx(z2,{circuit:s,componentLibrary:e,portValues:d,sequentialState:null,onToggleNode:D,onSetNodeValue:$,onNodeDoubleClick:l,nodeTypes:Tw,edgeTypes:Nw,theme:o,showControls:!0,height:"100%",panOnMobile:!0})]})}function CU({stack:t,onNavigate:e,theme:n="dark"}){const s=t[t.length-1]?.componentDef.metadata?.description,a=n==="dark";return M.jsxs("div",{className:"flex items-center gap-1 text-sm min-w-0",children:[t.map((l,u)=>M.jsxs(ko.Fragment,{children:[u>0&&M.jsx("span",{className:`${a?"text-gray-500":"text-gray-400"} shrink-0`,children:">"}),u<t.length-1?M.jsxs("button",{onClick:()=>e(u),className:`${a?"text-blue-400 hover:text-blue-300":"text-blue-600 hover:text-blue-800"} hover:underline font-medium shrink-0`,children:[l.nodeLabel," (",l.componentName,")"]}):M.jsxs("span",{className:`font-semibold shrink-0 ${a?"text-gray-100":"text-gray-900"}`,children:[l.nodeLabel," (",l.componentName,")"]})]},u)),s&&M.jsxs(M.Fragment,{children:[M.jsx("span",{className:`${a?"text-gray-600":"text-gray-300"} shrink-0`,children:"—"}),M.jsx("span",{className:`${a?"text-gray-400":"text-gray-500"} text-xs italic truncate`,children:s})]})]})}const TU={enterIn:{opacity:0},enterOut:{opacity:0},center:{opacity:1},exitIn:{opacity:0},exitOut:{opacity:0}};function NU({stack:t,componentLibrary:e,theme:n="dark",onClose:o,onPopLevel:s,onPushLevel:a,onNavigate:l}){const u=t.length>0,d=N.useRef(0),[h,p]=N.useState("in");N.useEffect(()=>{t.length>d.current?p("in"):t.length<d.current&&p("out"),d.current=t.length},[t.length]),N.useEffect(()=>{if(!u)return;const x=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=x}},[u]);const m=N.useCallback(x=>{x.target===x.currentTarget&&o()},[o]),y=N.useCallback(x=>{x.key==="Escape"&&(x.stopPropagation(),t.length>1?s():o())},[t.length,s,o]),b=u?t[t.length-1]:null;return M.jsx(FS,{children:u&&b&&M.jsxs(M.Fragment,{children:[M.jsx(hu.div,{className:"fixed inset-0 z-50 bg-black/50",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.25},onClick:m,onKeyDown:y,tabIndex:-1},"inspector-backdrop"),M.jsx(hu.div,{className:"fixed inset-0 z-50 flex items-center justify-center p-8 pointer-events-none",children:M.jsxs(hu.div,{className:`flex h-[80vh] w-full max-w-5xl flex-col rounded-lg shadow-xl pointer-events-auto overflow-hidden ${n==="dark"?"bg-gray-900":"bg-white"}`,initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.15},children:[M.jsxs("div",{className:`flex items-center justify-between border-b px-4 py-3 ${n==="dark"?"border-gray-700":"border-gray-200"}`,children:[M.jsx(CU,{stack:t,onNavigate:l,theme:n}),M.jsx("button",{onClick:o,className:`rounded p-1 ${n==="dark"?"text-gray-400 hover:bg-gray-800 hover:text-gray-300":"text-gray-400 hover:bg-gray-100 hover:text-gray-600"}`,"aria-label":"Close inspector",children:M.jsx("svg",{className:"h-5 w-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:M.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),M.jsx("div",{className:"relative flex-1 overflow-hidden",children:M.jsx(FS,{mode:"wait",initial:!1,children:M.jsx(hu.div,{className:"absolute inset-0",initial:h==="in"?"enterIn":"enterOut",animate:"center",exit:h==="in"?"exitIn":"exitOut",variants:TU,transition:{duration:.2,ease:"easeInOut"},children:M.jsx(EU,{frame:b,componentLibrary:e,onPushLevel:a,theme:n})},`${t.length}-${b.componentName}`)})})]})},"inspector-dialog")]})})}function AU(){const{fitView:t,zoomIn:e,zoomOut:n}=da(),o="bg-[var(--embed-bg-tertiary)] hover:opacity-80 text-[var(--embed-text-secondary)] p-1.5 rounded border border-[var(--embed-border)] transition-colors";return M.jsxs("div",{className:"flex items-center gap-1",children:[M.jsx("button",{onClick:()=>n(),className:o,title:"Zoom out","aria-label":"Zoom out",children:M.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",strokeWidth:1.5,children:M.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 12h14"})})}),M.jsx("button",{onClick:()=>e(),className:o,title:"Zoom in","aria-label":"Zoom in",children:M.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",strokeWidth:1.5,children:M.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 5v14M5 12h14"})})}),M.jsx("button",{onClick:()=>t({padding:.3}),className:o,title:"Fit view","aria-label":"Fit view",children:M.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",strokeWidth:1.5,children:M.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.75 3.75v4.5m0-4.5h4.5m-4.5 0L9 9M3.75 20.25v-4.5m0 4.5h4.5m-4.5 0L9 15M20.25 3.75h-4.5m4.5 0v4.5m0-4.5L15 9m5.25 11.25h-4.5m4.5 0v-4.5m0 4.5L15 15"})})})]})}let dm=null;function MU(){if(!dm){const t=new Map;dm={resolveCircuit:e=>t.get(e),getAllPrimitiveNames:()=>[...t.entries()].filter(([,e])=>e.implementation.kind==="primitive").map(([e])=>e),addCircuit:e=>{t.set(e.name,e)}}}return dm}function RU({circuit:t,componentLibrary:e,portValues:n,sequentialState:o,draggable:s=!0,layout:a,onToggleNode:l,onSetNodeValue:u,onLoadMemory:d,onNodeDoubleClick:h,height:p="100%",focus:m,className:y,renderEmptyState:b,renderOverlay:x,nodeTypes:w,edgeTypes:_,showControls:S=!0,showPortLabels:k,onPortClick:C,glowUnconnected:E,theme:R,panOnMobile:A=!1,onRequestRemount:O}){const D=m1(),$=R??D,q=Y8(),Y=w??Tw,K=_??Nw,W=e??MU(),B=N.useMemo(()=>m?new Set(Array.isArray(m)?m:[m]):null,[m]),H=N.useMemo(()=>t?Vj(t):null,[t]),{metadata:j}=U8(a?null:H),I=N.useMemo(()=>{if(!H)return{components:{},connections:{}};if(!a)return j;const mt={};for(const Ct of H.nodes){const It=Ct.label||Ct.id,zt=a[It]??a[Ct.id];zt&&(mt[Ct.id]={id:Ct.id,position:zt})}return{components:mt,connections:{}}},[H,j,a]),{projectedNodes:z,projectedEdges:U}=N.useMemo(()=>{if(!H)return{projectedNodes:[],projectedEdges:[]};const mt=pL(H,I,W,n??void 0,o??void 0),Ct=mt.nodes.map(It=>{const zt=It.data,Vt=zt?.componentRef,ve={...It.data};if(k&&(ve.showPortLabels=!0),E&&(ve.glowUnconnected=!0),C){const Wt=zt.label||zt.componentRef;ve.onPortClick=(je,xn)=>C(Wt,je,xn)}return Vt==="Input"&&u&&(ve.onValueChange=Wt=>u(It.id,Wt)),l&&(Vt==="Switch"||Vt==="Button")&&(ve.onToggle=()=>l(It.id)),d&&(Vt==="RV32I_InstrMem"||Vt==="DualPortROM")&&(ve.onLoadMemory=Wt=>d(It.id,Wt)),{...It,data:ve}});if(B){const It=new Set;for(const zt of Ct){const Vt=zt.data?.label??zt.id;B.has(Vt)&&It.add(zt.id)}return{projectedNodes:Ct.map(zt=>{const Vt=zt.data?.label??zt.id;return{...zt,style:{...zt.style,opacity:B.has(Vt)?1:.15,transition:"opacity 0.2s"}}}),projectedEdges:mt.edges.map(zt=>({...zt,style:{...zt.style,opacity:It.has(zt.source)||It.has(zt.target)?1:.15,transition:"opacity 0.2s"}}))}}return{projectedNodes:Ct,projectedEdges:mt.edges}},[H,I,W,n,o,l,u,d,B,k,C,E]),[G,L]=N.useState([]),[F,et]=N.useState([]),{fitView:rt}=da(),ct=cj(),ht=N.useRef(null),ft=N.useRef(new Set),ut=N.useRef(new Map),dt=N.useRef(0);N.useLayoutEffect(()=>{const mt=ht.current,Ct=ft.current,It=ut.current,zt=H?.name??null,Vt=new Set(z.map(Re=>Re.id)),ve=new Map;for(const Re of z){const me=Re.data,le=`${(me.inputNames??[]).join("|")}>${(me.outputNames??[]).join("|")}`;ve.set(Re.id,le)}ht.current=zt,ft.current=Vt,ut.current=ve;const Wt=zt!==mt;let je=0;for(const Re of Vt)Ct.has(Re)&&je++;const xn=Math.max(Ct.size,Vt.size),Pa=xn>0&&je/xn<.5,Hn=Wt||Pa,tr=[];if(!Hn)for(const[Re,me]of ve){const le=It.get(Re);le!==void 0&&le!==me&&tr.push(Re)}const Ba=dt.current===0;dt.current=z.length,L(Re=>{const me=new Map(Re.map(le=>[le.id,le]));return z.map(le=>{const ze=me.get(le.id);return ze&&!Hn?{...ze,type:le.type,data:le.data,selectable:le.selectable,deletable:le.deletable}:le})}),et(U),Hn&&Ct.size>0?O?.():tr.length>0&&requestAnimationFrame(()=>ct(tr)),z.length>0&&Ba&&!Hn&&requestAnimationFrame(()=>rt({padding:.3}))},[z,U]);const Ot=N.useCallback(mt=>{L(Ct=>pb(mt,Ct))},[]),[At,bt]=N.useState([]),Tt=N.useCallback((mt,Ct,It)=>{bt(zt=>[...zt,{componentName:mt,componentDef:Ct,nodeLabel:It}])},[]),Dt=N.useCallback(()=>{bt(mt=>mt.slice(0,-1))},[]),Xt=N.useCallback(()=>{bt([])},[]),Ft=N.useCallback(mt=>{bt(Ct=>Ct.slice(0,mt+1))},[]),pt=N.useCallback(mt=>{if(!mt.isComposite)return;const Ct=W.resolveCircuit(mt.componentRef);Ct&&Ct.implementation.kind==="composite"&&Ct.nodes.length>0&&bt([{componentName:mt.componentRef,componentDef:Ct,nodeLabel:mt.label??mt.componentRef}])},[W]),yt=h??pt,vt=N.useCallback((mt,Ct)=>{yt(Ct.data)},[yt]);return M.jsxs("div",{"data-embed-theme":$,className:`bg-[var(--embed-bg-primary)] overflow-hidden relative ${y??""}`,style:{height:p},"aria-label":"Circuit diagram",children:[M.jsxs(lj,{nodes:G,edges:F,nodeTypes:Y,edgeTypes:K,onNodesChange:Ot,onNodeDoubleClick:vt,fitView:!0,minZoom:.1,maxZoom:3,fitViewOptions:{padding:.3,...B&&{nodes:G.filter(mt=>{const Ct=mt.data?.label??mt.id;return B.has(Ct)})}},nodesDraggable:s&&!q,nodesConnectable:!1,elementsSelectable:!0,selectionOnDrag:!1,panOnDrag:q&&!A?!1:[1,2],zoomOnScroll:!0,zoomOnPinch:!0,zoomOnDoubleClick:!1,preventScrolling:!1,proOptions:{hideAttribution:!0},deleteKeyCode:null,panActivationKeyCode:null,children:[M.jsx(pj,{variant:pi.Dots,gap:20,size:1,color:"var(--embed-dot-color)"}),S&&M.jsx(ua,{position:"bottom-left",children:M.jsx(AU,{})})]}),x?.(),!t&&(b?b():M.jsx("div",{className:"absolute inset-0 flex items-center justify-center text-[var(--embed-text-muted)]",children:"No circuit"})),!h&&At.length>0&&M.jsx(NU,{stack:At,componentLibrary:W,theme:$,onClose:Xt,onPopLevel:Dt,onPushLevel:Tt,onNavigate:Ft})]})}function z2(t){const[e,n]=N.useState(0),o=N.useCallback(()=>{n(s=>s+1)},[]);return M.jsx(Jb,{children:M.jsx(RU,{...t,onRequestRemount:o})},e)}const kU=N.forwardRef(function({circuit:e,height:n=300,showControls:o=!0,autoHarness:s=!1,initialInputs:a,layout:l,theme:u,focus:d,showPortLabels:h,onPortClick:p,glowUnconnected:m,renderEmptyState:y,renderOverlay:b,onPortValuesChange:x},w){const _=kM(e,{autoHarness:s,initialInputs:a}),S=m1(),k=u??S,C=N.useRef(x);N.useEffect(()=>{C.current=x}),N.useEffect(()=>{!_.ready||!_.portValues||_.portValues.size===0||C.current?.(_.portValues)},[_.ready,_.portValues]);const E=N.useCallback(()=>{_.tick()},[_.tick]),R=N.useCallback(()=>{_.reset()},[_.reset]);if(N.useImperativeHandle(w,()=>({tick:E,reset:R,setNodeValue:_.setNodeValue,startAutoRun:_.startAutoRun,stopAutoRun:_.stopAutoRun}),[E,R,_.setNodeValue,_.startAutoRun,_.stopAutoRun]),_.error)return M.jsx("div",{style:{height:n},className:"flex items-center justify-center p-4",children:M.jsxs("div",{className:"text-sm text-red-400 bg-red-500/10 rounded p-3 border border-red-500/20",children:[M.jsx("div",{className:"font-medium mb-1",children:"Compilation Error"}),M.jsx("div",{className:"font-mono text-xs",children:_.error})]})});if(!_.ready)return M.jsx("div",{style:{height:n},className:"flex items-center justify-center text-muted-foreground/60 text-sm",children:"Compiling..."});const A=_.isSequential&&o?40:0,O=typeof n=="number"?n-A:n;return M.jsxs("div",{style:{height:n},className:"flex flex-col","data-embed-theme":k,children:[M.jsx("div",{className:"flex-1 min-h-0",children:M.jsx(z2,{circuit:_.circuit,componentLibrary:_.componentLibrary??void 0,portValues:_.portValues,sequentialState:_.sequentialState,onToggleNode:_.toggleNode,onSetNodeValue:_.setNodeValue,onLoadMemory:(D,$)=>{const q=_.getSimulator();q&&(q.setNode(D,$),_.runCombinational())},height:O,focus:d,showPortLabels:h,onPortClick:p,glowUnconnected:m,renderEmptyState:y,renderOverlay:b,...l?{layout:l}:{},...u?{theme:u}:{}})}),_.isSequential&&o&&M.jsx(j2,{cycle:_.cycleCount,historyLength:_.history?.length??0,historyIndex:_.historyIndex??-1,isRunning:_.isRunning,isViewingPast:_.isViewingPast??!1,onStep:E,onRun:()=>_.startAutoRun(15),onPause:()=>_.stopAutoRun(),onReset:R,onStepBack:()=>_.stepBack(),onStepForward:()=>{_.isViewingPast?_.stepForward():E()},speed:5})]})});var hm={exports:{}},V2;function OU(){return V2||(V2=1,(function(t){var e=(function(){var n=String.fromCharCode,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",a={};function l(d,h){if(!a[d]){a[d]={};for(var p=0;p<d.length;p++)a[d][d.charAt(p)]=p}return a[d][h]}var u={compressToBase64:function(d){if(d==null)return"";var h=u._compress(d,6,function(p){return o.charAt(p)});switch(h.length%4){default:case 0:return h;case 1:return h+"===";case 2:return h+"==";case 3:return h+"="}},decompressFromBase64:function(d){return d==null?"":d==""?null:u._decompress(d.length,32,function(h){return l(o,d.charAt(h))})},compressToUTF16:function(d){return d==null?"":u._compress(d,15,function(h){return n(h+32)})+" "},decompressFromUTF16:function(d){return d==null?"":d==""?null:u._decompress(d.length,16384,function(h){return d.charCodeAt(h)-32})},compressToUint8Array:function(d){for(var h=u.compress(d),p=new Uint8Array(h.length*2),m=0,y=h.length;m<y;m++){var b=h.charCodeAt(m);p[m*2]=b>>>8,p[m*2+1]=b%256}return p},decompressFromUint8Array:function(d){if(d==null)return u.decompress(d);for(var h=new Array(d.length/2),p=0,m=h.length;p<m;p++)h[p]=d[p*2]*256+d[p*2+1];var y=[];return h.forEach(function(b){y.push(n(b))}),u.decompress(y.join(""))},compressToEncodedURIComponent:function(d){return d==null?"":u._compress(d,6,function(h){return s.charAt(h)})},decompressFromEncodedURIComponent:function(d){return d==null?"":d==""?null:(d=d.replace(/ /g,"+"),u._decompress(d.length,32,function(h){return l(s,d.charAt(h))}))},compress:function(d){return u._compress(d,16,function(h){return n(h)})},_compress:function(d,h,p){if(d==null)return"";var m,y,b={},x={},w="",_="",S="",k=2,C=3,E=2,R=[],A=0,O=0,D;for(D=0;D<d.length;D+=1)if(w=d.charAt(D),Object.prototype.hasOwnProperty.call(b,w)||(b[w]=C++,x[w]=!0),_=S+w,Object.prototype.hasOwnProperty.call(b,_))S=_;else{if(Object.prototype.hasOwnProperty.call(x,S)){if(S.charCodeAt(0)<256){for(m=0;m<E;m++)A=A<<1,O==h-1?(O=0,R.push(p(A)),A=0):O++;for(y=S.charCodeAt(0),m=0;m<8;m++)A=A<<1|y&1,O==h-1?(O=0,R.push(p(A)),A=0):O++,y=y>>1}else{for(y=1,m=0;m<E;m++)A=A<<1|y,O==h-1?(O=0,R.push(p(A)),A=0):O++,y=0;for(y=S.charCodeAt(0),m=0;m<16;m++)A=A<<1|y&1,O==h-1?(O=0,R.push(p(A)),A=0):O++,y=y>>1}k--,k==0&&(k=Math.pow(2,E),E++),delete x[S]}else for(y=b[S],m=0;m<E;m++)A=A<<1|y&1,O==h-1?(O=0,R.push(p(A)),A=0):O++,y=y>>1;k--,k==0&&(k=Math.pow(2,E),E++),b[_]=C++,S=String(w)}if(S!==""){if(Object.prototype.hasOwnProperty.call(x,S)){if(S.charCodeAt(0)<256){for(m=0;m<E;m++)A=A<<1,O==h-1?(O=0,R.push(p(A)),A=0):O++;for(y=S.charCodeAt(0),m=0;m<8;m++)A=A<<1|y&1,O==h-1?(O=0,R.push(p(A)),A=0):O++,y=y>>1}else{for(y=1,m=0;m<E;m++)A=A<<1|y,O==h-1?(O=0,R.push(p(A)),A=0):O++,y=0;for(y=S.charCodeAt(0),m=0;m<16;m++)A=A<<1|y&1,O==h-1?(O=0,R.push(p(A)),A=0):O++,y=y>>1}k--,k==0&&(k=Math.pow(2,E),E++),delete x[S]}else for(y=b[S],m=0;m<E;m++)A=A<<1|y&1,O==h-1?(O=0,R.push(p(A)),A=0):O++,y=y>>1;k--,k==0&&(k=Math.pow(2,E),E++)}for(y=2,m=0;m<E;m++)A=A<<1|y&1,O==h-1?(O=0,R.push(p(A)),A=0):O++,y=y>>1;for(;;)if(A=A<<1,O==h-1){R.push(p(A));break}else O++;return R.join("")},decompress:function(d){return d==null?"":d==""?null:u._decompress(d.length,32768,function(h){return d.charCodeAt(h)})},_decompress:function(d,h,p){var m=[],y=4,b=4,x=3,w="",_=[],S,k,C,E,R,A,O,D={val:p(0),position:h,index:1};for(S=0;S<3;S+=1)m[S]=S;for(C=0,R=Math.pow(2,2),A=1;A!=R;)E=D.val&D.position,D.position>>=1,D.position==0&&(D.position=h,D.val=p(D.index++)),C|=(E>0?1:0)*A,A<<=1;switch(C){case 0:for(C=0,R=Math.pow(2,8),A=1;A!=R;)E=D.val&D.position,D.position>>=1,D.position==0&&(D.position=h,D.val=p(D.index++)),C|=(E>0?1:0)*A,A<<=1;O=n(C);break;case 1:for(C=0,R=Math.pow(2,16),A=1;A!=R;)E=D.val&D.position,D.position>>=1,D.position==0&&(D.position=h,D.val=p(D.index++)),C|=(E>0?1:0)*A,A<<=1;O=n(C);break;case 2:return""}for(m[3]=O,k=O,_.push(O);;){if(D.index>d)return"";for(C=0,R=Math.pow(2,x),A=1;A!=R;)E=D.val&D.position,D.position>>=1,D.position==0&&(D.position=h,D.val=p(D.index++)),C|=(E>0?1:0)*A,A<<=1;switch(O=C){case 0:for(C=0,R=Math.pow(2,8),A=1;A!=R;)E=D.val&D.position,D.position>>=1,D.position==0&&(D.position=h,D.val=p(D.index++)),C|=(E>0?1:0)*A,A<<=1;m[b++]=n(C),O=b-1,y--;break;case 1:for(C=0,R=Math.pow(2,16),A=1;A!=R;)E=D.val&D.position,D.position>>=1,D.position==0&&(D.position=h,D.val=p(D.index++)),C|=(E>0?1:0)*A,A<<=1;m[b++]=n(C),O=b-1,y--;break;case 2:return _.join("")}if(y==0&&(y=Math.pow(2,x),x++),m[O])w=m[O];else if(O===b)w=k+k.charAt(0);else return null;_.push(w),m[b++]=k+w.charAt(0),y--,k=w,y==0&&(y=Math.pow(2,x),x++)}}};return u})();t!=null?t.exports=e:typeof angular<"u"&&angular!=null&&angular.module("LZString",[]).factory("LZString",function(){return e})})(hm)),hm.exports}var DU=OU();function jU(t){return DU.compressToEncodedURIComponent(t)}const zU=N.createContext(null);function VU(){return N.useContext(zU)}function L2(){return typeof window>"u"?"https://simten.dev":window.location.hostname==="localhost"?window.location.origin:"https://simten.dev"}const LU=160,IU=90;function PU(t){if(!t)return 1.5;const e=Object.values(t);if(e.length===0)return 1.5;const n=Math.max(...e.map(s=>s.x))+LU,o=Math.max(...e.map(s=>s.y))+IU;return n<=0||o<=0?1.5:n/o}function I2({onFork:t,forkError:e,forkPending:n,className:o,tooltipSide:s="top"}){return M.jsx(Th,{delayDuration:300,children:M.jsxs(Nh,{children:[M.jsx(Ah,{asChild:!0,children:M.jsx("button",{type:"button",onClick:t,className:`cursor-pointer ${o}`,children:e?"Fork failed":n?"Forking…":"Fork →"})}),M.jsx(Mh,{side:s,children:e??"Open and modify this circuit in the Simten editor"})]})})}const BU=N.forwardRef(function({circuit:e,height:n,aspectRatio:o,showControls:s=!0,layout:a,theme:l,title:u,subtitle:d,description:h,href:p,focus:m,showPortLabels:y,onPortClick:b,glowUnconnected:x,autoRunSpeed:w=500,initialInputs:_,forkSource:S,onPortValuesChange:k},C){const E=u||h,[R,A]=N.useState(null),[O,D]=N.useState(!1),$=VU(),q=async()=>{if(!O)try{const j=S??xM(e);if($){D(!0);const{hash:I}=await $(j);window.open(`${L2()}/circuit/s/${I}`,"_blank","noopener")}else{const I=jU(j);window.open(`${L2()}/circuit/${I}`,"_blank","noopener")}}catch(j){A(j instanceof Error?j.message:"Couldn't fork this circuit"),setTimeout(()=>A(null),3e3)}finally{D(!1)}},Y=n===void 0,K=o??PU(a),W={width:"100%",aspectRatio:String(K),minHeight:240,maxHeight:"70vh"},B=E?void 0:Y?W:{height:n},H=E?Y?W:{height:n}:{height:"100%"};return M.jsxs("div",{style:B,className:`relative flex flex-col ${E?"rounded-xl border border-[var(--embed-border)] overflow-hidden bg-[var(--embed-bg-secondary)]":""}`,children:[!E&&!p&&M.jsx(I2,{onFork:q,forkError:R,forkPending:O,tooltipSide:"bottom",className:"absolute top-2 right-2 z-10 hidden md:flex items-center px-2.5 py-1 rounded border border-[var(--embed-border)] bg-[var(--embed-bg-secondary)] text-[11px] text-[var(--embed-text-primary)] hover:opacity-80 transition-colors shadow-sm"}),M.jsx("div",{style:H,className:"min-h-0",children:M.jsx(kU,{ref:C,circuit:e,height:"100%",showControls:s,autoHarness:!0,initialInputs:_,layout:a,theme:l,focus:m,showPortLabels:y,onPortClick:b,glowUnconnected:x,autoRunSpeed:w,onPortValuesChange:k})}),E&&M.jsxs("div",{className:"border-t border-[var(--embed-border)] px-4 py-3 flex items-end justify-between gap-4",children:[M.jsxs("div",{children:[M.jsx("div",{className:"text-base font-semibold text-[var(--embed-text-primary)]",children:u}),d&&M.jsx("div",{className:"text-xs text-[var(--embed-text-muted)] font-mono mt-0.5",children:d}),h&&M.jsx("div",{className:"text-sm text-[var(--embed-text-secondary)] mt-1.5 leading-relaxed",children:h})]}),p?M.jsx("a",{href:p,className:"shrink-0 px-3 py-1.5 rounded border border-[var(--embed-border)] text-xs text-[var(--embed-text-primary)] hover:opacity-80 transition-colors",children:"Open →"}):M.jsx(I2,{onFork:q,forkError:R,forkPending:O,tooltipSide:"top",className:"hidden md:flex items-center shrink-0 px-3 py-1.5 rounded border border-[var(--embed-border)] text-xs text-[var(--embed-text-primary)] hover:opacity-80 transition-colors"})]})]})});function HU({code:t,height:e,showControls:n,title:o,subtitle:s,description:a,href:l,autoRunSpeed:u,theme:d}){const h=Wf(),[p,m]=N.useState(null),[y,b]=N.useState(null);return N.useEffect(()=>{if(!t){m(null),b(null);return}let x=!1;return h.compile(t).then(w=>{if(x)return;if("error"in w){b(w.error),m(null);return}const _=w.circuits[w.circuits.length-1];if(!_){b("No circuit found in code"),m(null);return}b(null),m(vM(_,w.libraryCircuits))}),()=>{x=!0}},[t,h]),t?y?M.jsx("div",{style:{height:e},className:"flex items-center justify-center p-4",children:M.jsxs("div",{className:"text-sm text-red-400 bg-red-500/10 rounded p-3 border border-red-500/20",children:[M.jsx("div",{className:"font-medium mb-1",children:"Error"}),M.jsx("div",{className:"font-mono text-xs whitespace-pre-wrap",children:y})]})}):p?M.jsx("div",{"data-embed-theme":d??"dark",children:M.jsx(BU,{circuit:p,height:e,showControls:n,title:o,subtitle:s,description:a,href:l,forkSource:t,autoRunSpeed:u,theme:d})}):M.jsx("div",{style:{height:e},className:"flex items-center justify-center text-sm text-gray-500",children:"Compiling..."}):M.jsx("div",{style:{height:e},className:"flex items-center justify-center text-sm text-gray-500",children:"No circuit code provided"})}function $U(t){return M.jsx(XN,{children:M.jsx(HU,{...t})})}const P2=$N($U,{props:{code:"string",height:"number",showControls:"boolean",title:"string",subtitle:"string",description:"string",href:"string",autoRunSpeed:"number",theme:"string"}});return customElements.get("circuit-embed")||customElements.define("circuit-embed",P2),Hf.CircuitEmbedWC=P2,Object.defineProperty(Hf,Symbol.toStringTag,{value:"Module"}),Hf})({});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@simten/embed",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.13",
|
|
4
4
|
"description": "Embeddable interactive hardware circuits. Drop live, cycle-accurate simulations into any React app or HTML page.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Charles Harris",
|
|
@@ -54,8 +54,8 @@
|
|
|
54
54
|
"clsx": "^2.1.1",
|
|
55
55
|
"elkjs": "^0.9.3",
|
|
56
56
|
"tailwind-merge": "^3.0.0",
|
|
57
|
-
"@simten/core": "0.6.
|
|
58
|
-
"@simten/ui": "0.1.
|
|
57
|
+
"@simten/core": "0.6.1",
|
|
58
|
+
"@simten/ui": "0.1.13"
|
|
59
59
|
},
|
|
60
60
|
"peerDependencies": {
|
|
61
61
|
"react": "^18 || ^19",
|