const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/parseUrdf-C7WqROHT.js","assets/vendor-react-7jnMmQ9s.js","assets/vendor-ui-CtsphK4U.js","assets/vendor-icons-FFp724MI.js","assets/vendor-three-SYzIooV9.js","assets/parseSdf-D2U6Dgo_.js"])))=>i.map(i=>d[i]); import{r as f,j as c,i as oz}from"./vendor-react-7jnMmQ9s.js";import{S as XT,T as YT,C as Dy,O as qT,a as ZT,P as JT,R as QT,b as eR,D as tR,c as iz,d as sz,e as az,A as lz,f as cz,g as uz,h as dz,i as nR,j as fz,k as mz,I as pz,l as hz,L as gz,m as bz,n as yz,o as xz,p as Sz,q as Ez,r as wz,s as vz,H as Cz,t as Mz,u as Iz,v as Az,w as Nz,x as _z,y as Tz,z as Rz,B as Pz,E as Oz,F as kz,G as Dz,J as jz,K as Lz,M as Fz,N as zz,Q as Bz,U as Vz,V as $z,W as Gz,X as Uz,Y as Wz,Z as Hz,_ as Kz,$ as Xz,a0 as Yz,a1 as qz,a2 as Zz,a3 as Jz,a4 as Qz,a5 as e3,a6 as t3,a7 as n3,a8 as r3,a9 as o3,aa as i3,ab as s3,ac as a3,ad as l3,ae as c3,af as u3,ag as d3,ah as f3,ai as m3,aj as p3,ak as h3,al as g3,am as b3,an as y3,ao as x3,ap as S3}from"./vendor-ui-CtsphK4U.js";import{X as eh,P as E3,M as PE,a as OE,R as ws,N as w3,C as Vd,b as v3,c as jy,d as mu,e as vu,F as kE,L as Ly,f as DE,g as sf,B as jE,h as Fy,i as LE,D as FE,j as zE,k as BE,l as LS,A as C3,m as M3,n as I3,o as A3,E as rR,p as oR,S as N3,q as iR,r as _3,s as T3,t as R3,u as P3,T as sR,v as aR,w as lR,x as VE,y as $E,z as cR,G as O3,U as k3,H as D3,I as j3,J as uR,K as L3,O as F3,Q as z3,V as B3,W as V3,Y as dR,Z as $3,_ as G3,$ as U3,a0 as W3,a1 as H3,a2 as K3}from"./vendor-icons-FFp724MI.js";import{T as gb,W as X3,O as Y3,P as q3,a as Z3,V as vs,M as qi,b as FS,S as fR}from"./vendor-three-SYzIooV9.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(o){if(o.ep)return;o.ep=!0;const i=n(o);fetch(o.href,i)}})();function mR(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var o=e.length;for(t=0;ttypeof e=="boolean"?`${e}`:e===0?"0":e,WM=pR,th=(e,t)=>n=>{var r;if(t?.variants==null)return WM(e,n?.class,n?.className);const{variants:o,defaultVariants:i}=t,s=Object.keys(o).map(u=>{const d=n?.[u],m=i?.[u];if(d===null)return null;const p=UM(d)||UM(m);return o[u][p]}),a=n&&Object.entries(n).reduce((u,d)=>{let[m,p]=d;return p===void 0||(u[m]=p),u},{}),l=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((u,d)=>{let{class:m,className:p,...g}=d;return Object.entries(g).every(x=>{let[y,S]=x;return Array.isArray(S)?S.includes({...i,...a}[y]):{...i,...a}[y]===S})?[...u,m,p]:u},[]);return WM(e,s,l,n?.class,n?.className)},GE=520,J3=GE,Q3=1024,eB=`(max-width: ${GE-1}px)`,Od=Object.freeze({DESKTOP:"desktop",MOBILE:"mobile"});function zy(e){const t=Number(e);return Number.isFinite(t)?t>=J3?Od.DESKTOP:Od.MOBILE:Od.DESKTOP}function ox(e){return zy(e)===Od.MOBILE}function tB(e){return zy(e)===Od.DESKTOP}function nB(e){const t=Number(e);return Number.isFinite(t)?t>=GE&&ttypeof window>"u"?!1:ox(window.innerWidth));return f.useEffect(()=>{const n=window.matchMedia(eB),r=()=>{t(ox(window.innerWidth))};return n.addEventListener("change",r),t(ox(window.innerWidth)),()=>n.removeEventListener("change",r)},[]),!!e}const iB=(e,t)=>{const n=new Array(e.length+t.length);for(let r=0;r({classGroupId:e,validator:t}),hR=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),zb="-",HM=[],aB="arbitrary..",lB=e=>{const t=uB(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:s=>{if(s.startsWith("[")&&s.endsWith("]"))return cB(s);const a=s.split(zb),l=a[0]===""&&a.length>1?1:0;return gR(a,l,t)},getConflictingClassGroupIds:(s,a)=>{if(a){const l=r[s],u=n[s];return l?u?iB(u,l):l:u||HM}return n[s]||HM}}},gR=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const o=e[t],i=n.nextPart.get(o);if(i){const u=gR(e,t+1,i);if(u)return u}const s=n.validators;if(s===null)return;const a=t===0?e.join(zb):e.slice(t).join(zb),l=s.length;for(let u=0;ue.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),n=t.indexOf(":"),r=t.slice(0,n);return r?aB+r:void 0})(),uB=e=>{const{theme:t,classGroups:n}=e;return dB(n,t)},dB=(e,t)=>{const n=hR();for(const r in e){const o=e[r];UE(o,n,r,t)}return n},UE=(e,t,n,r)=>{const o=e.length;for(let i=0;i{if(typeof e=="string"){mB(e,t,n);return}if(typeof e=="function"){pB(e,t,n,r);return}hB(e,t,n,r)},mB=(e,t,n)=>{const r=e===""?t:bR(t,e);r.classGroupId=n},pB=(e,t,n,r)=>{if(gB(e)){UE(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(sB(n,e))},hB=(e,t,n,r)=>{const o=Object.entries(e),i=o.length;for(let s=0;s{let n=e;const r=t.split(zb),o=r.length;for(let i=0;i"isThemeGetter"in e&&e.isThemeGetter===!0,bB=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null);const o=(i,s)=>{n[i]=s,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(i){let s=n[i];if(s!==void 0)return s;if((s=r[i])!==void 0)return o(i,s),s},set(i,s){i in n?n[i]=s:o(i,s)}}},zS="!",KM=":",yB=[],XM=(e,t,n,r,o)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:o}),xB=e=>{const{prefix:t,experimentalParseClassName:n}=e;let r=o=>{const i=[];let s=0,a=0,l=0,u;const d=o.length;for(let y=0;yl?u-l:void 0;return XM(i,g,p,x)};if(t){const o=t+KM,i=r;r=s=>s.startsWith(o)?i(s.slice(o.length)):XM(yB,!1,s,void 0,!0)}if(n){const o=r;r=i=>n({className:i,parseClassName:o})}return r},SB=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((n,r)=>{t.set(n,1e6+r)}),n=>{const r=[];let o=[];for(let i=0;i0&&(o.sort(),r.push(...o),o=[]),r.push(s)):o.push(s)}return o.length>0&&(o.sort(),r.push(...o)),r}},EB=e=>({cache:bB(e.cacheSize),parseClassName:xB(e),sortModifiers:SB(e),...lB(e)}),wB=/\s+/,vB=(e,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:o,sortModifiers:i}=t,s=[],a=e.trim().split(wB);let l="";for(let u=a.length-1;u>=0;u-=1){const d=a[u],{isExternal:m,modifiers:p,hasImportantModifier:g,baseClassName:x,maybePostfixModifierPosition:y}=n(d);if(m){l=d+(l.length>0?" "+l:l);continue}let S=!!y,b=r(S?x.substring(0,y):x);if(!b){if(!S){l=d+(l.length>0?" "+l:l);continue}if(b=r(x),!b){l=d+(l.length>0?" "+l:l);continue}S=!1}const I=p.length===0?"":p.length===1?p[0]:i(p).join(":"),A=g?I+zS:I,N=A+b;if(s.indexOf(N)>-1)continue;s.push(N);const P=o(b,S);for(let R=0;R0?" "+l:l)}return l},CB=(...e)=>{let t=0,n,r,o="";for(;t{if(typeof e=="string")return e;let t,n="";for(let r=0;r{let n,r,o,i;const s=l=>{const u=t.reduce((d,m)=>m(d),e());return n=EB(u),r=n.cache.get,o=n.cache.set,i=a,a(l)},a=l=>{const u=r(l);if(u)return u;const d=vB(l,n);return o(l,d),d};return i=s,(...l)=>i(CB(...l))},IB=[],to=e=>{const t=n=>n[e]||IB;return t.isThemeGetter=!0,t},xR=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,SR=/^\((?:(\w[\w-]*):)?(.+)\)$/i,AB=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,NB=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,_B=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,TB=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,RB=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,PB=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Dl=e=>AB.test(e),Ut=e=>!!e&&!Number.isNaN(Number(e)),jl=e=>!!e&&Number.isInteger(Number(e)),ix=e=>e.endsWith("%")&&Ut(e.slice(0,-1)),$a=e=>NB.test(e),ER=()=>!0,OB=e=>_B.test(e)&&!TB.test(e),WE=()=>!1,kB=e=>RB.test(e),DB=e=>PB.test(e),jB=e=>!Ge(e)&&!Ue(e),LB=e=>Ec(e,CR,WE),Ge=e=>xR.test(e),Vc=e=>Ec(e,MR,OB),YM=e=>Ec(e,WB,Ut),FB=e=>Ec(e,AR,ER),zB=e=>Ec(e,IR,WE),qM=e=>Ec(e,wR,WE),BB=e=>Ec(e,vR,DB),Sg=e=>Ec(e,NR,kB),Ue=e=>SR.test(e),mm=e=>Cu(e,MR),VB=e=>Cu(e,IR),ZM=e=>Cu(e,wR),$B=e=>Cu(e,CR),GB=e=>Cu(e,vR),Eg=e=>Cu(e,NR,!0),UB=e=>Cu(e,AR,!0),Ec=(e,t,n)=>{const r=xR.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},Cu=(e,t,n=!1)=>{const r=SR.exec(e);return r?r[1]?t(r[1]):n:!1},wR=e=>e==="position"||e==="percentage",vR=e=>e==="image"||e==="url",CR=e=>e==="length"||e==="size"||e==="bg-size",MR=e=>e==="length",WB=e=>e==="number",IR=e=>e==="family-name",AR=e=>e==="number"||e==="weight",NR=e=>e==="shadow",HB=()=>{const e=to("color"),t=to("font"),n=to("text"),r=to("font-weight"),o=to("tracking"),i=to("leading"),s=to("breakpoint"),a=to("container"),l=to("spacing"),u=to("radius"),d=to("shadow"),m=to("inset-shadow"),p=to("text-shadow"),g=to("drop-shadow"),x=to("blur"),y=to("perspective"),S=to("aspect"),b=to("ease"),I=to("animate"),A=()=>["auto","avoid","all","avoid-page","page","left","right","column"],N=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],P=()=>[...N(),Ue,Ge],R=()=>["auto","hidden","clip","visible","scroll"],v=()=>["auto","contain","none"],C=()=>[Ue,Ge,l],T=()=>[Dl,"full","auto",...C()],k=()=>[jl,"none","subgrid",Ue,Ge],z=()=>["auto",{span:["full",jl,Ue,Ge]},jl,Ue,Ge],Y=()=>[jl,"auto",Ue,Ge],K=()=>["auto","min","max","fr",Ue,Ge],J=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],G=()=>["start","end","center","stretch","center-safe","end-safe"],Q=()=>["auto",...C()],D=()=>[Dl,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...C()],$=()=>[Dl,"screen","full","dvw","lvw","svw","min","max","fit",...C()],ie=()=>[Dl,"screen","full","lh","dvh","lvh","svh","min","max","fit",...C()],W=()=>[e,Ue,Ge],Z=()=>[...N(),ZM,qM,{position:[Ue,Ge]}],Ee=()=>["no-repeat",{repeat:["","x","y","space","round"]}],re=()=>["auto","cover","contain",$B,LB,{size:[Ue,Ge]}],be=()=>[ix,mm,Vc],_e=()=>["","none","full",u,Ue,Ge],Ie=()=>["",Ut,mm,Vc],oe=()=>["solid","dashed","dotted","double"],me=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],se=()=>[Ut,ix,ZM,qM],Ae=()=>["","none",x,Ue,Ge],we=()=>["none",Ut,Ue,Ge],ct=()=>["none",Ut,Ue,Ge],ut=()=>[Ut,Ue,Ge],Tt=()=>[Dl,"full",...C()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[$a],breakpoint:[$a],color:[ER],container:[$a],"drop-shadow":[$a],ease:["in","out","in-out"],font:[jB],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[$a],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[$a],shadow:[$a],spacing:["px",Ut],text:[$a],"text-shadow":[$a],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Dl,Ge,Ue,S]}],container:["container"],columns:[{columns:[Ut,Ge,Ue,a]}],"break-after":[{"break-after":A()}],"break-before":[{"break-before":A()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:P()}],overflow:[{overflow:R()}],"overflow-x":[{"overflow-x":R()}],"overflow-y":[{"overflow-y":R()}],overscroll:[{overscroll:v()}],"overscroll-x":[{"overscroll-x":v()}],"overscroll-y":[{"overscroll-y":v()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:T()}],"inset-x":[{"inset-x":T()}],"inset-y":[{"inset-y":T()}],start:[{"inset-s":T(),start:T()}],end:[{"inset-e":T(),end:T()}],"inset-bs":[{"inset-bs":T()}],"inset-be":[{"inset-be":T()}],top:[{top:T()}],right:[{right:T()}],bottom:[{bottom:T()}],left:[{left:T()}],visibility:["visible","invisible","collapse"],z:[{z:[jl,"auto",Ue,Ge]}],basis:[{basis:[Dl,"full","auto",a,...C()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Ut,Dl,"auto","initial","none",Ge]}],grow:[{grow:["",Ut,Ue,Ge]}],shrink:[{shrink:["",Ut,Ue,Ge]}],order:[{order:[jl,"first","last","none",Ue,Ge]}],"grid-cols":[{"grid-cols":k()}],"col-start-end":[{col:z()}],"col-start":[{"col-start":Y()}],"col-end":[{"col-end":Y()}],"grid-rows":[{"grid-rows":k()}],"row-start-end":[{row:z()}],"row-start":[{"row-start":Y()}],"row-end":[{"row-end":Y()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":K()}],"auto-rows":[{"auto-rows":K()}],gap:[{gap:C()}],"gap-x":[{"gap-x":C()}],"gap-y":[{"gap-y":C()}],"justify-content":[{justify:[...J(),"normal"]}],"justify-items":[{"justify-items":[...G(),"normal"]}],"justify-self":[{"justify-self":["auto",...G()]}],"align-content":[{content:["normal",...J()]}],"align-items":[{items:[...G(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...G(),{baseline:["","last"]}]}],"place-content":[{"place-content":J()}],"place-items":[{"place-items":[...G(),"baseline"]}],"place-self":[{"place-self":["auto",...G()]}],p:[{p:C()}],px:[{px:C()}],py:[{py:C()}],ps:[{ps:C()}],pe:[{pe:C()}],pbs:[{pbs:C()}],pbe:[{pbe:C()}],pt:[{pt:C()}],pr:[{pr:C()}],pb:[{pb:C()}],pl:[{pl:C()}],m:[{m:Q()}],mx:[{mx:Q()}],my:[{my:Q()}],ms:[{ms:Q()}],me:[{me:Q()}],mbs:[{mbs:Q()}],mbe:[{mbe:Q()}],mt:[{mt:Q()}],mr:[{mr:Q()}],mb:[{mb:Q()}],ml:[{ml:Q()}],"space-x":[{"space-x":C()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":C()}],"space-y-reverse":["space-y-reverse"],size:[{size:D()}],"inline-size":[{inline:["auto",...$()]}],"min-inline-size":[{"min-inline":["auto",...$()]}],"max-inline-size":[{"max-inline":["none",...$()]}],"block-size":[{block:["auto",...ie()]}],"min-block-size":[{"min-block":["auto",...ie()]}],"max-block-size":[{"max-block":["none",...ie()]}],w:[{w:[a,"screen",...D()]}],"min-w":[{"min-w":[a,"screen","none",...D()]}],"max-w":[{"max-w":[a,"screen","none","prose",{screen:[s]},...D()]}],h:[{h:["screen","lh",...D()]}],"min-h":[{"min-h":["screen","lh","none",...D()]}],"max-h":[{"max-h":["screen","lh",...D()]}],"font-size":[{text:["base",n,mm,Vc]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,UB,FB]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",ix,Ge]}],"font-family":[{font:[VB,zB,t]}],"font-features":[{"font-features":[Ge]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[o,Ue,Ge]}],"line-clamp":[{"line-clamp":[Ut,"none",Ue,YM]}],leading:[{leading:[i,...C()]}],"list-image":[{"list-image":["none",Ue,Ge]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Ue,Ge]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:W()}],"text-color":[{text:W()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...oe(),"wavy"]}],"text-decoration-thickness":[{decoration:[Ut,"from-font","auto",Ue,Vc]}],"text-decoration-color":[{decoration:W()}],"underline-offset":[{"underline-offset":[Ut,"auto",Ue,Ge]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:C()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Ue,Ge]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Ue,Ge]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:Z()}],"bg-repeat":[{bg:Ee()}],"bg-size":[{bg:re()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},jl,Ue,Ge],radial:["",Ue,Ge],conic:[jl,Ue,Ge]},GB,BB]}],"bg-color":[{bg:W()}],"gradient-from-pos":[{from:be()}],"gradient-via-pos":[{via:be()}],"gradient-to-pos":[{to:be()}],"gradient-from":[{from:W()}],"gradient-via":[{via:W()}],"gradient-to":[{to:W()}],rounded:[{rounded:_e()}],"rounded-s":[{"rounded-s":_e()}],"rounded-e":[{"rounded-e":_e()}],"rounded-t":[{"rounded-t":_e()}],"rounded-r":[{"rounded-r":_e()}],"rounded-b":[{"rounded-b":_e()}],"rounded-l":[{"rounded-l":_e()}],"rounded-ss":[{"rounded-ss":_e()}],"rounded-se":[{"rounded-se":_e()}],"rounded-ee":[{"rounded-ee":_e()}],"rounded-es":[{"rounded-es":_e()}],"rounded-tl":[{"rounded-tl":_e()}],"rounded-tr":[{"rounded-tr":_e()}],"rounded-br":[{"rounded-br":_e()}],"rounded-bl":[{"rounded-bl":_e()}],"border-w":[{border:Ie()}],"border-w-x":[{"border-x":Ie()}],"border-w-y":[{"border-y":Ie()}],"border-w-s":[{"border-s":Ie()}],"border-w-e":[{"border-e":Ie()}],"border-w-bs":[{"border-bs":Ie()}],"border-w-be":[{"border-be":Ie()}],"border-w-t":[{"border-t":Ie()}],"border-w-r":[{"border-r":Ie()}],"border-w-b":[{"border-b":Ie()}],"border-w-l":[{"border-l":Ie()}],"divide-x":[{"divide-x":Ie()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":Ie()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...oe(),"hidden","none"]}],"divide-style":[{divide:[...oe(),"hidden","none"]}],"border-color":[{border:W()}],"border-color-x":[{"border-x":W()}],"border-color-y":[{"border-y":W()}],"border-color-s":[{"border-s":W()}],"border-color-e":[{"border-e":W()}],"border-color-bs":[{"border-bs":W()}],"border-color-be":[{"border-be":W()}],"border-color-t":[{"border-t":W()}],"border-color-r":[{"border-r":W()}],"border-color-b":[{"border-b":W()}],"border-color-l":[{"border-l":W()}],"divide-color":[{divide:W()}],"outline-style":[{outline:[...oe(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Ut,Ue,Ge]}],"outline-w":[{outline:["",Ut,mm,Vc]}],"outline-color":[{outline:W()}],shadow:[{shadow:["","none",d,Eg,Sg]}],"shadow-color":[{shadow:W()}],"inset-shadow":[{"inset-shadow":["none",m,Eg,Sg]}],"inset-shadow-color":[{"inset-shadow":W()}],"ring-w":[{ring:Ie()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:W()}],"ring-offset-w":[{"ring-offset":[Ut,Vc]}],"ring-offset-color":[{"ring-offset":W()}],"inset-ring-w":[{"inset-ring":Ie()}],"inset-ring-color":[{"inset-ring":W()}],"text-shadow":[{"text-shadow":["none",p,Eg,Sg]}],"text-shadow-color":[{"text-shadow":W()}],opacity:[{opacity:[Ut,Ue,Ge]}],"mix-blend":[{"mix-blend":[...me(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":me()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[Ut]}],"mask-image-linear-from-pos":[{"mask-linear-from":se()}],"mask-image-linear-to-pos":[{"mask-linear-to":se()}],"mask-image-linear-from-color":[{"mask-linear-from":W()}],"mask-image-linear-to-color":[{"mask-linear-to":W()}],"mask-image-t-from-pos":[{"mask-t-from":se()}],"mask-image-t-to-pos":[{"mask-t-to":se()}],"mask-image-t-from-color":[{"mask-t-from":W()}],"mask-image-t-to-color":[{"mask-t-to":W()}],"mask-image-r-from-pos":[{"mask-r-from":se()}],"mask-image-r-to-pos":[{"mask-r-to":se()}],"mask-image-r-from-color":[{"mask-r-from":W()}],"mask-image-r-to-color":[{"mask-r-to":W()}],"mask-image-b-from-pos":[{"mask-b-from":se()}],"mask-image-b-to-pos":[{"mask-b-to":se()}],"mask-image-b-from-color":[{"mask-b-from":W()}],"mask-image-b-to-color":[{"mask-b-to":W()}],"mask-image-l-from-pos":[{"mask-l-from":se()}],"mask-image-l-to-pos":[{"mask-l-to":se()}],"mask-image-l-from-color":[{"mask-l-from":W()}],"mask-image-l-to-color":[{"mask-l-to":W()}],"mask-image-x-from-pos":[{"mask-x-from":se()}],"mask-image-x-to-pos":[{"mask-x-to":se()}],"mask-image-x-from-color":[{"mask-x-from":W()}],"mask-image-x-to-color":[{"mask-x-to":W()}],"mask-image-y-from-pos":[{"mask-y-from":se()}],"mask-image-y-to-pos":[{"mask-y-to":se()}],"mask-image-y-from-color":[{"mask-y-from":W()}],"mask-image-y-to-color":[{"mask-y-to":W()}],"mask-image-radial":[{"mask-radial":[Ue,Ge]}],"mask-image-radial-from-pos":[{"mask-radial-from":se()}],"mask-image-radial-to-pos":[{"mask-radial-to":se()}],"mask-image-radial-from-color":[{"mask-radial-from":W()}],"mask-image-radial-to-color":[{"mask-radial-to":W()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":N()}],"mask-image-conic-pos":[{"mask-conic":[Ut]}],"mask-image-conic-from-pos":[{"mask-conic-from":se()}],"mask-image-conic-to-pos":[{"mask-conic-to":se()}],"mask-image-conic-from-color":[{"mask-conic-from":W()}],"mask-image-conic-to-color":[{"mask-conic-to":W()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:Z()}],"mask-repeat":[{mask:Ee()}],"mask-size":[{mask:re()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Ue,Ge]}],filter:[{filter:["","none",Ue,Ge]}],blur:[{blur:Ae()}],brightness:[{brightness:[Ut,Ue,Ge]}],contrast:[{contrast:[Ut,Ue,Ge]}],"drop-shadow":[{"drop-shadow":["","none",g,Eg,Sg]}],"drop-shadow-color":[{"drop-shadow":W()}],grayscale:[{grayscale:["",Ut,Ue,Ge]}],"hue-rotate":[{"hue-rotate":[Ut,Ue,Ge]}],invert:[{invert:["",Ut,Ue,Ge]}],saturate:[{saturate:[Ut,Ue,Ge]}],sepia:[{sepia:["",Ut,Ue,Ge]}],"backdrop-filter":[{"backdrop-filter":["","none",Ue,Ge]}],"backdrop-blur":[{"backdrop-blur":Ae()}],"backdrop-brightness":[{"backdrop-brightness":[Ut,Ue,Ge]}],"backdrop-contrast":[{"backdrop-contrast":[Ut,Ue,Ge]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Ut,Ue,Ge]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Ut,Ue,Ge]}],"backdrop-invert":[{"backdrop-invert":["",Ut,Ue,Ge]}],"backdrop-opacity":[{"backdrop-opacity":[Ut,Ue,Ge]}],"backdrop-saturate":[{"backdrop-saturate":[Ut,Ue,Ge]}],"backdrop-sepia":[{"backdrop-sepia":["",Ut,Ue,Ge]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":C()}],"border-spacing-x":[{"border-spacing-x":C()}],"border-spacing-y":[{"border-spacing-y":C()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Ue,Ge]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Ut,"initial",Ue,Ge]}],ease:[{ease:["linear","initial",b,Ue,Ge]}],delay:[{delay:[Ut,Ue,Ge]}],animate:[{animate:["none",I,Ue,Ge]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[y,Ue,Ge]}],"perspective-origin":[{"perspective-origin":P()}],rotate:[{rotate:we()}],"rotate-x":[{"rotate-x":we()}],"rotate-y":[{"rotate-y":we()}],"rotate-z":[{"rotate-z":we()}],scale:[{scale:ct()}],"scale-x":[{"scale-x":ct()}],"scale-y":[{"scale-y":ct()}],"scale-z":[{"scale-z":ct()}],"scale-3d":["scale-3d"],skew:[{skew:ut()}],"skew-x":[{"skew-x":ut()}],"skew-y":[{"skew-y":ut()}],transform:[{transform:[Ue,Ge,"","none","gpu","cpu"]}],"transform-origin":[{origin:P()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Tt()}],"translate-x":[{"translate-x":Tt()}],"translate-y":[{"translate-y":Tt()}],"translate-z":[{"translate-z":Tt()}],"translate-none":["translate-none"],accent:[{accent:W()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:W()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Ue,Ge]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":C()}],"scroll-mx":[{"scroll-mx":C()}],"scroll-my":[{"scroll-my":C()}],"scroll-ms":[{"scroll-ms":C()}],"scroll-me":[{"scroll-me":C()}],"scroll-mbs":[{"scroll-mbs":C()}],"scroll-mbe":[{"scroll-mbe":C()}],"scroll-mt":[{"scroll-mt":C()}],"scroll-mr":[{"scroll-mr":C()}],"scroll-mb":[{"scroll-mb":C()}],"scroll-ml":[{"scroll-ml":C()}],"scroll-p":[{"scroll-p":C()}],"scroll-px":[{"scroll-px":C()}],"scroll-py":[{"scroll-py":C()}],"scroll-ps":[{"scroll-ps":C()}],"scroll-pe":[{"scroll-pe":C()}],"scroll-pbs":[{"scroll-pbs":C()}],"scroll-pbe":[{"scroll-pbe":C()}],"scroll-pt":[{"scroll-pt":C()}],"scroll-pr":[{"scroll-pr":C()}],"scroll-pb":[{"scroll-pb":C()}],"scroll-pl":[{"scroll-pl":C()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Ue,Ge]}],fill:[{fill:["none",...W()]}],"stroke-w":[{stroke:[Ut,mm,Vc,YM]}],stroke:[{stroke:["none",...W()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},KB=MB(HB);function H(...e){return KB(pR(e))}const HE=th("inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",xs:"h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",sm:"h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-xs":"size-6 rounded-md [&_svg:not([class*='size-'])]:size-3","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}}),Qe=f.forwardRef(function({className:t,variant:n="default",size:r="default",asChild:o=!1,...i},s){const a=o?XT:"button";return c.jsx(a,{ref:s,"data-slot":"button","data-variant":n,"data-size":r,className:H(HE({variant:n,size:r,className:t})),...i})});function go({className:e,type:t,...n}){return c.jsx("input",{type:t,"data-slot":"input",className:H("h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30","focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50","aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",e),...n})}function _R({...e}){return c.jsx(QT,{"data-slot":"sheet",...e})}f.forwardRef(function({...t},n){return c.jsx(YT,{ref:n,"data-slot":"sheet-trigger",...t})});f.forwardRef(function({...t},n){return c.jsx(Dy,{ref:n,"data-slot":"sheet-close",...t})});function XB({...e}){return c.jsx(JT,{"data-slot":"sheet-portal",...e})}const YB=f.forwardRef(function({className:t,...n},r){return c.jsx(qT,{ref:r,"data-slot":"sheet-overlay",className:H("fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",t),...n})}),TR=f.forwardRef(function({className:t,overlayClassName:n,children:r,side:o="right",showCloseButton:i=!0,...s},a){return c.jsxs(XB,{children:[c.jsx(YB,{className:n}),c.jsxs(ZT,{ref:a,"data-slot":"sheet-content",className:H("cad-glass-popover fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:animate-in data-[state=open]:duration-500",o==="right"&&"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm",o==="left"&&"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",o==="top"&&"inset-x-0 top-0 h-auto border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",o==="bottom"&&"inset-x-0 bottom-0 h-auto border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",t),...s,children:[r,i&&c.jsxs(Dy,{className:"absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-secondary",children:[c.jsx(eh,{className:"size-4"}),c.jsx("span",{className:"sr-only",children:"Close"})]})]})]})});function RR({className:e,...t}){return c.jsx("div",{"data-slot":"sheet-header",className:H("flex flex-col gap-1.5 p-4",e),...t})}function PR({className:e,...t}){return c.jsx(eR,{"data-slot":"sheet-title",className:H("font-semibold text-foreground",e),...t})}function OR({className:e,...t}){return c.jsx(tR,{"data-slot":"sheet-description",className:H("text-sm text-muted-foreground",e),...t})}function By({delayDuration:e=0,...t}){return c.jsx(cz,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function KE({...e}){return c.jsx(uz,{"data-slot":"tooltip",...e})}const XE=f.forwardRef(function({...t},n){return c.jsx(iz,{ref:n,"data-slot":"tooltip-trigger",...t})}),YE=f.forwardRef(function({className:t,arrowClassName:n,sideOffset:r=0,children:o,...i},s){return c.jsx(sz,{children:c.jsxs(az,{ref:s,"data-slot":"tooltip-content",sideOffset:r,className:H("cad-glass-popover z-50 w-fit origin-(--radix-tooltip-content-transform-origin) animate-in rounded-md border border-border bg-popover px-3 py-1.5 text-xs text-balance text-popover-foreground shadow-lg shadow-black/10 fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",t),...i,children:[o,c.jsx(lz,{className:H("z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-popover fill-popover",n)})]})})}),qB="16rem",ZB="3rem",JB="b",kR=f.createContext(null);function nh(){const e=f.useContext(kR);if(!e)throw new Error("useSidebar must be used within a SidebarProvider.");return e}function QB({defaultOpen:e=!0,defaultMobileOpen:t=!1,open:n,onOpenChange:r,mobileOpen:o,onMobileOpenChange:i,className:s,style:a,children:l,...u}){const d=oB(),[m,p]=f.useState(t),[g,x]=f.useState(e),y=n??g,S=o??m,b=f.useCallback(R=>{const v=typeof R=="function"?R(y):R;r?r(v):x(v)},[r,y]),I=f.useCallback(R=>{const v=typeof R=="function"?R(S):R;i?i(v):p(v)},[i,S]),A=f.useCallback(()=>d?I(R=>!R):b(R=>!R),[d,b,I]);f.useEffect(()=>{const R=v=>{v.key===JB&&(v.metaKey||v.ctrlKey)&&(v.preventDefault(),A())};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[A]);const N=y?"expanded":"collapsed",P=f.useMemo(()=>({state:N,open:y,setOpen:b,isMobile:d,openMobile:S,setOpenMobile:I,toggleSidebar:A}),[N,y,b,d,S,I,A]);return c.jsx(kR.Provider,{value:P,children:c.jsx(By,{delayDuration:0,children:c.jsx("div",{"data-slot":"sidebar-wrapper",style:{"--sidebar-width":qB,"--sidebar-width-icon":ZB,...a},className:H("group/sidebar-wrapper flex min-h-svh w-full has-data-[variant=inset]:bg-sidebar",s),...u,children:l})})})}function e5({className:e,onClick:t,...n}){const{toggleSidebar:r}=nh();return c.jsxs(Qe,{"data-sidebar":"trigger","data-slot":"sidebar-trigger",variant:"ghost",size:"icon",className:H("size-7",e),onClick:o=>{t?.(o),r()},...n,children:[c.jsx(E3,{}),c.jsx("span",{className:"sr-only",children:"Toggle Sidebar"})]})}function t5({className:e,...t}){return c.jsx("main",{"data-slot":"sidebar-inset",className:H("relative flex w-full flex-1 flex-col bg-transparent","md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",e),...t})}function n5({className:e,...t}){return c.jsx(go,{"data-slot":"sidebar-input","data-sidebar":"input",className:H("cad-glass-control h-8 w-full shadow-none",e),...t})}function r5({className:e,...t}){return c.jsx("div",{"data-slot":"sidebar-header","data-sidebar":"header",className:H("flex flex-col gap-2 p-2",e),...t})}function o5({className:e,...t}){return c.jsx("div",{"data-slot":"sidebar-content","data-sidebar":"content",className:H("flex min-h-0 flex-1 flex-col gap-2 overflow-hidden",e),...t})}function i5({className:e,...t}){return c.jsx("div",{"data-slot":"sidebar-group","data-sidebar":"group",className:H("relative flex w-full min-w-0 flex-col p-2",e),...t})}function s5({className:e,...t}){return c.jsx("div",{"data-slot":"sidebar-group-content","data-sidebar":"group-content",className:H("w-full text-sm",e),...t})}function a5({className:e,...t}){return c.jsx("ul",{"data-slot":"sidebar-menu","data-sidebar":"menu",className:H("flex w-full min-w-0 flex-col gap-1",e),...t})}function DR({className:e,...t}){return c.jsx("li",{"data-slot":"sidebar-menu-item","data-sidebar":"menu-item",className:H("group/menu-item relative",e),...t})}const l5=th("peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm ring-sidebar-ring outline-hidden transition-[width,height,padding] group-has-data-[sidebar=menu-action]/menu-item:pr-8 group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",{variants:{variant:{default:"hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",outline:"bg-background shadow-[0_0_0_1px_var(--sidebar-border)] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_var(--sidebar-accent)]"},size:{default:"h-8 text-sm",sm:"h-7 text-xs",lg:"h-12 text-sm group-data-[collapsible=icon]:p-0!"}},defaultVariants:{variant:"default",size:"default"}});function jR({asChild:e=!1,isActive:t=!1,variant:n="default",size:r="default",tooltip:o,className:i,...s}){const a=e?XT:"button",{isMobile:l,state:u}=nh(),d=c.jsx(a,{"data-slot":"sidebar-menu-button","data-sidebar":"menu-button","data-size":r,"data-active":t,className:H(l5({variant:n,size:r}),i),...s});return o?(typeof o=="string"&&(o={children:o}),c.jsxs(KE,{children:[c.jsx(XE,{asChild:!0,children:d}),c.jsx(YE,{side:"right",align:"center",hidden:u!=="collapsed"||l,...o})]})):d}function c5({className:e,...t}){return c.jsx("ul",{"data-slot":"sidebar-menu-sub","data-sidebar":"menu-sub",className:H("mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5","group-data-[collapsible=icon]:hidden",e),...t})}function JM({className:e,...t}){return c.jsx("li",{"data-slot":"sidebar-menu-sub-item","data-sidebar":"menu-sub-item",className:H("group/menu-sub-item relative",e),...t})}const u5=/^\s*#([^\s]*)/,d5=/^o((?:\d+)(?:\.\d+)*)$/,f5=/^o((?:\d+)(?:\.\d+)*)\.([sfev])(\d+)$/,m5=/^([sfev])(\d+)$/;function sx(e){return e==="s"?"shape":e==="f"?"face":e==="e"?"edge":"vertex"}function qE(e){let t=String(e||"").replace(/\\/g,"/").trim().replace(/^\/+|\/+$/g,"");return!t||t.split("/").some(n=>!n||n==="."||n==="..")?"":t}function ZE(e,{inheritedOccurrenceId:t=""}={}){const n=String(e||"").trim().replace(/^#/,"");if(!n)return null;const r=n.match(f5);if(r){const s=`o${r[1]}`,a=r[2],l=Number(r[3]);return{selectorType:sx(a),occurrenceId:s,ordinal:l,kind:a,canonical:`${s}.${a}${l}`}}const o=n.match(d5);if(o)return{selectorType:"occurrence",occurrenceId:`o${o[1]}`,ordinal:null,kind:"",canonical:`o${o[1]}`};const i=n.match(m5);if(i){const s=i[1],a=Number(i[2]);return t?{selectorType:sx(s),occurrenceId:t,ordinal:a,kind:s,canonical:`${t}.${s}${a}`}:{selectorType:sx(s),occurrenceId:"",ordinal:a,kind:s,canonical:`${s}${a}`}}return{selectorType:"opaque",occurrenceId:"",ordinal:null,kind:"",canonical:n}}function p5(e,t={}){return ZE(e,t)}function JE(e){const t=Array.isArray(e)?e.flatMap(o=>String(o||"").split(",")):String(e||"").split(","),n=[];let r="";for(const o of t){const i=ZE(o,{inheritedOccurrenceId:r});i&&(n.push(i.canonical),i.occurrenceId&&(r=i.occurrenceId))}return n}function BS(e){const t=JE(e),n=[...new Set(t.filter(Boolean))],r={occurrence:1,shape:2,face:3,edge:4,vertex:5,opaque:6};return n.map((o,i)=>({selector:o,index:i,parsed:ZE(o)})).sort((o,i)=>{const s=o.parsed?.occurrenceId||"",a=i.parsed?.occurrenceId||"";if(s!==a)return s.localeCompare(a);const l=r[o.parsed?.selectorType]??99,u=r[i.parsed?.selectorType]??99;if(l!==u)return l-u;const d=Number(o.parsed?.ordinal||0),m=Number(i.parsed?.ordinal||0);return d!==m?d-m:o.selector!==i.selector?o.selector.localeCompare(i.selector):o.index-i.index}).map(o=>o.selector)}function rh(e){const t=String(e||"").trim().match(u5);if(!t)return null;const n=String(t[1]||"").trim();return{token:t[0],cadPath:"",selectors:JE(n)}}function dc({cadPath:e="",selector:t="",selectors:n}={}){const r=BS(n!==void 0?n:t?[t]:[]);return r.length?`#${r.join(",")}`:"#"}const hs="__step_model__",op="__model__",Ap="step-topology:",h5=new Set(["occurrence","shape","face","edge"]);function pt(e,t=""){return String(e??t).trim()}function g5(e){const t=Number(e);return!Number.isFinite(t)||t<1?null:Math.floor(t)}function VS(e){const t=pt(e);return t?t.split(/[\\/]/).filter(Boolean).pop()||t:""}function b5(e){return pt(e).replace(/\.(?:step|stp)$/i,"")||"STEP part"}function Cs(e){return pt(e?.id||e?.occurrenceId)}function QE(e){return pt(e?.displayName||e?.name||e?.label||e?.sourcePath&&VS(e.sourcePath)||e?.partSourcePath&&VS(e.partSourcePath)||e?.id,"STEP")}function LR(e){return pt(e?.detail||e?.summary||e?.shortSummary)}function hr(e){return Array.isArray(e?.children)?e.children:[]}function y5(e){const t=pt(e?.nodeType);return t.startsWith("topology-")?t.slice(9):""}function FR(e){const t=Array.isArray(e?.leafPartIds)?e.leafPartIds.map(s=>pt(s)).filter(Boolean):[];if(t.length)return[...new Set(t)];const n=pt(e?.nodeType),r=Cs(e);if(n==="part"&&r)return[r];const o=[],i=[...hr(e)].reverse();for(;i.length;){const s=i.pop(),a=pt(s?.nodeType),l=hr(s);if(l.length){for(let u=l.length-1;u>=0;u-=1)i.push(l[u]);continue}if(a==="part"){const u=Cs(s);u&&o.push(u)}}return[...new Set(o)]}function x5({selectedEntry:e=null,meshData:t=null}={}){const n=pt(e?.file&&VS(e.file)||"STEP part");return{id:hs,occurrenceId:"",nodeType:"part",displayName:n,name:n,sourceKind:"entry",leafPartIds:[op],bbox:t?.bounds||null,children:[]}}function S5({selectedEntry:e=null,assemblyRoot:t=null,meshData:n=null}={}){return t&&typeof t=="object"?t:n?x5({selectedEntry:e,meshData:n}):null}function E5(e,t){if(!t)return!0;const n=pt(t).toLowerCase();return n?[QE(e),LR(e),Cs(e),e?.occurrenceId,e?.topologyReferenceId,e?.displaySelector,e?.sourcePath,e?.partSourcePath].map(o=>pt(o).toLowerCase()).join(" ").includes(n):!0}function pu(e){return pt(e?.displaySelector||e?.normalizedSelector||e?.id)}function w5(e){const t=pt(e);return t?t.split(".").filter(Boolean).pop()||t:""}function v5(e){const t=pt(e);if(!t)return"";const n=t.match(/^(.*)\.[sfe]\d+$/i);return n?n[1]:t}function zR(e){return pt(e?.selectorType)==="occurrence"?pu(e):pt(e?.occurrenceId)||v5(pu(e))}function C5(e){const t=e?.pickData&&typeof e.pickData=="object"?e.pickData:{};return pt(e?.name||e?.sourceName||t.name||t.sourceName)}function BR(e){const t=pt(e?.selectorType),n=pu(e),r=w5(n),o=C5(e),i=pt(e?.summary||e?.shortSummary);return t==="occurrence"?i||o||n||"Occurrence":t==="shape"?o||(r?`Shape ${r}`:"Shape"):t==="face"?r?`Face ${r}`:"Face":t==="edge"?r?`Edge ${r}`:"Edge":i||n||"Topology"}function M5(e){const t=pt(e?.selectorType),n=pu(e),r=BR(e),o=pt(e?.summary||e?.shortSummary);return t==="occurrence"?o&&o!==n&&o!==r?n:"":t==="shape"?o&&o!==r?o:n:o}function ew(e,t,n){return`${Ap}${e||"part"}:${t}:${n||"item"}`}function ax(e,t){const n=Number(e?.rowIndex),r=Number(t?.rowIndex);return Number.isFinite(n)&&Number.isFinite(r)&&n!==r?n-r:Number.isFinite(n)?-1:Number.isFinite(r)?1:pu(e).localeCompare(pu(t))}function wg({reference:e,selectorType:t,partId:n,occurrenceId:r}){const o=pu(e);return{id:ew(n,t,o||pt(e?.id)),nodeType:`topology-${t}`,displayName:BR(e),detail:M5(e),topologyReferenceId:pt(e?.id),displaySelector:o,partId:n,occurrenceId:r,shapeId:pt(e?.shapeId),children:[]}}function I5({partId:e,occurrenceId:t,children:n}){const r=ew(e,"occurrence",t);return{id:r,nodeType:"topology-occurrence",displayName:t||"Occurrence",detail:"",topologyReferenceId:r,displaySelector:t,partId:e,occurrenceId:t,children:n}}function A5({partNode:e,partId:t,children:n}){const r=b5(QE(e));return{id:ew(t,"folder","faces-edges"),nodeType:"topology-folder",displayName:r,name:r,detail:"",topologyReferenceId:"",displaySelector:"",partId:t,selectionPartId:t,leafPartIds:[op],visualOnly:!0,children:n}}function QM(e){const t=pt(e);if(!t)return[];const n=[t];if(t.startsWith("#")&&n.push(t.slice(1)),t.startsWith(Ap)){const r=pt(t.split(":").pop());r&&n.push(r)}return[...new Set(n.filter(Boolean))]}function N5(e,t,n){return pt(t?.nodeType)!=="topology-occurrence"?!1:n===1?!0:VR(e,t)}function VR(e,t){if(pt(t?.nodeType)!=="topology-occurrence")return!1;const n=pt(t?.occurrenceId||t?.displaySelector);if(!n)return!1;const r=[Cs(e),e?.occurrenceId,e?.sourceOccurrenceId,e?.sourceRootTargetOccurrenceId,e?.topologyReferenceId,e?.displaySelector,e?.displayName,e?.name,e?.label].flatMap(QM);return[n,Cs(t),t?.topologyReferenceId,t?.displaySelector,t?.displayName,t?.name,t?.label].flatMap(QM).some(i=>r.includes(i))}function _5(e,t){const n=Array.isArray(t)?t:[];return n.flatMap(r=>N5(e,r,n.length)?hr(r):[r])}function T5(e,t){const n=Array.isArray(t)?t:[];return!n.length||pt(e?.nodeType)!=="part"||Cs(e)!==hs?n:[A5({partNode:e,partId:hs,children:n})]}function R5(e,t){return pt(e?.partId)||pt(t)}function pm(e,t,n,r,o=0){const i=pt(n),s=pt(r);if(!i||!s)return;const a=`${i}\0${s}`;t.has(a)||(t.add(a),e.push({partId:i,occurrenceId:s,priority:Number.isFinite(Number(o))?Number(o):0}))}function P5(e){const t=[],n=new Set,r=e?[e]:[];for(;r.length;){const o=r.pop(),i=hr(o);for(let a=i.length-1;a>=0;a-=1)r.push(i[a]);if(pt(o?.nodeType)!=="part")continue;const s=Cs(o);if(s){pm(t,n,s,s,0),pm(t,n,s,o?.occurrenceId,0);for(const a of FR(o))pm(t,n,s,a,1);pm(t,n,s,o?.sourceOccurrenceId,2),pm(t,n,s,o?.sourceRootTargetOccurrenceId,2)}}return t.sort((o,i)=>i.occurrenceId.length-o.occurrenceId.length||o.priority-i.priority)}function O5(e,t){const n=pt(e),r=pt(t);return!!(n&&r&&(n===r||n.startsWith(`${r}.`)))}function k5(e=null,t=[]){const n=Array.isArray(t)?t:[],r=P5(e);if(!n.length||!r.length)return n;let o=!1;const i=n.map(s=>{if(!s||typeof s!="object"||pt(s.partId))return s;const a=zR(s),l=r.find(u=>O5(a,u.occurrenceId));return l?(o=!0,{...s,partId:l.partId}):s});return o?i:n}function D5(e,t){const n=new Map;for(const r of Array.isArray(e)?e:[]){const o=pt(r?.selectorType);if(!h5.has(o))continue;const i=R5(r,t),s=zR(r);if(!i||!s)continue;let a=n.get(i);a||(a=new Map,n.set(i,a));let l=a.get(s);l||(l={occurrence:null,shapes:[],faces:[],edges:[]},a.set(s,l)),o==="occurrence"?l.occurrence=r:o==="shape"?l.shapes.push(r):o==="face"?l.faces.push(r):o==="edge"&&l.edges.push(r)}return new Map([...n.entries()].map(([r,o])=>{const i=[...o.entries()].sort(([s],[a])=>s.localeCompare(a)).map(([s,a])=>{const l=[...a.shapes.sort(ax).map(u=>wg({reference:u,selectorType:"shape",partId:r,occurrenceId:s})),...a.faces.sort(ax).map(u=>wg({reference:u,selectorType:"face",partId:r,occurrenceId:s})),...a.edges.sort(ax).map(u=>wg({reference:u,selectorType:"edge",partId:r,occurrenceId:s}))];return a.occurrence?{...wg({reference:a.occurrence,selectorType:"occurrence",partId:r,occurrenceId:s}),children:l}:I5({partId:r,occurrenceId:s,children:l})});return[r,i]}))}function j5({root:e=null,references:t=[],fallbackPartId:n="",topologyPartIds:r=null}={}){if(!e||typeof e!="object")return e;const o=r==null?null:new Set((Array.isArray(r)?r:[r]).map(a=>pt(a)).filter(Boolean)),i=D5(t,n||Cs(e));if(!i.size)return e;function s(a){const l=Cs(a),u=hr(a).map(p=>s(p)),m=(!o||o.has(l))&&pt(a?.nodeType)==="part"?T5(a,_5(a,i.get(l)||[])):[];return!u.length&&!m.length?a:{...a,children:[...u,...m]}}return s(e)}function $R(e,t){return!t||E5(e,t)?!0:hr(e).some(n=>$R(n,t))}function GR(e,t){const n=pt(t);return!e||!n?!1:Cs(e)===n?!0:hr(e).some(r=>GR(r,n))}function L5(e,t){const n=pt(t);if(!e||!n)return-1;const r=hr(e);for(let o=0;opt(g)).filter(Boolean)),a=pt(n).toLowerCase(),l=g5(o),u=!!(l&&i!==!0&&!a),d=[];function m(g){return u?g.slice(0,l):g}function p(g,x,y={},S=null){if(a&&!$R(g,a))return;const b=Cs(g),I=hr(g),A=I.length>0,P=!!(a&&A)||s.has(b),R=S&&VR(S,g);if(R||d.push({id:b,node:g,label:QE(g),detail:LR(g),nodeType:pt(g?.nodeType),topologyType:y5(g),topologyReferenceId:pt(g?.topologyReferenceId),depth:x,hasChildren:A,expanded:P,leafPartIds:FR(g)}),!A||!P&&!R)return;const v=y.isRoot?m(I):I;for(const C of v)p(C,R?x:x+1,{},g)}if(r)for(const g of m(hr(e)))p(g,0,{},e);else p(e,0,{isRoot:!0});return d}function F5(e,t){const n=pt(t);if(!e||!n)return[];const r=[];function o(i){const s=Cs(i);if(r.push(s),s===n)return!0;for(const a of hr(i))if(o(a))return!0;return r.pop(),!1}return o(e)?r.slice(0,-1).filter(Boolean):[]}function z5(e){if(!e||typeof e.getSelection!="function")return null;try{return e.getSelection()}catch{return null}}function B5(e){if(!e||typeof e.rangeCount!="number"||typeof e.getRangeAt!="function")return[];const t=[];for(let n=0;nG5(a,o));if(!n?.write||typeof r!="function")throw new Error("Clipboard image copy is not supported in this browser");let s;try{s=new r({[o]:i})}catch{const a=await i,l=String(a.type||o).trim()||o;s=new r({[l]:a})}try{await n.write([s])}catch(a){throw i.catch(()=>{}),U5(a)}return await i}async function ps(e){const t=String(e??""),n=globalThis.navigator?.clipboard;let r=null;if(typeof n?.writeText=="function")try{await n.writeText(t);return}catch(o){r=o}if(!$5(t))throw r instanceof Error?r:new Error("Clipboard is unavailable")}async function tI(){const e=globalThis.navigator?.clipboard;if(typeof e?.readText!="function")throw new Error("Clipboard paste is unavailable");try{return await e.readText()}catch(t){throw W5(t)}}const H5="Download was blocked by the browser";function WR(e){return String(e||"").trim()}function K5(e){const t=WR(e);return t?`Downloading ${t}`:"Downloading file"}function X5(){const e=globalThis.document;if(!e||typeof e.createElement!="function")throw new Error("Downloads are not available in this browser");return e}function Y5(e){if(typeof e.click!="function")throw new Error("Downloads are not available in this browser");try{e.click()}catch(t){throw t instanceof Error?t:new Error(H5)}}function $S(e,{filename:t=""}={}){const n=String(e||"").trim();if(!n)throw new Error("No download URL is available");const r=X5(),o=r.createElement("a");o.href=n,o.rel="noopener";const i=WR(t);i&&(o.download=i),o.style&&(o.style.display="none"),r.body?.appendChild?.(o);try{Y5(o)}finally{r.body?.removeChild?.(o)}return{filename:i,message:K5(i),status:"requested"}}function nw(e,{filename:t=""}={}){if(!e||typeof e!="object")throw new Error("No download data is available");const n=globalThis.URL;if(typeof n?.createObjectURL!="function")throw new Error("Downloads are not available in this browser");const r=n.createObjectURL(e);try{return $S(r,{filename:t})}finally{const o=()=>{n.revokeObjectURL?.(r)};typeof globalThis.setTimeout=="function"?globalThis.setTimeout(o,1e3):o()}}function q5(e,{fieldName:t="camera vector",required:n=!1,nonZero:r=!1,strict:o=!0}={}){if(e==null){if(n&&o)throw new Error(`${t} must be a three-number array`);return null}if(!Array.isArray(e)||e.length<3){if(o)throw new Error(`${t} must be a three-number array`);return null}const i=[Number(e[0]),Number(e[1]),Number(e[2])];if(!i.every(Number.isFinite)){if(o)throw new Error(`${t} must contain only finite numbers`);return null}if(r&&i[0]**2+i[1]**2+i[2]**2<=1e-12){if(o)throw new Error(`${t} must not be the zero vector`);return null}return i}function Z5(e){return q5(e,{strict:!1})}function GS(e,t=1,{fieldName:n="camera.zoom",strict:r=!1}={}){if(e==null||e==="")return t;const o=Number(e);if(Number.isFinite(o)&&o>0)return o;if(r)throw new Error(`${n} must be a positive finite number`);return t}function ai(e){return String(e||"").trim()}const yo=Object.freeze({PERSPECTIVE:"perspective",ORTHOGRAPHIC:"orthographic"});function ul(e,t=yo.PERSPECTIVE){const n=String(e||"").trim().toLowerCase();return n===yo.ORTHOGRAPHIC?yo.ORTHOGRAPHIC:n===yo.PERSPECTIVE?yo.PERSPECTIVE:t===yo.ORTHOGRAPHIC?yo.ORTHOGRAPHIC:yo.PERSPECTIVE}function lx(e){return Z5(e)}function Bs(e){if(!e||typeof e!="object")return null;const t=lx(e.position),n=lx(e.target),r=lx(e.up);if(!t||!n||!r)return null;const o={position:t,target:n,up:r};Object.prototype.hasOwnProperty.call(e,"zoom")&&(o.zoom=GS(e.zoom,1)),Object.prototype.hasOwnProperty.call(e,"projection")&&(o.projection=ul(e.projection));const i=ai(e.modelKey),s=ai(e.sceneScaleMode),a=ai(e.coordinateSystem);return i&&(o.modelKey=i),s&&(o.sceneScaleMode=s),a&&(o.coordinateSystem=a),o}function J5(e,{modelKey:t="",sceneScaleMode:n="",coordinateSystem:r=""}={}){const o=Bs(e);if(!o)return null;const i=ai(t),s=ai(n),a=ai(r);return i&&(o.modelKey=i),s&&(o.sceneScaleMode=s),a&&(o.coordinateSystem=a),o}function nI(e,t){return Bs(typeof e<"u"?e:t)}function cx(e,t,n=1e-4){if(e===t)return!0;if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;for(let r=0;rn)return!1;return!0}function HR(e,t,n=1e-4){return e===t?!0:!e||!t?!e&&!t:cx(e.position,t.position,n)&&cx(e.target,t.target,n)&&cx(e.up,t.up,n)&&Math.abs(GS(e.zoom,1)-GS(t.zoom,1))<=n&&ul(e.projection)===ul(t.projection)&&ai(e.modelKey)===ai(t.modelKey)&&ai(e.sceneScaleMode)===ai(t.sceneScaleMode)&&ai(e.coordinateSystem)===ai(t.coordinateSystem)}function rI(e,{modelKey:t="",sceneScaleMode:n="",coordinateSystem:r="",requireModelKey:o=!1,requireSceneScaleMode:i=!1,requireCoordinateSystem:s=!1}={}){const a=Bs(e);if(!a)return!1;const l=ai(t);if(o&&l&&a.modelKey!==l||l&&a.modelKey&&a.modelKey!==l)return!1;const u=ai(n);if(i&&u&&a.sceneScaleMode!==u||u&&a.sceneScaleMode&&a.sceneScaleMode!==u)return!1;const d=ai(r);return!(s&&d&&a.coordinateSystem!==d||d&&a.coordinateSystem&&a.coordinateSystem!==d)}const si={NONE:"none",AUTO:"auto",ASSEMBLY:"assembly",PARTS:"parts"},Vb=Object.freeze(["x","y","z"]),Np=Object.freeze({x:0,y:0,z:0}),_p=Object.freeze({enabled:!1,axis:"x",offset:Np.x,offsets:Np,invert:!1}),oI=Object.freeze({x:0,y:1,z:2}),KR=1e-6;function $d(e,t){const n=Number(e);return Number.isFinite(n)?n:t}function XR(e,t,n){return Math.min(Math.max(e,t),n)}function Ws(e=null){const t=e&&typeof e=="object"?e:{},n=Vb.includes(String(t.axis||"").toLowerCase())?String(t.axis).toLowerCase():_p.axis,r=t.offsets&&typeof t.offsets=="object"?t.offsets:{},o=$d(t.offset,_p.offset),i=Object.fromEntries(Vb.map(u=>[u,XR($d(r[u],u===n?o:Np[u]),0,1)])),s=i[n],a=s>KR;return{enabled:(t.enabled===!0?!0:t.enabled===!1?!1:a)&&a,axis:n,offset:s,offsets:i,invert:t.invert===!0}}function Q5(e,t){const n=Ws(e),r=Ws(t);return n.enabled===r.enabled&&n.axis===r.axis&&Math.abs(n.offset-r.offset)<1e-6&&Vb.every(o=>Math.abs((n.offsets?.[o]??Np[o])-(r.offsets?.[o]??Np[o]))<1e-6)&&n.invert===r.invert}function YR(e){return oI[String(e||"").toLowerCase()]??oI.x}function qR(e,t){const n=YR(t),r=$d(e?.min?.[n],0),o=$d(e?.max?.[n],r);return r<=o?{min:r,max:o}:{min:o,max:r}}function eV(e,t){const n=Ws(t),{min:r,max:o}=qR(e,n.axis);return r+(o-r)*n.offset}function tV(e,t,n=1e-5){if(!e||!t||typeof e.distanceToPoint!="function")return!0;const r=Math.abs($d(n,1e-5));return e.distanceToPoint(t)>=-r}function nV(e,t){const n=Ws(e),r=t&&typeof t=="object"?t:{},o=Object.prototype.hasOwnProperty.call(r,"enabled"),i=Object.prototype.hasOwnProperty.call(r,"offset")||r.offsets&&typeof r.offsets=="object",s=Vb.includes(String(r.axis||"").toLowerCase())?String(r.axis).toLowerCase():n.axis,a={...n.offsets,...r.offsets&&typeof r.offsets=="object"?r.offsets:{}};Object.prototype.hasOwnProperty.call(r,"offset")&&(a[s]=r.offset);const l=XR($d(a[s],0),0,1);return Ws({...n,...r,...!o&&i?{enabled:l>KR}:{},axis:s,offsets:a,offset:a[s]})}const pr=Object.freeze({FREEHAND:"freehand",LINE:"line",SURFACE_LINE:"surface-line",ARROW:"arrow",DOUBLE_ARROW:"double-arrow",RECTANGLE:"rectangle",CIRCLE:"circle",FILL:"fill",ERASE:"erase"});function US(e,t,n){return Math.min(Math.max(e,t),n)}function bb(e,t,n){const r=n[0]-t[0],o=n[1]-t[1];if(Math.abs(r)<1e-9&&Math.abs(o)<1e-9)return Math.hypot(e[0]-t[0],e[1]-t[1]);const i=US(((e[0]-t[0])*r+(e[1]-t[1])*o)/(r*r+o*o),0,1),s=[t[0]+r*i,t[1]+o*i];return Math.hypot(e[0]-s[0],e[1]-s[1])}function ZR(e,t){let n=!1;for(let r=0,o=t.length-1;re[1]!=s[1]>e[1]&&e[0]<(s[0]-i[0])*(e[1]-i[1])/(s[1]-i[1]||1e-9)+i[0]&&(n=!n)}return n}function iI(e,t){const n=t.getBoundingClientRect(),r=n.width||1,o=n.height||1;return{x:US((e.clientX-n.left)/r,0,1),y:US((e.clientY-n.top)/o,0,1)}}function tl(e,t,n){return[e.x*t,e.y*n]}function rV(e,t,n){const r=Array.isArray(e?.points)?e.points:[];if(r.length<2)return 0;let o=0;for(let i=1;it&&Number.isFinite(t.x)&&Number.isFinite(t.y)):[]}function JR(e){return Array.isArray(e?.fillPoints)?e.fillPoints.filter(t=>t&&Number.isFinite(t.x)&&Number.isFinite(t.y)):[]}function ow(e){return e?.tool===pr.FILL}function QR(e){return e?.tool===pr.SURFACE_LINE&&!!e?.surfaceLine}function oV(e){return e?.tool===pr.RECTANGLE||e?.tool===pr.CIRCLE}function iw(e){return!!e&&e.tool!==pr.ERASE&&e.tool!==pr.FILL&&e.tool!==pr.SURFACE_LINE}function iV(e){return e===pr.LINE||e===pr.SURFACE_LINE||e===pr.ARROW||e===pr.DOUBLE_ARROW||e===pr.RECTANGLE||e===pr.CIRCLE}function sV(e,t,n,r){if(ow(t)){const l=tl(e,n,r),u=JR(t).map(m=>tl(m,n,r));if(u.length<3)return 1/0;if(ZR(l,u))return 0;let d=1/0;for(let m=0;mtl(l,n,r));if(s.length===1){const l=s[0];return Math.hypot(i[0]-l[0],i[1]-l[1])}if(t.tool===pr.RECTANGLE){const l=s[0],u=s[s.length-1],d=[[l[0],l[1]],[u[0],l[1]],[u[0],u[1]],[l[0],u[1]]];let m=1/0;for(let p=0;pt&&(t=o)}return t}function gV(e,t){return[[e[0],e[1]],[t[0],e[1]],[t[0],t[1]],[e[0],t[1]]]}function bV(e,t,n=56){const r=Math.hypot(t[0]-e[0],t[1]-e[1]);if(r<1e-4)return[e];const o=Math.max(n,12),i=[];for(let s=0;s<=o;s+=1){const a=s/o*Math.PI*2;i.push([e[0]+Math.cos(a)*r,e[1]+Math.sin(a)*r])}return i}function yV(e,t,n){const r=rw(e).map(o=>tl(o,t,n));if(r.length<2)return r;if(e.tool===pr.RECTANGLE){const o=gV(r[0],r[r.length-1]);return[...o,o[0]]}return e.tool===pr.CIRCLE?bV(r[0],r[r.length-1]):r}function uI(e,t,n,r){const o=n[0]-t[0],i=n[1]-t[1],s=Math.hypot(o,i);if(s<1)return;const a=o/s,l=i/s,u=Math.PI/7,d=Math.max(aV,r*3.25),m=Math.cos(u),p=Math.sin(u),g=[n[0]-d*(a*m-l*p),n[1]-d*(l*m+a*p)],x=[n[0]-d*(a*m+l*p),n[1]-d*(l*m-a*p)];e.beginPath(),e.moveTo(n[0],n[1]),e.lineTo(g[0],g[1]),e.moveTo(n[0],n[1]),e.lineTo(x[0],x[1]),e.stroke()}function xV(e,t,n){e.beginPath(),e.arc(t[0],t[1],n*.65,0,Math.PI*2),e.fill()}function SV(e,t){e.beginPath(),t.forEach((n,r)=>{if(r===0){e.moveTo(n[0],n[1]);return}e.lineTo(n[0],n[1])}),e.stroke()}function EV(e,t,n){const r=Math.min(t[0],n[0]),o=Math.min(t[1],n[1]),i=Math.abs(n[0]-t[0]),s=Math.abs(n[1]-t[1]);e.strokeRect(r,o,i,s)}function wV(e,t,n){const r=Math.hypot(n[0]-t[0],n[1]-t[1]);e.beginPath(),e.arc(t[0],t[1],r,0,Math.PI*2),e.stroke()}function vV(e,t,n,r,{color:o,alpha:i=1}){const s=JR(t);if(s.length<3)return;const a=s.map(l=>tl(l,n,r));e.save(),e.globalAlpha=i,e.fillStyle=o,e.beginPath(),a.forEach((l,u)=>{if(u===0){e.moveTo(l[0],l[1]);return}e.lineTo(l[0],l[1])}),e.closePath(),e.fill(),e.restore()}function zm(e,t,n,r,{color:o,lineWidth:i,alpha:s=1}){if(ow(t))return;const a=rw(t);if(!a.length)return;const l=a.map(u=>tl(u,n,r));if(e.save(),e.globalAlpha=s,e.strokeStyle=o,e.fillStyle=o,e.lineCap="round",e.lineJoin="round",e.lineWidth=i,l.length===1){xV(e,l[0],i),e.restore();return}if(t.tool===pr.RECTANGLE){EV(e,l[0],l[l.length-1]),e.restore();return}if(t.tool===pr.CIRCLE){wV(e,l[0],l[l.length-1]),e.restore();return}SV(e,l),(t.tool===pr.ARROW||t.tool===pr.DOUBLE_ARROW)&&uI(e,l[l.length-2],l[l.length-1],i),t.tool===pr.DOUBLE_ARROW&&uI(e,l[1],l[0],i),e.restore()}function CV(e,t){if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(e,t);const n=document.createElement("canvas");return n.width=e,n.height=t,n}function MV(e,t,n){if(!iw(e)||oV(e))return[];const r=yV(e,t,n);if(r.length<2)return[];const o=e?.tool===pr.FREEHAND&&r.length>2;return[{strokeId:String(e?.id||""),point:r[0],allowSelfConnect:o},{strokeId:String(e?.id||""),point:r[r.length-1],allowSelfConnect:o}]}function IV(e,t){if(!Array.isArray(e)||e.length<2||t<=0)return[];const n=[];for(let i=0;ii.distance-s.distance);const r=new Set,o=[];for(const i of n)r.has(i.leftIndex)||r.has(i.rightIndex)||(r.add(i.leftIndex),r.add(i.rightIndex),o.push([e[i.leftIndex].point,e[i.rightIndex].point]));return o}function dI(e,t,n,{gapPx:r=0,lineWidth:o=$b}={}){const s=CV(t,n).getContext("2d",{willReadFrequently:!0});if(!s)return null;s.clearRect(0,0,t,n);const a=Array.isArray(e)?e.filter(iw):[];for(const d of a)zm(s,d,t,n,{color:"#000000",lineWidth:o,alpha:1});if(r>0){const d=IV(a.flatMap(m=>MV(m,t,n)),Math.max(r,o*1.15));if(d.length){s.save(),s.strokeStyle="#000000",s.lineWidth=o,s.lineCap="round";for(const[m,p]of d)s.beginPath(),s.moveTo(m[0],m[1]),s.lineTo(p[0],p[1]),s.stroke();s.restore()}}const{data:l}=s.getImageData(0,0,t,n),u=new Uint8Array(t*n);for(let d=0;d20?1:0;return u}function n2(e,t,n,r,o,i=5){const s=Gd(Math.round(r),0,t-1),a=Gd(Math.round(o),0,n-1);for(let l=0;l<=i;l+=1){let u=null,d=1/0;for(let m=-l;m<=l;m+=1)for(let p=-l;p<=l;p+=1){const g=s+p,x=a+m;if(g<0||x<0||g>=t||x>=n||e[x*t+g])continue;const y=Math.hypot(p,m);y0){const y=p-1;!e[y]&&!i[y]&&(i[y]=1,s[l++]=y)}if(g+10){const y=p-t;!e[y]&&!i[y]&&(i[y]=1,s[l++]=y)}if(x+11&&Gb(t[0],t[t.length-1])&&t.pop(),t}function sw(e){const t=r2(e);if(t.length<3)return t;const n=[];for(let r=0;r1e-4&&n.push(i)}return n.length>=3?n:t}function o2(e,t=160){if(e.length<=t)return e;const n=e.length/t,r=[];let o=0;for(let i=0;i{const d=r.length;r.push([l,u]);const m=fI(l),p=o.get(m);if(p){p.push(d);return}o.set(m,[d])};for(let l=0;l!s[y])??-1,m+=1}if(u.length>=4&&Gb(u[0],u[u.length-1])){const p=sw(u.slice(0,-1));p.length>=3&&a.push(p)}}return a}function i2(e,t,n){return e.map(r=>({x:Gd(r[0]/t,0,1),y:Gd(r[1]/n,0,1)}))}function _V(e,t,n,r){const o=NV(e,t,n);if(!o.length)return null;const i=[r[0]+.5,r[1]+.5],s=o.filter(d=>ZR(i,d)),l=(s.length?s:o).reduce((d,m)=>d?Math.abs(WS(m))>Math.abs(WS(d))?m:d:m,null);if(!l)return null;const u=o2(sw(l));return u.length>=3?i2(u,t,n):null}function mI(e,t,n){for(let r=1;rnull);for(let y=0;y=t||P>=n)break;if(e[P*t+N]){s[y]=Math.max(A-1.5,1);break}}}const a=s.filter(Number.isFinite);if(a.lengthy-S),u=l[Math.floor(l.length/2)]||1;let m=s.map((y,S)=>{if(Number.isFinite(y))return y;const b=mI(s,S,-1),I=mI(s,S,1);if(b&&I){const A=b.offset+I.offset;return(b.value*I.offset+I.value*b.offset)/Math.max(A,1)}return b?b.value:I?I.value:u});for(let y=0;y<2;y+=1)m=m.map((S,b)=>{const I=m[(b+m.length-1)%m.length],A=m[(b+1)%m.length];return(I+S*2+A)/4});const p=m.map((y,S)=>{const b=S/nd*Math.PI*2;return[Gd(o[0]+Math.cos(b)*y,0,t),Gd(o[1]+Math.sin(b)*y,0,n)]}),g=o2(sw(p),nd);if(g.length<3)return null;const x=Math.abs(WS(g));return xt*n*t2?null:i2(g,t,n)}function RV(e,t,n){const r=Array.isArray(t)?t.filter(iw):[];if(!r.length)return null;const o=n.width||1,i=n.height||1,s=Math.max(o,i,1),a=Math.min(1,mV/s),l=Math.max(cI,Math.round(o*a)),u=Math.max(cI,Math.round(i*a)),d=[e.x*(l-1),e.y*(u-1)],m=Math.max(3,$b*a+3),p=[{gapPx:0,guessed:!1},{gapPx:ux*.45*a,guessed:!0},{gapPx:ux*a,guessed:!0}];for(const y of p){const S=dI(r,l,u,{gapPx:y.gapPx,lineWidth:m});if(!S)continue;const b=AV(S,l,u,d);if(!b||b.areal*u*t2)continue;const I=_V(b.mask,l,u,b.seed);if(I?.length>=3)return{tool:pr.FILL,points:[e],fillPoints:I,guessed:y.guessed}}const g=dI(r,l,u,{gapPx:ux*a,lineWidth:m});if(!g)return null;const x=TV(g,l,u,d);return!x?.length||x.length<3?null:{tool:pr.FILL,points:[e],fillPoints:x,guessed:!0}}function pI(e,t,n=null){if(!e)return;const r=e.getContext("2d");if(!r)return;const o=e.width,i=e.height;r.clearRect(0,0,o,i);const s=Array.isArray(t)?t:[];for(const a of s)ow(a)&&vV(r,a,o,i,{color:a?.guessed?fV:dV,alpha:1});for(const a of s)QR(a)||(zm(r,a,o,i,{color:aI,lineWidth:lI}),zm(r,a,o,i,{color:sI,lineWidth:$b}));n&&(zm(r,n,o,i,{color:aI,lineWidth:lI,alpha:.78}),zm(r,n,o,i,{color:sI,lineWidth:$b,alpha:.9}))}const PV=5e5;function OV(e,t=1){return(Array.isArray(e)||ArrayBuffer.isView(e))&&e.length>=t&&e.length%t===0}function kV(e,{triangleLimit:t=PV}={}){return OV(e?.edge_indices,2)?!0:Math.floor((e?.indices?.length||0)/3)<=t}function DV({edgesVisible:e=!1,topologyDisplayEdgesVisible:t=!1,displayEdgesVisible:n=!1,wireframeMode:r=!1}={}){return!!(e&&!t&&(n||r))}const Dt=Object.freeze({HIDDEN_EDGES:"hidden_edges",HIDDEN_LINES_REMOVED:"hidden_lines_removed",RENDERED:"rendered",SOLID:"solid",TRANSPARENT:"transparent",UNSHADED:"unshaded",WIREFRAME:"wireframe"}),jV=Object.freeze(Object.values(Dt)),LV=Object.freeze(["x","y","z","radial"]),HS=8,FV=/^#(?:[0-9a-fA-F]{3}){1,2}$/,Vs="#132232",aw="#8dc5ff",zV=Object.freeze(["feature","tangent","seam","degenerate"]),KS=Object.freeze({feature:Object.freeze({color:Vs,opacity:1,thickness:1.15}),tangent:Object.freeze({color:Vs,opacity:.5,thickness:1.15}),seam:Object.freeze({color:Vs,opacity:.85,thickness:1.15}),degenerate:Object.freeze({color:Vs,opacity:1,thickness:0})}),Vy=Object.freeze({enabled:!0,contrastMode:"manual",color:Vs,thickness:1,classes:KS,highlightColor:aw,highlightOpacity:1,highlightThickness:3,silhouette:!1,silhouetteScale:0}),BV=Object.freeze({...Vy,enabled:!1}),ba=Object.freeze({enabled:!1,axis:"z",direction:"positive",spacing:1.45,depth:1,keepBaseGrounded:!0,mergeCoplanar:!1,autoFrame:!0}),VV=Object.freeze({projection:yo.ORTHOGRAPHIC,mode:Dt.SOLID,clip:_p,exploded:ba,edges:Vy});function hu(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function s2(e,t,n){return Math.min(Math.max(e,t),n)}function Qc(e,t,n=-1/0,r=1/0){const o=Number(e);return Number.isFinite(o)?s2(o,n,r):t}function Ub(e,t){const n=String(e||"").trim();return FV.test(n)?n.length===4?`#${n[1]}${n[1]}${n[2]}${n[2]}${n[3]}${n[3]}`.toLowerCase():n.toLowerCase():t}function Ed(e,t=!1){return typeof e=="boolean"?e:t}function $V(e,t="manual"){const n=String(e||"").trim().toLowerCase();return["auto","manual"].includes(n)?n:t}function GV(e={},t=KS,n=Vs){const r=hu(e)?e:{},o=Ub(n,Vs);return Object.fromEntries(zV.map(i=>{const s=hu(r[i])?r[i]:{},a=t?.[i]||KS[i],l=s.enabled===!1;return[i,{color:Ub(s.color,o),opacity:Qc(s.opacity,a.opacity,0,1),thickness:l?0:Qc(s.thickness,a.thickness,0,6)}]}))}function Ql(e=null,t=Vy){const n=hu(e)?e:{},r=Ub(n.color,t.color),o={enabled:Ed(n.enabled,t.enabled),contrastMode:$V(n.contrastMode,t.contrastMode),color:r,thickness:Qc(n.thickness,t.thickness,.5,6),classes:GV(n.classes,t.classes,r),highlightColor:Ub(n.highlightColor,t.highlightColor||aw),highlightOpacity:Qc(n.highlightOpacity,t.highlightOpacity||1,0,1),highlightThickness:Qc(n.highlightThickness,t.highlightThickness||3,.5,6),silhouette:Ed(n.silhouette,t.silhouette||!1),silhouetteScale:Qc(n.silhouetteScale,t.silhouetteScale||0,0,.04)};return typeof n.depthTest=="boolean"&&(o.depthTest=n.depthTest),o}function UV(e){return String(e||"").trim().toLowerCase().replace(/\s+/g,"_").replace(/-/g,"_")}function Ys(e){const t=UV(e);return t?t==="wire"||t==="wire_frame"?Dt.WIREFRAME:t==="edges"||t==="edge"||t==="shaded_edges"||t==="shaded_with_edges"||t==="with_edges"?Dt.SOLID:t==="shaded"||t==="shaded_without_edges"||t==="without_edges"?Dt.RENDERED:t==="translucent"||t==="xray"||t==="x_ray"||t==="see_through"?Dt.TRANSPARENT:t==="hidden_edge"||t==="hidden_edges_visible"||t==="hidden_edge_display"||t==="shaded_hidden_edges"?Dt.HIDDEN_EDGES:t==="visible_edges"||t==="visible_edges_only"||t==="hidden_lines"||t==="hidden_line_removed"||t==="hidden_lines_removed"||t==="hidden_edges_removed"?Dt.HIDDEN_LINES_REMOVED:t==="flat"?Dt.UNSHADED:t==="appearance"||t==="material"||t==="materials"?Dt.RENDERED:jV.includes(t)?t:Dt.SOLID:Dt.SOLID}function WV(e,t=ba.axis){const n=String(e||"").trim().toLowerCase(),r=n.startsWith("-")?n.slice(1):n;return LV.includes(r)?r:t}function HV(e,t=ba.direction){const n=String(e).trim().toLowerCase();return["negative","reverse","down","backward","-","-1"].includes(n)?"negative":["positive","forward","up","+","+1","1"].includes(n)?"positive":t}function KV(e,t=ba.depth){const n=String(e??"").trim().toLowerCase();if(["all","full","parts","leaves","leaf"].includes(n))return HS;const r=Math.round(Number(e));return Number.isFinite(r)?s2(r,1,HS):t}function Wb(e=null,t={}){const n=hu(e)?e:{},r=hu(t)?{...n,...t}:n,o=String(r.axis||"").trim().toLowerCase();return{enabled:Ed(r.enabled,ba.enabled),axis:WV(r.axis),direction:HV(r.direction||(o.startsWith("-")?"negative":"positive")),spacing:Qc(r.spacing??r.distance??r.distanceScale,ba.spacing,.25,4),depth:KV(r.depth??r.levels??r.scopeDepth),keepBaseGrounded:Ed(r.keepBaseGrounded??r.groundBase,ba.keepBaseGrounded),mergeCoplanar:Ed(r.mergeCoplanar??r.mergeLayers??r.coalesceLayers,ba.mergeCoplanar),autoFrame:Ed(r.autoFrame,ba.autoFrame)}}function So(e=null){const t=hu(e)?e:{},n={};return hu(t.exploded)&&t.exploded.enabled!==void 0&&(n.enabled=t.exploded.enabled),{projection:ul(t.projection,VV.projection),mode:Ys(t.mode),clip:Ws(t.clip),exploded:Wb(t.exploded,n),edges:Ql(t.edges)}}function XV(e,t){const n=So(e),r=So(t);return n.projection===r.projection&&n.mode===r.mode&&Q5(n.clip,r.clip)&&JSON.stringify(n.exploded)===JSON.stringify(r.exploded)&&JSON.stringify(n.edges)===JSON.stringify(r.edges)}function a2(e){return So(e).edges}function ml(e){return Ys(e)===Dt.WIREFRAME}function $y(e){return[Dt.SOLID,Dt.TRANSPARENT,Dt.HIDDEN_EDGES,Dt.HIDDEN_LINES_REMOVED].includes(Ys(e))}function YV(e){return![Dt.RENDERED,Dt.UNSHADED].includes(Ys(e))}function qV(e,t=null){const n=Ys(e);return n===Dt.WIREFRAME||$y(n)}function Gy(e){return[Dt.TRANSPARENT,Dt.HIDDEN_EDGES].includes(Ys(e))}function ZV(e){return[Dt.TRANSPARENT,Dt.HIDDEN_LINES_REMOVED,Dt.WIREFRAME].includes(Ys(e))}function JV(e){return[Dt.UNSHADED,Dt.HIDDEN_LINES_REMOVED,Dt.WIREFRAME].includes(Ys(e))}function Hb(e,t=1){const n=Ys(e);if(n===Dt.WIREFRAME)return .035;if(n===Dt.TRANSPARENT)return .22;if(n===Dt.HIDDEN_LINES_REMOVED)return .045;const r=Number(t);return Number.isFinite(r)?r:1}function QV(e){return e instanceof Float32Array}function lw(e){return e instanceof Uint32Array}function xa(e,t){return Math.hypot(Number(t?.[0]||0)-Number(e?.[0]||0),Number(t?.[1]||0)-Number(e?.[1]||0),Number(t?.[2]||0)-Number(e?.[2]||0))}function e$(e){const t=[1/0,1/0,1/0],n=[-1/0,-1/0,-1/0];for(const r of e)for(let o=0;o+2=e.edgePositions.length?null:[e.edgePositions[n],e.edgePositions[n+1],e.edgePositions[n+2]]}function Xb(e){return new Set((Array.isArray(e)?e:[e]).map(t=>String(t||"").trim()).filter(Boolean))}function l2(e){const t=(Array.isArray(e)?e:[e]).map(n=>String(n||"").trim().toLowerCase()).filter(Boolean);return t.length?new Set(t):null}function n$(e,t){const n=String(e||"").trim();if(!n||!t?.size)return!1;for(const r of t)if(n===r||n.startsWith(`${r}.`))return!0;return!1}function hI(e,t){return n$(e?.occurrenceId||e?.partId||e?.id,t)}function r$(e,t,n){return!(t.size&&!hI(e,t)||n.size&&hI(e,n))}function o$(e,t){if(!t?.size)return!0;const n=String(e?.visibilityClass||"feature").trim().toLowerCase()||"feature";return t.has(n)}function c2(e,t,n,r){return r$(e,t,n)&&o$(e,r)}function XS(e,t,n=1e-7){if(!t)return;const r=e.length>=3?[e[e.length-3],e[e.length-2],e[e.length-1]]:null;(!r||xa(r,t)>n)&&e.push(t[0],t[1],t[2])}function YS(e,t,n){const r=[];let o=[],i=null;for(let s=t;s1e-5&&(o.length>=6&&r.push(new Float32Array(o)),o=[],i=null),i||XS(o,u),XS(o,d),i=d)}return o.length>=6&&r.push(new Float32Array(o)),r}function i$(e,t,n,r){const o=[];let i=-1,s=0;const a=()=>{i>=0&&s>0&&o.push(...YS(e,i,s)),i=-1,s=0};for(let l=0;l=0;n-=3)t.push(e[n],e[n+1],e[n+2]);return t}function vg(e,t,{skipFirst:n=!0,tolerance:r=1e-7}={}){const o=n?3:0;for(let i=o;i+2t)return e;const o=Array.from(e);return o[o.length-3]=o[0],o[o.length-2]=o[1],o[o.length-1]=o[2],new Float32Array(o)}function bI(e){if(!Array.isArray(e)||e.length<=1)return e||[];const t=t$(e),n=e.filter(r=>r?.length>=6).map(r=>Array.from(r));for(let r=0;rr.length>=6).map(r=>s$(new Float32Array(r),t))}function cw(e){const t=e?.proxy||{};return QV(t.edgePositions)&&lw(t.edgeIndices)&&t.edgePositions.length>=6&&t.edgeIndices.length>=2}function a$(e){return!e?.surfaceEdgeRendering&&Number(e?.schemaVersion||0)<3&&cw(e)}function yI(e,{includePartIds:t=[],excludePartIds:n=[],visibilityClasses:r=null}={}){if(!cw(e))return null;const o=e.proxy,i=Math.floor(o.edgeIndices.length/2);if(i<=0)return null;const s=Xb(t),a=Xb(n),l=s.size>0||a.size>0,u=l2(r),d=Array.isArray(e.edges)?e.edges:[],m=!!(u?.size&&d.length),p=l||m,g=lw(o.edgeIds)?o.edgeIds:null,x=new Float32Array(i*6);let y=0;const S=b=>{const I=Number(o.edgeIndices[b*2]),A=Number(o.edgeIndices[b*2+1]),N=Kb(o,I),P=Kb(o,A);!N||!P||xa(N,P)<=1e-10||(x[y]=N[0],x[y+1]=N[1],x[y+2]=N[2],x[y+3]=P[0],x[y+4]=P[1],x[y+5]=P[2],y+=6)};if(p){if(!d.length)return null;for(let b=0;b=0&&N>0&&A+N<=i){for(let P=A;P0||u.size>0,m=l2(r),p=!!(m?.size&&s.length),g=d||p,x=[];if(s.length){for(let y=0;y=0&&I>0&&b+I<=i?x.push(...YS(o,b,I)):a&&x.push(...i$(o,a,y,i))}return bI(x)}if(g)return[];for(let y=0;yString(t||"").trim()).filter(Boolean)}function x$(e,t=[]){const n=String(e||"").trim();return!n||!t.length?!1:t.some(r=>n===r||n.startsWith(`${r}.`))}function xI(e,t=[]){return x$(e?.occurrenceId||e?.partId||e?.id,t)}function S$(e,{includePartIds:t=[],excludePartIds:n=[],visibilityClasses:r=[]}={}){if(t.length&&!xI(e,t)||n.length&&xI(e,n))return!1;if(r.length){const o=String(e?.visibilityClass||"feature").trim().toLowerCase()||"feature";if(!r.includes(o))return!1}return!0}function E$(e,t={}){const n=Array.isArray(e?.edges)?e.edges:[];if(!n.length)return!1;let r=0,o=0;for(const i of n){if(!S$(i,t))continue;const s=Number.isFinite(Number(i?.segmentCount))?Math.max(1,Number(i.segmentCount)):1;if(r+=1,o+=(s+1)*3,r>f2||o>m2)return!1}return r>0}function w$(e,t=d2){const n=(Array.isArray(e)?e:[e]).map(r=>String(r||"").trim().toLowerCase()).filter(Boolean);return n.length?n:t}function SI(e,t){const n=String(e||"").trim();return g$.test(n)?n.length===4?`#${n[1]}${n[1]}${n[2]}${n[2]}${n[3]}${n[3]}`.toLowerCase():n.toLowerCase():t}function v$(e={},t={},n=d2){const r=e?.classes&&typeof e.classes=="object"?e.classes:null,o=r?[]:w$(e?.visibilityClasses,n),i=Number.isFinite(Number(e?.opacity))?Xo(Number(e.opacity),0,1):t?.edgeOpacity??.84,s=Number.isFinite(Number(e?.thickness))?Xo(Number(e.thickness),.5,6):t?.edgeThickness??1,a=SI(e?.color,t?.edge||"#18181b");return r?h$.map(l=>{const u=r[l]||fx[l],d=Number.isFinite(Number(u.opacity))?Xo(Number(u.opacity),0,1):fx[l].opacity,m=Number.isFinite(Number(u.thickness))?Xo(Number(u.thickness),0,6):fx[l].thickness,p=SI(u.color,a);return m<=0||d<=0?null:{classId:l,color:p,opacity:d,thickness:m}}).filter(Boolean):o.map(l=>({classId:l,color:a,opacity:i,thickness:s}))}function C$(e){return Array.isArray(e?.edges)&&e.edges.some(t=>String(t?.visibilityClass||"").trim())}function iu(e={},t,{color:n,opacity:r=1,lineWidth:o=1,renderOrder:i=3,depthTest:s=!0,depthWrite:a=!1,depthBias:l=af}={},u=null){const d=e.LineSegments2,m=e.LineSegmentsGeometry,p=e.LineMaterial;if(!d||!m||!p||!(Array.isArray(t)||ArrayBuffer.isView(t))||!t.length)return null;const g=new m;g.setPositions(t);const x=b2(p,{color:n,opacity:r,lineWidth:o,depthTest:s,depthWrite:a,depthBias:l});h2(e,x,u);const y=new d(g,x);return y.renderOrder=i,y.frustumCulled=!1,y.userData.beforeDispose=()=>{g2(e,x,u)},y.userData.disposeGeometry=!0,y.userData.disposeMaterial=!0,y}function b2(e,{color:t,opacity:n=1,lineWidth:r=1,depthTest:o=!0,depthWrite:i=!1,depthBias:s=af}={}){const a=new e({color:t,linewidth:r,opacity:n,depthTest:o,depthWrite:i,toneMapped:!1,worldUnits:!1});return p2(a,n),uw(a,s),a}function uw(e,t=af){const n=Xo(Number(t)||0,0,.01);return!e||n<=0||(e.polygonOffset=!0,e.polygonOffsetFactor=0,e.polygonOffsetUnits=-Xo(Math.round(n*1e3),1,10),e.needsUpdate=!0),e}function EI(e={},t,{color:n,opacity:r=1,lineWidth:o=1,renderOrder:i=3,depthTest:s=!0,depthWrite:a=!1,depthBias:l=af}={},u=null){const d=e.Line2,m=e.LineGeometry,p=e.LineMaterial;if(!d||!m||!p||!(Array.isArray(t)||ArrayBuffer.isView(t))||t.length<6)return null;const g=new m;g.setPositions(t);const x=b2(p,{color:n,opacity:r,lineWidth:o,depthTest:s,depthWrite:a,depthBias:l});h2(e,x,u);const y=new d(g,x);return y.renderOrder=i,y.frustumCulled=!1,y.userData.beforeDispose=()=>{g2(e,x,u)},y.userData.disposeGeometry=!0,y.userData.disposeMaterial=!0,y}function wI(e={},t,{color:n,opacity:r=1,lineWidth:o=1,renderOrder:i=3,depthTest:s=!0,depthWrite:a=!1,depthBias:l=af}={}){const u=e.THREE;if(!u||!(Array.isArray(t)||ArrayBuffer.isView(t))||t.length<6)return null;const d=new u.BufferGeometry,m=t instanceof Float32Array?t:new Float32Array(t);d.setAttribute("position",new u.BufferAttribute(m,3));const p=new u.LineBasicMaterial({color:n,linewidth:Number.isFinite(Number(o))?Number(o):1,transparent:Number(r)<.999,opacity:Xo(Number(r)||0,0,1),depthTest:s,depthWrite:a,toneMapped:!1});uw(p,l);const g=new u.Line(d,p);return g.renderOrder=i,g.frustumCulled=!1,g.userData.disposeGeometry=!0,g.userData.disposeMaterial=!0,g}function M$(e={},t,{color:n,opacity:r=1,renderOrder:o=3,depthTest:i=!0,depthWrite:s=!1,depthBias:a=af}={}){const l=e.THREE;if(!l||!(Array.isArray(t)||ArrayBuffer.isView(t))||t.length<6)return null;const u=new l.BufferGeometry,d=t instanceof Float32Array?t:new Float32Array(t);u.setAttribute("position",new l.BufferAttribute(d,3));const m=new l.LineBasicMaterial({color:n,transparent:Number(r)<.999,opacity:Xo(Number(r)||0,0,1),depthTest:i,depthWrite:s,toneMapped:!1});uw(m,a);const p=new l.LineSegments(u,m);return p.renderOrder=o,p.frustumCulled=!1,p.userData.disposeGeometry=!0,p.userData.disposeMaterial=!0,p}function I$(e,t,n,r=null){const o=b$(t);return o?iu(e,o,n,r):null}function A$(e={},{geometry:t,edgeSettings:n,baseTheme:r,partId:o,displayMode:i,thickness:s,wireframeEdgeColor:a=""},l=null){const u=e.THREE,d=ml(i),m=n?.depthTest!==!1,p=Number.isFinite(Number(n?.opacity))?Xo(Number(n.opacity),0,1):r?.edgeOpacity??.84,g=d?a||n?.color||r?.edge||"#18181b":n?.color||r?.edge||"#18181b";if(d&&u){const y=Math.max(p,.9),S=new u.LineBasicMaterial({color:g,transparent:y<.999,opacity:y,depthTest:!1,depthWrite:!1,toneMapped:!1}),b=new u.LineSegments(t,S);return b.renderOrder=4,b.frustumCulled=!1,b.userData.partId=o,{edgeMesh:b,edgeMaterial:S}}const x=I$(e,t,{color:g,opacity:p,lineWidth:Number.isFinite(Number(s))?Number(s):1,renderOrder:3,depthTest:m,depthWrite:!1,depthBias:Yb(s)},l);return x?(x.userData.partId=o,{edgeMesh:x,edgeMaterial:x.material}):{edgeMesh:null,edgeMaterial:null}}function dw(e={},t,n,r,o=null){const i=Cg(n?.includePartIds),s=Cg(n?.excludePartIds),a=Cg(n?.focusedPartIds),l=Cg(n?.highlightPartIds),u=v$(n,r).filter(v=>v.classId==="feature"||C$(t)),d=u.map(v=>v.classId),m=Number.isFinite(Number(n?.opacity))?Xo(Number(n.opacity),0,1):r?.edgeOpacity??.84,p=Number.isFinite(Number(n?.highlightOpacity))?Xo(Number(n.highlightOpacity),0,1):m,g=Number.isFinite(Number(n?.dimmedOpacity))?Xo(Number(n.dimmedOpacity),0,1):m,x=Number.isFinite(Number(n?.thickness))?Xo(Number(n.thickness),.5,6):r?.edgeThickness??1,y={color:n?.color||r?.edge||"#18181b",lineWidth:x,renderOrder:3,depthTest:n?.depthTest!==!1,depthWrite:!1,depthBias:Yb(x)},S=(v,C)=>iu(e,v,C,o)||M$(e,v,C),b=(v,C={})=>(Number.isFinite(Number(C.lineWidth))?Number(C.lineWidth):1)<=1.05?wI(e,v,C)||EI(e,v,C,o):EI(e,v,C,o)||wI(e,v,C),I=v=>{const C=v.filter(Boolean);if(!C.length)return null;if(C.length===1)return C[0];const T=e.THREE?new e.THREE.Group:null;if(!T)return C[0];for(const k of C)T.add(k);return T},A=(v,C)=>{if(!e.THREE||!Array.isArray(v)||!v.length)return null;const T=v.reduce((k,z)=>k+(z?.length||0),0);return v.length>f2||T>m2?null:I(v.map(k=>b(k,C)))},N=(v,C={})=>{const T=Number.isFinite(Number(C.lineWidth))?Number(C.lineWidth):v.thickness,k={includePartIds:C.includePartIds||i,excludePartIds:C.excludePartIds||s,visibilityClasses:[v.classId]},z={...y,...C,color:C.color||v.color||y.color,lineWidth:T,opacity:Number.isFinite(Number(C.opacity))?C.opacity:v.opacity,depthBias:Number.isFinite(Number(C.depthBias))?C.depthBias:Yb(T,{visibilityClass:v.classId})},Y=E$(t,k)?l$(t,k):[],K=A(Y,z);if(K)return K;const J=yI(t,{...k});return J?.length?S(J,z):null};if(l.length){const v=yI(t,{includePartIds:l,visibilityClasses:d});if(!v?.length)return null;const C=S(v,{...y,color:n?.highlightColor||y.color,opacity:p,depthBias:Number.isFinite(Number(n?.highlightDepthBias))?Xo(Number(n.highlightDepthBias),0,.01):0,renderOrder:Number.isFinite(Number(n?.highlightRenderOrder))?Number(n.highlightRenderOrder):26});return C&&(C.name="TopologyDisplayEdgeHighlights",C.userData.partId="__topology_highlight__"),C}if(a.length&&e.THREE){const v=new e.THREE.Group;for(const C of u){const T=N(C,{excludePartIds:a,opacity:Math.min(g,C.opacity),renderOrder:3}),k=N(C,{includePartIds:a,opacity:C.opacity,renderOrder:4});T&&v.add(T),k&&v.add(k)}return v.children.length?(v.name="TopologyDisplayEdges",v.userData.partId="__topology__",v):null}const P=u.map(v=>N(v)),R=I(P);return R?(R.name="TopologyDisplayEdges",R.userData.partId="__topology__",R):null}const ql=100,Zl=50,N$="#38bdf8",_$="#1e3a8a",T$="#bae6fd",R$=3.25,P$=.155,O$=.238;function yb(e,t,n){return Math.min(Math.max(e,t),n)}function k$(e){const t=Array.isArray(e?.center)?e.center:[0,0,0],n=[Number(t[0]),Number(t[1]),Number(t[2])];return n.every(Number.isFinite)?n:[0,0,0]}function D$(e,t){if(!e?.THREE||!e?.modelGroup)return null;const{THREE:n}=e;e.modelGroup.updateMatrixWorld(!0);const r=e.controls?.target;if(r&&Number.isFinite(r.x)&&Number.isFinite(r.y)&&Number.isFinite(r.z))return r.clone();const o=k$(t),i=new n.Vector3(...o);return e.modelGroup.localToWorld(i),i}function Hs(e,t){if(!e?.THREE||!e?.camera||!e?.modelGroup)return null;const n=D$(e,t);if(!n)return null;const r=e.modelGroup.worldToLocal(n.clone()),o=[r.x,r.y,r.z],i=e.camera.position.distanceTo(n),s=Math.max(Number(e.modelRadius||0),.08),a=Math.max(s*.12,.025),l=Math.max(s*3.2,a*3),u=yb(i*O$,a,l),d=i>1e-4?Math.min(u,i*.92):u;return{centerLocal:o,centerWorld:n,radius:d}}function y2(e,t,n=e?.raycaster?.ray){if(!e?.THREE||!e?.modelGroup||!n)return null;const r=Hs(e,t);if(!r)return null;const{THREE:o}=e,i=new o.Vector3,s=new o.Sphere(r.centerWorld,r.radius);if(!n.intersectSphere(s,i))return null;const a=e.modelGroup.worldToLocal(i.clone());return{point:[a.x,a.y,a.z],source:"sphere"}}function j$(e,t,n){if(!e?.THREE||!e?.camera||!n)return null;const{THREE:r}=e,o=new r.Vector3;e.camera.getWorldPosition(o);const s=new r.Vector3(Number(n.x)||0,Number(n.y)||0,.5).unproject(e.camera).sub(o).normalize();return y2(e,t,new r.Ray(o,s))}function Ud(e){return e?`${e.x}:${e.y}`:""}function fc(e){return e&&Number.isInteger(e.x)&&Number.isInteger(e.y)&&e.x>=0&&e.x=0&&e.y{t.push(o.x,o.y,o.z)};for(let o=1;os.multiplyScalar(r)),i=new n.BufferGeometry;return i.setAttribute("position",new n.BufferAttribute(new Float32Array([o[0].x,o[0].y,o[0].z,o[1].x,o[1].y,o[1].z,o[2].x,o[2].y,o[2].z,o[0].x,o[0].y,o[0].z,o[2].x,o[2].y,o[2].z,o[3].x,o[3].y,o[3].z]),3)),i.computeVertexNormals(),i}function Sb(e,t){if(!e?.THREE||!fc(t))return null;const{THREE:n}=e,r=1.0045,o=[ec(n,t,0,0),ec(n,t,1,0),ec(n,t,1,1),ec(n,t,0,1)].map(i=>i.multiplyScalar(r));return new Float32Array([o[0].x,o[0].y,o[0].z,o[1].x,o[1].y,o[1].z,o[1].x,o[1].y,o[1].z,o[2].x,o[2].y,o[2].z,o[2].x,o[2].y,o[2].z,o[3].x,o[3].y,o[3].z,o[3].x,o[3].y,o[3].z,o[0].x,o[0].y,o[0].z])}function z$(e,t){const n=Hs(e,t);if(!e?.THREE||!n)return null;const{THREE:r}=e,o=F$(r),i=new r.LineBasicMaterial({color:N$,transparent:!0,opacity:P$,depthTest:!1,depthWrite:!1,toneMapped:!1}),s=new r.LineSegments(o,i);return s.position.set(...n.centerLocal),s.scale.setScalar(n.radius),s.renderOrder=28,s.frustumCulled=!1,s.onBeforeRender=()=>{const a=Hs(e,t);a&&(s.position.set(...a.centerLocal),s.scale.setScalar(a.radius))},s.userData.disposeGeometry=!0,s.userData.disposeMaterial=!0,s}function B$(e,t){const n=Hs(e,t),r=Wd(e,t),o=xb(e,r)||xb(e,{x:0,y:0});if(!e?.THREE||!n||!o)return null;const{THREE:i}=e,s=new i.MeshBasicMaterial({color:_$,transparent:!1,opacity:1,side:i.DoubleSide,blending:i.NoBlending,depthTest:!1,depthWrite:!1,toneMapped:!1}),a=new i.Mesh(o,s);return a.position.set(...n.centerLocal),a.scale.setScalar(n.radius),a.renderOrder=80,a.frustumCulled=!1,a.visible=fc(r),a.userData.lastHoverCellKey=Ud(r),e.urdfPosePickerHoverCellMesh=a,a.onBeforeRender=()=>{const l=Hs(e,t),u=Wd(e,t),d=Ud(u);if(a.visible=fc(u),!(!l||!a.visible)){if(a.position.set(...l.centerLocal),a.scale.setScalar(l.radius),a.userData.lastHoverCellKey!==d){const m=xb(e,u);if(!m)return;a.geometry?.dispose?.(),a.geometry=m}a.userData.lastHoverCellKey=d}},a.userData.disposeGeometry=!0,a.userData.disposeMaterial=!0,a}function V$(e,t){const n=Hs(e,t),r=Wd(e,t),o=Sb(e,r)||Sb(e,{x:0,y:0});if(!e?.THREE||!n||!o)return null;const i=iu(e,o,{color:T$,opacity:.98,lineWidth:R$,renderOrder:82,depthTest:!1,depthWrite:!1});return i?(i.position.set(...n.centerLocal),i.scale.setScalar(n.radius),i.visible=fc(r),i.userData.lastHoverCellKey=Ud(r),e.urdfPosePickerHoverCellOutline=i,i.onBeforeRender=()=>{const s=Hs(e,t),a=Wd(e,t),l=Ud(a);if(i.visible=fc(a),!(!s||!i.visible)){if(i.position.set(...s.centerLocal),i.scale.setScalar(s.radius),i.userData.lastHoverCellKey!==l){const u=Sb(e,a);if(!u)return;i.geometry?.setPositions?.(u),i.geometry?.computeBoundingSphere?.()}i.userData.lastHoverCellKey=l}},i):null}function $$(e,t,n){if(!e?.THREE||!t)return!1;const r=Hs(e,n),o=Wd(e,n),i=Ud(o);if(t.visible=fc(o),!r||!t.visible)return t.userData.lastHoverCellKey="",!1;if(t.position.set(...r.centerLocal),t.scale.setScalar(r.radius),t.userData.lastHoverCellKey===i)return!0;const s=xb(e,o);return s?(t.geometry?.dispose?.(),t.geometry=s,t.userData.lastHoverCellKey=i,!0):(t.visible=!1,t.userData.lastHoverCellKey="",!1)}function G$(e,t,n){if(!e?.THREE||!t)return!1;const r=Hs(e,n),o=Wd(e,n),i=Ud(o);if(t.visible=fc(o),!r||!t.visible)return t.userData.lastHoverCellKey="",!1;if(t.position.set(...r.centerLocal),t.scale.setScalar(r.radius),t.userData.lastHoverCellKey===i)return!0;const s=Sb(e,o);return s?(t.geometry?.setPositions?.(s),t.geometry?.computeBoundingSphere?.(),t.userData.lastHoverCellKey=i,!0):(t.visible=!1,t.userData.lastHoverCellKey="",!1)}function Mg(e,t){const n=$$(e,e?.urdfPosePickerHoverCellMesh,t),r=G$(e,e?.urdfPosePickerHoverCellOutline,t);return n||r}const Er=Object.freeze({CAD:"cad",URDF:"urdf"}),U$=Object.freeze({[Er.CAD]:Object.freeze({minModelRadius:1,minGridSize:280,lightingScopeRadius:140,lightingReferenceModelRadius:760}),[Er.URDF]:Object.freeze({minModelRadius:.05,minGridSize:.28,lightingScopeRadius:.14,lightingReferenceModelRadius:.76})}),W$=Object.freeze({[Er.CAD]:Object.freeze({minExtent:60,normalBias:.024,radius:14}),[Er.URDF]:Object.freeze({minExtent:.55,normalBias:12e-6,radius:14})});function Mu(e){return e===Er.URDF?Er.URDF:Er.CAD}function qs(e){return U$[Mu(e)]}function lf(e,t){const n=Number(e);return Math.max(Number.isFinite(n)?n:0,qs(t).minModelRadius)}function H$(e){return qs(e).minGridSize/2}function K$(e){return qs(e).lightingScopeRadius}function X$(e,t){const n=Mu(t),r=qs(n),o=lf(e,n),i=Math.max(Number(r.lightingReferenceModelRadius)||0,r.minModelRadius);return o/i*r.lightingScopeRadius}function Y$(e,{radius:t=0,keyLightDistance:n=0}={}){const r=Mu(e),o=W$[r],i=lf(t,r),s=Math.max(i*2.8,o.minExtent),a=r===Er.URDF?Math.max(i*8,Math.max(Number(n)||0,0)+i*6+1):Math.max(i*8,320);return{scopeRadius:i,extent:s,far:a,normalBias:o.normalBias,radius:o.radius}}const q$=/^#(?:[0-9a-fA-F]{3}){1,2}$/,Tp=50,oh=Vy,ih=BV;function x2(e,t,n){return Math.min(Math.max(e,t),n)}function hn(e,t,n=-1/0,r=1/0){const o=Number(e);return Number.isFinite(o)?x2(o,n,r):t}function xr(e,t){const n=String(e||"").trim();return q$.test(n)?n.length===4?`#${n[1]}${n[1]}${n[2]}${n[2]}${n[3]}${n[3]}`.toLowerCase():n.toLowerCase():t}function S2(e,t=Le?.materials?.defaultColor||"#ffffff"){const r=(Array.isArray(e)?e:[e]).map(o=>xr(o,"")).filter(Boolean).slice(0,Tp);return r.length?r:[xr(t,"#ffffff")]}function Uy(e={},t=0){const n=S2(e.fillColors,e.defaultColor||Le?.materials?.defaultColor||"#ffffff"),o=$i(e.cycleColors,Le?.materials?.cycleColors||!1)?Math.max(Math.floor(Number(t)||0),0)%n.length:0;return n[o]}function Z$(e,t="#000000"){const n=xr(e,t),r=n.length===4?`#${n[1]}${n[1]}${n[2]}${n[2]}${n[3]}${n[3]}`:n,o=i=>{const s=parseInt(r.slice(i,i+2),16)/255;return s<=.03928?s/12.92:((s+.055)/1.055)**2.4};return{r:o(1),g:o(3),b:o(5)}}function E2(e,t="#000000"){const n=Z$(e,t);return .2126*n.r+.7152*n.g+.0722*n.b}function $i(e,t=!1){return typeof e=="boolean"?e:t}function J$(e,t="solid"){const n=String(e||"").trim().toLowerCase();return["solid","linear","radial","transparent"].includes(n)?n:t}function Q$(e,t="multiply"){const n=String(e||"").trim().toLowerCase();return["multiply","blend"].includes(n)?n:t}const Bn=Object.freeze({STAGE:"stage",GRID:"grid",NONE:"none"}),Ht=Object.freeze({SYSTEM:"system",LIGHT:"light",DARK:"dark"}),eG=Object.freeze(Object.values(Ht));function qb(e,t=Ht.SYSTEM){const n=String(e||"").trim().toLowerCase();return eG.includes(n)?n:t}const w2=Object.freeze([Object.freeze(["background","solidColor"]),Object.freeze(["background","linearStart"]),Object.freeze(["background","linearEnd"]),Object.freeze(["background","radialInner"]),Object.freeze(["background","radialOuter"]),Object.freeze(["floor","color"]),Object.freeze(["floor","gridCenterColor"]),Object.freeze(["floor","gridCellColor"]),Object.freeze(["floor","grid","centerColor"]),Object.freeze(["floor","grid","cellColor"]),Object.freeze(["lighting","directional","color"]),Object.freeze(["lighting","spot","color"]),Object.freeze(["lighting","point","color"]),Object.freeze(["lighting","ambient","color"]),Object.freeze(["lighting","hemisphere","skyColor"]),Object.freeze(["lighting","hemisphere","groundColor"])]);function JS(e,t){return t.reduce((n,r)=>n&&typeof n=="object"?n[r]:void 0,e)}function v2(e,t,n){let r=e;for(let o=0;o{const l=parseInt(r.slice(a,a+2),16),u=parseInt(o.slice(a,a+2),16);return Math.round(l+(u-l)*i).toString(16).padStart(2,"0")};return`#${s(1)}${s(3)}${s(5)}`}function aG(e,t){const n=Array.isArray(e)?e:[],r=Array.isArray(t)?t:[],o=Math.max(n.length,r.length);return Object.freeze(o?Array.from({length:o},(i,s)=>{const a=n[s]||n.at(-1)||"#ffffff",l=r[s]||r.at(-1)||a;return gs(a,l)}):["#ffffff"])}function Zs(e,t={}){const n=xr(e,"#f1f5f9"),r=$i(t.enabled,!1),o=E2(n)>=.36,i=xr(t.centerColor,o?gs(n,"#0f172a",.48):gs(n,"#f8fafc",.46)),s=xr(t.cellColor,o?gs(n,"#475569",.26):gs(n,"#cbd5e1",.22)),a=hn(t.opacity,QS.opacity,0,1),l=hn(t.density,QS.density,mw,pw);return{gridCenterColor:i,gridCellColor:s,gridOpacity:a,gridDensity:l,grid:{enabled:r,centerColor:i,cellColor:s,opacity:a,density:l},centerColor:i,cellColor:s,opacity:a,density:l}}const ys=Object.freeze({materials:{defaultColor:Jb[0],fillColors:Jb,cycleColors:!1,overrideSourceColors:!1,tintMode:"blend",tintStrength:0,saturation:1.18,contrast:1.12,brightness:1.02,roughness:.58,metalness:.02,clearcoat:.12,clearcoatRoughness:.42,opacity:1,envMapIntensity:.42,emissiveIntensity:.02},edges:{...oh},background:{type:"linear",solidColor:"#edf5fb",linearStart:"#fbfdff",linearEnd:"#b8cadb",linearAngle:135,radialInner:"#ffffff",radialOuter:"#b3c4d4"},floor:{mode:Bn.STAGE,color:"#edf3f8",roughness:.7,reflectivity:.14,shadowOpacity:.16,horizonBlend:.18,...Zs("#edf3f8",{opacity:.2}),enabled:!1},environment:{enabled:!0,presetId:"studio-hdri-43",intensity:.32,rotationY:-.25,useAsBackground:!1},lighting:{toneMappingExposure:1.16,directional:{enabled:!0,color:"#ffffff",intensity:1.16,position:{x:-210,y:260,z:270}},spot:{enabled:!0,color:"#f4fbff",intensity:.52,angle:.74,distance:0,position:{x:190,y:210,z:170}},point:{enabled:!0,color:"#ffe2ba",intensity:.28,distance:0,position:{x:-240,y:110,z:-210}},ambient:{enabled:!0,color:"#ffffff",intensity:.4},hemisphere:{enabled:!0,skyColor:"#ffffff",groundColor:"#d6e2ee",intensity:1.12}}}),Hn=Object.freeze({materials:{defaultColor:Jb[0],fillColors:Jb,cycleColors:!1,overrideSourceColors:!1,tintMode:"blend",tintStrength:0,saturation:1.2,contrast:1.14,brightness:1.06,roughness:.54,metalness:.02,clearcoat:.14,clearcoatRoughness:.4,opacity:1,envMapIntensity:.5,emissiveIntensity:.03},edges:{...ih},background:{type:"linear",solidColor:"#081b2d",linearStart:"#18304a",linearEnd:"#030914",linearAngle:135,radialInner:"#174267",radialOuter:"#030914"},floor:{mode:Bn.STAGE,color:"#0a2238",roughness:.38,reflectivity:.1,shadowOpacity:.42,horizonBlend:.1,...Zs("#0a2238",{opacity:.22}),enabled:!1},environment:{enabled:!0,presetId:"studio-hdri-43",intensity:.18,rotationY:-.25,useAsBackground:!1},lighting:{toneMappingExposure:1.22,directional:{enabled:!0,color:"#ffffff",intensity:1.42,position:{x:-210,y:260,z:270}},spot:{enabled:!0,color:"#70c4ff",intensity:.24,angle:.74,distance:0,position:{x:190,y:210,z:170}},point:{enabled:!0,color:"#9bd0ff",intensity:.36,distance:0,position:{x:-240,y:110,z:-210}},ambient:{enabled:!0,color:"#c6d8ea",intensity:.24},hemisphere:{enabled:!0,skyColor:"#ffffff",groundColor:"#020713",intensity:.98}}}),Gl=Object.freeze({...Hn,materials:{...Hn.materials,defaultColor:vI[0],fillColors:vI},background:{...Hn.background,solidColor:"#151617",linearStart:"#2a2b2d",linearEnd:"#070809",radialInner:"#303133",radialOuter:"#070809"},floor:{...Hn.floor,color:"#171819",...Zs("#171819",{opacity:.22})}}),CI=aG(Hn.materials.fillColors,Gl.materials.fillColors),Ll=Object.freeze({...Hn,materials:{...Hn.materials,defaultColor:CI[0],fillColors:CI},edges:{...oh},background:{...Hn.background,solidColor:gs(Hn.background.solidColor,Gl.background.solidColor),linearStart:gs(Hn.background.linearStart,Gl.background.linearStart),linearEnd:gs(Hn.background.linearEnd,Gl.background.linearEnd),radialInner:gs(Hn.background.radialInner,Gl.background.radialInner),radialOuter:gs(Hn.background.radialOuter,Gl.background.radialOuter)},floor:{...Hn.floor,color:gs(Hn.floor.color,Gl.floor.color),...Zs(gs(Hn.floor.color,Gl.floor.color),{opacity:.22})}}),lG=Object.freeze({materials:{...Hn.materials,defaultColor:ip[0],fillColors:ip,cycleColors:!1},edges:{...ih},background:{type:"radial",solidColor:"#04131f",linearStart:"#07253a",linearEnd:"#0b8edc",linearAngle:128,radialInner:"#0b8edc",radialOuter:"#02070c"},floor:{mode:Bn.STAGE,color:"#06324f",roughness:.58,reflectivity:.2,shadowOpacity:.3,horizonBlend:.18,...Zs("#06324f",{opacity:.24}),enabled:!1},environment:Hn.environment,lighting:Hn.lighting}),cG=Object.freeze({materials:{...Hn.materials,defaultColor:sp[0],fillColors:sp,cycleColors:!1},edges:{...ih},background:{type:"radial",solidColor:"#281323",linearStart:"#7a1a52",linearEnd:"#301426",linearAngle:140,radialInner:"#7f1a55",radialOuter:"#25101f"},floor:{mode:Bn.STAGE,color:"#4a1833",roughness:.56,reflectivity:.2,shadowOpacity:.26,horizonBlend:.22,...Zs("#4a1833",{opacity:.24}),enabled:!1},environment:Hn.environment,lighting:Hn.lighting}),uG=Object.freeze({materials:{...Hn.materials,defaultColor:ap[0],fillColors:ap,cycleColors:!1},edges:{...ih},background:{type:"linear",solidColor:"#f3eadc",linearStart:"#f7ead8",linearEnd:"#c88d5d",linearAngle:162,radialInner:"#f7ead8",radialOuter:"#b06c43"},floor:{mode:Bn.STAGE,color:"#d4a070",roughness:.72,reflectivity:.14,shadowOpacity:.34,horizonBlend:.12,...Zs("#d4a070",{opacity:.18}),enabled:!1},environment:Hn.environment,lighting:Hn.lighting}),dG=Object.freeze({materials:{...ys.materials,defaultColor:Hl[0],fillColors:Hl,cycleColors:!0},edges:{...ih},background:{type:"linear",solidColor:"#dff7f7",linearStart:"#fff4d6",linearEnd:"#47c5d6",linearAngle:152,radialInner:"#fff8e8",radialOuter:"#1a8fb5"},floor:{mode:Bn.STAGE,color:"#f2d59b",roughness:.74,reflectivity:.18,shadowOpacity:.2,horizonBlend:.2,...Zs("#f2d59b",{opacity:.18}),enabled:!1},environment:{enabled:!0,presetId:"studio-hdri-12",intensity:.36,rotationY:-.18,useAsBackground:!1},lighting:{toneMappingExposure:1.18,directional:{enabled:!0,color:"#fff7df",intensity:1.3,position:{x:-220,y:280,z:250}},spot:{enabled:!0,color:"#e4fbff",intensity:.36,angle:.72,distance:0,position:{x:190,y:210,z:170}},point:{enabled:!0,color:"#ffd08a",intensity:.24,distance:0,position:{x:-240,y:110,z:-210}},ambient:{enabled:!0,color:"#fff8e6",intensity:.34},hemisphere:{enabled:!0,skyColor:"#bff8ff",groundColor:"#f2d59b",intensity:1.04}}}),fG=Object.freeze({materials:{...Hn.materials,defaultColor:lp[0],fillColors:lp,cycleColors:!1},edges:{...sG},background:{type:"radial",solidColor:"#020403",linearStart:"#031109",linearEnd:"#000000",linearAngle:180,radialInner:"#062414",radialOuter:"#000201"},floor:{mode:Bn.GRID,color:"#020403",roughness:.58,reflectivity:.12,shadowOpacity:.35,horizonBlend:0,gridCenterColor:M2,gridCellColor:"#0c3d22",gridOpacity:.34,gridDensity:1.15},environment:Hn.environment,lighting:Hn.lighting}),hm="#f0f4f9",MI="#e2e9f0",II=Object.freeze({...ys,background:{...ys.background,type:"solid",solidColor:hm,linearStart:hm,linearEnd:hm,radialInner:hm,radialOuter:hm},edges:{...oh},floor:{...ys.floor,color:MI,enabled:!0,...Zs(MI,{enabled:!0,opacity:.2})},environment:{...ys.environment,enabled:!1},lighting:{...ys.lighting,hemisphere:{...ys.lighting.hemisphere,groundColor:"#c7d5e3"}}}),AI="#202832",mG=Object.freeze({...Ll,edges:{...oh,color:"#1c2836"},background:{...Ll.background,solidColor:"#181f28",linearStart:"#242e3a",linearEnd:"#0c1016",radialInner:"#293443",radialOuter:"#0c1016"},floor:{...Ll.floor,color:AI,enabled:!0,...Zs(AI,{enabled:!0,opacity:.22})},lighting:{...Ll.lighting,spot:{...Ll.lighting.spot,color:"#b3d4f2"},point:{...Ll.lighting.point,color:"#bfd8f0"},ambient:{...Ll.lighting.ambient,color:"#dfe7f0"},hemisphere:{...Ll.lighting.hemisphere,groundColor:"#333d4b"}}}),hw=cf(II,Ht.SYSTEM,fw(II,mG)),pG=cf(lG,Ht.DARK),hG=cf(cG,Ht.DARK),gG=cf(uG,Ht.LIGHT),bG=cf(dG,Ht.LIGHT),yG=cf(fG,Ht.DARK),ic=Object.freeze([{id:"workbench",label:"Workbench",description:"Balanced CAD workbench lighting with system-aware light and dark canvas colors.",preview:{background:"#f0f4f9",modelColor:"#b6c4ce",accentColor:"#4ea7d8"},settings:hw},{id:"blue",label:"Blue",description:"Single cyan fill against deep-navy CAD lighting.",preview:{background:ip[0],modelColor:ip[0],accentColor:ip[0]},settings:pG},{id:"pink",label:"Magenta",description:"Single saturated magenta fill against a near-black studio backdrop.",preview:{background:sp[0],modelColor:sp[0],accentColor:sp[0]},settings:hG},{id:"clay-sunrise",label:"Clay",description:"Single warm clay fill with a soft presentation stage.",preview:{background:ap[0],modelColor:ap[0],accentColor:ap[0]},settings:gG},{id:"beach",label:"Beach",description:"Two-color aqua-and-coral fill with warm beach presentation lighting.",preview:{background:`linear-gradient(135deg, ${Hl[0]} 0%, ${Hl[0]} 50%, ${Hl[1]} 50%, ${Hl[1]} 100%)`,modelColor:Hl[0],accentColor:Hl[1]},settings:bG},{id:"terminal",label:"Terminal",description:"Single terminal-green fill with green CAD edge linework and a dark grid floor.",preview:{background:lp[0],modelColor:lp[0],accentColor:lp[0]},settings:yG}]),xG=Object.freeze({cinematic:"workbench",light:"workbench",dark:"workbench",charcoal:"workbench",darkoal:"workbench","dark-2":"workbench"}),Hd="workbench",Rp=Object.freeze(ic.find(e=>e.id===Hd)||ic[0]),Le=Object.freeze(Rp.settings);function NI({prefersDark:e=!1}={}){return Hd}const SG=new Set(e1.map(e=>e.id)),EG=Object.freeze({defaultColor:"#aeb9c3",tintStrength:.28,saturation:.42,contrast:1.02,brightness:.94,roughness:.46,metalness:.02,clearcoat:.18,clearcoatRoughness:.34,opacity:1,envMapIntensity:.58}),wG=Object.freeze({defaultColor:"#aeb9c3",tintMode:"blend",tintStrength:.08,saturation:1,contrast:1.04,brightness:1.02,roughness:.46,metalness:.02,clearcoat:.18,clearcoatRoughness:.34,opacity:1,envMapIntensity:.58,emissiveIntensity:.06}),vG=Object.freeze({defaultColor:"#aeb9c3",tintMode:"blend",tintStrength:0,saturation:1.34,contrast:1.02,brightness:.82,roughness:.76,metalness:0,clearcoat:0,clearcoatRoughness:.72,opacity:1,envMapIntensity:.08,emissiveIntensity:.01}),CG=Object.freeze({defaultColor:"#bcc8d4",tintMode:"blend",tintStrength:0,saturation:1.18,contrast:1.07,brightness:1.04,roughness:.58,metalness:.02,clearcoat:.12,clearcoatRoughness:.42,opacity:1,envMapIntensity:.42,emissiveIntensity:.02}),MG=Object.freeze({defaultColor:"#748899",tintMode:"blend",tintStrength:0,saturation:1.18,contrast:1.07,brightness:1.04,roughness:.58,metalness:.02,clearcoat:.12,clearcoatRoughness:.42,opacity:1,envMapIntensity:.42,emissiveIntensity:.02}),IG=Object.freeze({defaultColor:"#556c7f",tintMode:"blend",tintStrength:0,saturation:1.18,contrast:1.12,brightness:1.02,roughness:.58,metalness:.02,clearcoat:.12,clearcoatRoughness:.42,opacity:1,envMapIntensity:.42,emissiveIntensity:.02}),I2=Object.freeze({solidColor:"#050711",linearStart:"#02040b",linearEnd:"#252f47",linearAngle:90,radialInner:"#171d30",radialOuter:"#02040b"}),AG=I2,NG=Object.freeze({solidColor:"#0a0f18",linearStart:"#08111c",linearEnd:"#1f2c3d",linearAngle:90,radialInner:"#182337",radialOuter:"#08111c"}),_G=Object.freeze({mode:Bn.STAGE,color:"#141a29",roughness:.62,reflectivity:.22,shadowOpacity:.24,horizonBlend:.28}),TG=Object.freeze({mode:Bn.STAGE,color:"#141a29",roughness:.62,reflectivity:.06,shadowOpacity:.24,horizonBlend:.12}),RG=Object.freeze({mode:Bn.STAGE,color:"#121a24",roughness:.86,reflectivity:.06,shadowOpacity:.24,horizonBlend:.28}),PG=Object.freeze({enabled:!0,presetId:"studio-hdri-43",intensity:.46,rotationY:-.35,useAsBackground:!1}),OG=Object.freeze({enabled:!1,presetId:"studio-hdri-43",intensity:0,rotationY:-.35,useAsBackground:!1}),kG=Object.freeze({toneMappingExposure:1.2,directional:{enabled:!0,color:"#f1f6fb",intensity:2.45,position:{x:-190,y:300,z:210}},spot:{enabled:!0,color:"#dbeafe",intensity:1.34,angle:.72,distance:0,position:{x:160,y:245,z:126}},point:{enabled:!0,color:"#8fb6d8",intensity:.34,distance:0,position:{x:-260,y:95,z:-220}},ambient:{enabled:!0,color:"#1e293b",intensity:.2},hemisphere:{enabled:!0,skyColor:"#dbe7f3",groundColor:"#070a14",intensity:.68}}),DG=Object.freeze({toneMappingExposure:1.03,directional:{enabled:!0,color:"#f1f6fb",intensity:1.28,position:{x:-190,y:300,z:210}},spot:{enabled:!0,color:"#dbeafe",intensity:.18,angle:.72,distance:0,position:{x:160,y:245,z:126}},point:{enabled:!0,color:"#8fb6d8",intensity:.08,distance:0,position:{x:-260,y:95,z:-220}},ambient:{enabled:!0,color:"#1e293b",intensity:.42},hemisphere:{enabled:!0,skyColor:"#dbe7f3",groundColor:"#070a14",intensity:.92}});function jG(e){const t=String(e||"").trim();return SG.has(t)?t:Le.environment.presetId}function mx(e,t){return{x:hn(e?.x,t.x,-5e3,5e3),y:hn(e?.y,t.y,-5e3,5e3),z:hn(e?.z,t.z,-5e3,5e3)}}function A2(e,t){return typeof t=="number"?Math.abs((Number(e)||0)-t)<1e-6:t&&typeof t=="object"?!e||typeof e!="object"?!1:Object.entries(t).every(([n,r])=>A2(e[n],r)):e===t}function gm(e,t){return t.some(n=>A2(e,n))}function LG(e){const t=gm(e?.materials,[EG,wG,vG,CG,MG,IG,ys.materials]),n=gm(e?.floor,[_G,TG,RG,ys.floor]),r=gm(e?.environment,[PG,OG,ys.environment,hw.environment]),o=gm(e?.background,[I2,AG,NG,ys.background]),i=gm(e?.lighting,[kG,DG,ys.lighting]);return t&&o&&n&&r&&i}function fr(e={}){const t=e&&typeof e=="object"?e:{},n=t.materials&&typeof t.materials=="object"?t.materials:{},r=t.background&&typeof t.background=="object"?t.background:{},o=t.environment&&typeof t.environment=="object"?t.environment:{},i=t.floor&&typeof t.floor=="object"?t.floor:{},s=t.lighting&&typeof t.lighting=="object"?t.lighting:{},a=!!(t.materials&&typeof t.materials=="object"),l=a&&!Object.hasOwn(n,"tintMode"),u=a&&!Object.hasOwn(n,"emissiveIntensity"),d=xr(n.defaultColor||n.tintColor,Le.materials.defaultColor),m=S2(n.fillColors,d),p=xr(i.color,Le.floor?.color||"#141416"),g=rG(i.mode,Le.floor?.mode||Bn.STAGE),x=i.grid&&typeof i.grid=="object"&&!Array.isArray(i.grid)?i.grid:{},y=Zs(p),S=xr(x.centerColor??i.gridCenterColor??i.gridCenter,y.centerColor),b=xr(x.cellColor??i.gridCellColor??i.gridCell,y.cellColor),I=hn(x.opacity??i.gridOpacity,y.opacity,0,1),A=hn(x.density??i.gridDensity,y.density,mw,pw),P={colorMode:qb(t.colorMode,Le?.colorMode||Ht.SYSTEM),materials:{defaultColor:m[0]||d,fillColors:m,cycleColors:$i(n.cycleColors,Le.materials.cycleColors||!1),overrideSourceColors:$i(n.overrideSourceColors,Le.materials.overrideSourceColors||!1),tintMode:Q$(n.tintMode,l?"multiply":Le.materials.tintMode),tintStrength:hn(n.tintStrength,Le.materials.tintStrength,0,1),saturation:hn(n.saturation,Le.materials.saturation,0,2.5),contrast:hn(n.contrast,Le.materials.contrast,0,2.5),brightness:hn(n.brightness,Le.materials.brightness,0,2),roughness:hn(n.roughness,Le.materials.roughness,0,1),metalness:hn(n.metalness,Le.materials.metalness,0,1),clearcoat:hn(n.clearcoat,Le.materials.clearcoat,0,1),clearcoatRoughness:hn(n.clearcoatRoughness,Le.materials.clearcoatRoughness,0,1),opacity:hn(n.opacity,Le.materials.opacity,0,1),envMapIntensity:hn(n.envMapIntensity,Le.materials.envMapIntensity,0,4),emissiveIntensity:hn(n.emissiveIntensity,u?0:Le.materials.emissiveIntensity,0,2)},background:{type:J$(r.type,Le.background.type),solidColor:xr(r.solidColor,Le.background.solidColor),linearStart:xr(r.linearStart,Le.background.linearStart),linearEnd:xr(r.linearEnd,Le.background.linearEnd),linearAngle:hn(r.linearAngle,Le.background.linearAngle,-360,360),radialInner:xr(r.radialInner,Le.background.radialInner),radialOuter:xr(r.radialOuter,Le.background.radialOuter)},floor:{mode:g,enabled:$i(i.enabled,g!==Bn.NONE),color:p,roughness:hn(i.roughness,Le.floor?.roughness??.72,0,1),reflectivity:hn(i.reflectivity,Le.floor?.reflectivity??.12,0,1),shadowOpacity:hn(i.shadowOpacity,Le.floor?.shadowOpacity??.45,0,1),horizonBlend:hn(i.horizonBlend,Le.floor?.horizonBlend??0,0,1),gridCenterColor:S,gridCellColor:b,gridOpacity:I,gridDensity:A,grid:{enabled:$i(x.enabled,g===Bn.GRID),centerColor:S,cellColor:b,opacity:I,density:A}},environment:{enabled:$i(o.enabled,Le.environment.enabled),presetId:jG(o.presetId),intensity:hn(o.intensity,Le.environment.intensity,0,4),rotationY:hn(o.rotationY,Le.environment.rotationY,-Math.PI*2,Math.PI*2),useAsBackground:$i(o.useAsBackground,Le.environment.useAsBackground)},lighting:{toneMappingExposure:hn(s.toneMappingExposure,Le.lighting.toneMappingExposure,.05,6),directional:{enabled:$i(s.directional?.enabled,Le.lighting.directional.enabled),color:xr(s.directional?.color,Le.lighting.directional.color),intensity:hn(s.directional?.intensity,Le.lighting.directional.intensity,0,20),position:mx(s.directional?.position,Le.lighting.directional.position)},spot:{enabled:$i(s.spot?.enabled,Le.lighting.spot.enabled),color:xr(s.spot?.color,Le.lighting.spot.color),intensity:hn(s.spot?.intensity,Le.lighting.spot.intensity,0,20),angle:hn(s.spot?.angle,Le.lighting.spot.angle,.01,Math.PI/2),distance:hn(s.spot?.distance,Le.lighting.spot.distance,0,5e3),position:mx(s.spot?.position,Le.lighting.spot.position)},point:{enabled:$i(s.point?.enabled,Le.lighting.point.enabled),color:xr(s.point?.color,Le.lighting.point.color),intensity:hn(s.point?.intensity,Le.lighting.point.intensity,0,20),distance:hn(s.point?.distance,Le.lighting.point.distance,0,5e3),position:mx(s.point?.position,Le.lighting.point.position)},ambient:{enabled:$i(s.ambient?.enabled,Le.lighting.ambient.enabled),color:xr(s.ambient?.color,Le.lighting.ambient.color),intensity:hn(s.ambient?.intensity,Le.lighting.ambient.intensity,0,20)},hemisphere:{enabled:$i(s.hemisphere?.enabled,Le.lighting.hemisphere.enabled),skyColor:xr(s.hemisphere?.skyColor,Le.lighting.hemisphere.skyColor),groundColor:xr(s.hemisphere?.groundColor,Le.lighting.hemisphere.groundColor),intensity:hn(s.hemisphere?.intensity,Le.lighting.hemisphere.intensity,0,20)}}};return P.modeColors=tG(t.modeColors,P),!Object.hasOwn(t,"colorMode")&&!Object.hasOwn(t,"modeColors")&&LG(P)?fr(C2(hw)):P}function FG(e=Le){return fr(JSON.parse(JSON.stringify(e)))}function ol(e){const t=String(e||"").trim(),n=xG[t]||t;return ic.some(r=>r.id===n)?n:""}function gw(e){const t=ol(e);return ic.find(n=>n.id===t)||Rp}function N2(e){return FG(gw(e).settings)}function zG(e={},{prefersDark:t=!1,systemFallback:n=Ht.LIGHT}={}){const r=qb(e?.colorMode,Le?.colorMode||Ht.SYSTEM);return r===Ht.SYSTEM?t===!0||qb(n,Ht.LIGHT)===Ht.DARK?Ht.DARK:Ht.LIGHT:r}function _2(e={},t={}){const n=fr(e),r=zG(n,t),o=C2(n);return o.colorMode=r,nG(o,n.modeColors?.[r]),fr(o)}function BG(e={}){return fr(e).colorMode===Ht.SYSTEM}function T2(e,t={}){const n=_2(e,t);return E2(n.floor?.color,Le.floor?.color||Le.background.solidColor)>=.36?"light":"dark"}function _I(e){return e1.find(t=>t.id===e)||e1[0]}const Yn={sceneBackground:"#09090b",surface:"#f4f4f5",surfaceRoughness:.92,surfaceMetalness:.03,surfaceClearcoat:0,surfaceClearcoatRoughness:.6,edge:"#18181b",edgeThickness:1,edgeOpacity:.84,selected:"#2563eb",hover:"#0ea5e9",gridCenter:"#3f3f46",gridCell:"#27272a",gridOpacity:.16,stageFloorColor:"#141416",stageFloorOpacity:.78,stageFloorRoughness:.92,stageFloorMetalness:0,stageFloorTransmission:0,stageFloorIor:1.35,stageFloorThickness:.035,stageFloorAttenuationDistance:4,viewPlanePalette:{axis:{x:{front:[250,88,79],back:[122,32,28]},y:{front:[92,233,123],back:[30,99,46]},z:{front:[84,131,255],back:[30,53,126]}},center:{fill:[252,215,74],stroke:[255,235,153]},shell:{inner:[24,31,48],outer:[8,12,20],stroke:[148,163,184]}}},Ia={SOLID:"solid",LINEAR:"linear",RADIAL:"radial",TRANSPARENT:"transparent"},Pp=/^#(?:[0-9a-fA-F]{3}){1,2}$/,TI=1024,px=512,VG=3,RI="#dbeafe",PI="#111827";function Fn(e,t,n){return Math.min(Math.max(e,t),n)}function Wy(e,t=""){const n=String(e||"").trim();return Pp.test(n)?n.length===4?`#${n[1]}${n[1]}${n[2]}${n[2]}${n[3]}${n[3]}`.toLowerCase():n.toLowerCase():t}function hx(e){const t=e/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function OI(e){const t=Wy(e,"#000000"),n=parseInt(t.slice(1,3),16),r=parseInt(t.slice(3,5),16),o=parseInt(t.slice(5,7),16);return .2126*hx(n)+.7152*hx(r)+.0722*hx(o)}function $G(e,t){const n=OI(e),r=OI(t),o=Math.max(n,r),i=Math.min(n,r);return(o+.05)/(i+.05)}function gx(e,t){const n=t.map(r=>Wy(r,"")).filter(Boolean);return n.length?Math.min(...n.map(r=>$G(e,r))):1/0}function GG(e={},t=Yn){const n=e?.background||{},r=String(n.type||"").trim().toLowerCase(),o=[];r===Ia.LINEAR?o.push(n.linearStart,n.linearEnd):r===Ia.RADIAL?o.push(n.radialInner,n.radialOuter):r===Ia.SOLID&&o.push(n.solidColor);const i=o.map(s=>Wy(s,"")).filter(Boolean);return i.length?i:[t?.sceneBackground,Yn.sceneBackground]}function UG({edgeColor:e="",themeSettings:t={},viewerTheme:n=Yn,minimumContrastRatio:r=VG}={}){const o=Wy(e,""),i=GG(t,n);return o&&gx(o,i)>=r?o:gx(RI,i)>=gx(PI,i)?RI:PI}function Eb(e,t,n){return e?.[t]??Yn[t]??n}function Ya(e,t,n){const r=Number(Eb(e,t,n));return Number.isFinite(r)?r:n}function WG(e,t=Bn.STAGE){const n=String(e||"").trim().toLowerCase();return n==="glass"?Bn.STAGE:Object.values(Bn).includes(n)?n:t}function R2(e){return Array.isArray(e)?e.filter(Boolean):e?[e]:[]}function eu(e,t,n=1){const r=new e.Color(t||"#000000");return`rgba(${Math.round(r.r*255)}, ${Math.round(r.g*255)}, ${Math.round(r.b*255)}, ${Fn(n,0,1)})`}function HG(e){const t=R2(e);return t.length?t.map((n,r)=>{if(typeof n=="string")return{offset:t.length===1?0:r/(t.length-1),color:n};const o=t.length===1?0:r/(t.length-1),i=Number(n?.offset);return{offset:Number.isFinite(i)?Fn(i,0,1):o,color:n?.color||n?.value||"#000000"}}).sort((n,r)=>n.offset-r.offset):[]}function KG(e,t,n=null){const r=String(n?.type||"").trim().toLowerCase(),o=!!r,i=o?r===Ia.LINEAR?[{offset:0,color:n.linearStart||"#000000"},{offset:1,color:n.linearEnd||"#ffffff"}]:r===Ia.RADIAL?[{offset:0,color:n.radialInner||"#000000"},{offset:1,color:n.radialOuter||"#ffffff"}]:[]:HG(t?.sceneBackgroundGradient),s=o?[]:R2(t?.sceneBackgroundGlow);if(!i.length&&!s.length)return null;const a=document.createElement("canvas");a.width=TI,a.height=TI;const l=a.getContext("2d");if(!l)return null;if(l.fillStyle=o?n.solidColor||Yn.sceneBackground:t?.sceneBackground||Yn.sceneBackground,l.fillRect(0,0,a.width,a.height),i.length)if(r===Ia.RADIAL){const d=l.createRadialGradient(a.width/2,a.height/2,a.width*.1,a.width/2,a.height/2,a.width*.75);for(const m of i)d.addColorStop(m.offset,m.color);l.fillStyle=d,l.fillRect(0,0,a.width,a.height)}else{const m=(Number.isFinite(Number(n?.linearAngle))?Number(n.linearAngle):180)*Math.PI/180,p=a.width/2,g=a.height/2,x=Math.max(a.width,a.height),y=p-Math.cos(m)*x,S=g-Math.sin(m)*x,b=p+Math.cos(m)*x,I=g+Math.sin(m)*x,A=l.createLinearGradient(y,S,b,I);for(const N of i)A.addColorStop(N.offset,N.color);l.fillStyle=A,l.fillRect(0,0,a.width,a.height)}for(const d of s){const m=Number(d?.x),p=Number(d?.y),g=Number.isFinite(m)?Fn(m,0,1):.5,x=Number.isFinite(p)?Fn(p,0,1):.5,y=Math.max(Number(d?.radius)||0,.08),S=Fn(Number(d?.opacity)||0,0,1);if(S<=0)continue;const b=a.width*g,I=a.height*x,A=a.width*y,N=l.createRadialGradient(b,I,0,b,I,A);N.addColorStop(0,eu(e,d?.color||"#ffffff",S)),N.addColorStop(.5,eu(e,d?.color||"#ffffff",S*.3)),N.addColorStop(1,eu(e,d?.color||"#ffffff",0)),l.fillStyle=N,l.fillRect(0,0,a.width,a.height)}const u=new e.CanvasTexture(a);return u.colorSpace=e.SRGBColorSpace,u.minFilter=e.LinearFilter,u.magFilter=e.LinearFilter,u.generateMipmaps=!1,u}function cp(e){e?.dispose?.()}function Ig(e,t,n=null){if(!(!e?.THREE||!e?.scene)){if(String(n?.type||"").toLowerCase()===Ia.TRANSPARENT){cp(e.sceneBackgroundTexture),e.sceneBackgroundTexture=null,e.scene.background=null,e.renderer?.setClearAlpha?.(0);return}if(e.renderer?.setClearAlpha?.(1),cp(e.sceneBackgroundTexture),e.sceneBackgroundTexture=KG(e.THREE,t,n),e.sceneBackgroundTexture){e.scene.background=e.sceneBackgroundTexture;return}e.scene.background=new e.THREE.Color(n?.solidColor||t.sceneBackground||Yn.sceneBackground)}}function Fs(e,t,n="#000000"){const r=String(t||"").trim(),o=String(n||"#000000").trim(),i=Pp.test(r)?r:o;try{return new e.Color(i)}catch{return new e.Color(Pp.test(o)?o:"#000000")}}function XG(e,t={},n=Yn){const r=n?.stageFloorColor||n?.sceneBackground||Yn.stageFloorColor,o=String(t?.type||"").trim().toLowerCase();return o===Ia.LINEAR?Fs(e,t.linearStart,r).lerp(Fs(e,t.linearEnd,r),.7):o===Ia.RADIAL?Fs(e,t.radialInner,r).lerp(Fs(e,t.radialOuter,r),.72):o===Ia.SOLID?Fs(e,t.solidColor,r):Fs(e,r,Yn.stageFloorColor)}function P2(e={}){const t=e?.materials||{},n=e?.environment||{},r=Fn(Number(t.roughness)||0,0,1),o=Fn(Number(t.clearcoat)||0,0,1),i=n?.enabled?Fn((Number(t.envMapIntensity)||0)*(Number(n.intensity)||0)/3,0,1):0;return Fn(o*.5+(1-r)*.25+i*.35,0,1)}function YG(e,t,n={}){const r=String(n?.floor?.color||"").trim();if(Pp.test(r))return Fs(e,r,t?.stageFloorColor||Yn.stageFloorColor);const o=XG(e,n?.background,t),i=P2(n);if(i>=.35){const p={};o.getHSL(p);const g=o.clone(),x=p.l<.42?Fn(p.l+.012,.06,.14):Fn(p.l-.045,.36,.78);return g.setHSL(p.h,Fn(p.s*.14,0,.04),x),g}const s=Fs(e,n?.lighting?.hemisphere?.groundColor,t?.stageFloorColor||Yn.stageFloorColor),a=Fs(e,n?.materials?.defaultColor,"#ffffff"),l=o.clone().lerp(s,.42-i*.24).lerp(a,.07-i*.04).lerp(o,i*.5),u={},d={};l.getHSL(u),o.getHSL(d);const m=d.l<.42?Fn(Math.max(u.l,d.l+(.055-i*.035)),.1-i*.04,.34-i*.13):Fn(Math.min(u.l,d.l-.075),.38,.78);return l.setHSL(u.h,Fn(u.s*(.58-i*.2),.025,.38),m),l}function kd(e,t,n,r=0,o=1){const i=Number(e?.floor?.[t]);return Number.isFinite(i)?Fn(i,r,o):n}function qG(e,t,n){const r=Fn(Number(n)||0,0,1);if(r<=.001||typeof document>"u")return null;const o=document.createElement("canvas");o.width=px,o.height=px;const i=o.getContext("2d");if(!i)return null;const s=px/2,a=i.createRadialGradient(s,s,0,s,s,s);a.addColorStop(0,eu(e,t,r)),a.addColorStop(.28,eu(e,t,r*.56)),a.addColorStop(.62,eu(e,t,r*.16)),a.addColorStop(1,eu(e,t,0)),i.fillStyle=a,i.fillRect(0,0,o.width,o.height);const l=new e.CanvasTexture(o);return l.colorSpace=e.SRGBColorSpace,l.minFilter=e.LinearFilter,l.magFilter=e.LinearFilter,l.generateMipmaps=!1,l}function ZG(e,t,n=Er.CAD){const r=qs(n),o=Math.max(Number(e)||0,r.minModelRadius);return Math.min(Math.max(Number(t)||0,0)*.24,o*8)}function JG(e,t,n,r,o,i=0){const s=P2(n),a=kd(n,"horizonBlend",0,0,1),l=kd(n,"reflectivity",.12,0,1),u=YG(e,t,n),d=kd(n,"roughness",Fn(Ya(t,"stageFloorRoughness",.92)-s*.48,.16,1),0,1),m=a<=.001?1:Fn((Ya(t,"stageFloorOpacity",.78)-s*.02)*(1-a*.3),.62,1),p={};u.getHSL(p);const g=p.l<.18,x=g?u.clone().lerp(new e.Color("#1c5f8f"),.5):new e.Color("#ffffff"),y=g?Fn(l*.38,0,.06):Fn(l*1.4,.04,.36),S=g?Fn(l*.22,0,.05):Fn(l*.58+s*.12,0,.9),b=g?Fn(Math.max(d*.95,.35),.35,.85):Fn(d*.62,.04,.8),I=Fn(Number(n?.materials?.envMapIntensity||0)*(n?.environment?.enabled?Number(n?.environment?.intensity||0):0)*(.08+s*.1)+l*.48,0,1.15),A=new e.MeshPhysicalMaterial({color:u,roughness:d,metalness:Fn(Ya(t,"stageFloorMetalness",0)+l*.06,0,.18),clearcoat:S,clearcoatRoughness:b,reflectivity:l,specularColor:x,specularIntensity:y,transmission:Fn(Ya(t,"stageFloorTransmission",Yn.stageFloorTransmission)+s*.005,0,.02),ior:Ya(t,"stageFloorIor",Yn.stageFloorIor),thickness:Ya(t,"stageFloorThickness",Yn.stageFloorThickness),attenuationDistance:Ya(t,"stageFloorAttenuationDistance",Yn.stageFloorAttenuationDistance),transparent:m<.999,opacity:m,side:e.FrontSide,depthWrite:m>=.999,envMapIntensity:I}),N=new e.Mesh(new e.PlaneGeometry(1,1,1,1),A);return N.position.set(0,0,o+i),N.scale.set(r,r,1),N.receiveShadow=!1,N.castShadow=!1,N.renderOrder=-3,N}function QG(e,t,n,r,o,i,s=.008){const a=t?.lighting?.spot||{};if(a.enabled===!1)return null;const l=kd(t,"reflectivity",.12,0,1),u=kd(t,"shadowOpacity",.45,0,1),d=Math.max(Number(a.intensity)||0,0),m=Fn(.025+d*.11+l*.32-u*.06,0,.36),p=qG(e,a.color||"#ffffff",m);if(!p)return null;const g=ZG(n,r,i),x=new e.MeshBasicMaterial({map:p,transparent:!0,opacity:1,depthWrite:!1,blending:e.AdditiveBlending,side:e.FrontSide,toneMapped:!0}),y=new e.Mesh(new e.PlaneGeometry(1,1,1,1),x);return y.position.set(0,0,o+s),y.scale.set(g*1.45,g,1),y.receiveShadow=!1,y.castShadow=!1,y.renderOrder=-2.8,y}function eU(e,t,n,r,o=.01){const i=kd(t,"shadowOpacity",.45,0,1);if(i<=.001)return null;const s=new e.ShadowMaterial({color:0,opacity:i,transparent:!0,depthWrite:!1}),a=new e.Mesh(new e.PlaneGeometry(1,1,1,1),s);return a.position.set(0,0,r+o),a.scale.set(n,n,1),a.receiveShadow=!0,a.castShadow=!1,a.renderOrder=-2,a}function Ag(e){if(!e?.spotLight?.target?.position)return;const t=Number(e.gridFloorZ),n=e.floorMode!==Bn.NONE&&Number.isFinite(t)?t:0;e.spotLight.target.position.set(0,0,n),e.spotLight.target.updateMatrixWorld?.()}function tU(e,t=Er.CAD){const n=qs(t),r=lf(e,t);return Math.max(n.minGridSize*80,r*160)}const gu=1.04,wd=1e-6;function Sr(e,t=0){const n=Number(e);return Number.isFinite(n)?n:t}function t1(e){return String(e||"").trim()}function nU(e,t){const n=t1(e);if(!t?.size||t.has("__model__"))return!0;if(!n)return!1;for(const r of t){const o=t1(String(r||"").startsWith("#")?String(r||"").slice(1):r);if(n===o||n.startsWith(`${o}.`))return!0}return!1}function Hy(e){return Array.isArray(e?.min)&&Array.isArray(e?.max)&&e.min.length>=3&&e.max.length>=3}function O2(e){return e?.isVector3?[e.x,e.y,e.z]:Array.isArray(e)||ArrayBuffer.isView(e)?[Sr(e[0]),Sr(e[1]),Sr(e[2])]:[0,0,0]}function kI(e,t){if(!t)return null;const[n,r,o]=O2(t),i=new e.Vector3(n,r,o);return i.lengthSq()>wd?i.normalize():null}function Op(e=[]){const t=[1/0,1/0,1/0],n=[-1/0,-1/0,-1/0];let r=0;for(const o of Array.isArray(e)?e:[])if(Hy(o)){r+=1;for(let i=0;i<3;i+=1)t[i]=Math.min(t[i],Sr(o.min[i])),n[i]=Math.max(n[i],Sr(o.max[i]))}return r>0&&t.every(Number.isFinite)&&n.every(Number.isFinite)?{min:t,max:n}:null}function rU(e,t=null){if(!Hy(e))return null;const n=O2(t);return{min:e.min.slice(0,3).map((r,o)=>Sr(r)+n[o]),max:e.max.slice(0,3).map((r,o)=>Sr(r)+n[o])}}function oU(e=[],{partIds:t=null,translationByRecord:n=null}={}){const r=t instanceof Set&&t.size>0?t:null,o=[];for(const i of Array.isArray(e)?e:[]){if(!i||!Hy(i.partBounds))continue;const s=t1(i.partId);if(r&&!nU(s,r))continue;const a=n instanceof Map?n.get(i):null;o.push(rU(i.partBounds,a))}return Op(o)}function iU(e,t,{offset:n=null}={}){if(!e?.Vector3||!Hy(t))return null;const r=new e.Vector3((Sr(t.min[0])+Sr(t.max[0]))/2,(Sr(t.min[1])+Sr(t.max[1]))/2,(Sr(t.min[2])+Sr(t.max[2]))/2);n?.isVector3&&r.add(n);const o=new e.Vector3(Math.max(Sr(t.max[0])-Sr(t.min[0]),0),Math.max(Sr(t.max[1])-Sr(t.min[1]),0),Math.max(Sr(t.max[2])-Sr(t.min[2]),0)).length()/2;return{center:r,radius:o}}function sU(e,t,{aspect:n=e?.aspect||1,minRadius:r=0,padding:o=gu}={}){const i=Math.max(Sr(e?.fov,48),wd),s=Math.max(Sr(t)*Math.max(Sr(o,gu),wd),Sr(r)),a=i*Math.PI/360,l=Math.atan(Math.tan(a)*Math.max(Sr(n,1),wd)),u=Math.max(Math.min(a,l),wd);return s/Math.sin(u)}function aU(e,{camera:t,controls:n,bounds:r,modelOffset:o=null,frameAspect:i=t?.aspect||1,minRadius:s=0,padding:a=gu,defaultDirection:l=[2.1,-1.65,1.08],viewDirection:u=null,viewUp:d=null}={}){if(!e?.Vector3||!t||!n)return null;const m=iU(e,r,{offset:o});if(!m||!Number.isFinite(m.radius))return null;const p=t.position.clone().sub(n.target),g=kI(e,u)||(p.lengthSq()>wd?p.normalize():new e.Vector3(...l).normalize()),x=kI(e,d)||t.up.clone(),y=sU(t,m.radius,{aspect:i,minRadius:s,padding:a}),S=m.center.clone().add(g.multiplyScalar(y));return{center:m.center,radius:m.radius,distance:y,position:S,target:m.center.clone(),up:x,zoom:t.zoom}}const lU=28,cU=1.25;function n1(e,t,n){return Math.min(Math.max(e,t),n)}function uU(e){const t=Number(e);return Number.isFinite(t)?n1(t,mw,pw):QS.density}function dU(e={},t={}){const n=t?.grid||{};return{centerColor:n?.centerColor||t?.gridCenterColor||t?.gridCenter||e?.gridCenter||Yn.gridCenter,cellColor:n?.cellColor||t?.gridCellColor||t?.gridCell||e?.gridCell||Yn.gridCell,opacity:Number.isFinite(Number(n?.opacity))?n1(Number(n.opacity),0,1):Number.isFinite(Number(t?.gridOpacity))?n1(Number(t.gridOpacity),0,1):e?.gridOpacity??Yn.gridOpacity}}function fU(e,t,n={}){const r=uU(n?.grid?.density??n?.gridDensity),o=lf(e,t),i=cU*r,s=o*2*gu/i;let a=Math.max(2,Math.round(lU*r));return a%2!==0&&(a+=1),{size:s*a,cellSize:s,divisions:a}}function mU(e,t,n,r=0,o=Er.CAD,i=Bn.STAGE,{disposeSceneObject:s=()=>{},floorSettings:a={}}={}){if(!e?.THREE||!e?.scene)return;e.gridRadius=n,e.gridFloorZ=r;const l=a?.grid?.enabled===!0||i===Bn.GRID;if(e.floorMode=l?Bn.GRID:i,!l){s(e.gridHelper),e.gridHelper=null,e.gridConfig=null;return}const u={...fU(n,o,a),...dU(t,a)},d=e.gridConfig;if(d&&d.size===u.size&&d.cellSize===u.cellSize&&d.divisions===u.divisions&&d.centerColor===u.centerColor&&d.cellColor===u.cellColor&&d.opacity===u.opacity){e.gridHelper&&(e.gridHelper.rotation.x=Math.PI/2),e.gridHelper?.position.set(0,0,r);return}s(e.gridHelper),e.gridHelper=new e.THREE.GridHelper(u.size,u.divisions,u.centerColor,u.cellColor);const m=Array.isArray(e.gridHelper.material)?e.gridHelper.material:[e.gridHelper.material];for(const p of m)p.transparent=!0,p.opacity=u.opacity,p.depthWrite=!1,p.toneMapped=!1;e.gridHelper.rotation.x=Math.PI/2,e.gridHelper.position.set(0,0,r),e.scene.add(e.gridHelper),e.gridConfig=u}function Ei(e,t,n){return Math.min(Math.max(e,t),n)}function up(e,t){const n=String(t||"").trim();if(!Pp.test(n))return null;const r=n.length===4?`#${n[1]}${n[1]}${n[2]}${n[2]}${n[3]}${n[3]}`:n;return new e.Color(r)}function k2(e,t,n={},{applyTint:r=!0}={}){const o=(t||new e.Color("#ffffff")).clone(),i=Ei(Number(n.tintStrength)||0,0,1);if(r&&i>0){const u=Fs(e,n.defaultColor||n.tintColor,"#ffffff");n.tintMode==="blend"?o.lerp(u,i):o.lerp(o.clone().multiply(u),i)}const s=Ei(Number(n.saturation)||1,0,2.5);if(Math.abs(s-1)>1e-4){const u={};o.getHSL(u),o.setHSL(u.h,Ei(u.s*s,0,1),u.l)}const a=Ei(Number(n.contrast)||1,0,2.5),l=Ei(Number(n.brightness)||1,0,2);return o.r=Ei(((o.r-.5)*a+.5)*l,0,1),o.g=Ei(((o.g-.5)*a+.5)*l,0,1),o.b=Ei(((o.b-.5)*a+.5)*l,0,1),o}function pU(e,t={},n=0){return Fs(e,Uy(t,n),t?.defaultColor||Yn.surface)}function DI(e,t={},n=0){return k2(e,pU(e,t,n),t,{applyTint:!1})}function hU(e,{hasVertexColors:t=!1,sourceColor:n=null,materialSettings:r,fallbackColor:o="#ffffff",fillIndex:i=0,forceFill:s=!1}){return s?DI(e,r,i):t?new e.Color("#ffffff"):n?k2(e,n,r):DI(e,{...r,defaultColor:o||r?.defaultColor},i)}function gU(e,t,n,{displayMode:r=Dt.SOLID}={}){if(!t?.material||!n)return;const o=ml(r),i=n.overrideSourceColors===!0||o,s=!i&&!!t.hasVertexColors,a=s;t.useVertexColors=a,t.baseColor=hU(e,{hasVertexColors:s,sourceColor:i?null:t.sourceColor||null,materialSettings:n,fallbackColor:n?.defaultColor||Yn.surface,fillIndex:t.fillIndex||0,forceFill:i}),t.material.vertexColors=a,t.material.roughness=Ei(Number(n.roughness)||0,0,1),t.material.metalness=Ei(Number(n.metalness)||0,0,1),t.material.clearcoat=Ei(Number(n.clearcoat)||0,0,1),t.material.clearcoatRoughness=Ei(Number(n.clearcoatRoughness)||0,0,1),t.baseOpacity=Ei(Hb(r,Number(n.opacity)||0),0,1),t.material.opacity=t.baseOpacity,t.material.transparent=o||t.baseOpacity<.999,t.material.depthWrite=r===Dt.TRANSPARENT||o?!1:t.baseOpacity>=.999,t.material.envMapIntensity=Math.max(Number(n.envMapIntensity)||0,0),t.material.color&&t.baseColor&&t.material.color.copy(t.baseColor),t.baseEmissiveIntensity=Ei(Number(n.emissiveIntensity)||0,0,2),t.baseEmissiveColor=t.baseColor?t.baseColor.clone():null,"emissive"in t.material&&t.material.emissive&&(t.baseEmissiveColor&&t.baseEmissiveIntensity>0?t.material.emissive.copy(t.baseEmissiveColor):t.material.emissive.set(0),t.material.emissiveIntensity=t.baseEmissiveIntensity),t.material.needsUpdate=!0}const Qb="#4f9dff",bU="#2563eb",yU=3;function xU(e){const t=String(e?.pickData?.surfaceType||e?.pickData?.surface?.type||"").trim().toLowerCase();return!t||t.includes("plane")||t.includes("planar")}function D2(e,t){if(!xU(t))return[0,0,0];const n=Array.isArray(t?.pickData?.normal)?t.pickData.normal:null;if(!e?.camera||!e?.modelGroup||!n||n.length<3)return[0,0,0];const r=Math.hypot(n[0],n[1],n[2]);if(r<=1e-9)return[0,0,0];const o=[n[0]/r,n[1]/r,n[2]/r],i=Array.isArray(t?.pickData?.center)?t.pickData.center:[0,0,0],s=e.modelGroup.position,a=[Number(i[0]||0)+Number(s?.x||0),Number(i[1]||0)+Number(s?.y||0),Number(i[2]||0)+Number(s?.z||0)],l=[e.camera.position.x-a[0],e.camera.position.y-a[1],e.camera.position.z-a[2]],u=o[0]*l[0]+o[1]*l[1]+o[2]*l[2]>=0?1:-1,d=Math.max(Number(e.modelRadius||1)*75e-5,.015);return[o[0]*u*d,o[1]*u*d,o[2]*u*d]}function SU(e,t,n,r){const o=n?.proxy||{},i=Number(r?.pickData?.triangleStart||0),s=Number(r?.pickData?.triangleCount||0);if(!(o.facePositions instanceof Float32Array)||!(o.faceIndices instanceof Uint32Array)||s<=0)return null;const a=o.faceIndices.slice(i*3,(i+s)*3);if(!a.length)return null;const l=D2(e,r),u=new Float32Array(a.length*3);let d=0;for(const p of a){const g=Number(p)*3;u[d]=o.facePositions[g]+l[0],u[d+1]=o.facePositions[g+1]+l[1],u[d+2]=o.facePositions[g+2]+l[2],d+=3}const m=new t.BufferGeometry;return m.setAttribute("position",new t.BufferAttribute(u,3)),m}function EU(e,t,n){const r=Number(n?.rowIndex);if(!Number.isInteger(r)||!Array.isArray(e?.displayRecords))return null;const o=D2(e,n),i=new t.Vector3,s=[];for(const l of e.displayRecords){const u=l?.mesh,d=u?.geometry,m=u?.userData?.faceIds,p=d?.getAttribute?.("position"),g=d?.getIndex?.();if(!(m instanceof Uint32Array)||!p||!g||!g.count)continue;const x=Math.min(m.length,Math.floor(g.count/3));for(let y=0;yString(t||"").trim()).filter(Boolean)}function jI(e){const t=String(e||"").trim();return t.startsWith("#")?t.slice(1).trim():t}function $m(e,t){if(!t?.size)return!1;if(t.has("__model__"))return!0;const n=jI(e);if(!n)return!1;for(const r of t){const o=jI(r);if(o&&(n===o||n.startsWith(`${o}.`)))return!0}return!1}function RU(e,t){if(!t?.size)return!0;const n=String(e?.partId||"").trim();return n?$m(n,t):t.has("__model__")}function PU(e,t,n){return t?(Number.isFinite(Number(e[n]))||(e[n]=Number.isFinite(Number(t.renderOrder))?Number(t.renderOrder):0),e[n]):0}function LI(e,t,n,r,o){if(!t)return;const i=PU(e,t,n);t.renderOrder=r?o:i}function OU(e,t,n,{writeTransparentDepth:r=!0}={}){const o=e?.material;if(!o)return;Object.hasOwn(e,"baseDepthWrite")||(e.baseDepthWrite=o.depthWrite!==!1);const i=t||n<.999;o.transparent!==i&&(o.transparent=i,o.needsUpdate=!0),o.depthWrite=i&&!r?!1:e.baseDepthWrite}const kU=Object.freeze({feature:"cadSurfaceFeatureOpacity",tangent:"cadSurfaceTangentOpacity",seam:"cadSurfaceSeamOpacity",degenerate:"cadSurfaceDegenerateOpacity"}),DU=Object.freeze({feature:"cadSurfaceFeatureColor",tangent:"cadSurfaceTangentColor",seam:"cadSurfaceSeamColor",degenerate:"cadSurfaceDegenerateColor"});function jU(e,t,n,r=null){const o=t?.material,i=o?.userData;if(!o||i?.cadSurfaceEdges!==!0)return;const s=n?.isColor?n:up(e,n)||i.cadSurfaceEdgeBaseColor;if(s?.isColor){i.cadSurfaceEdgeColor=s.clone();const m=i.cadSurfaceEdgeShader?.uniforms?.cadSurfaceEdgeColor;m?.value?.copy&&m.value.copy(s)}const a=r!=null&&Number.isFinite(Number(r))?Xa(Number(r),0,1):null,l=i.cadSurfaceEdgeBaseClassSettings||{},u=i.cadSurfaceEdgeShader?.uniforms||null,d=a!==null||s?.isColor&&i.cadSurfaceEdgeBaseColor?.isColor&&!s.equals(i.cadSurfaceEdgeBaseColor);for(const[m,p]of Object.entries(DU)){const g=up(e,l[m]?.color)||i.cadSurfaceEdgeBaseColor,x=d?s:g;x?.isColor&&u?.[p]?.value?.copy&&u[p].value.copy(x)}for(const[m,p]of Object.entries(kU)){const g=Number(l[m]?.opacity),x=a===null?Number.isFinite(g)?g:null:a;x!==null&&(i[`cadSurfaceEdge${m}Opacity`]=x,u?.[p]&&(u[p].value=x))}}function Ng(e,t,{viewerTheme:n,edgeSettings:r,hiddenPartIds:o,hoveredPartId:i,focusedPartId:s,selectedPartIds:a,showEdges:l,displayMode:u=Dt.SOLID}){const d=new Set(Array.isArray(o)?o:[]),m=new Set(Array.isArray(a)?a:[]),p=new Set((Array.isArray(i)?i:[i]).map(C=>String(C||"").trim()).filter(Boolean)),g=r?.color||n?.edge||Yn.edge,x=Number.isFinite(Number(n?.surfaceOpacity))?Number(n.surfaceOpacity):1,y=new Set(Ja(s)),S=y.size>0,b=Number.isFinite(Number(r?.opacity))?Xa(Number(r.opacity),0,1):n?.edgeOpacity??Yn.edgeOpacity??MU,I=ZV(u),A=Number.isFinite(Number(r?.highlightOpacity))?Xa(Number(r.highlightOpacity),0,1):1,{hoveredSurfaceColor:N,hoveredEdgeColor:P,selectedSurfaceColor:R,selectedEdgeColor:v}=TU(e,{edgeSettings:r});for(const C of Array.isArray(t)?t:[]){const T=C.effectStyle&&typeof C.effectStyle=="object"?C.effectStyle:{},k=C.effectVisible===!1,z=up(e,T.color),Y=up(e,T.edgeColor),K=up(e,T.emissive),J=$m(C.partId,d),G=!J&&($m(C.partId,m)||C.effectHighlighted===!0),Q=!J&&!k&&$m(C.partId,p),D=!J&&!k&&S&&$m(C.partId,y),$=!J&&!k&&S&&!D,ie=G||Q;C.mesh.visible=!k&&!J,C.edges&&(C.edges.visible=l&&!k&&!J),LI(C,C.mesh,"baseMeshRenderOrder",ie,IU),LI(C,C.edges,"baseEdgeRenderOrder",ie,AU);const W=Number.isFinite(Number(C.baseOpacity))?Number(C.baseOpacity):x,Z=Number.isFinite(Number(T.opacity))?Xa(Number(T.opacity),0,1):1,Ee=Number.isFinite(Number(T.edgeOpacity))?Xa(Number(T.edgeOpacity),0,1):Z,re=G||Q?A*Ee:null,be=Math.min(W*Z,Vm),_e=W*Z,Ie=ie?Xa(I?_e+(G?_U:NU)*Z:A*Z,0,1):_e,oe=J?0:$?be:Ie;OU(C,J||$||ie,oe,{writeTransparentDepth:!J&&!$&&!I}),C.material.opacity=oe,C.baseColor&&C.material.color&&C.material.color.copy(G?R:Q?N:z||C.baseColor),"emissive"in C.material&&C.material.emissive&&(G?C.material.emissive.copy(R):Q?C.material.emissive.copy(N):C.baseEmissiveColor&&C.baseEmissiveIntensity>0?C.material.emissive.copy(C.baseEmissiveColor):C.material.emissive.set(0),C.material.emissiveIntensity=G?.08:Q?.12:Xa(K?Number(T.emissiveIntensity)||.22:Number(C.baseEmissiveIntensity)||0,0,2),!G&&!Q&&K&&C.material.emissive.copy(K));const me=G?v:Q?P:Y||g;jU(e,C,me,re),C.edgeMaterial&&(C.edgeMaterial.color.set(me),p2(C.edgeMaterial,G||Q?A*Ee:J||$?oe:b*Ee))}}function uf(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Gm(e,t,n){const r=e?.tables?.[n],o=e?.[t];return!Array.isArray(r)||!Array.isArray(o)?[]:o.filter(Array.isArray).map(i=>Object.fromEntries(r.map((s,a)=>[s,i[a]])))}function FI(e,t,n,r){const o=e?.relations?.[n];if(Array.isArray(o)||ArrayBuffer.isView(o))return o;const i=e?.relations?.[r];return typeof i=="string"&&t?.[i]?t[i]:[]}function LU(e,t,n,r){const o=e?.[n]?.[r];return typeof o=="string"&&t?.[o]?t[o]:new Uint32Array(0)}function dp(e,t){if(!e||!t.startsWith(`${e}.`))return t;const n=t.slice(e.length+1);return n.startsWith("s")||n.startsWith("f")||n.startsWith("e")?n:t}function FU(e){return e==="occurrence"?"Occurrence":e==="shape"?"Shape":e==="face"?"Face":"Edge"}function _a(e,t){if(!Array.isArray(t)||t.length<3)return t;if(!Array.isArray(e)||e.length<16)return[Number(t[0]),Number(t[1]),Number(t[2])];const n=Number(t[0]),r=Number(t[1]),o=Number(t[2]);return[e[0]*n+e[1]*r+e[2]*o+e[3],e[4]*n+e[5]*r+e[6]*o+e[7],e[8]*n+e[9]*r+e[10]*o+e[11]]}function zI(e){const t=Number(e?.[0]||0),n=Number(e?.[1]||0),r=Number(e?.[2]||0),o=Math.hypot(t,n,r);return o<=1e-9?null:[t/o,n/o,r/o]}function sh(e,t){return!Array.isArray(t)||t.length<3||!Array.isArray(e)||e.length<16?zI(t||[]):zI([e[0]*t[0]+e[1]*t[1]+e[2]*t[2],e[4]*t[0]+e[5]*t[1]+e[6]*t[2],e[8]*t[0]+e[9]*t[1]+e[10]*t[2]])}function mc(e,t){if(!uf(t))return t;const n=Array.isArray(t.min)?t.min:[0,0,0],r=Array.isArray(t.max)?t.max:[0,0,0],o=[[n[0],n[1],n[2]],[n[0],n[1],r[2]],[n[0],r[1],n[2]],[n[0],r[1],r[2]],[r[0],n[1],n[2]],[r[0],n[1],r[2]],[r[0],r[1],n[2]],[r[0],r[1],r[2]]].map(l=>_a(e,l)),i=o.map(l=>l[0]),s=o.map(l=>l[1]),a=o.map(l=>l[2]);return{min:[Math.min(...i),Math.min(...s),Math.min(...a)],max:[Math.max(...i),Math.max(...s),Math.max(...a)]}}function bw(e,t){if(!uf(t))return t;const n=new Set(["origin","center","location"]),r=new Set(["axis","direction","normal"]);return Object.fromEntries(Object.entries(t).map(([o,i])=>n.has(o)&&Array.isArray(i)&&i.length===3?[o,_a(e,i)]:r.has(o)&&Array.isArray(i)&&i.length===3?[o,sh(e,i)]:[o,i]))}function r1(e,t){return Array.isArray(t)?t.map(n=>Array.isArray(n)&&n.length>=3?_a(e,n):n):t}function zU(e,t){return Array.isArray(t)?t.map(n=>uf(n)&&Array.isArray(n.points)?{...n,points:r1(e,n.points)}:n):t}function BU(e,t){if(!uf(t))return t;const n=new Set(["origin","center","location"]),r=new Set(["axis","direction","normal","xDir","yDir"]);return Object.fromEntries(Object.entries(t).map(([o,i])=>n.has(o)&&Array.isArray(i)&&i.length===3?[o,_a(e,i)]:r.has(o)&&Array.isArray(i)&&i.length===3?[o,sh(e,i)]:[o,i]))}function o1(e,t){if(!(e instanceof Float32Array)||!Array.isArray(t)||t.length<16)return e;const n=new Float32Array(e.length);for(let r=0;rr1(t,n)):e.loops,loopsMeta:zU(t,e.loopsMeta),surface:BU(t,e.surface),centroid:Array.isArray(e.centroid)?_a(t,e.centroid):e.centroid,transform:t}}function $U(e,t,n){return n?`topology|${n}|${t}|${e}`:e}function GU(e,t){if(e==="occurrence")return String(t.name||t.sourceName||t.id||"").trim();if(e==="shape"){const n=String(t.name||t.sourceName||"").trim(),r=`${t.kind||"shape"}${t.volume?` volume=${t.volume}`:t.area?` area=${t.area}`:""}`;return n?`${n} ${r}`:r}return e==="face"?`${t.surfaceType||"face"} area=${t.area??0}`:`${t.curveType||"edge"} length=${t.length??0}`}function UU(e,t){const n=String(e||"").trim(),r=String(t||"").trim();return!r||n===r||n.startsWith(`${r}.`)}function yw(e,t){const n=String(e||"").trim();if(!n||!t||typeof t!="object"||!UU(n,t.sourceOccurrenceId))return"";const r=String(t.sourceRootOccurrenceId||"").trim(),o=String(t.targetRootOccurrenceId||"").trim();if(!r||!o)return"";if(n===r)return o;const i=`${r}.`;return n.startsWith(i)?`${o}.${n.slice(i.length)}`:""}function xw(e,t,n,r,o="",i=null){if(!t||!Number.isFinite(Number(n)))return"";if(i&&typeof i=="object"){const a=e==="occurrence"?String(t?.id||"").trim():String(t?.occurrenceId||"").trim(),l=yw(a,i);return l?e==="occurrence"?l:`${l}.${e==="shape"?"s":e==="face"?"f":"e"}${n+1}`:""}const s=String(o||"").trim();return s?e==="occurrence"?s:`${s}.${e==="shape"?"s":e==="face"?"f":"e"}${n+1}`:dp(r,String(t?.id||"").trim())}function WU(e,t,n="",r=null){const o=String(e||"").trim();if(!o)return"";const i=o.match(/^(.*)\.([sfe]\d+)$/i);if(!i)return dp(t,o);const s=String(i[1]||"").trim(),a=String(i[2]||"").trim();if(!s||!a)return dp(t,o);if(r&&typeof r=="object"){const u=yw(s,r);return u?`${u}.${a}`:""}const l=String(n||"").trim();return l?`${l}.${a}`:dp(t,o)}function HU(e,t,n,r="",o=null){if(e==="occurrence")return"";const i=String(t?.occurrenceId||"").trim();return i?o&&typeof o=="object"?yw(i,o):String(r||"").trim()||dp(n,i):""}function KU(e,t,n,r,o,i,s,a,l,u){const d=Number(e?.[i]||0),m=Number(e?.[s]||0),p=[],g=Math.min(t?.length||0,d+m);for(let x=d;xString(t.occurrenceId||"").trim()).filter(Boolean))].sort()}function Um(e,t){return!Array.isArray(t)||t.length<16?e:e.map(n=>({...n,transform:Array.isArray(n.transform)?n.transform:t,bbox:n.bbox?mc(t,n.bbox):n.bbox,center:Array.isArray(n.center)?_a(t,n.center):n.center,normal:Array.isArray(n.normal)?sh(t,n.normal):n.normal,params:n.params?bw(t,n.params):n.params}))}function YU(e,t){return!e||!Array.isArray(t)||t.length<16?e:{...e,bbox:e.bbox?mc(t,e.bbox):e.bbox,center:Array.isArray(e.center)?_a(t,e.center):e.center,normal:Array.isArray(e.normal)?sh(t,e.normal):e.normal,params:e.params?bw(t,e.params):e.params}}function BI(e,t){const n=Array.isArray(t?.[0])?t:[t],r=n.map(()=>0);return e.map(o=>{const i={...o};return n.forEach(([s,a],l)=>{const u=Math.max(0,Number(o?.[a]||0));i[s]=r[l],i[a]=u,r[l]+=u}),i})}function qU(e,{copyCadPath:t="",partId:n="",transform:r=null,remapOccurrenceId:o="",remapOccurrencePrefix:i=null}={}){const s=e?.manifest||{},a=e?.buffers||{},l=FI(s,a,"faceEdgeRows","faceEdgeRowsView"),u=FI(s,a,"edgeFaceRows","edgeFaceRowsView"),d=Um(Gm(s,"occurrences","occurrenceColumns"),r),m=Um(Gm(s,"shapes","shapeColumns"),r),p=BI(Um(Gm(s,"faces","faceColumns"),r),[["edgeStart","edgeCount"]]),g=BI(Um(Gm(s,"edges","edgeColumns"),r),[["faceStart","faceCount"]]),x=XU(m),y=x.length===1?x[0]:"",S={facePositions:o1(a.facePositions,r),faceIndices:a.faceIndices||new Uint32Array(0),faceIds:a.faceIds||new Uint32Array(0),faceRuns:LU(s,a,"faceProxy","runsView"),faceRunColumns:Array.isArray(s?.faceProxy?.runColumns)?s.faceProxy.runColumns:[],edgePositions:o1(a.edgePositions,r),edgeIndices:a.edgeIndices||new Uint32Array(0),edgeIds:a.edgeIds||new Uint32Array(0),faceEdgeRows:l,edgeFaceRows:u},b=[];b.push(...d.map((T,k)=>_g({selectorType:"occurrence",row:T,rowIndex:k,singleOccurrenceId:y,copyCadPath:t,partId:n,selectorTransform:r,remapOccurrenceId:o,remapOccurrencePrefix:i}))),b.push(...m.map((T,k)=>_g({selectorType:"shape",row:T,rowIndex:k,singleOccurrenceId:y,copyCadPath:t,partId:n,selectorTransform:r,remapOccurrenceId:o,remapOccurrencePrefix:i}))),b.push(...p.map((T,k)=>_g({selectorType:"face",row:T,rowIndex:k,singleOccurrenceId:y,copyCadPath:t,partId:n,selectorTransform:r,relationRows:l,targetRows:g,targetKey:"id",startKey:"edgeStart",countKey:"edgeCount",remapOccurrenceId:o,remapOccurrencePrefix:i,targetSelectorType:"edge"}))),b.push(...g.map((T,k)=>_g({selectorType:"edge",row:T,rowIndex:k,singleOccurrenceId:y,copyCadPath:t,partId:n,selectorTransform:r,relationRows:u,targetRows:p,targetKey:"id",startKey:"faceStart",countKey:"faceCount",remapOccurrenceId:o,remapOccurrencePrefix:i,targetSelectorType:"face"})));const I=b.filter(T=>String(T?.normalizedSelector||"").trim()),A=new Map(I.map(T=>[T.id,T])),N=new Map(I.map(T=>[T.normalizedSelector,T])),P=new Map(I.map(T=>[T.displaySelector,T])),R=new Map(I.filter(T=>T.selectorType==="face").map(T=>[T.rowIndex,T])),v=new Map(I.filter(T=>T.selectorType==="edge").map(T=>[T.rowIndex,T])),C=new Map(d.map((T,k)=>[k,xw("occurrence",T,k,y,o,i)||String(T?.id||"").trim()]));return{schemaVersion:Number(s.schemaVersion||1),surfaceEdgeRendering:!!s?.capabilities?.surfaceEdgeRendering,capabilities:s.capabilities||null,cadPath:t||String(s.cadRef||"").trim(),stepHash:String(s.stepHash||""),bbox:r?mc(r,s.bbox||{}):s.bbox,occurrences:d,shapes:m,faces:p,edges:g,vertices:[],references:I,referenceMap:A,referenceByNormalizedSelector:N,referenceByDisplaySelector:P,faceReferenceByRowIndex:R,edgeReferenceByRowIndex:v,vertexReferenceByRowIndex:new Map,occurrenceIdByRowIndex:C,faceReferenceMap:new Map(I.filter(T=>T.selectorType==="face").map(T=>[T.id,T])),edgeReferenceMap:new Map(I.filter(T=>T.selectorType==="edge").map(T=>[T.id,T])),vertexReferenceMap:new Map,singleOccurrenceId:y,proxy:S}}function ZU(e,{transform:t=null}={}){const n=e?.manifest||{};if(String(n.profile||"")==="surface-edges"){const m=n.edgeRendering&&typeof n.edgeRendering=="object"?n.edgeRendering:{};return{schemaVersion:Number(n.schemaVersion||1),surfaceEdgeRendering:!0,edgeRendering:{visibilityClasses:Array.isArray(m.visibilityClasses)?m.visibilityClasses.map(p=>String(p||"").trim()).filter(Boolean):[],generatedVisibilityClasses:Array.isArray(m.generatedVisibilityClasses)?m.generatedVisibilityClasses.map(p=>String(p||"").trim()).filter(Boolean):[],visibilityClassCounts:m.visibilityClassCounts||{},generatedVisibilityClassCounts:m.generatedVisibilityClassCounts||{}},stepHash:String(n.stepHash||""),bbox:t?mc(t,n.bbox||{}):n.bbox,edges:[],proxy:{edgePositions:new Float32Array(0),edgeIndices:new Uint32Array(0),edgeIds:new Uint32Array(0)}}}const r=e?.buffers||{},o=n?.edgeProxy||{},i=String(o.positionsView||"edgePositions"),s=String(o.indicesView||"edgeIndices"),a=String(o.edgeIdsView||"edgeIds"),l=r[i]instanceof Float32Array?r[i]:new Float32Array(0),u=r[s]instanceof Uint32Array?r[s]:new Uint32Array(0),d=r[a]instanceof Uint32Array?r[a]:new Uint32Array(0);return{schemaVersion:Number(n.schemaVersion||1),stepHash:String(n.stepHash||""),bbox:t?mc(t,n.bbox||{}):n.bbox,edges:Um(Gm(n,"edges","edgeColumns"),t),proxy:{edgePositions:o1(l,t),edgeIndices:u,edgeIds:d}}}function L2(e){return(e instanceof Map?[...e.entries()]:uf(e)?Object.entries(e):[]).map(([n,r])=>[String(n||"").trim(),Array.isArray(r)&&r.length>=16?r.slice(0,16).map(o=>Number(o)):null]).filter(([n,r])=>n&&r&&r.every(Number.isFinite))}function JU(e,t){const n=String(t||"").trim(),r=e.find(([i])=>i==="__model__"||i==="*"||i==="__all__")?.[1]||null;let o=null;for(const[i,s]of e)i==="__model__"||i==="*"||i==="__all__"||n&&(n===i||n.startsWith(`${i}.`))&&(!o||i.length>o[0].length)&&(o=[i,s]);return o?.[1]||r}function QU(e,t){return t==="occurrence"?String(e?.id||"").trim():String(e?.occurrenceId||e?.partId||"").trim()}function Wm(e,t,n){const r=[];return{rows:(Array.isArray(e)?e:[]).map(i=>{const s=JU(n,QU(i,t));return r.push(s),s?YU(i,s):i}),transforms:r}}function e4(e,t){return t?{...e,pickData:VU(e.pickData,t)}:e}function i1({positions:e,indices:t,ids:n,rowTransforms:r,elementSize:o}){if(!(e instanceof Float32Array)||!(t instanceof Uint32Array)||!t.length||!(n instanceof Uint32Array)||!n.length)return{positions:e,indices:t,ids:n};const i=Math.floor(t.length/o),s=new Float32Array(i*o*3),a=new Uint32Array(i*o),l=new Uint32Array(i);let u=0;for(let d=0;de4(b,a[b?.selectorType]?.[Number(b?.rowIndex)]||null)),u=new Map(l.map(b=>[b.id,b])),d=new Map(l.map(b=>[b.normalizedSelector,b])),m=new Map(l.map(b=>[b.displaySelector,b])),p=new Map(l.filter(b=>b.selectorType==="face").map(b=>[b.rowIndex,b])),g=new Map(l.filter(b=>b.selectorType==="edge").map(b=>[b.rowIndex,b])),x=e.proxy||{},y=i1({positions:x.facePositions,indices:x.faceIndices,ids:x.faceIds,rowTransforms:i.transforms,elementSize:3}),S=i1({positions:x.edgePositions,indices:x.edgeIndices,ids:x.edgeIds,rowTransforms:s.transforms,elementSize:2});return{...e,bbox:e.bbox?mc(n.find(([b])=>b==="__model__"||b==="*"||b==="__all__")?.[1],e.bbox):e.bbox,occurrences:r.rows,shapes:o.rows,faces:i.rows,edges:s.rows,references:l,referenceMap:u,referenceByNormalizedSelector:d,referenceByDisplaySelector:m,faceReferenceByRowIndex:p,edgeReferenceByRowIndex:g,faceReferenceMap:new Map(l.filter(b=>b.selectorType==="face").map(b=>[b.id,b])),edgeReferenceMap:new Map(l.filter(b=>b.selectorType==="edge").map(b=>[b.id,b])),proxy:{...x,facePositions:y.positions,faceIndices:y.indices,faceIds:y.ids,edgePositions:S.positions,edgeIndices:S.indices,edgeIds:S.ids}}}function n4(e,t=null){const n=L2(t);if(!e||!n.length)return e||null;const r=Wm(e.edges,"edge",n),o=e.proxy||{},i=i1({positions:o.edgePositions,indices:o.edgeIndices,ids:o.edgeIds,rowTransforms:r.transforms,elementSize:2}),s=n.find(([a])=>a==="__model__"||a==="*"||a==="__all__")?.[1]||null;return{...e,bbox:s&&e.bbox?mc(s,e.bbox):e.bbox,edges:r.rows,proxy:{...o,edgePositions:i.positions,edgeIndices:i.indices,edgeIds:i.ids}}}const VI=new WeakMap,r4=new WeakMap,o4=new WeakMap,i4=32;function $I(e,t={}){for(const n of Array.isArray(e)?e:[]){const r=n?.material;r&&(r.polygonOffset=!1,r.polygonOffsetFactor=0,r.polygonOffsetUnits=0,r.needsUpdate=!0)}}function F2(e){if(e){for(;e.children?.length;)F2(e.children[0]);if(e.parent?.remove?.(e),typeof e.userData?.beforeDispose=="function"&&(e.userData.beforeDispose(e),delete e.userData.beforeDispose),e.userData?.disposeGeometry!==!1&&e.geometry?.dispose?.(),e.userData?.disposeMaterial!==!1){const t=Array.isArray(e.material)?e.material:[e.material];for(const n of t)n?.dispose?.()}}}function s4(e,t=1e-6){if(!e?.elements||e.elements.length!==16)return!1;const n=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return e.elements.some((r,o)=>Math.abs(Number(r)-n[o])>t)}function a4(e){if(!e?.elements||e.elements.length!==16)return null;const t=e.elements;return[t[0],t[4],t[8],t[12],t[1],t[5],t[9],t[13],t[2],t[6],t[10],t[14],t[3],t[7],t[11],t[15]]}function l4(e){const t=Number(e);return Number.isFinite(t)?String(t):"0"}function c4(e){return e?.size?[...e.entries()].map(([t,n])=>{const r=Array.isArray(n)||ArrayBuffer.isView(n)?Array.from(n,l4):[];return`${String(t||"").trim()}:${r.join(",")}`}).sort().join("|"):""}function GI(e,t,n,r){if(!t||!n?.size)return null;const o=c4(n);if(!o)return null;let i=e.get(t);if(i||(i=new Map,e.set(t,i)),i.has(o))return i.get(o);const s=r(t,n);return i.set(o,s),i.size>i4&&i.delete(i.keys().next().value),s}function u4(e){const t=new Map;for(const n of Array.isArray(e)?e:[]){const r=String(n?.partId||"").trim();if(!r||!n?.effectMatrix||!s4(n.effectMatrix))continue;const o=a4(n.effectMatrix);o&&t.set(r,o)}return t}function UI(e){return Array.isArray(e?.edges)&&e.edges.some(t=>String(t?.visibilityClass||"").trim())}function d4(e,t){const n=Array.isArray(e?.edges)?e.edges:[],r=Array.isArray(t?.edges)?t.edges:[],o=n.every((i,s)=>{const a=r[s]||{},l=Number(i?.segmentStart),u=Number(a?.segmentStart),d=Number(i?.segmentCount),m=Number(a?.segmentCount);return(!Number.isFinite(l)||!Number.isFinite(u)||l===u)&&(!Number.isFinite(d)||!Number.isFinite(m)||d===m)});return!!(n.length&&n.length===r.length&&o&&!UI(e)&&UI(t))}function f4(e){return!!(e?.surfaceEdgeRendering||Number(e?.schemaVersion||0)>=3)}function m4(e,t){if(!d4(e,t))return e||null;const n=VI.get(e);if(n?.selectorRuntime===t)return n.runtime;const r={...e,edges:e.edges.map((o,i)=>({...o,visibilityClass:t.edges[i]?.visibilityClass||"feature"}))};return VI.set(e,{selectorRuntime:t,runtime:r}),r}function bx({selectorRuntime:e=null,displayEdgeRuntime:t=null,displayRecords:n=null,transformDisplayEdges:r=!0}={}){const o=u4(n),i=m4(t,e),s=o.size&&e?GI(r4,e,o,t4):null,a=r&&o.size&&i?GI(o4,i,o,n4):null,l=s||e||null,u=a||i||null;return{selectorTransforms:o,transformCount:o.size,transformedSelectorRuntime:s,transformedDisplayEdgeRuntime:a,selectorRuntime:l,displayEdgeRuntime:u,topologyRuntime:u||l}}function yx({edgesVisible:e=!1,wireframeMode:t=!1,cadEdgeSource:n=!1,displayEdgeRuntime:r=null,selectorRuntime:o=null,edgeSettings:i=null}={}){return!!(e&&!t&&n&&!f4(r||o)&&a$(r||o))}function WI({transformDetected:e=!1,topologyDisplayEdgesVisible:t=!1,displayEdgeRuntime:n=null,displayRecords:r=[]}={}){return!!(e&&t&&n&&Array.isArray(r)&&r.length>1)}const HI=1,p4=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;function di(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function zn(e,t=""){return String(e??t).trim()||t}function Wr(e,t=0){const n=Number(e);return Number.isFinite(n)?n:t}function h4(e,t,n){return Math.min(Math.max(e,t),n)}function z2(e){const t=zn(e,"number").toLowerCase();return["number","boolean","enum","select","color","string","button"].includes(t)?t==="select"?"enum":t:"number"}function g4(e){return(Array.isArray(e)?e:[]).map(t=>{if(di(t)){const r=zn(t.value);return r?{value:r,label:zn(t.label,r)}:null}const n=zn(t);return n?{value:n,label:n}:null}).filter(Boolean)}function b4(e,t){const n=di(t)?t:{},r=z2(n.type),o=Wr(n.min,0),i=Math.max(Wr(n.max,r==="number"?1:o),o),s=g4(n.options||n.values),a=r==="boolean"?!1:r==="color"?"#ffffff":r==="enum"?s[0]?.value||"":r==="string"?"":0;return{id:e,type:r,label:zn(n.label,e),description:zn(n.description),unit:zn(n.unit),min:o,max:i,step:Math.max(Wr(n.step,r==="number"?.01:1),0),defaultValue:B2({type:r,min:o,max:i,options:s},n.default??n.defaultValue??a),options:s}}function B2(e,t){const n=z2(e?.type);if(n==="boolean")return t===!0;if(n==="color"){const i=zn(t,zn(e?.defaultValue,"#ffffff"));return p4.test(i)?i:"#ffffff"}if(n==="enum"){const i=Array.isArray(e?.options)?e.options:[],s=zn(t,i[0]?.value||"");return i.some(a=>a.value===s)?s:i[0]?.value||""}if(n==="string")return String(t??"");if(n==="button")return Math.max(0,Math.floor(Wr(t,0)));const r=Wr(e?.min,0),o=Math.max(Wr(e?.max,r),r);return h4(Wr(t,Wr(e?.defaultValue,r)),r,o)}function y4(e){return Object.entries(di(e)?e:{}).map(([t,n])=>b4(zn(t),n)).filter(t=>t.id)}function x4(e){let t=String(e||"").split("?")[0].split("#")[0].replace(/\\/g,"/").trim();if(!t)return"";try{t=new URL(t,"http://localhost").pathname}catch{}const n=t.replace(/^\/+|\/+$/g,""),r=n.lastIndexOf("/"),o=r>=0?n.slice(0,r):"",s=(r>=0?n.slice(r+1):n).match(/^\.?(.+)\.step\.js$/);return s?.[1]?qE([o,s[1]].filter(Boolean).join("/")):""}function S4(e){const t=zn(e).replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||/^[a-z][a-z0-9+.-]*:/i.test(t))return"";const n=t.split("/").filter(o=>o&&o!==".");if(!n.length||n.some(o=>o===".."))return"";const r=n.join("/");return/\.(step|stp)$/i.test(r)?r:""}function E4(e){return qE(String(e||"").replace(/\.(step|stp)$/i,""))}function w4(e){const t=di(e)?e:{};return{...t,path:S4(t.path)}}function v4(e,t){if(!di(e)&&!t.path)return null;const n=di(e)?{...e}:{};return t.path?n.path=t.path:delete n.path,Object.keys(n).length?n:null}function C4(e,t=""){const n=di(e)?e:{},r=zn(n.ref),o=rh(r);if(o)return dc({selectors:o.selectors});const i=r.startsWith("#")?r.slice(1):"",s=JE(i||n.selector||n.selectors||n.occurrence||n.occurrences||[]);return s.length?dc({selectors:s}):r}function M4(e,{cadPath:t=""}={}){return Object.entries(di(e)?e:{}).map(([n,r])=>{const o=di(r)?r:{},i=zn(n);return i?{id:i,label:zn(o.label,i),description:zn(o.description),ref:C4(o,t),partIds:Array.isArray(o.partIds)?o.partIds.map(s=>zn(s)).filter(Boolean):[],axis:V2(o.axis,[0,0,1]),origin:A4(o.origin,null)}:null}).filter(Boolean)}function I4(e){return Object.entries(di(e)?e:{}).map(([t,n])=>{const r=di(n)?n:{},o=zn(t);return o?{id:o,label:zn(r.label,o),description:zn(r.description),duration:Math.max(Wr(r.duration??r.durationSeconds,1),.001),loop:r.loop!==!1,update:typeof r.update=="function"?r.update:null,raw:r}:null}).filter(Boolean)}function V2(e,t=[0,0,0]){const n=Array.isArray(e)?e:t;return[Wr(n?.[0],t[0]||0),Wr(n?.[1],t[1]||0),Wr(n?.[2],t[2]||0)]}function A4(e,t=[0,0,0]){return!Array.isArray(e)&&t===null?null:V2(e,t||[0,0,0])}function N4(e,{url:t="",cadPath:n=""}={}){if(!di(e))throw new Error("STEP runtime module must export an object");const r=di(e.manifest)?e.manifest:e,o=Number(r.schemaVersion||e.schemaVersion||1);if(o!==HI)throw new Error(`Unsupported STEP runtime module schemaVersion ${o||"unknown"}`);const i=w4(r.step),s=E4(i.path),a=s||qE(n)||x4(t),l=y4(r.parameters),u=Object.fromEntries(l.map(g=>[g.id,g])),d=Object.fromEntries(l.map(g=>[g.id,g.defaultValue])),m=v4(r.step,i),p={...r,schemaVersion:HI};return m?p.step=m:delete p.step,{url:zn(t),cadPath:a,step:{path:i.path,cadPath:s||a,explicit:!!i.path,inferred:!i.path&&!!a},module:e,manifest:p,features:M4(r.features,{cadPath:a}),parameters:l,parameterMap:u,defaultParameterValues:d,animations:I4(r.animations)}}async function _4(e,t={}){const n=await import(e);return N4(n?.default??n,{url:e,...t})}function wb(e,t={}){const n=e?.parameterMap||{};return Object.fromEntries(Object.values(n).map(r=>[r.id,B2(r,di(t)&&Object.hasOwn(t,r.id)?t[r.id]:r.defaultValue)]))}function T4(e){const t=Array.isArray(e?.min)?e.min:[0,0,0],n=Array.isArray(e?.max)?e.max:t;return[(Wr(t[0])+Wr(n[0]))/2,(Wr(t[1])+Wr(n[1]))/2,(Wr(t[2])+Wr(n[2]))/2]}function R4(e){const t=(Array.isArray(e)?e:[]).filter(o=>Array.isArray(o?.min)&&Array.isArray(o?.max));if(!t.length)return null;const n=[1/0,1/0,1/0],r=[-1/0,-1/0,-1/0];for(const o of t)for(let i=0;i<3;i+=1)n[i]=Math.min(n[i],Wr(o.min[i])),r[i]=Math.max(r[i],Wr(o.max[i]));return{min:n,max:r}}function s1(e,t){const n=zn(e),r=Array.isArray(t?.parts)?t.parts:[];return!n||!r.length?[]:r.filter(o=>[o?.id,o?.occurrenceId].map(s=>zn(s)).filter(Boolean).some(s=>s===n||s.startsWith(`${n}.`)||n.startsWith(`${s}.`))).map(o=>zn(o.id||o.occurrenceId)).filter(Boolean)}function KI(e,t){const n=zn(e);return!n||!t?null:t.referenceByNormalizedSelector?.get(n)||t.referenceByDisplaySelector?.get(n)||t.referenceMap?.get(n)||null}function Ul(e){return[...new Set((Array.isArray(e)?e:[]).map(t=>zn(t)).filter(Boolean))]}function P4(e){const t=rh(e?.ref);return t?t.selectors.length?t.selectors:["__model__"]:[]}function ey(e,{meshData:t=null,selectorRuntime:n=null}={}){const r=Array.isArray(t?.parts)?t.parts:[],o=new Map(r.map(s=>[zn(s.id||s.occurrenceId),s])),i=r.length?r.map(s=>zn(s.id||s.occurrenceId)).filter(Boolean):["__model__"];return Object.fromEntries((Array.isArray(e?.features)?e.features:[]).map(s=>{const a=P4(s),l=a.map(g=>g==="__model__"?null:KI(g,n)).filter(Boolean),u=a.flatMap(g=>{if(g==="__model__")return i;const x=p5(g);if(x?.occurrenceId)return s1(x.occurrenceId,t);const y=KI(g,n);return s1(y?.partId||y?.occurrenceId||g,t)}),d=Ul([...s.partIds,...u]),m=d.map(g=>o.get(g)).filter(Boolean),p=R4(m.map(g=>g.bounds))||t?.bounds||null;return[s.id,{...s,selectors:a,references:l,partIds:d,parts:m,bounds:p,center:s.origin||T4(p),transform:m.length===1&&m[0]?.transform||null,transforms:m.map(g=>g?.transform||null),missing:a.length>0&&d.length===0&&a[0]!=="__model__"}]}))}function vd(e,t,n){if(Array.isArray(e))return Ul(e.flatMap(s=>vd(s,t,n)));if(di(e)){if(Array.isArray(e.partIds))return Ul(e.partIds);if(e.partId)return Ul([e.partId]);if(e.feature)return vd(e.feature,t,n);if(e.ref)return vd(e.ref,t,n)}const r=zn(e);if(!r)return[];if(r==="*"||r==="all"||r==="__all__"){const s=Array.isArray(n?.parts)?n.parts:[];return s.length?Ul(s.map(a=>a?.id||a?.occurrenceId)):["__model__"]}const o=t?.[r];if(o)return Ul(o.partIds);const i=rh(r);if(i){const s=i.selectors.length?i.selectors:["*"];return Ul(s.flatMap(a=>vd(a,t,n)))}return Ul(s1(r,n))}function ha(e,t=0){const n=Number(e);return Number.isFinite(n)?n:t}function O4(e,t,n){return Math.min(Math.max(e,t),n)}function ty(e){return[...new Set((Array.isArray(e)?e:[]).map(t=>String(t||"").trim()).filter(Boolean))]}function Sw(e,t){const n=new e.Matrix4;return!Array.isArray(t)||t.length!==16?(n.identity(),n):(n.set(Number(t[0])||0,Number(t[1])||0,Number(t[2])||0,Number(t[3])||0,Number(t[4])||0,Number(t[5])||0,Number(t[6])||0,Number(t[7])||0,Number(t[8])||0,Number(t[9])||0,Number(t[10])||0,Number(t[11])||0,Number(t[12])||0,Number(t[13])||0,Number(t[14])||0,Number(t[15])||0),n)}function $2(e,t,n=!0){return!n||e?.partTransformsBaked===!0?null:t?.transform||null}function Ew(e,t=[0,0,0]){return Array.isArray(e)||ArrayBuffer.isView(e)?[ha(e[0],t[0]||0),ha(e[1],t[1]||0),ha(e[2],t[2]||0)]:e&&typeof e=="object"?[ha(e.x,t[0]||0),ha(e.y,t[1]||0),ha(e.z,t[2]||0)]:[...t]}function a1(e,t,n=[0,0,0]){const r=Ew(t,n);return new e.Vector3(r[0],r[1],r[2])}function k4(e,t={}){const n=a1(e,t.axis,[0,0,1]);n.lengthSq()<=1e-12&&n.set(0,0,1),n.normalize();const r=a1(e,t.origin,[0,0,0]),o=Number.isFinite(Number(t.angleRad))?Number(t.angleRad):ha(t.angleDeg,0)*Math.PI/180;return new e.Matrix4().makeTranslation(r.x,r.y,r.z).multiply(new e.Matrix4().makeRotationAxis(n,o)).multiply(new e.Matrix4().makeTranslation(-r.x,-r.y,-r.z))}function D4(e,t={}){const n=t.scale??t,r=Array.isArray(n)||ArrayBuffer.isView(n)?Ew(n,[1,1,1]):[ha(n,1),ha(n,1),ha(n,1)],o=a1(e,t.origin,[0,0,0]);return new e.Matrix4().makeTranslation(o.x,o.y,o.z).multiply(new e.Matrix4().makeScale(r[0],r[1],r[2])).multiply(new e.Matrix4().makeTranslation(-o.x,-o.y,-o.z))}function j4(e,t){const n=Ew(t,[0,0,0]);return new e.Matrix4().makeTranslation(n[0],n[1],n[2])}function L4(e,t={}){if(!t||typeof t!="object")return new e.Matrix4;if(Array.isArray(t.matrix)&&t.matrix.length===16)return Sw(e,t.matrix);const n=new e.Matrix4;return t.scale!==void 0&&n.premultiply(D4(e,t)),t.rotate&&typeof t.rotate=="object"&&n.premultiply(k4(e,t.rotate)),t.translate!==void 0&&n.premultiply(j4(e,t.translate)),n}function F4(e,t={}){if(!t||typeof t!="object")return new e.Matrix4;const n=Array.isArray(t.transforms)?t.transforms:[t],r=new e.Matrix4;for(const o of n)r.premultiply(L4(e,o));return r}function z4(e,t=1e-6){if(!e?.elements||e.elements.length!==16)return!1;const n=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return e.elements.some((r,o)=>Math.abs(Number(r)-n[o])>t)}function G2(e){for(const t of Array.isArray(e)?e:[])t.effectMatrix=null,t.effectStyle=null,t.effectVisible=null,t.effectHighlighted=!1}function B4(e,t){const n=Array.isArray(e?.parts)?e.parts.map(o=>String(o?.id||o?.occurrenceId||"").trim()).filter(Boolean):[];if(n.length)return ty(n);const r=(Array.isArray(t)?t:[]).map(o=>String(o?.partId||"").trim()).filter(Boolean);return ty(r.length?r:["__model__"])}function l1(e,t,n,r){if(e&&typeof e=="object"&&!Array.isArray(e)){if(Array.isArray(e.partIds))return ty(e.partIds);if(e.partId)return ty([e.partId]);if(e.feature)return l1(e.feature,t,n,r);if(e.ref)return vd(String(e.ref),t,n)}const o=String(e||"").trim();return o==="*"||o==="all"||o==="__all__"?B4(n,r):vd(e,t,n)}function ny(e,{meshData:t,features:n,runtime:r,effectsByPartId:o,onTransformEffect:i}){const s=l=>{const u=String(l||"").trim();if(!u)return null;const d=o.get(u)||{matrix:null,style:null,visible:null,highlighted:!1};return o.set(u,d),d},a=(l,u)=>{const d=l1(l,n,t,r?.displayRecords);for(const m of d){const p=s(m);p&&u(p,m)}return d};return{transform(l,u){const d=F4(e,u),m=a(l,p=>{p.matrix=p.matrix?p.matrix.clone().premultiply(d):d.clone()});m.length&&z4(d)&&i?.({target:l,spec:u,partIds:m,matrix:d.clone()})},style(l,u={}){!u||typeof u!="object"||a(l,d=>{d.style={...d.style||{},...u}})},visible(l,u=!0){a(l,d=>{d.visible=u!==!1})},highlight(l,u=!0){a(l,d=>{d.highlighted=u!==!1})},clear(l){const u=l1(l,n,t,r?.displayRecords);for(const d of u)o.delete(d)}}}function V4(e={}){const t=Math.max(Number(e.duration)||0,0),n=Math.max(Number(e.elapsedSec)||0,0);return{elapsed:n,elapsedSec:n,duration:t,progress:t>0?O4(n/t,0,1):0,cycle:t>0?n/t:0,playing:e.playing===!0,speed:Math.max(Number(e.speed)||1,0)}}function kp({runtime:e,stepModuleRuntime:t,features:n,effects:r,cleanup:o}){const i=t?.definition||null;return{THREE:e?.THREE,scene:e?.scene,modelGroup:e?.modelGroup,edgesGroup:e?.edgesGroup,runtime:e,manifest:i?.manifest||{},module:i?.module||null,cadPath:t?.cadPath||i?.cadPath||"",params:t?.parameterValues||{},features:n,effects:r,time:V4(t?.animationState),cleanup:typeof o=="function"?o:()=>{},requestRender:()=>e?.requestRender?.()}}function U2(e,t,n){G2(t);for(const r of Array.isArray(t)?t:[]){const o=n.get(String(r?.partId||"").trim());o&&(r.effectMatrix=o.matrix instanceof e.Matrix4?o.matrix.clone():null,r.effectStyle=o.style&&typeof o.style=="object"?{...o.style}:null,r.effectVisible=o.visible,r.effectHighlighted=o.highlighted===!0)}}function xx(e,t,n){if(!t||!(n instanceof e.Matrix4))return;t.matrixAutoUpdate=!1;const r=t.matrix instanceof e.Matrix4?t.matrix:new e.Matrix4;r.copy(n),t.matrix=r,t.matrixWorldNeedsUpdate=!0}function W2(e,t){if(!t||!e?.Matrix4)return null;const n=[t.effectMatrix,t.explodedViewMatrix].filter(o=>o instanceof e.Matrix4);if(!n.length)return null;const r=new e.Matrix4;for(const o of n)r.premultiply(o);return r}function $4(e,t){const n=Sw(e,t?.baseTransform),r=W2(e,t);return r?r.multiply(n):n}function tc(e,t){if(!t)return;const n=$4(e,t);xx(e,t.mesh,n),xx(e,t.edges,n),xx(e,t.silhouette,n)}function Cd(e){return(Array.isArray(e)?e:[e]).map(t=>String(t||"").trim()).filter(Boolean)}function XI(e,t=[]){const n=String(e||"").trim();if(!n)return!1;for(const r of t)if(n===r||n.startsWith(`${r}.`))return!0;return!1}function ww(e=[]){const t=[],n=new Set;for(const r of Array.isArray(e)?e:[]){const o=String(r?.partId||"").trim();!o||n.has(o)||(n.add(o),t.push(r))}return t}function G4(e=[]){return ww(e).map(t=>String(t.partId||"").trim())}function U4(e={},t=[],n={},r=.035,{transformByRecord:o=!1,displayRecords:i=[]}={}){const s=a=>Number.isFinite(Number(a))?Number(a):null;return JSON.stringify({color:String(e?.color||""),opacity:s(e?.opacity),thickness:s(e?.thickness),includePartIds:Cd(e?.includePartIds),excludePartIds:Cd(e?.excludePartIds),visibilityClasses:Cd(e?.visibilityClasses),classes:e?.classes&&typeof e.classes=="object"?Object.fromEntries(Object.entries(e.classes).map(([a,l])=>[a,{color:String(l?.color||""),opacity:s(l?.opacity),thickness:s(l?.thickness)}])):null,highlightColor:String(e?.highlightColor||""),highlightOpacity:s(e?.highlightOpacity),highlightRenderOrder:s(e?.highlightRenderOrder),focusedPartIds:Cd(t),dimmedOpacity:r,baseEdge:String(n?.edge||""),baseEdgeOpacity:s(n?.edgeOpacity),baseEdgeThickness:s(n?.edgeThickness),transformByRecord:o===!0,recordPartIds:o===!0?G4(i):[]})}function H2(e,t,n){const r=e?.THREE;if(!r||!t)return!1;const o=W2(r,n)||new r.Matrix4;t.matrixAutoUpdate=!1;const i=t.matrix instanceof r.Matrix4?t.matrix:new r.Matrix4,s=!i.equals(o);s&&(i.copy(o),t.matrix=i,t.matrixWorldNeedsUpdate=!0);const a=n?.mesh?.visible!==!1&&n?.effectVisible!==!1;return t.visible!==a?(t.visible=a,!0):s}function K2(e,t,n=[]){if(!t?.children?.length)return!1;const r=new Map;for(const i of ww(n))r.set(String(i.partId||"").trim(),i);let o=!1;for(const i of t.children){const s=String(i?.userData?.cadTopologyDisplayRecordPartId||"").trim(),a=r.get(s)||null;if(!a){i.visible!==!1&&(i.visible=!1,o=!0);continue}o=H2(e,i,a)||o}return o&&e.edgesGroup?.updateMatrixWorld?.(!0),o}function X2(e,t=[]){return K2(e,e?.topologyDisplayEdgeLine,t)}function Y2(e,t,{edgeSettings:n={},focusedPartIds:r=[],viewerTheme:o={},dimmedOpacity:i=.035,displayRecords:s=[]}={}){if(!e?.THREE||!t)return null;const a=ww(s);if(!a.length)return null;const l=new e.THREE.Group,u=Cd(r),d=Cd(n?.highlightPartIds),m=Number.isFinite(Number(n?.opacity))?Number(n.opacity):null;for(const p of a){const g=String(p?.partId||"").trim();if(!g||d.length&&!XI(g,d))continue;const x=u.length&&!XI(g,u)?i:m,y=d.length?{...n,highlightPartIds:[g]}:{...n,includePartIds:[g],...x!==null?{opacity:x}:{}},S=dw(e,t,y,o);S&&(S.userData={...S.userData||{},cadTopologyDisplayRecordPartId:g},H2(e,S,p),l.add(S))}return l.children.length?(l.name="TopologyDisplayEdges",l.userData.partId="__topology__",l.userData.disposeGeometry=!1,l.userData.disposeMaterial=!1,l):null}function Tg(e,t,{visible:n=!1,edgeSettings:r={},focusedPartIds:o=[],viewerTheme:i={},dimmedOpacity:s=.035,transformByRecord:a=!1,displayRecords:l=[],syncClip:u=null}={}){if(!e?.THREE||!e?.edgesGroup)return!1;const d=n?t:null,m=d?U4(r,o,i,s,{transformByRecord:a,displayRecords:l}):"",p=e.topologyDisplayEdgeLine||null;if(p&&p.userData?.cadTopologyDisplayEdgeRuntime===d&&p.userData?.cadTopologyDisplayEdgeSettingsKey===m){const x=a?K2(e,p,l):!1;return x&&($I(e.displayRecords,r),u?.(e),e.requestRender?.()),x}if(p&&(e.edgesGroup.remove(p),F2(p),e.topologyDisplayEdgeLine=null),!d)return u?.(e),e.requestRender?.(),!0;const g=a?Y2(e,d,{edgeSettings:r,focusedPartIds:o,viewerTheme:i,dimmedOpacity:s,displayRecords:l}):dw(e,d,{...r,focusedPartIds:o,dimmedOpacity:s},i);return g?(g.userData={...g.userData||{},cadTopologyDisplayEdgeRuntime:d,cadTopologyDisplayEdgeSettingsKey:m},e.topologyDisplayEdgeLine=g,e.edgesGroup.add(g),e.edgesGroup.updateMatrixWorld?.(!0),$I(e.displayRecords,r),u?.(e),e.requestRender?.(),!0):(u?.(e),e.requestRender?.(),!0)}const xo=1e-6,W4=Math.PI*(3-Math.sqrt(5)),q2=Object.freeze({x:0,y:1,z:2});function Z2(e,t,n){return Math.min(Math.max(e,t),n)}function dn(e,t=0){const n=Number(e);return Number.isFinite(n)?n:t}function J2(e,t,n=null){const r=Array.isArray(t?.min)||ArrayBuffer.isView(t?.min)?t.min:null,o=Array.isArray(t?.max)||ArrayBuffer.isView(t?.max)?t.max:null;return!r||!o?n?.clone?.()||new e.Vector3:new e.Vector3((dn(r[0])+dn(o[0]))/2,(dn(r[1])+dn(o[1]))/2,(dn(r[2])+dn(o[2]))/2)}function ry(e,t){const n=Array.isArray(t?.min)||ArrayBuffer.isView(t?.min)?t.min:null,r=Array.isArray(t?.max)||ArrayBuffer.isView(t?.max)?t.max:null;return!n||!r?0:new e.Vector3(Math.max(dn(r[0])-dn(n[0]),0),Math.max(dn(r[1])-dn(n[1]),0),Math.max(dn(r[2])-dn(n[2]),0)).length()/2}function Jl(e,t){const n=Array.isArray(e?.min)||ArrayBuffer.isView(e?.min)?e.min:null,r=Array.isArray(e?.max)||ArrayBuffer.isView(e?.max)?e.max:null;return!n||!r?0:Math.max(dn(r[t])-dn(n[t]),0)}function H4(e){return Math.max(Jl(e,0),Jl(e,1),Jl(e,2))}function K4(e,t=[0,0,0],n=1){return!e||!Array.isArray(e.min)||!Array.isArray(e.max)?null:{min:e.min.map((r,o)=>dn(r)+dn(t[o])*n),max:e.max.map((r,o)=>dn(r)+dn(t[o])*n)}}function vw(e){const t=[1/0,1/0,1/0],n=[-1/0,-1/0,-1/0];let r=0;for(const o of Array.isArray(e)?e:[])if(!(!o||!Array.isArray(o.min)||!Array.isArray(o.max))){r+=1;for(let i=0;i<3;i+=1)t[i]=Math.min(t[i],dn(o.min[i])),n[i]=Math.max(n[i],dn(o.max[i]))}return r>0&&t.every(Number.isFinite)&&n.every(Number.isFinite)?{min:t,max:n}:null}function Sx(e,t,n=null){return t?.isVector3?t:Array.isArray(t)||ArrayBuffer.isView(t)?new e.Vector3(dn(t[0]),dn(t[1]),dn(t[2])):n}function Q2(e){const n=String(e||"").trim().match(/^o\d+(?:\.\d+)*/i);return n?n[0].split(".").filter(Boolean):[]}function X4(e=[]){const t=e.map(o=>Q2(o?.partId)).filter(o=>o.length>1);if(!t.length)return[];const n=[],r=Math.min(...t.map(o=>o.length));for(let o=0;os[o]===i))break;n.push(i)}return n.length>=r?n.slice(0,-1):n}function Y4(e,{depth:t=1,commonPrefix:n=[]}={}){const r=String(e||"").trim(),o=Q2(r);if(!o.length)return r;const i=Math.max(1,Math.min(Math.round(Number(t))||1,HS)),s=Math.min(n.length,Math.max(o.length-1,0)),a=Math.min(o.length,s+i);return o.slice(0,a).join(".")||r}function q4(e){const t=String(e?.partId||"").trim();return!!(e?.mesh&&t&&t!=="__model__")}function Z4(e,t,n){const r=X4(t),o=new Map;return t.forEach((i,s)=>{const a=Y4(i?.partId,{depth:n.depth,commonPrefix:r})||String(i?.partId||`part:${s}`),l=i?.partBounds&&Array.isArray(i.partBounds.min)&&Array.isArray(i.partBounds.max)?i.partBounds:null,u=o.get(a)||{key:a,records:[],recordIndex:s,boundsList:[]};u.records.push(i),l&&u.boundsList.push(l),o.set(a,u)}),[...o.values()].map(i=>{const s=vw(i.boundsList)||i.records[0]?.partBounds||null;return{...i,bounds:s,center:J2(e,s),radius:ry(e,s)}})}function J4(e,t,n){const r=new e.Vector3;return r.setComponent(q2[t]??2,n==="negative"?-1:1),r}function Q4(e,t,n){const r=Math.max(1,n),o=r>1?1-(t+.5)/r*2:0,i=Math.sqrt(Math.max(0,1-o*o)),s=t*W4,a=new e.Vector3(Math.cos(s)*i,Math.sin(s)*i,o);return a.lengthSq()<=xo&&a.set(1,0,0),a.normalize()}function eW(e,t,n,r,o,i){const s=t.center?.isVector3?t.center.clone().sub(n):new e.Vector3;return s.lengthSq()<=xo?s.copy(Q4(e,r,o)):s.normalize(),i==="negative"?s.multiplyScalar(-1):s}function tW(e,t,n,r){const o=J2(e,n),i=Math.max(ry(e,n),xo),s=Math.max(H4(n),xo),a=Math.max(dn(r.spacing,1.45),.25),l=Math.max(i*.32*a,i*.12),u=[],d=t.filter(m=>m.records.length>0&&m.bounds).sort((m,p)=>m.recordIndex-p.recordIndex);if(d.forEach((m,p)=>{const g=eW(e,m,o,p,d.length,r.direction),x=ry(e,m.bounds),y=l+Math.min(x*.18*a,i*.2*a),S=g.clone().multiplyScalar(y);for(const b of m.records)u.push({record:b,partId:String(b.partId||"").trim(),groupKey:m.key,layerIndex:p,direction:g.clone(),distance:y,translation:S.clone(),matrix:new e.Matrix4})}),r.keepBaseGrounded!==!1){const m=Array.isArray(n?.min)||ArrayBuffer.isView(n?.min)?n.min:null,p=m?dn(m[2]):null,g=vw(u.map(y=>K4(y.record?.partBounds,y.translation.toArray(),1))),x=Array.isArray(g?.min)?dn(g.min[2]):null;if(Number.isFinite(p)&&Number.isFinite(x)&&xxo?S.translation.clone().normalize():S.direction}}return u}function nW(e,t=[],n=null,r={}){if(!e?.Vector3||!e?.Matrix4)return[];const o=Wb(r),i=o.axis==="radial",s=q2[o.axis]??2,a=(Array.isArray(t)?t:[]).filter(q4);if(a.length<2)return[];const l=Math.max(ry(e,n),xo),u=Math.max(Jl(n,s),xo),d=Z4(e,a,o).filter(C=>C.records.length>0&&C.bounds);if(d.length<2)return[];if(i)return tW(e,d,n,o);const m=d.sort((C,T)=>{const k=dn(C.center?.getComponent?.(s)),z=dn(T.center?.getComponent?.(s));return Math.abs(k-z)>xo?k-z:C.recordIndex-T.recordIndex}),p=Math.max(...m.map(C=>Jl(C.bounds,s)),u*.08,xo),g=m.map(C=>Jl(C.bounds,s)).filter(C=>C>xo).sort((C,T)=>C-T),x=g.length?g[Math.floor(g.length/2)]:p,y=Math.max(u*.025,p*.18,xo),S=Math.max(dn(o.spacing,1.45),.25),b=Math.max(u*.075,x*.35,l*.035,xo)*S,I=J4(e,o.axis,o.direction),A=[];for(const C of m){const T=dn(C.center.getComponent(s)),k=A[A.length-1];o.mergeCoplanar===!0&&k&&Math.abs(T-k.center)<=y?(k.groups.push(C),k.bounds=vw([k.bounds,C.bounds])||k.bounds,k.center=(k.center*(k.groups.length-1)+T)/k.groups.length):A.push({center:T,bounds:C.bounds,groups:[C]})}const N=(C,T)=>{const k=C?Jl(C.bounds,s):x,z=T?Jl(T.bounds,s):x;return Math.max(b,Math.min(k,z)*.22*S)};let P=null,R=null;const v=[];return A.forEach((C,T)=>{const k=dn(C.bounds.min[s]),z=dn(C.bounds.max[s]);let Y=0;if(o.keepBaseGrounded!==!1&&T===0)Y=0,P=z;else{const K=P===null?k:P+N(R,C);Y=Math.max(0,K-k),P=z+Y}R=C;for(const K of C.groups){const J=I.clone().multiplyScalar(Y);for(const G of K.records)v.push({record:G,partId:String(G.partId||"").trim(),groupKey:K.key,layerIndex:T,direction:J.lengthSq()>xo?J.clone().normalize():I.clone(),distance:J.length(),translation:J,matrix:new e.Matrix4})}}),v}function eP(e,t,n=0){if(!e?.Vector3)return null;const r=Z2(dn(n),0,1),o=Sx(e,t?.toTranslation,Sx(e,t?.translation,new e.Vector3(0,0,dn(t?.distance)))),i=Sx(e,t?.fromTranslation,null);if(!i&&r<=xo)return null;const s=i?i.x+(o.x-i.x)*r:o.x*r,a=i?i.y+(o.y-i.y)*r:o.y*r,l=i?i.z+(o.z-i.z)*r:o.z*r;return i&&Math.abs(s)<=xo&&Math.abs(a)<=xo&&Math.abs(l)<=xo?null:new e.Vector3(s,a,l)}function rW(e,t=[],n=0){for(const r of Array.isArray(t)?t:[]){const o=r?.record;if(!o)continue;const i=eP(e,r,n);if(!i){o.explodedViewMatrix=null;continue}const s=r.matrix instanceof e.Matrix4?r.matrix:new e.Matrix4;s.makeTranslation(i.x,i.y,i.z),r.matrix=s,o.explodedViewMatrix=s}}function oW(e=[]){for(const t of Array.isArray(e)?e:[])t&&(t.explodedViewMatrix=null)}function iW(e){return 1-(1-Z2(dn(e),0,1))**3}const sW=Er,Cw=.84,YI=16,qI="#8dc5ff",Rg="#4f9dff",aW=.08,lW=.12,cW=23,uW=26,dW=.035,fW=/^#(?:[0-9a-fA-F]{3}){1,2}$/,Kd="__model__",ao=Object.freeze({surface:"#f4f4f5",surfaceRoughness:.92,surfaceMetalness:.03,surfaceClearcoat:0,surfaceClearcoatRoughness:.6,edge:"#18181b",edgeThickness:1,edgeOpacity:Cw}),oy="_cad_edge_barycentric",iy="_cad_edge_class",mW=Object.freeze(["feature","tangent","seam","degenerate"]),ZI=Object.freeze({feature:Object.freeze({color:"#132232",thickness:1.15,opacity:1}),tangent:Object.freeze({color:"#132232",thickness:1.15,opacity:.5}),seam:Object.freeze({color:"#132232",thickness:1.15,opacity:.85}),degenerate:Object.freeze({color:"#132232",thickness:0,opacity:1})}),JI=new WeakMap;function pW(e){const t=e?.geometrySource;return t&&typeof t=="object"?t:e}function un(e,t,n){return Math.min(Math.max(e,t),n)}function kt(e,t=0){return Number.isFinite(Number(e))?Number(e):t}function QI(e){return Array.isArray(e)?e:[]}function Aa(e,t=1){return(Array.isArray(e)||ArrayBuffer.isView(e))&&e.length>=t&&e.length%t===0}function tP(e){return Mu(e)}function c1(e){const t=[1/0,1/0,1/0],n=[-1/0,-1/0,-1/0];for(let r=0;r+2<(e?.length||0);r+=3){const o=Number(e[r]),i=Number(e[r+1]),s=Number(e[r+2]);[o,i,s].every(Number.isFinite)&&(t[0]=Math.min(t[0],o),t[1]=Math.min(t[1],i),t[2]=Math.min(t[2],s),n[0]=Math.max(n[0],o),n[1]=Math.max(n[1],i),n[2]=Math.max(n[2],s))}return!t.every(Number.isFinite)||!n.every(Number.isFinite)?{min:[0,0,0],max:[1,1,1]}:{min:t,max:n}}function vb(e,t,n=sW.CAD){const r=tP(n),o=qs(r),i=Array.isArray(t?.min)?t.min:[0,0,0],s=Array.isArray(t?.max)?t.max:[1,1,1],a=new e.Vector3((kt(i[0])+kt(s[0],1))/2,(kt(i[1])+kt(s[1],1))/2,(kt(i[2])+kt(s[2],1))/2),l=new e.Vector3(Math.max(kt(s[0],1)-kt(i[0]),o.minModelRadius),Math.max(kt(s[1],1)-kt(i[1]),o.minModelRadius),Math.max(kt(s[2],1)-kt(i[2]),o.minModelRadius));return{center:a,size:l,radius:lf(l.length()/2,r)}}function nP(e){const t=pW(e);let n=JI.get(t);return n||(n={whole:new Map,part:new Map,edge:new Map},JI.set(t,n)),n}function hW(e){return e.map((t,n)=>String(t?.id||t?.occurrenceId||`part:${n}`)).join("|")}function rP(e){return e&&(e.userData={...e.userData||{},cadSceneCachedGeometry:!0}),e}function gW(e){const t=Array.isArray(e)?e:[e];for(const n of t)n?.map?.dispose?.(),n?.alphaMap?.dispose?.(),n?.dispose?.()}function oP(e,{disposeCachedGeometry:t=!1}={}){if(e){for(;e.children?.length;)oP(e.children[0],{disposeCachedGeometry:t});e.parent?.remove(e),typeof e.userData?.beforeDispose=="function"&&(e.userData.beforeDispose(e),delete e.userData.beforeDispose),(t||e.geometry?.userData?.cadSceneCachedGeometry!==!0)&&e.geometry?.dispose?.(),gW(e.material)}}function Ex(e,t={}){for(;e?.children?.length;)oP(e.children[0],t)}function iP(e,t,n,r){const o=Aa(n,3);if(!r&&o){t.setAttribute("normal",new e.BufferAttribute(new Float32Array(n),3));return}t.computeVertexNormals()}function sP(e,t,n,r=0,o=0){const i=n?.surfaceEdgeBarycentric,s=n?.surfaceEdgeClass,a=Math.max(0,Math.floor(Number(r)||0))*3,l=Math.max(0,Math.floor(Number(o)||0))*3;!(i instanceof Float32Array)||!(s instanceof Uint8Array)||l<=0||i.length0&&t.count===n.count}function su(e,t){const n=String(t||"").trim();if(!fW.test(n))return null;const r=n.length===4?`#${n[1]}${n[1]}${n[2]}${n[2]}${n[3]}${n[3]}`:n;return new e.Color(r)}function Mw(e,t,n={},{applyTint:r=!0}={}){const o=(t||new e.Color("#ffffff")).clone(),i=un(Number(n.tintStrength)||0,0,1);if(r&&i>0){const u=new e.Color(n.defaultColor||n.tintColor||"#ffffff");n.tintMode==="blend"?o.lerp(u,i):o.lerp(o.clone().multiply(u),i)}const s=un(Number(n.saturation)||1,0,2.5);if(Math.abs(s-1)>1e-4){const u={};o.getHSL(u),o.setHSL(u.h,un(u.s*s,0,1),u.l)}const a=un(Number(n.contrast)||1,0,2.5),l=un(Number(n.brightness)||1,0,2);return o.r=un(((o.r-.5)*a+.5)*l,0,1),o.g=un(((o.g-.5)*a+.5)*l,0,1),o.b=un(((o.b-.5)*a+.5)*l,0,1),o}function yW(e,t,n={}){if(!Aa(t,3))return null;const r=new Float32Array(t.length),o=new e.Color;for(let i=0;i+2[l,EW(n,l,o)])),s=new e.Color(o),a=Object.fromEntries(Object.entries(i).map(([l,u])=>[l,su(e,u.color)||s.clone()]));t.userData.cadSurfaceEdges=!0,t.userData.cadSurfaceEdgeBaseColor=s.clone(),t.userData.cadSurfaceEdgeColor=s.clone(),t.userData.cadSurfaceEdgeBaseClassSettings=Object.fromEntries(Object.entries(i).map(([l,u])=>[l,{...u}])),t.extensions={...t.extensions||{},derivatives:!0},t.onBeforeCompile=l=>{const u=t.userData.cadSurfaceEdgeColor?.isColor?t.userData.cadSurfaceEdgeColor:s;t.userData.cadSurfaceEdgeShader=l,l.uniforms.cadSurfaceEdgeColor={value:u.clone()},l.uniforms.cadSurfaceFeatureColor={value:a.feature.clone()},l.uniforms.cadSurfaceTangentColor={value:a.tangent.clone()},l.uniforms.cadSurfaceSeamColor={value:a.seam.clone()},l.uniforms.cadSurfaceDegenerateColor={value:a.degenerate.clone()},l.uniforms.cadSurfaceFeatureThickness={value:i.feature.thickness},l.uniforms.cadSurfaceTangentThickness={value:i.tangent.thickness},l.uniforms.cadSurfaceSeamThickness={value:i.seam.thickness},l.uniforms.cadSurfaceDegenerateThickness={value:i.degenerate.thickness},l.uniforms.cadSurfaceFeatureOpacity={value:i.feature.opacity},l.uniforms.cadSurfaceTangentOpacity={value:i.tangent.opacity},l.uniforms.cadSurfaceSeamOpacity={value:i.seam.opacity},l.uniforms.cadSurfaceDegenerateOpacity={value:i.degenerate.opacity},l.vertexShader=l.vertexShader.replace("#include ",`#include attribute vec3 ${oy}; attribute vec3 ${iy}; varying vec3 vCadSurfaceEdgeBarycentric; varying vec3 vCadSurfaceEdgeClass;`).replace("#include ",`#include vCadSurfaceEdgeBarycentric = ${oy}; vCadSurfaceEdgeClass = ${iy};`),l.fragmentShader=l.fragmentShader.replace("#include ",`#include uniform vec3 cadSurfaceEdgeColor; uniform vec3 cadSurfaceFeatureColor; uniform vec3 cadSurfaceTangentColor; uniform vec3 cadSurfaceSeamColor; uniform vec3 cadSurfaceDegenerateColor; uniform float cadSurfaceFeatureThickness; uniform float cadSurfaceTangentThickness; uniform float cadSurfaceSeamThickness; uniform float cadSurfaceDegenerateThickness; uniform float cadSurfaceFeatureOpacity; uniform float cadSurfaceTangentOpacity; uniform float cadSurfaceSeamOpacity; uniform float cadSurfaceDegenerateOpacity; varying vec3 vCadSurfaceEdgeBarycentric; varying vec3 vCadSurfaceEdgeClass; float cadSurfaceEdgeThicknessFor(float classCode) { if (classCode < 0.5) { return 0.0; } if (abs(classCode - 2.0) < 0.5) { return cadSurfaceTangentThickness; } if (abs(classCode - 3.0) < 0.5) { return cadSurfaceSeamThickness; } if (abs(classCode - 4.0) < 0.5) { return cadSurfaceDegenerateThickness; } return cadSurfaceFeatureThickness; } float cadSurfaceEdgeOpacityFor(float classCode) { if (classCode < 0.5) { return 0.0; } if (abs(classCode - 2.0) < 0.5) { return cadSurfaceTangentOpacity; } if (abs(classCode - 3.0) < 0.5) { return cadSurfaceSeamOpacity; } if (abs(classCode - 4.0) < 0.5) { return cadSurfaceDegenerateOpacity; } return cadSurfaceFeatureOpacity; } vec3 cadSurfaceEdgeColorFor(float classCode) { if (classCode < 0.5) { return cadSurfaceEdgeColor; } if (abs(classCode - 2.0) < 0.5) { return cadSurfaceTangentColor; } if (abs(classCode - 3.0) < 0.5) { return cadSurfaceSeamColor; } if (abs(classCode - 4.0) < 0.5) { return cadSurfaceDegenerateColor; } return cadSurfaceFeatureColor; } float cadSurfaceEdgeCoverage(float barycentric, float classCode) { float thickness = cadSurfaceEdgeThicknessFor(classCode); float opacity = cadSurfaceEdgeOpacityFor(classCode); if (thickness <= 0.0 || opacity <= 0.0) { return 0.0; } float pixelDistance = barycentric / max(fwidth(barycentric), 1e-6); float halfWidth = max(thickness * 0.5, 0.001); float coverage = 1.0 - smoothstep(max(halfWidth - 0.75, 0.0), halfWidth + 0.75, pixelDistance); return clamp(coverage * opacity, 0.0, 1.0); } vec4 cadSurfaceEdgeLayerFor(float barycentric, float classCode) { float edgeAlpha = cadSurfaceEdgeCoverage(barycentric, classCode); return vec4(cadSurfaceEdgeColorFor(classCode), edgeAlpha); } vec4 cadSurfaceEdgeLayer() { vec4 edge0 = cadSurfaceEdgeLayerFor(vCadSurfaceEdgeBarycentric.x, vCadSurfaceEdgeClass.x); vec4 edge1 = cadSurfaceEdgeLayerFor(vCadSurfaceEdgeBarycentric.y, vCadSurfaceEdgeClass.y); vec4 edge2 = cadSurfaceEdgeLayerFor(vCadSurfaceEdgeBarycentric.z, vCadSurfaceEdgeClass.z); vec4 edge = edge0; if (edge1.a > edge.a) { edge = edge1; } if (edge2.a > edge.a) { edge = edge2; } return edge; }`).replace("#include ",`vec4 cadSurfaceEdgeMix = cadSurfaceEdgeLayer(); if (cadSurfaceEdgeMix.a > 0.0) { outgoingLight = mix(outgoingLight, cadSurfaceEdgeMix.rgb, cadSurfaceEdgeMix.a); } #include `)},t.customProgramCacheKey=()=>"cad-surface-edges-v2"}function vW(e,t,{color:n,useVertexColors:r=!1,edgeSettings:o=null}={}){const i=Number.isFinite(Number(t?.surfaceOpacity))?Number(t.surfaceOpacity):1,s=new e.MeshPhysicalMaterial({color:n||t?.surface||ao.surface,roughness:Number.isFinite(Number(t?.surfaceRoughness))?Number(t.surfaceRoughness):ao.surfaceRoughness,metalness:Number.isFinite(Number(t?.surfaceMetalness))?Number(t.surfaceMetalness):ao.surfaceMetalness,clearcoat:Number.isFinite(Number(t?.surfaceClearcoat))?Number(t.surfaceClearcoat):ao.surfaceClearcoat,clearcoatRoughness:Number.isFinite(Number(t?.surfaceClearcoatRoughness))?Number(t.surfaceClearcoatRoughness):ao.surfaceClearcoatRoughness,side:e.DoubleSide,vertexColors:r,transparent:i<.999,opacity:i,emissive:0,emissiveIntensity:0,polygonOffset:!1,polygonOffsetFactor:0,polygonOffsetUnits:0});return o?.enabled&&wW(e,s,o,t),s}function CW(e,t,n=0){return new e.MeshBasicMaterial({color:Uy(t||{},n),transparent:!0,opacity:.035,depthWrite:!1})}function MW(e,{color:t,useVertexColors:n=!1,opacity:r=1}={}){return new e.MeshBasicMaterial({color:t||ao.surface,side:e.DoubleSide,vertexColors:n,transparent:r<.999,opacity:r,depthWrite:r>=.999})}function IW(e,t,n){return su(e,t?.color||n?.sourceColor)}function AW(e,t=1){const n=Number(e?.opacity);return Number.isFinite(n)?un(n,0,1):t}function NW(e,t){const n=Array.isArray(t)?t:[],r=n.map(o=>String(o?.color||"").trim().toLowerCase()).filter(Boolean);return r.length?r.length!==n.length||new Set(r).size>1:!1}function _W(e){return(Array.isArray(e)?e:[]).some(n=>{const r=Number(n?.opacity);return Number.isFinite(r)&&un(r,0,1)<.999})}function TW(e){const t=new e.BufferGeometry;return t.setAttribute("position",new e.BufferAttribute(new Float32Array(0),3)),t}function RW(e,t){return[String(e?.occurrenceId||""),String(e?.id||""),String(e?.partSourcePath||e?.sourcePath||""),String(e?.label||e?.name||""),String(t).padStart(8,"0")].join("\0")}function PW(e=[]){return new Map([...e].map((t,n)=>({part:t,key:RW(t,n)})).sort((t,n)=>t.key.localeCompare(n.key)).map(({part:t},n)=>[t,n]))}function cP(e,t,n,r){const o=nP(t),i=o.part.get(n)||o.whole.get(n);if(i)return i;const s=r();return s?.geometry?(rP(s.geometry),n===Kd?o.whole.set(n,s):o.part.set(n,s),s):null}function OW(e,t,n,r=!1){const o=String(n?.id||n?.occurrenceId||"").trim(),i=n?.sourceMesh&&typeof n.sourceMesh=="object"?n.sourceMesh:null,s=i&&n?.hasSourceColors?"source-colors":"flat",l=(i?`source:${String(n?.sourceMeshKey||n?.meshUrl||n?.partFileRef||o||"").trim()}:${s}`:"")||o||`${kt(n?.vertexOffset)}:${kt(n?.triangleOffset)}`;return cP(e,t,l,()=>{const u=i?0:kt(n?.vertexOffset,0),d=i?Math.floor((i.vertices?.length||0)/3):kt(n?.vertexCount,0),m=i?0:kt(n?.triangleOffset,0),p=i?Math.floor((i.indices?.length||0)/3):kt(n?.triangleCount,0);if(d<=0||p<=0)return null;let g,x,y,S;if(i)g=i.vertices||new Float32Array(0),x=n?.hasSourceColors&&Aa(i.colors,3)&&i.colors.length===g.length?new Float32Array(i.colors):null,y=Aa(i.normals,3)?i.normals:null,S=i.indices||new Uint32Array(0);else{const I=u*3,A=I+d*3;g=t.vertices.slice(I,A),x=xW(t,n)?new Float32Array(t.colors.slice(I,A)):null,y=Aa(t.normals,3)?t.normals.slice(I,A):null;const N=t.indices.slice(m*3,m*3+p*3);S=new Uint32Array(N.length);for(let P=0;P{const r=new e.BufferGeometry;r.setAttribute("position",new e.BufferAttribute(new Float32Array(t.vertices||[]),3)),r.setIndex(new e.BufferAttribute(new Uint32Array(t.indices||[]),1));const o=aP(t)&&t.colors?.length===t.vertices?.length?new Float32Array(t.colors):null;return o&&r.setAttribute("color",new e.BufferAttribute(new Float32Array(o),3)),sP(e,r,t,0,Math.floor((t.vertices?.length||0)/3)),iP(e,r,t.normals,n),r.computeBoundingSphere(),{geometry:r,rawColors:o}})}function DW(e,t,n){if(!t?.geometry||!t.rawColors||!t.hasVertexColors)return;const r=yW(e,t.rawColors,n);if(!r)return;const o=t.geometry.getAttribute("color");if(o?.array?.length===r.length){o.array.set(r),o.needsUpdate=!0;return}t.geometry.setAttribute("color",new e.BufferAttribute(r,3))}function tA(e,t,n){if(!Aa(t,3)||!Aa(n,2))return null;const r=Math.floor(t.length/3),o=Math.floor(n.length/2);if(o<=0)return null;const i=new Float32Array(o*6);let s=0;for(let u=0;u+1=r||m>=r)continue;const p=d*3,g=m*3;i[s]=Number(t[p]),i[s+1]=Number(t[p+1]),i[s+2]=Number(t[p+2]),i[s+3]=Number(t[g]),i[s+4]=Number(t[g+1]),i[s+5]=Number(t[g+2]),s+=6}if(!s)return null;const a=new e.BufferGeometry,l=s===i.length?i:i.subarray(0,s);return a.setAttribute("position",new e.BufferAttribute(l,3)),a}function jW(e,t,n,r,o,i={}){const s=nP(t),a=n?String(n?.id||n?.occurrenceId||"").trim():Kd,l=n?.sourceMesh?String(n?.sourceMeshKey||n?.meshUrl||n?.partFileRef||"").trim():"",u=`${o}:${l?`source:${l}`:a||Kd}`,d=s.edge.get(u);if(d)return d;let m=null;if(ml(o))m=new e.WireframeGeometry(r);else if(n){const p=kt(n?.edgeIndexOffset,0),g=kt(n?.edgeIndexCount,0);if(g>=2&&Aa(t?.edge_indices,2)){const y=typeof t.edge_indices.subarray=="function"?t.edge_indices.subarray(p,p+g):t.edge_indices.slice(p,p+g);m=tA(e,t.vertices,y)}m||=new e.EdgesGeometry(r,YI)}else Aa(t?.edge_indices,2)&&(m=tA(e,t.vertices,t.edge_indices));return m||=new e.EdgesGeometry(r,YI),m.getAttribute("position")?.count||(m.dispose(),m=TW(e)),rP(m),s.edge.set(u,m),m}function LW(e=null,t=null){const n=Number.isFinite(Number(t?.edgeThickness))?Number(t.edgeThickness):ao.edgeThickness;return Number.isFinite(Number(e?.thickness))?un(Number(e.thickness),.5,6):n}function FW(e,t){if(!e)return;const n=un(Number(t)||0,0,1),r=n<.999;e.opacity=n,e.depthWrite=!1,e.transparent!==r&&(e.transparent=r,e.needsUpdate=!0)}function zW(e,t,n,r,o,i){const s=ml(i),a=r?.depthTest===!1?!1:!s,l=new e.LineBasicMaterial({color:r?.color||n?.edge||ao.edge,transparent:!0,opacity:s?Math.max(kt(r?.opacity,.92),.9):kt(r?.opacity,n?.edgeOpacity??Cw),depthTest:a,depthWrite:!1}),u=new e.LineSegments(t,l);return u.userData.partId=o,{object:u,material:l}}function BW(e){if(!e)return{object:null,material:null};const t=e.object||e.edgeMesh||e.mesh||e.line||null;return{object:t,material:e.material||e.edgeMaterial||t?.material||null}}function VW(e=null){if(!e||typeof e!="object")return{mode:"basic"};const t=String(e.mode||e.type||"").trim().toLowerCase();return{...e,mode:t==="screen-space"||t==="screenspace"?"screen-space":"basic",wireframeEdgeColor:String(e.wireframeEdgeColor||"").trim()}}function $W(e,t={}){e.edgeRendering=t;for(const n of["Line2","LineGeometry","LineSegments2","LineSegmentsGeometry","LineMaterial"])e[n]=t[n]||t.constructors?.[n]||null}function GW(e,t,n,r){const o=r*un(kt(n?.silhouetteScale,.004),0,.04);if(!(o>0))return null;const i=new e.ShaderMaterial({uniforms:{color:{value:new e.Color(n?.color||ao.edge)},opacity:{value:un(kt(n?.opacity,.9),0,1)},offset:{value:o}},vertexShader:` uniform float offset; void main() { vec3 displaced = position + normal * offset; gl_Position = projectionMatrix * modelViewMatrix * vec4(displaced, 1.0); } `,fragmentShader:` uniform vec3 color; uniform float opacity; void main() { gl_FragColor = vec4(color, opacity); } `,side:e.BackSide,transparent:!0,depthTest:!0,depthWrite:!1}),s=new e.Mesh(t,i);return s.renderOrder=-1,s}function UW(e,t,n={}){return n.silhouette!==!1&&!ml(t)&&e.silhouette===!0&&(e.enabled===!0||n.silhouette===!0)}function uP(e,t){const n=Array.isArray(t?.min)?t.min:[0,0,0],r=Array.isArray(t?.max)?t.max:n;return new e.Vector3((kt(n[0])+kt(r[0]))/2,(kt(n[1])+kt(r[1]))/2,(kt(n[2])+kt(r[2]))/2)}function dP(e,t,n,{baseTheme:r=ao,displayMode:o=Dt.SOLID}={}){if(!t?.material||!n)return;const i=ml(o),s=n.overrideSourceColors===!0||i,a=!s&&!!t.hasVertexColors;if(t.useVertexColors=a,t.baseColor=lP(e,{hasVertexColors:a,sourceColor:s?null:t.sourceColor||null,materialSettings:n,fallbackColor:n?.defaultColor||r?.surface||ao.surface,fillIndex:t.fillIndex||0,forceFill:s||!t.hasSourceColor}),t.material.vertexColors=a,i){t.material.color&&t.baseColor&&t.material.color.copy(t.baseColor),t.baseOpacity=Hb(o,.035),t.material.opacity=t.baseOpacity,t.material.transparent=!0,t.material.depthWrite=!1,t.material.needsUpdate=!0;return}DW(e,t,n),t.material.roughness=un(Number(n.roughness)||0,0,1),t.material.metalness=un(Number(n.metalness)||0,0,1),t.material.clearcoat=un(Number(n.clearcoat)||0,0,1),t.material.clearcoatRoughness=un(Number(n.clearcoatRoughness)||0,0,1);const l=Number.isFinite(Number(t.sourceOpacity))?un(Number(t.sourceOpacity),0,1):1;t.baseOpacity=un(Hb(o,n.opacity)*l,0,1),t.material.opacity=t.baseOpacity,t.material.transparent=t.baseOpacity<.999,t.material.depthWrite=o===Dt.TRANSPARENT?!1:t.baseOpacity>=.999,t.material.envMapIntensity=Math.max(Number(n.envMapIntensity)||0,0),t.material.color&&t.baseColor&&t.material.color.copy(t.baseColor),t.baseEmissiveIntensity=un(Number(n.emissiveIntensity)||0,0,2),t.baseEmissiveColor=t.baseColor?t.baseColor.clone():null,"emissive"in t.material&&t.material.emissive&&(t.baseEmissiveColor&&t.baseEmissiveIntensity>0?t.material.emissive.copy(t.baseEmissiveColor):t.material.emissive.set(0),t.material.emissiveIntensity=t.baseEmissiveIntensity),t.material.needsUpdate=!0}function WW(e){return(Array.isArray(e)?e:[e]).map(t=>String(t||"").trim()).filter(Boolean)}function nA(e){const t=String(e||"").trim();return t.startsWith("#")?t.slice(1).trim():t}function Pg(e,t){if(!t?.size)return!1;if(t.has(Kd))return!0;const n=nA(e);if(!n)return!1;for(const r of t){const o=nA(r);if(o&&(n===o||n.startsWith(`${o}.`)))return!0}return!1}function HW(e,t,n){return t?(Number.isFinite(Number(e[n]))||(e[n]=Number.isFinite(Number(t.renderOrder))?Number(t.renderOrder):0),e[n]):0}function rA(e,t,n,r,o){if(!t)return;const i=HW(e,t,n);t.renderOrder=r?o:i}function KW(e,t,n,{writeTransparentDepth:r=!0}={}){const o=e?.material;if(!o)return;Object.hasOwn(e,"baseDepthWrite")||(e.baseDepthWrite=o.depthWrite!==!1);const i=t||n<.999;o.transparent!==i&&(o.transparent=i,o.needsUpdate=!0),o.depthWrite=i&&!r?!1:e.baseDepthWrite}const XW=Object.freeze({feature:"cadSurfaceFeatureOpacity",tangent:"cadSurfaceTangentOpacity",seam:"cadSurfaceSeamOpacity",degenerate:"cadSurfaceDegenerateOpacity"}),YW=Object.freeze({feature:"cadSurfaceFeatureColor",tangent:"cadSurfaceTangentColor",seam:"cadSurfaceSeamColor",degenerate:"cadSurfaceDegenerateColor"});function qW(e,t,n,r=null){const o=t?.material,i=o?.userData;if(!o||i?.cadSurfaceEdges!==!0)return;const s=n?.isColor?n:su(e,n)||i.cadSurfaceEdgeBaseColor;if(s?.isColor){i.cadSurfaceEdgeColor=s.clone();const m=i.cadSurfaceEdgeShader?.uniforms?.cadSurfaceEdgeColor;m?.value?.copy&&m.value.copy(s)}const a=r!=null&&Number.isFinite(Number(r))?un(Number(r),0,1):null,l=i.cadSurfaceEdgeBaseClassSettings||{},u=i.cadSurfaceEdgeShader?.uniforms||null,d=a!==null||s?.isColor&&i.cadSurfaceEdgeBaseColor?.isColor&&!s.equals(i.cadSurfaceEdgeBaseColor);for(const[m,p]of Object.entries(YW)){const g=su(e,l[m]?.color)||i.cadSurfaceEdgeBaseColor,x=d?s:g;x?.isColor&&u?.[p]?.value?.copy&&u[p].value.copy(x)}for(const[m,p]of Object.entries(XW)){const g=Number(l[m]?.opacity),x=a===null?Number.isFinite(g)?g:null:a;x!==null&&(i[`cadSurfaceEdge${m}Opacity`]=x,u?.[p]&&(u[p].value=x))}}function ZW(e,t,{baseTheme:n=ao,edgeSettings:r,hiddenPartIds:o,hoveredPartId:i,focusedPartId:s,selectedPartIds:a,showEdges:l=!0}={}){const u=new Set(Array.isArray(o)?o:[]),d=new Set(Array.isArray(a)?a:[]),m=new Set((Array.isArray(i)?i:[i]).map(v=>String(v||"").trim()).filter(Boolean)),p=r?.color||n?.edge||ao.edge,g=Number.isFinite(Number(n?.surfaceOpacity))?Number(n.surfaceOpacity):1,x=new Set(WW(s)),y=x.size>0,S=Number.isFinite(Number(r?.opacity))?un(Number(r.opacity),0,1):n?.edgeOpacity??ao.edgeOpacity??Cw,b=Number.isFinite(Number(r?.highlightOpacity))?un(Number(r.highlightOpacity),0,1):1,I=String(r?.highlightColor||Rg).trim()||Rg,A=new e.Color(qI),N=new e.Color(I),P=new e.Color(Rg),R=new e.Color(I);for(const v of Array.isArray(t)?t:[]){if(!v?.mesh||!v?.material)continue;const C=v.effectStyle&&typeof v.effectStyle=="object"?v.effectStyle:{},T=v.effectVisible===!1,k=su(e,C.color),z=su(e,C.edgeColor),Y=su(e,C.emissive),K=Pg(v.partId,u),J=!K&&(Pg(v.partId,d)||v.effectHighlighted===!0),G=!K&&!T&&Pg(v.partId,m),Q=!K&&!T&&y&&Pg(v.partId,x),D=!K&&!T&&y&&!Q,$=J||G;v.mesh.visible=!T,v.edges&&(v.edges.visible=l&&!T),v.silhouette&&(v.silhouette.visible=!T),rA(v,v.mesh,"baseMeshRenderOrder",$,cW),rA(v,v.edges,"baseEdgeRenderOrder",$,uW);const ie=Number.isFinite(Number(v.baseOpacity))?Number(v.baseOpacity):g,W=Number.isFinite(Number(C.opacity))?un(Number(C.opacity),0,1):1,Z=Number.isFinite(Number(C.edgeOpacity))?un(Number(C.edgeOpacity),0,1):W,Ee=J||G?b*Z:null,re=Math.min(ie*W,dW),be=J?un(ie*W+lW,0,1):G?un(ie*W+aW,0,1):ie*W,_e=K||D?re:be;KW(v,K||D||$,_e,{writeTransparentDepth:!K&&!D}),v.material.opacity=_e,v.baseColor&&v.material.color&&v.material.color.copy(J?P:G?A:k||v.baseColor),"emissive"in v.material&&v.material.emissive&&(J?v.material.emissive.set(Rg):G?v.material.emissive.set(qI):v.baseEmissiveColor&&v.baseEmissiveIntensity>0?v.material.emissive.copy(v.baseEmissiveColor):v.material.emissive.set(0),v.material.emissiveIntensity=J?.08:G?.12:un(Y?Number(C.emissiveIntensity)||.22:Number(v.baseEmissiveIntensity)||0,0,2),!J&&!G&&Y&&v.material.emissive.copy(Y));const Ie=J?R:G?N:z||p;qW(e,v,Ie,Ee),v.edgeMaterial&&(v.edgeMaterial.color?.set?.(Ie),FW(v.edgeMaterial,J||G?b*Z:K||D?_e:S*Z))}}function JW(e){for(const t of Array.isArray(e)?e:[])t.effectMatrix=null,t.effectStyle=null,t.effectVisible=null,t.effectHighlighted=!1}function QW(e,t){const n=Array.isArray(t?.min)?t.min:[0,0,0],r=Array.isArray(t?.max)?t.max:[1,1,1];return[[n[0],n[1],n[2]],[n[0],n[1],r[2]],[n[0],r[1],n[2]],[n[0],r[1],r[2]],[r[0],n[1],n[2]],[r[0],n[1],r[2]],[r[0],r[1],n[2]],[r[0],r[1],r[2]]].map(o=>new e.Vector3(kt(o[0]),kt(o[1]),kt(o[2])))}function eH(e,t,n=null){if(!t||!Array.isArray(t.min)||!Array.isArray(t.max))return null;if(!(n instanceof e.Matrix4))return{min:[...t.min],max:[...t.max]};const r=QW(e,t).map(s=>s.applyMatrix4(n)),o=[1/0,1/0,1/0],i=[-1/0,-1/0,-1/0];for(const s of r)o[0]=Math.min(o[0],s.x),o[1]=Math.min(o[1],s.y),o[2]=Math.min(o[2],s.z),i[0]=Math.max(i[0],s.x),i[1]=Math.max(i[1],s.y),i[2]=Math.max(i[2],s.z);return o.every(Number.isFinite)&&i.every(Number.isFinite)?{min:o,max:i}:null}function tH(e){const t=[1/0,1/0,1/0],n=[-1/0,-1/0,-1/0];let r=0;for(const o of Array.isArray(e)?e:[])if(!(!o||!Array.isArray(o.min)||!Array.isArray(o.max))){r+=1;for(let i=0;i<3;i+=1)t[i]=Math.min(t[i],kt(o.min[i])),n[i]=Math.max(n[i],kt(o.max[i]))}return r>0&&t.every(Number.isFinite)&&n.every(Number.isFinite)?{min:t,max:n}:null}function nH(e,t,n){const r=[];for(const o of Array.isArray(t)?t:[]){if(o.effectVisible===!1)continue;const i=Sw(e,o.baseTransform),s=o.effectMatrix instanceof e.Matrix4?o.effectMatrix.clone():null,a=s?s.multiply(i):i;r.push(eH(e,o.partBounds,a))}return tH(r)||n}function rH(e,t,n,r,o={}){const i=n?.definition||null,s=i?.module||null;if(!i||!s?.setup)return;const a=new Map,l=ey(i,{meshData:r,selectorRuntime:n?.selectorRuntime||null}),u=kp({runtime:t,stepModuleRuntime:n,features:l,effects:ny(e,{meshData:r,features:l,runtime:t,effectsByPartId:a}),cleanup:d=>{typeof d=="function"&&t.cleanups.push(d)}});try{s.setup(u)}catch(d){o.onWarning?.({title:"STEP parameter setup failed",message:d instanceof Error?d.message:String(d),error:d})}}function oA(e,t,n={}){for(;e.cleanups.length;)try{e.cleanups.pop()?.()}catch(i){n.onWarning?.({title:"STEP parameter cleanup failed",message:i instanceof Error?i.message:String(i),error:i})}const r=t?.definition?.module||null;if(!r?.dispose)return;const o=kp({runtime:e,stepModuleRuntime:t,features:{},effects:{},cleanup:()=>{}});try{r.dispose(o)}catch(i){n.onWarning?.({title:"STEP parameter dispose failed",message:i instanceof Error?i.message:String(i),error:i})}}function oH(e,t,n,r,o={}){const i=n?.definition||null,s=i?.module||null;if(!i||!s){JW(t.displayRecords);for(const m of t.displayRecords)tc(e,m);return t.baseBounds}const a=new Map,l=ey(i,{meshData:r,selectorRuntime:n?.selectorRuntime||null}),u=ny(e,{meshData:r,features:l,runtime:t,effectsByPartId:a}),d=kp({runtime:t,stepModuleRuntime:n,features:l,effects:u,cleanup:m=>{typeof m=="function"&&t.cleanups.push(m)}});try{s.update?.(d),s.render?.(d)}catch(m){o.onWarning?.({title:"STEP parameter update failed",message:m instanceof Error?m.message:String(m),error:m})}U2(e,t.displayRecords,a);for(const m of t.displayRecords)tc(e,m);return nH(e,t.displayRecords,t.baseBounds)}function fP(e,t,n,r=null){const o=Ws(t);if(!o.enabled||!n)return null;const i=YR(o.axis),s=Array.isArray(n?.min)?n.min:[0,0,0],a=Array.isArray(n?.max)?n.max:s,l=kt(s[i]),u=kt(a[i]),d=Math.min(l,u),m=Math.max(l,u),p=d+(m-d)*o.offset,g=new e.Vector3(i===0?1:0,i===1?1:0,i===2?1:0);o.invert&&g.multiplyScalar(-1);const x=r?.clone?r.clone():new e.Vector3(0,0,0);return x.setComponent(i,x.getComponent(i)+p),new e.Plane().setFromNormalAndCoplanarPoint(g,x)}function Dd(e,t){if(!e)return;const n=Array.isArray(e)?e:[e],r=Array.isArray(t)&&t.length>0;for(const o of n){if(!o)continue;const i=o.userData?.cadClipPlaneEnabled===!0,s=Number(o.userData?.cadClipPlaneCount)||0,a=o.clipping===!0;o.clippingPlanes=r?t:null,o.clipIntersection=!1,o.clipShadows=r,"clipping"in o&&(o.clipping=r),o.userData={...o.userData||{},cadClipPlaneEnabled:r,cadClipPlaneCount:r?t.length:0},(i!==r||s!==(r?t.length:0)||a!==(o.clipping===!0))&&(o.needsUpdate=!0)}}function iH(e,t,n,r=null){const o=fP(e.THREE,t,n,r),i=o?[o]:[];e.activeClipPlane=o,e.activeClipPlanes=i;for(const s of e.displayRecords)Dd(s.material,i),Dd(s.edgeMaterial,i),Dd(s.silhouette?.material,i)}function iA(e={}){return e&&typeof e=="object"?e:{}}function sH(e){return Array.isArray(e)?e:String(e||"").trim().split(",")}function aH(e){const t=String(e||"").trim();return t?(t.startsWith("#")?t.slice(1):t).split(",").map(r=>r.trim()).filter(Boolean):[]}function wx(e){return sH(e).flatMap(aH)}function sA(e,t,{descendants:n=!1}={}){const r=String(e||"").trim(),o=String(t||"").trim();return!r||!o?!1:r===o||n&&r.startsWith(`${o}.`)}function aA(e,t){const n=String(t||"").trim();return n?[e?.id,e?.occurrenceId].some(r=>sA(r,n,{descendants:!0}))?!0:[e?.name,e?.label,e?.linkName].some(r=>sA(r,n)):!1}function lH(e){const t=[1/0,1/0,1/0],n=[-1/0,-1/0,-1/0];let r=0;for(const o of Array.isArray(e)?e:[]){const i=o?.bounds;if(!(!Array.isArray(i?.min)||!Array.isArray(i?.max))){r+=1;for(let s=0;s<3;s+=1)t[s]=Math.min(t[s],Number(i.min[s])),n[s]=Math.max(n[s],Number(i.max[s]))}}return r>0&&t.every(Number.isFinite)&&n.every(Number.isFinite)?{min:t,max:n}:null}function cH(e,t={}){const n=Array.isArray(e?.parts)?e.parts:[];if(!n.length)return e;const r=[...wx(t.focus),...wx(t.refs)],o=wx(t.hide);if(!r.length&&!o.length)return e;const i=n.filter(s=>r.length&&!r.some(a=>aA(s,a))?!1:!o.some(a=>aA(s,a)));if(!i.length)throw new Error("No renderable parts remain after applying focus/hide filters");return{...e,parts:i,bounds:lH(i)||e.bounds}}function uH(e,t={}){return t.materialSettings&&typeof t.materialSettings=="object"?t.materialSettings:e.materials||{}}function mP(e,t,n){if(Array.isArray(n.parts))return n.parts.filter(o=>kt(o?.vertexCount)>0&&kt(o?.triangleCount)>0);const r=QI(e?.parts).filter(o=>kt(o?.vertexCount)>0&&kt(o?.triangleCount)>0);if(!r.length)return[];if(n.renderPartsIndividually===!0)return r;if(n.renderPartsIndividually===!1){const o=QI(n.pickableParts).filter(s=>kt(s?.vertexCount)>0&&kt(s?.triangleCount)>0);return o.length?o:NW(e,r)||_W(r)||t?.materials?.cycleColors===!0&&Array.isArray(t?.materials?.fillColors)&&t.materials.fillColors.length>1?r:[]}return r}function dH(e,t,n,r,o){const i=t.edgeSettings,s=t.baseTheme,a=t.displayMode,u=t.edgeRendering?.mode==="screen-space"?A$(t,{geometry:r,edgeSettings:i,baseTheme:s,partId:n.partId,displayMode:a,thickness:LW(i,s),wireframeEdgeColor:t.edgeRendering?.wireframeEdgeColor||""},t.screenSpaceLineMaterials):zW(e,r,s,i,n.partId,a),{object:d,material:m}=BW(u);d&&(d.userData.partId=n.partId,n.edges=d,n.edgeMaterial=m,n.baseEdgeColor=m?.color?.isColor?m.color.clone():new e.Color(i?.color||s?.edge||ao.edge),n.baseEdgeOpacity=Number.isFinite(Number(m?.opacity))?Number(m.opacity):1,t.edgesGroup.add(d))}function fH(e,t,n,r){const o=t.theme,i=t.materialSettings,s=t.displayMode,a=t.baseTheme,l=t.edgeSettings,u=n.bounds||c1(n.vertices||[]),{radius:d}=vb(e,u,t.scale),m=UW(l,s,r),p=mP(n,o,r),g=PW(p),x=p.length===0,y=[],S=({part:b=null,geometryEntry:I,fillIndex:A=0,baseTransform:N=null})=>{const P=b?String(b?.id||b?.occurrenceId||`part:${y.length}`):Kd,R=ml(s),v=i.overrideSourceColors===!0||R,C=!!I.geometry.getAttribute("color"),T=!R&&!Gy(s)&&l.enabled&&bW(I.geometry),k=IW(e,b,n),z=AW(b),Y=C||!!k,K=!v&&C,J=lP(e,{hasVertexColors:K,sourceColor:v?null:k,materialSettings:i,fallbackColor:i.defaultColor||a?.surface||ao.surface,fillIndex:A,forceFill:v||!Y}),G=R?CW(e,i,A):JV(s)?MW(e,{color:J,useVertexColors:K,opacity:Hb(s,i.opacity)}):vW(e,a,{color:J,useVertexColors:K,edgeSettings:T?l:null});l.enabled&&!R&&!T&&(G.polygonOffset=!0,G.polygonOffsetFactor=1,G.polygonOffsetUnits=1);const Q=new e.Mesh(I.geometry,G);Q.castShadow=!0,Q.receiveShadow=!1,Q.userData.partId=P;const D=b?r.callbacks?.faceIdsForPart?.(b):r.callbacks?.faceIdsForMesh?.(n);D&&(Q.userData.faceIds=D),t.modelGroup.add(Q);const $={partId:P,sourcePart:b||null,mesh:Q,edges:null,silhouette:null,material:G,edgeMaterial:null,baseColor:J,sourceColor:k,sourceOpacity:z,baseTransform:N,partCenter:uP(e,b?.bounds||u),partBounds:b?.bounds||b?.sourceBounds||u,effectMatrix:null,effectStyle:null,effectVisible:null,effectHighlighted:!1,fillIndex:A,hasSourceColor:Y,hasVertexColors:K,useVertexColors:K,rawColors:I.rawColors,geometry:I.geometry,baseOpacity:Number.isFinite(Number(G.opacity))?Number(G.opacity):1,baseEmissiveColor:J?J.clone():null,baseEmissiveIntensity:0,baseEdgeColor:null,baseEdgeOpacity:1};if(m){const ie=GW(e,I.geometry,l,d);ie&&($.silhouette=ie,t.modelGroup.add(ie))}r.selection?.showEdges!==!1&&!T&&(l.enabled||R)&&dH(e,t,$,jW(e,n,b,I.geometry,s,l)),dP(e,$,i,{baseTheme:a,displayMode:s}),tc(e,$),y.push($)};if(x){const b=kW(e,n,r.recomputeNormals===!0);b&&S({geometryEntry:b,fillIndex:0})}else for(const b of p){const I=OW(e,n,b,r.recomputeNormals===!0);I&&S({part:b,geometryEntry:I,fillIndex:g.get(b)??y.length,baseTransform:$2(n,b,r.renderPartsIndividually===!0)})}return y}function lA(e,t,n){const r=Ql(t?.edges);return JSON.stringify({meshData:e?"mesh":"",displayMode:Ys(n.displayMode),parts:hW(mP(e,t,n)),recomputeNormals:n.recomputeNormals===!0,edgeSettings:r,silhouette:n.silhouette!==!1&&r.silhouette===!0&&(r.enabled!==!1||n.silhouette===!0),edgeRendering:n.edgeRendering?.mode||"basic",wireframeEdgeColor:n.edgeRendering?.wireframeEdgeColor||""})}function cA(e={}){const t=Ys(e.displayMode),n=e.theme||e.themeSettings||e.settings||void 0,r=fr(n),o=Ql(n?.edges),i=e.applyDisplayModeEdgePolicy!==!1,s={...r,edges:i?{...o,enabled:YV(t)&&($y(t)||o.enabled===!0),depthTest:Gy(t)?!1:o.depthTest}:o},a=tP(e.scale??e.sceneScale??e.sceneScaleMode),l=e.callbacks&&typeof e.callbacks=="object"?e.callbacks:{},u=e.baseTheme&&typeof e.baseTheme=="object"?e.baseTheme:ao;return{...e,theme:s,displayMode:t,scale:a,callbacks:l,baseTheme:u,selection:iA(e.selection),filterSelection:e.filterSelection===!1?{}:iA(e.filterSelection??e.selection),clip:Ws(e.clip),stepParameters:e.stepParameters||null,parameterSetup:e.parameterSetup!==!1,materialSettings:uH(s,e),edgeRendering:VW(e.edgeRendering)}}function vx(e,t){e.theme=t.theme,e.displayMode=t.displayMode,e.scale=t.scale,e.baseTheme=t.baseTheme,e.edgeSettings={...Ql(t.theme?.edges),depthTest:Gy(t.displayMode)?!1:void 0},e.materialSettings=t.materialSettings,$W(e,t.edgeRendering)}function mH(e){return e?.meshData||e}function pH(e,t,n={}){if(!e)throw new Error("buildModel requires THREE");const r=mH(t),o=cA(n),i=cH(r,o.filterSelection),s=new e.Group,a=new e.Group,l=new e.Group;s.name="CadSceneRoot",a.name="CadSceneModel",l.name="CadSceneEdges",s.add(a),s.add(l);const u=i?.bounds||c1(i?.vertices||[]),d={THREE:e,root:s,modelGroup:a,edgesGroup:l,displayRecords:[],records:[],baseBounds:u,bounds:u,modelBounds:u,modelRadius:vb(e,u,o.scale).radius,cleanups:[],activeClipPlane:null,activeClipPlanes:[],screenSpaceLineMaterials:new Set,syncScreenSpaceLineMaterials(A,N){y$(d.screenSpaceLineMaterials,A,N)},registerScreenSpaceLineMaterial(A){A?.resolution?.set&&d.screenSpaceLineMaterials.add(A)},unregisterScreenSpaceLineMaterial(A){d.screenSpaceLineMaterials.delete(A)},requestRender:()=>{}};vx(d,o);let m=!1,p=o,g="",x=null,y=!1;const S=(A=p)=>{Ex(a),Ex(l),vx(d,A),d.baseBounds=i?.bounds||c1(i?.vertices||[]),d.displayRecords=fH(e,d,i,A),d.records=d.displayRecords,d.bounds=d.baseBounds,d.modelBounds=d.baseBounds,d.modelRadius=vb(e,d.baseBounds,d.scale).radius,g=lA(i,d.theme,A)},b=(A=p)=>{vx(d,A);for(const v of d.displayRecords)dP(e,v,d.materialSettings,{baseTheme:d.baseTheme,displayMode:d.displayMode});const N=A.parameterSetup!==!1,P=A.stepParameters||null;(x!==P||y!==N)&&(y&&oA(d,x,A.callbacks),x=P,y=N,y&&rH(e,d,x,i,A.callbacks));const R=oH(e,d,x,i,A.callbacks);d.bounds=R||d.baseBounds,d.modelBounds=d.bounds,d.modelRadius=vb(e,d.bounds,d.scale).radius,ZW(e,d.displayRecords,{baseTheme:d.baseTheme,edgeSettings:d.edgeSettings,...A.selection,showEdges:A.selection?.showEdges!==!1}),iH(d,A.clip,d.bounds,A.modelOffset||a.position)};S(p),b(p);const I={source:t,meshData:i,root:s,modelGroup:a,edgesGroup:l,get displayRecords(){return d.displayRecords},get records(){return d.displayRecords},get bounds(){return d.bounds},get radius(){return d.modelRadius},get runtime(){return d},update(A={}){if(m)return I;const N={...p,...A,selection:{...p.selection||{},...A.selection||{}},callbacks:{...p.callbacks||{},...A.callbacks||{}}};return Object.prototype.hasOwnProperty.call(A,"theme")&&!Object.prototype.hasOwnProperty.call(A,"materialSettings")&&delete N.materialSettings,p=cA(N),lA(i,p.theme,p)!==g&&S(p),b(p),I},dispose(){m||(m=!0,y&&oA(d,x,p.callbacks),Ex(s))}};return I}function Ar(e,t=0){return Number.isFinite(Number(e))?Number(e):t}function uA(e){return String(e??"").trim()}function hH(e,t){if(!e?.hasVisibleModel)return!1;const n=uA(e.activeModelKey),r=uA(t);return n||r?n===r:!0}function Cx(e,t,n){const r=Ar(t?.z);if(Mu(n)===Er.URDF)return r;const o=Array.isArray(e?.min)?e.min:[0,0,0];return Ar(o[2])+r}function u1(e,t,n,r,{shadowMapSize:o=2048}={}){const i=Array.isArray(n?.min)?n.min:[0,0,0],s=Array.isArray(n?.max)?n.max:[0,0,0],a=lf(new e.Vector3(Ar(s[0])-Ar(i[0]),Ar(s[1])-Ar(i[1]),Ar(s[2])-Ar(i[2])).length()/2,r);if(t.modelBounds={min:i,max:s},t.modelRadius=a,t.keyLight?.shadow?.camera){const l=typeof t.keyLight.position?.length=="function"?t.keyLight.position.length():0,u=Y$(r,{radius:a,keyLightDistance:l});t.keyLight.shadow.mapSize.set(o,o),t.keyLight.shadow.bias=-25e-5,t.keyLight.shadow.normalBias=u.normalBias,t.keyLight.shadow.radius=u.radius,t.keyLight.shadow.camera.left=-u.extent,t.keyLight.shadow.camera.right=u.extent,t.keyLight.shadow.camera.top=u.extent,t.keyLight.shadow.camera.bottom=-u.extent,t.keyLight.shadow.camera.near=.1,t.keyLight.shadow.camera.far=u.far,t.keyLight.shadow.camera.updateProjectionMatrix?.()}return{boundsMin:i,boundsMax:s,radius:a}}function bm(e,t){e?.traverse&&e.traverse(n=>{Dd(n?.material,t)})}function $c(e,t){if(!e?.THREE)return;const n=fP(e.THREE,t,e.modelBounds,e.modelGroup?.position),r=n?[n]:[];e.activeClipPlane=n,e.activeClipPlanes=r,e.renderer&&(e.renderer.localClippingEnabled=!0);for(const o of Array.isArray(e.displayRecords)?e.displayRecords:[])Dd(o.material,r),Dd(o.edgeMaterial,r);bm(e.facePickGroup,r),bm(e.edgePickGroup,r),bm(e.vertexPickGroup,r),bm(e.surfaceLineGroup,r),bm(e.topologyDisplayEdgeLine,r)}const pP=4294967295;function gH(e,t){const n=t?.proxy||{};if(!(n.facePositions instanceof Float32Array)||!(n.faceIndices instanceof Uint32Array)||!n.faceIndices.length)return null;const r=new e.BufferGeometry;r.setAttribute("position",new e.BufferAttribute(n.facePositions,3)),r.setIndex(new e.BufferAttribute(n.faceIndices,1));const o=new e.MeshBasicMaterial({color:16777215,side:e.DoubleSide,transparent:!0,opacity:0,depthWrite:!1,toneMapped:!1,colorWrite:!1}),i=new e.Mesh(r,o);return i.userData.faceIds=n.faceIds||new Uint32Array(0),i.frustumCulled=!1,i}function bH(e){const t=Array.isArray(e?.proxy?.faceRunColumns)&&e.proxy.faceRunColumns.length?e.proxy.faceRunColumns:["occurrenceRow","primitiveIndex","triangleStart","triangleCount","faceRow"];return{stride:t.length,occurrenceRow:Math.max(0,t.indexOf("occurrenceRow")),primitiveIndex:Math.max(0,t.indexOf("primitiveIndex")),triangleStart:Math.max(0,t.indexOf("triangleStart")),triangleCount:Math.max(0,t.indexOf("triangleCount")),faceRow:Math.max(0,t.indexOf("faceRow"))}}function Iw(e,t){const n=t?.proxy?.faceRuns,r=Math.max(0,Math.floor(Number(e?.triangleCount||0)));if(!(n instanceof Uint32Array)||!n.length||r<=0)return null;const o=String(e?.occurrenceId||e?.id||"").trim();if(!o)return null;const i=Math.max(0,Math.floor(Number(e?.primitiveIndex||0))),s=bH(t),a=new Uint32Array(r);a.fill(pP);const l=Array.isArray(e?.sourcePartRanges)?e.sourcePartRanges.map(d=>({occurrenceId:String(d?.occurrenceId||"").trim(),primitiveIndex:Math.max(0,Math.floor(Number(d?.primitiveIndex||0))),triangleOffset:Math.max(0,Math.floor(Number(d?.triangleOffset||0))),triangleCount:Math.max(0,Math.floor(Number(d?.triangleCount||0)))})).filter(d=>d.occurrenceId&&d.triangleCount>0):[];let u=!1;for(let d=0;d+s.stride<=n.length;d+=s.stride){const m=t?.occurrenceIdByRowIndex?.get?.(Number(n[d+s.occurrenceRow])),p=Number(n[d+s.triangleStart]),g=Number(n[d+s.triangleCount]),x=Number(n[d+s.faceRow]);if(!Number.isInteger(p)||!Number.isInteger(g)||!Number.isInteger(x)||p<0||g<=0||x<0)continue;if(l.length){for(const S of l){if(m!==S.occurrenceId||Number(n[d+s.primitiveIndex])!==S.primitiveIndex||p>=S.triangleCount)continue;const b=S.triangleOffset+p,I=Math.min(S.triangleOffset+p+g,S.triangleOffset+S.triangleCount,r);I<=b||b>=r||(a.fill(x,b,I),u=!0)}continue}if(m!==o||Number(n[d+s.primitiveIndex])!==i||p>=r)continue;const y=Math.min(p+g,r);a.fill(x,p,y),u=!0}return u?a:null}function hP(e,t){const n=Math.floor((e?.indices?.length||0)/3),r=Array.isArray(e?.parts)?e.parts:[];if(n<=0||!r.length)return null;const o=new Uint32Array(n);o.fill(pP);let i=!1;for(const s of r){const a=Iw(s,t);if(!a)continue;const l=Math.max(0,Math.floor(Number(s?.triangleOffset||0))),u=Math.min(l+a.length,o.length);u<=l||(o.set(a.subarray(0,u-l),l),i=!0)}return i?o:null}function yH(e,t){const n=e?.sourcePart||e?.part||null,r=String(n?.id||n?.occurrenceId||"").trim();return r&&r===t?n:null}function dA(e,t,n){const r=Array.isArray(e?.displayRecords)?e.displayRecords:[];if(!r.length)return;const o=new Map((Array.isArray(t?.parts)?t.parts:[]).map(i=>[String(i?.id||""),i]).filter(([i])=>i));for(const i of r){const s=i?.mesh;if(!s?.userData)continue;let a=null;const l=String(i?.partId||"").trim();if(l&&l!=="__model__"){const u=o.get(l)||yH(i,l);a=u?Iw(u,n):null}else a=hP(t,n);a?s.userData.faceIds=a:delete s.userData.faceIds}}function xH(e,t){const n=t?.proxy||{};if(!(n.edgePositions instanceof Float32Array)||!(n.edgeIndices instanceof Uint32Array)||!n.edgeIndices.length)return null;const r=new e.BufferGeometry;r.setAttribute("position",new e.BufferAttribute(n.edgePositions,3)),r.setIndex(new e.BufferAttribute(n.edgeIndices,1));const o=new e.LineBasicMaterial({color:16777215,transparent:!0,opacity:0,depthWrite:!1,toneMapped:!1}),i=new e.LineSegments(r,o);return i.userData.edgeIds=n.edgeIds||new Uint32Array(0),i.frustumCulled=!1,i}function SH(e,t){const n=t?.proxy||{};if(!(n.vertexPositions instanceof Float32Array)||!n.vertexPositions.length)return null;const r=new e.BufferGeometry;r.setAttribute("position",new e.BufferAttribute(n.vertexPositions,3));const o=new e.PointsMaterial({color:16777215,transparent:!0,opacity:0,size:1.5,sizeAttenuation:!1,depthWrite:!1,toneMapped:!1}),i=new e.Points(r,o);return i.userData.vertexIds=n.vertexIds||new Uint32Array(0),i.frustumCulled=!1,i}function Mx(e,t){if(typeof t=="function"){t(e);return}for(;e?.children?.length;)e.remove(e.children[0])}function Ix(e,t,n=null,{clearSceneGroup:r=null}={}){if(!e?.THREE||!e?.facePickGroup||!e?.edgePickGroup||!e?.vertexPickGroup)return;Mx(e.facePickGroup,r),Mx(e.edgePickGroup,r),Mx(e.vertexPickGroup,r),e.facePickMesh=null,e.edgePickLines=null,e.vertexPickPoints=null,e.edgePickObjects=[];const o=gH(e.THREE,t);o&&(e.facePickMesh=o,e.facePickGroup.add(o));const i=xH(e.THREE,t);i&&(e.edgePickLines=i,e.edgePickGroup.add(i),e.edgePickObjects=[i]);const s=SH(e.THREE,t);s&&(e.vertexPickPoints=s,e.vertexPickGroup.add(s)),n?(e.facePickGroup.position.copy(n),e.edgePickGroup.position.copy(n),e.vertexPickGroup.position.copy(n)):(e.facePickGroup.position.set(0,0,0),e.edgePickGroup.position.set(0,0,0),e.vertexPickGroup.position.set(0,0,0)),e.facePickGroup.updateMatrixWorld(!0),e.edgePickGroup.updateMatrixWorld(!0),e.vertexPickGroup.updateMatrixWorld(!0)}const EH=new Set(["","SPHERICAL_SURFACE","TOROIDAL_SURFACE","BSPLINE_SURFACE"]);function wH(e){return Math.hypot(e[0],e[1],e[2])}function d1(e){const t=wH(e);return t<=1e-9?null:[e[0]/t,e[1]/t,e[2]/t]}function gP(e,t){return[Number(e[0])-Number(t[0]),Number(e[1])-Number(t[1]),Number(e[2])-Number(t[2])]}function fp(e,t){return Number(e[0])*Number(t[0])+Number(e[1])*Number(t[1])+Number(e[2])*Number(t[2])}function vH(e,t){let n=e;for(;n-t>Math.PI;)n-=Math.PI*2;for(;n-t<-Math.PI;)n+=Math.PI*2;return n}function fA(e){return Array.isArray(e)&&e.length>=3?[Number(e[0]),Number(e[1]),Number(e[2])]:null}function mA(e){return Array.isArray(e)&&e.length>=2?[Number(e[0]),Number(e[1])]:null}function CH(e,t){if(!Array.isArray(e)||!Array.isArray(t?.origin)||!Array.isArray(t?.xDir)||!Array.isArray(t?.yDir))return null;const n=gP(e,t.origin);return[fp(n,t.xDir),fp(n,t.yDir)]}function MH(e,t,n=null){if(!Array.isArray(e)||!Array.isArray(t?.origin)||!Array.isArray(t?.axis)||!Array.isArray(t?.xDir)||!Array.isArray(t?.yDir)||Number(t?.radius)<=0)return null;const r=Number(t.radius),o=gP(e,t.origin),i=fp(o,t.axis),s=[o[0]-Number(t.axis[0])*i,o[1]-Number(t.axis[1])*i,o[2]-Number(t.axis[2])*i],a=Math.atan2(fp(s,t.yDir),fp(s,t.xDir)),l=Number(n);return[(Number.isFinite(l)?vH(a,l):a)*r,i]}function IH(e,t,n=null){return!e||!Array.isArray(t)||t.length<3?null:e.type==="PLANE"&&Array.isArray(e.origin)&&Array.isArray(e.xDir)&&Array.isArray(e.yDir)?CH(t,e):e.type==="CYLINDRICAL_SURFACE"&&Array.isArray(e.origin)&&Array.isArray(e.axis)&&Array.isArray(e.xDir)&&Array.isArray(e.yDir)&&Number(e.radius)>0?MH(t,e,n):null}function AH(e,t){if(!e||!Array.isArray(t)||t.length<2)return null;if(e.type==="PLANE"&&Array.isArray(e.origin)&&Array.isArray(e.xDir)&&Array.isArray(e.yDir))return[e.origin[0]+e.xDir[0]*t[0]+e.yDir[0]*t[1],e.origin[1]+e.xDir[1]*t[0]+e.yDir[1]*t[1],e.origin[2]+e.xDir[2]*t[0]+e.yDir[2]*t[1]];if(e.type==="CYLINDRICAL_SURFACE"&&Array.isArray(e.origin)&&Array.isArray(e.axis)&&Array.isArray(e.xDir)&&Array.isArray(e.yDir)&&Number(e.radius)>0){const n=Number(e.radius),r=t[0]/n,o=Math.cos(r),i=Math.sin(r);return[e.origin[0]+e.axis[0]*t[1]+n*(e.xDir[0]*o+e.yDir[0]*i),e.origin[1]+e.axis[1]*t[1]+n*(e.xDir[1]*o+e.yDir[1]*i),e.origin[2]+e.axis[2]*t[1]+n*(e.xDir[2]*o+e.yDir[2]*i)]}return null}function NH(e,t){if(!e||!Array.isArray(t)||t.length<2)return null;if(e.type==="PLANE")return d1(e.normal||[]);if(e.type==="CYLINDRICAL_SURFACE"&&Array.isArray(e.xDir)&&Array.isArray(e.yDir)&&Number(e.radius)>0){const n=t[0]/Number(e.radius);return d1([e.xDir[0]*Math.cos(n)+e.yDir[0]*Math.sin(n),e.xDir[1]*Math.cos(n)+e.yDir[1]*Math.sin(n),e.xDir[2]*Math.cos(n)+e.yDir[2]*Math.sin(n)])}return null}function _H(e,t,{segments:n=48,offset:r=.04}={}){const o=e?.pickData?.surface||{},i=fA(t?.startPoint),s=fA(t?.endPoint),a=mA(t?.startUv),l=mA(t?.endUv);if(o.type==="PLANE"&&i&&s){const u=d1(e?.pickData?.normal||o.normal||[]),d=g=>u?[g[0]+u[0]*r,g[1]+u[1]*r,g[2]+u[2]*r]:g,m=d(i),p=d(s);return[m[0],m[1],m[2],p[0],p[1],p[2]]}if(o.type==="CYLINDRICAL_SURFACE"&&a&&l){const u=[],d=Math.max(4,Math.round(Number(n)||48));let m=null;for(let p=0;p<=d;p+=1){const g=p/d,x=[a[0]+(l[0]-a[0])*g,a[1]+(l[1]-a[1])*g],y=AH(o,x);if(!y)continue;const S=NH(o,x),b=S?[y[0]+S[0]*r,y[1]+S[1]*r,y[2]+S[2]*r]:y;m&&u.push(m[0],m[1],m[2],b[0],b[1],b[2]),m=b}return u}return i&&s?[i[0],i[1],i[2],s[0],s[1],s[2]]:[]}function TH(e){const t=String(e||"").split(",");if(t.length!==2)throw new Error("Screenshot capture failed");const r=t[0].match(/data:(.*?);base64/)?.[1]||"image/png",o=atob(t[1]),i=new Uint8Array(o.length);for(let s=0;s{if(!e){n(new Error("Screenshot capture failed"));return}if(typeof e.toBlob=="function"){e.toBlob(r=>{if(r){t(r);return}n(new Error("Screenshot capture failed"))},"image/png");return}try{t(TH(e.toDataURL("image/png")))}catch(r){n(r)}})}function bP(e,t,n){const r=Math.max(1,Math.floor(Number(t)||1)),o=Math.max(1,Math.floor(Number(n)||1)),i=Math.min(Math.max(0,Math.floor(Number(e?.x)||0)),r-1),s=Math.min(Math.max(0,Math.floor(Number(e?.y)||0)),o-1),a=Math.max(1,r-i),l=Math.max(1,o-s),u=Math.min(Math.max(1,Math.floor(Number(e?.width)||a)),a),d=Math.min(Math.max(1,Math.floor(Number(e?.height)||l)),l);return{x:i,y:s,width:u,height:d,isFullFrame:i===0&&s===0&&u===r&&d===o}}function pA(e){const t=String(e||"").trim().toLowerCase();return!t||t==="transparent"||/^[a-z]+\(\s*[^,]+,\s*[^,]+,\s*[^,]+,\s*0(?:\.0+)?%?\s*\)$/.test(t)?!0:/^[a-z]+\([^)]*\/\s*0(?:\.0+)?%?\s*\)$/.test(t)}function PH(e,t="#ffffff"){const n=globalThis.window?.getComputedStyle||globalThis.getComputedStyle;let r=e||null;const o=new Set;for(;r&&!o.has(r);){o.add(r);const s=typeof n=="function"?n(r)?.backgroundColor:"";if(!pA(s))return s;r=r.parentElement||null}const i=globalThis.document?.body||null;if(i&&!o.has(i)&&typeof n=="function"){const s=n(i)?.backgroundColor;if(!pA(s))return s}return t}function OH(e,t,n,r,{backgroundColor:o="",crop:i=null,overlayCanvas:s=null}={}){if(!e||!t)throw new Error("Screenshot capture failed");const a=bP(i,n,r),l=String(o||"").trim(),u=e.fillStyle;l&&(e.fillStyle="#ffffff",e.fillStyle=l,e.fillRect(0,0,a.width,a.height)),e.drawImage(t,a.x,a.y,a.width,a.height,0,0,a.width,a.height),e.fillStyle=u,s&&e.drawImage(s,a.x,a.y,a.width,a.height,0,0,a.width,a.height)}async function kH(e,t,{backgroundColor:n="",crop:r=null}={}){const o=e?.renderer,i=e?.scene,s=e?.camera,a=o?.domElement?.width||0,l=o?.domElement?.height||0;if(!o||!i||!s||a<=0||l<=0)throw new Error("Screenshot capture failed");const u=o.getRenderTarget(),d=o.xr?.enabled===!0;try{o.xr&&(o.xr.enabled=!1),o.setRenderTarget(null),o.render(i,s)}finally{o.setRenderTarget(u),o.xr&&(o.xr.enabled=d)}const m=bP(r,a,l),p=document.createElement("canvas");p.width=m.width,p.height=m.height;const g=p.getContext("2d");if(!g)throw new Error("Screenshot capture failed");return OH(g,o.domElement,a,l,{backgroundColor:n,crop:m,overlayCanvas:t}),RH(p)}const DH=/(?:error creating webgl context|webgl context could not be created|failed to create webgl|webgl is not supported)/i;function Aw(e){return e instanceof Error?e.message:String(e||"")}function yP(e){return DH.test(Aw(e))}function jH(e){const t=Aw(e).trim();return yP(e)?{severity:"error",blocking:!0,summary:"WebGL unavailable",title:"Browser WebGL is unavailable",message:"CAD Viewer needs browser WebGL to render 3D models, but this browser could not create a WebGL context.",resolution:"Enable hardware acceleration or software WebGL in the browser, update the graphics or Mesa drivers, then reload CAD Viewer. In Chrome, check chrome://gpu for the WebGL status."}:{severity:"error",blocking:!0,summary:"CAD Viewer startup failed",title:"CAD Viewer could not start",message:t||"The 3D renderer failed before CAD Viewer finished starting.",resolution:"Reload CAD Viewer. If the problem persists, check the browser console for the renderer startup error."}}const B=Object.freeze({STEP:"step",STL:"stl",THREE_MF:"3mf",GLB:"glb",GCODE:"gcode",DXF:"dxf",IMPLICIT:"implicit",URDF:"urdf",SRDF:"srdf",SDF:"sdf"}),LH=Object.freeze([B.STL,B.THREE_MF,B.GLB]),FH=Object.freeze([B.URDF,B.SRDF,B.SDF]);function pc(e){return String(e||"").trim().toLowerCase()}function zH(e,{defaultFormat:t=B.STEP}={}){const n=pc(e||t);return n==="stp"?B.STEP:n==="gltf"?B.GLB:n===B.STEP||n===B.STL||n===B.THREE_MF||n===B.GLB||n===B.GCODE||n===B.DXF||n===B.IMPLICIT||n===B.URDF||n===B.SRDF||n===B.SDF?n:t}function xP(e){return pc(e?.kind)}function or(e){const t=xP(e);return t===B.DXF?B.DXF:t===B.STL?B.STL:t===B.THREE_MF?B.THREE_MF:t===B.GLB||t==="gltf"?B.GLB:t===B.GCODE?B.GCODE:t===B.IMPLICIT?B.IMPLICIT:t===B.URDF?B.URDF:t===B.SRDF?B.SRDF:t===B.SDF?B.SDF:B.STEP}function df(e){return LH.includes(pc(e))}function Hi(e){return FH.includes(pc(e))}function BH(e){const t=pc(e);return df(t)?t:B.GLB}function Iu(e){return BH(or(e))}function hA(e){if(!e)return"";const t=xP(e);return t===B.DXF?B.DXF:t===B.URDF?B.URDF:t===B.SRDF?B.SRDF:t===B.SDF?B.SDF:t===B.GCODE?B.GCODE:t===B.IMPLICIT?B.IMPLICIT:or(e)===B.STEP?B.STEP:df(or(e))?"mesh":""}function VH(e,{baseUrl:t=""}={}){const n=String(e||"").trim();if(!n)return"";let r=n;try{r=new URL(n,t||"http://localhost/").pathname}catch{r=n.split("?")[0].split("#")[0]}const o=r.toLowerCase(),i=o.lastIndexOf("/"),s=o.lastIndexOf(".");return s>i?o.slice(s):""}function $H(e){const t=pc(e).replace(/^\./,"");return t==="step"||t==="stp"?B.STEP:t==="stl"?B.STL:t==="3mf"?B.THREE_MF:t==="glb"||t==="gltf"?B.GLB:t==="gcode"?B.GCODE:t==="implicit"||t==="implicit.js"||t==="implicit.mjs"?B.IMPLICIT:t==="dxf"?B.DXF:t==="urdf"?B.URDF:t==="srdf"?B.SRDF:t==="sdf"?B.SDF:""}function gA(e,t={}){const n=String(e||"").trim();let r=n;try{r=new URL(n,t.baseUrl||"http://localhost/").pathname}catch{r=n.split("?")[0].split("#")[0]}const o=r.toLowerCase();return o.endsWith(".implicit.js")||o.endsWith(".implicit.mjs")?B.IMPLICIT:$H(VH(e,t))}const ke={PENDING:"pending",LOADING:"loading",READY:"ready",ERROR:"error"},Wn={IDLE:"idle",DISABLED:"disabled",LOADING:"loading",READY:"ready",ERROR:"error"},oo={REFERENCES:"references",DRAW:"draw"},Jt={FREEHAND:"freehand",LINE:"line",SURFACE_LINE:"surface-line",ARROW:"arrow",DOUBLE_ARROW:"double-arrow",RECTANGLE:"rectangle",CIRCLE:"circle",FILL:"fill",ERASE:"erase"},Ax=Object.freeze({x:[1,0,0],y:[0,1,0],z:[0,0,1]}),Nx=Object.freeze({axis:{x:{front:[250,88,79],back:[122,32,28]},y:{front:[92,233,123],back:[30,99,46]},z:{front:[84,131,255],back:[30,53,126]}},center:{fill:[252,215,74],stroke:[255,235,153]}}),GH="6.71875rem";function il(e,t,n){return Math.min(Math.max(e,t),n)}function UH(e,t=""){return typeof e=="number"&&Number.isFinite(e)&&e>0?`${e}px`:String(e||"").trim()||t}function f1(e){const[t=0,n=0,r=0]=Array.isArray(e)?e:[0,0,0];return[Math.round(il(t,0,255)),Math.round(il(n,0,255)),Math.round(il(r,0,255))]}function bA(e,t,n){const r=il(n,0,1),o=f1(e),i=f1(t);return[o[0]+(i[0]-o[0])*r,o[1]+(i[1]-o[1])*r,o[2]+(i[2]-o[2])*r]}function rd(e,t=1){const[n,r,o]=f1(e);return`rgba(${n}, ${r}, ${o}, ${il(t,0,1)})`}function Og(e,t){if(!Array.isArray(e)||e.length<3)return[...t];const n=Number(e[0]),r=Number(e[1]),o=Number(e[2]);return!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(o)?[...t]:[il(n,0,255),il(r,0,255),il(o,0,255)]}function WH(e){const t=e?.viewPlanePalette||{},n=t?.axis||{},r={};for(const o of["x","y","z"]){const i=Nx.axis[o],s=n?.[o]||{};r[o]={front:Og(s.front,i.front),back:Og(s.back,i.back)}}return{axis:r,center:{fill:Og(t?.center?.fill,Nx.center.fill),stroke:Og(t?.center?.stroke,Nx.center.stroke)}}}function _x(e,t){if(!Array.isArray(e)||e.length!==3)return[...t];const n=Number(e[0]),r=Number(e[1]),o=Number(e[2]);if(!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(o))return[...t];const i=Math.hypot(n,r,o);return i<1e-6?[...t]:[n/i,r/i,o/i]}function HH(e){return{x:_x(e?.x,Ax.x),y:_x(e?.y,Ax.y),z:_x(e?.z,Ax.z)}}function KH(e,t){const[n=0,r=0,o=0]=Array.isArray(t)?t:[0,0,0];return[e.x[0]*n+e.y[0]*r+e.z[0]*o,e.x[1]*n+e.y[1]*r+e.z[1]*o,e.x[2]*n+e.y[2]*r+e.z[2]*o]}function XH(e){const t=String(e?.id||"");return t.startsWith("x")?"x":t.startsWith("y")?"y":"z"}function Nw({showViewPlane:e,previewMode:t,isLoading:n,meshData:r,viewPlaneOffsetRight:o,viewPlaneOffsetBottom:i=16,activeViewPlaneFace:s,viewPlaneFaces:a,viewPlaneOrientation:l,viewerTheme:u,compact:d=!1,variant:m="3d",viewPlaneSize:p,viewPlaneHeader:g=null,activateViewPlaneFace:x,activateDefaultViewPlane:y}){const[S,b]=f.useState("");if(!e||t||n||!r)return null;const I=HH(l),A=WH(u),P=(Array.isArray(a)?a:[]).map(D=>{const $=XH(D),ie=A.axis[$]||A.axis.z,[W,Z,Ee]=KH(I,D.direction),re=il((Ee+1)/2,0,1),be=bA(ie.back,ie.front,re),_e=bA([10,16,28],ie.front,re*.82+.08);return{id:D.id,title:D.title,x:50+W*28,y:50-Z*28,z:Ee,depth:re,radius:4.95+re*1.05,fill:rd(be),edge:rd(_e),stem:rd(be,.32+re*.48)}}).sort((D,$)=>D.z-$.z),R=P.filter(D=>D.z<0),v=P.filter(D=>D.z>=0),C=m==="2d",T=!d&&!C?UH(p,GH):"",k=d||C?"h-20 w-20":"",z=T?{width:T,height:T}:void 0,Y=C?"cad-glass-surface pointer-events-auto relative rounded-md border border-sidebar-border text-sidebar-foreground shadow-sm transition duration-150":"pointer-events-auto relative text-sidebar-foreground transition duration-150",K=C?"2D view selector":"Perspective selector",J=typeof i=="number"?`${i}px`:i,G=S==="__default__",Q=D=>{const $=s===D.id,ie=S===D.id;return c.jsxs("g",{role:"button",tabIndex:0,"aria-label":D.title,"aria-pressed":$,className:"group cursor-pointer focus:outline-none",onPointerDown:W=>{W.stopPropagation()},onPointerEnter:()=>{b(D.id)},onPointerMove:()=>{b(D.id)},onPointerLeave:()=>{b(W=>W===D.id?"":W)},onMouseEnter:()=>{b(D.id)},onMouseMove:()=>{b(D.id)},onMouseLeave:()=>{b(W=>W===D.id?"":W)},onFocus:()=>{b(D.id)},onBlur:()=>{b(W=>W===D.id?"":W)},onClick:W=>{W.stopPropagation(),x(D.id)},onKeyDown:W=>{W.key!=="Enter"&&W.key!==" "||(W.preventDefault(),W.stopPropagation(),x(D.id))},children:[c.jsx("circle",{cx:D.x,cy:D.y,r:D.radius+4.4,className:"transition-opacity duration-150",opacity:ie?1:0,fill:D.fill,fillOpacity:"0.12",stroke:"var(--sidebar-foreground)",strokeOpacity:"0.72",strokeWidth:"1.1"}),c.jsx("circle",{cx:D.x,cy:D.y,r:D.radius+($?2.1:0),fill:"none",stroke:$?"var(--sidebar-foreground)":"transparent",strokeWidth:$?1.6:0}),c.jsx("circle",{cx:D.x,cy:D.y,r:D.radius,className:"transition-transform duration-150 ease-out",style:{transform:ie?"scale(1.1)":"scale(1)",transformBox:"fill-box",transformOrigin:"center"},fill:D.fill,stroke:$?"var(--sidebar-foreground)":D.edge,strokeWidth:$?1.35:1})]},D.id)};return c.jsxs("div",{className:"pointer-events-none absolute z-30 flex flex-col items-end gap-1",style:{right:`${o}px`,bottom:J},children:[g?c.jsx("div",{className:"pointer-events-auto",onPointerDown:D=>{D.stopPropagation()},children:g}):null,c.jsx("div",{className:`${Y} ${k}`,style:z,onPointerDown:D=>{D.stopPropagation()},children:c.jsxs("svg",{className:"absolute inset-0 h-full w-full",viewBox:"0 0 100 100","aria-label":K,children:[c.jsx("defs",{children:c.jsxs("radialGradient",{id:"view-sphere-shell",cx:"34%",cy:"28%",r:"74%",children:[c.jsx("stop",{offset:"0%",stopColor:"var(--sidebar)"}),c.jsx("stop",{offset:"100%",stopColor:"var(--sidebar)"})]})}),C?c.jsxs(c.Fragment,{children:[c.jsx("rect",{x:"15",y:"15",width:"70",height:"70",rx:"8",fill:"url(#view-sphere-shell)",stroke:"var(--sidebar-border)",strokeWidth:"0.75"}),c.jsx("line",{x1:"22",y1:"50",x2:"78",y2:"50",fill:"none",stroke:"color-mix(in oklch, var(--sidebar-foreground) 18%, transparent)",strokeWidth:"1",strokeLinecap:"round"}),c.jsx("line",{x1:"50",y1:"22",x2:"50",y2:"78",fill:"none",stroke:"color-mix(in oklch, var(--sidebar-foreground) 18%, transparent)",strokeWidth:"1",strokeLinecap:"round"})]}):c.jsxs(c.Fragment,{children:[c.jsx("circle",{cx:"50",cy:"50",r:"44",fill:"url(#view-sphere-shell)",stroke:"var(--sidebar-border)",strokeWidth:"0.75"}),c.jsx("ellipse",{cx:"50",cy:"50",rx:"30",ry:"11.8",fill:"none",stroke:"color-mix(in oklch, var(--sidebar-foreground) 12%, transparent)",strokeWidth:"0.8"}),c.jsx("ellipse",{cx:"50",cy:"50",rx:"14",ry:"30",fill:"none",stroke:"color-mix(in oklch, var(--sidebar-foreground) 12%, transparent)",strokeWidth:"0.8"})]}),R.map(D=>c.jsx("line",{x1:"50",y1:"50",x2:D.x,y2:D.y,stroke:D.stem,strokeWidth:1.6+D.depth*.8,strokeLinecap:"round",pointerEvents:"none"},`${D.id}-stem`)),R.map(D=>Q(D)),c.jsxs("g",{role:"button",tabIndex:0,"aria-label":C?"Fit 2D view":"Reset to default isometric view",className:"group cursor-pointer focus:outline-none",onPointerDown:D=>{D.stopPropagation()},onPointerEnter:()=>{b("__default__")},onPointerMove:()=>{b("__default__")},onPointerLeave:()=>{b(D=>D==="__default__"?"":D)},onMouseEnter:()=>{b("__default__")},onMouseMove:()=>{b("__default__")},onMouseLeave:()=>{b(D=>D==="__default__"?"":D)},onFocus:()=>{b("__default__")},onBlur:()=>{b(D=>D==="__default__"?"":D)},onClick:D=>{D.stopPropagation(),y?.()},onKeyDown:D=>{D.key!=="Enter"&&D.key!==" "||(D.preventDefault(),D.stopPropagation(),y?.())},children:[c.jsx("circle",{cx:"50",cy:"50",r:"10.2",fill:"transparent",stroke:"none"}),c.jsx("circle",{cx:"50",cy:"50",r:"11.4",className:"transition-opacity duration-150",opacity:G?1:0,fill:rd(A.center.fill,.16),stroke:"var(--sidebar-foreground)",strokeOpacity:"0.72",strokeWidth:"1.1"}),c.jsx("circle",{cx:"50",cy:"50",r:"7.3",className:"transition-transform duration-150 ease-out",style:{transform:G?"scale(1.1)":"scale(1)",transformBox:"fill-box",transformOrigin:"center"},fill:rd(A.center.fill,.95),stroke:rd(A.center.stroke,.72),strokeWidth:"1.05"})]}),v.map(D=>c.jsx("line",{x1:"50",y1:"50",x2:D.x,y2:D.y,stroke:D.stem,strokeWidth:1.6+D.depth*.8,strokeLinecap:"round",pointerEvents:"none"},`${D.id}-stem-front`)),v.map(D=>Q(D))]})})]})}function YH({drawingCanvasRef:e,drawingDraftRef:t,drawingStrokesRef:n,drawingChangeRef:r,drawingIdRef:o,drawingEnabled:i,drawingTool:s,meshData:a,previewMode:l,viewerReadyTick:u,renderDrawingOverlay:d,redrawDrawingCanvas:m,buildDrawingPoint:p,distanceToStrokeInPixels:g,strokeLengthInPixels:x,drawingToolNeedsTwoPoints:y,buildFillStrokeAtPoint:S,buildSurfaceLineAnchor:b,updateSurfaceLineAnchor:I,drawingEraseThresholdPx:A,drawingMinPointDistancePx:N,drawingMinStrokeLengthPx:P}){f.useEffect(()=>{const R=e.current;if(!R)return;if(!i||l||!a){t.current=null,d();return}const v={pointerId:null,erasing:!1},C=D=>{n.current=D,r.current?.(D),m(R,D,t.current)},T=D=>{if(!D){m(R,n.current,t.current);return}o.current+=1,C([...n.current,{id:`stroke-${o.current}`,...D}])},k=D=>{const $=R.width||1,ie=R.height||1;let W=-1,Z=1/0;for(let re=0;reA)return;const Ee=n.current.filter((re,be)=>be!==W);C(Ee)},z=D=>{t.current={id:"__draft__",tool:s,points:[D]},m(R,n.current,t.current)},Y=D=>{const $=t.current;if($){if(s===Jt.FREEHAND){const ie=$.points[$.points.length-1],W=(D.x-ie.x)*(R.width||1),Z=(D.y-ie.y)*(R.height||1);Math.hypot(W,Z)>=N&&($.points=[...$.points,D])}else $.points=[$.points[0],D];m(R,n.current,$)}},K=()=>{const D=t.current;if(!D)return;t.current=null;const $=x(D,R.width||1,R.height||1);if(y(D.tool)&&(D.points.length<2||$1){m(R,n.current,null);return}T({tool:D.tool,points:D.points.map(ie=>({x:ie.x,y:ie.y})),surfaceLine:D.surfaceLine||null})},J=D=>{if(D.button!==0)return;v.erasing=s===Jt.ERASE;const $=p(D,R);if(v.erasing){D.preventDefault(),D.stopPropagation(),v.pointerId=D.pointerId,R.setPointerCapture?.(D.pointerId),k($);return}if(s===Jt.FILL){D.preventDefault(),D.stopPropagation(),T(S($,n.current,R));return}if(s===Jt.SURFACE_LINE){const ie=b?.(D,R);if(!ie){m(R,n.current,null);return}D.preventDefault(),D.stopPropagation(),v.pointerId=D.pointerId,R.setPointerCapture?.(D.pointerId),t.current={id:"__draft__",tool:s,points:[ie.screenPoint,ie.screenPoint],surfaceLine:ie.surfaceLine},m(R,n.current,t.current);return}D.preventDefault(),D.stopPropagation(),v.pointerId=D.pointerId,R.setPointerCapture?.(D.pointerId),z($)},G=D=>{if(v.pointerId!==D.pointerId)return;D.preventDefault(),D.stopPropagation();const $=p(D,R);if(v.erasing){k($);return}if(s===Jt.SURFACE_LINE){const ie=t.current;if(!ie?.surfaceLine?.referenceId)return;const W=I?.(D,R,ie.surfaceLine);if(!W)return;ie.points=[ie.points[0],W.screenPoint],ie.surfaceLine=W.surfaceLine,m(R,n.current,ie);return}Y($)},Q=D=>{if(v.pointerId===D.pointerId){if(D.preventDefault(),D.stopPropagation(),R.releasePointerCapture?.(D.pointerId),v.pointerId=null,v.erasing){v.erasing=!1,m(R,n.current,null);return}K()}};return R.addEventListener("pointerdown",J),R.addEventListener("pointermove",G),R.addEventListener("pointerup",Q),R.addEventListener("pointercancel",Q),()=>{v.pointerId=null,v.erasing=!1,t.current=null,m(R,n.current,null),R.removeEventListener("pointerdown",J),R.removeEventListener("pointermove",G),R.removeEventListener("pointerup",Q),R.removeEventListener("pointercancel",Q)}},[p,S,b,g,e,r,t,i,A,o,N,P,n,s,y,a,l,m,d,x,I,u])}function qH(e,t,n){const r=Number(t),o=Number(n);if(!e||!Number.isFinite(r)||r<=0||!Number.isFinite(o)||o<=0)return null;if(e.isPerspectiveCamera){const i=(Number(e.fov)||0)*(Math.PI/180);return i>0&&i0)||!Number.isFinite(s)||!Number.isFinite(a)?null:Math.abs(s-a)/i/r}return null}function ZH({baseThreshold:e,thresholdScale:t=1,maxScreenDistancePx:n,camera:r,viewportHeightPx:o,distance:i}={}){const s=Math.max((Number(e)||0)*(Number(t)||0),0);if(!(s>0))return 0;const a=Number(n);if(!(a>0))return s;const l=qH(r,o,i);return Number.isFinite(l)&&l>0?Math.min(s,l*a):s}const JH=1200;function QH({now:e=()=>Date.now(),suppressionMs:t=JH}={}){let n=0;return{suppressNextContextMenu(){n=Math.max(n,e()+t)},consumeSuppression(){return e()>n?(n=0,!1):(n=0,!0)},clear(){n=0},isSuppressed(){return e()<=n}}}const e8=1,SP=.0015,EP=.02,yA=.75,xA=.08,m1=10,wP=m1,vP=6,CP=vP,t8=wP,n8=CP,SA=5,r8=4,o8=4,i8=3,s8=2,a8=4,l8=12,c8=220;function EA(e,t=null){if(!e.length)return null;const n=e.map(r=>({intersection:r,screenDistance:typeof t=="function"?Number(t(r)):1/0,pickError:r.distanceToRay??r.distance??1/0,distance:r.distance??1/0,metric:r.object.userData.metric??1/0}));return n.sort((r,o)=>{const i=Number.isFinite(r.screenDistance)?r.screenDistance:1/0,s=Number.isFinite(o.screenDistance)?o.screenDistance:1/0;return Math.abs(i-s)>.25?i-s:Math.abs(r.pickError-o.pickError)>1e-4?r.pickError-o.pickError:Math.abs(r.distance-o.distance)>1e-4?r.distance-o.distance:r.metric-o.metric}),n[0].intersection}function wA(e){if(!Array.isArray(e)||!e.length)return[];const t=Number(e[0]?.distance);if(!Number.isFinite(t))return[];const n=Math.max(EP,t*SP);return e.filter(r=>Number(r?.distance)<=t+n)}function kg(e){return new Set((Array.isArray(e)?e:[e]).map(t=>String(t||"").trim()).filter(Boolean))}function u8(e,t){return tV(e?.activeClipPlane,t?.point)}function Dg(e,t){return!e?.activeClipPlane||!Array.isArray(t)||!t.length?t:t.filter(n=>u8(e,n))}function d8({runtimeRef:e,mountRef:t,sceneMountRef:n=null,drawingCanvasRef:r=null,previewMode:o,pickMode:i,selectorRuntime:s,pickableFaces:a,pickableEdges:l,pickableVertices:u,hiddenPartIds:d,focusedPartId:m,onHoverReferenceChange:p,onActivateReference:g,onDoubleActivateReference:x,onContextReference:y,viewerReadyTick:S}){const b=f.useRef(i),I=f.useRef(s),A=f.useRef(a),N=f.useRef(l),P=f.useRef(u),R=f.useRef(d),v=f.useRef(m),C=f.useRef(p),T=f.useRef(g),k=f.useRef(x),z=f.useRef(y),Y=f.useRef(new Set),K=f.useRef(new Set),J=f.useRef(new Set);b.current=i,I.current=s,A.current=a,N.current=l,P.current=u,R.current=d,v.current=m,C.current=p,T.current=g,k.current=x,z.current=y,Y.current=new Set((Array.isArray(a)?a:[]).map(G=>String(G?.id||"").trim()).filter(Boolean)),K.current=new Set((Array.isArray(l)?l:[]).map(G=>String(G?.id||"").trim()).filter(Boolean)),J.current=new Set((Array.isArray(u)?u:[]).map(G=>String(G?.id||"").trim()).filter(Boolean)),f.useEffect(()=>{const G=e.current;if(!G||!t.current||o){C.current?.("");return}const Q=t.current,D=n?.current||null,$=r?.current||null,W=(typeof window.matchMedia=="function"?window.matchMedia("(pointer: coarse)"):null)?.matches??!1,Z={active:!1,x:0,y:0,pointerType:"",referenceId:""},Ee={active:!1,x:0,y:0,pointerType:""},re={active:!1,blocked:!1,moved:!1,startedInScene:!1,x:0,y:0,pointerType:""},be={rafId:0,x:0,y:0,lastX:NaN,lastY:NaN,hoveredReferenceId:""},_e=!W;let Ie=0;const oe=QH();function me(j){const de=Number(j?.buttons);return Number.isFinite(de)?de:0}function se(j){return(me(j)&1)===1}function Ae(j){return(me(j)&2)===2}function we(j){return(me(j)&3)===3}function ct(){Ee.active=!1,Ee.pointerType=""}function ut(){re.active=!1,re.blocked=!1,re.moved=!1,re.startedInScene=!1,re.pointerType=""}function Tt(){oe.suppressNextContextMenu(),re.blocked=!0,re.moved=!0,Z.active=!1,Z.pointerType="",Z.referenceId=""}function Ve(j,de){const L=Q.getBoundingClientRect();G.pointer.x=(j-L.left)/L.width*2-1,G.pointer.y=-((de-L.top)/L.height)*2+1,G.raycaster.setFromCamera(G.pointer,G.camera),G.raycaster?.params?.Line&&(G.raycaster.params.Line.threshold=G.edgePickThreshold||1),G.raycaster?.params?.Points&&(G.raycaster.params.Points.threshold=G.vertexPickThreshold||1)}function St(j){if(!j?.clone||!G?.camera)return null;const de=j.clone().project(G.camera);if(!Number.isFinite(de.x)||!Number.isFinite(de.y))return null;const L=Q.getBoundingClientRect();return{x:L.left+(de.x+1)*.5*L.width,y:L.top+(1-de.y)*.5*L.height}}function wt(j,de,L){const te=St(j?.point);return te?Math.hypot(de-te.x,L-te.y):1/0}function Vn(){return Q.clientHeight||Q.getBoundingClientRect().height||1}function De(j){const de=Number(j?.[0]?.distance);if(Number.isFinite(de)&&de>0)return de;const L=G?.camera?.position?.distanceTo?.(G?.controls?.target);return Number.isFinite(L)&&L>0?L:Number(G?.modelRadius||1)}function xe(j,de,L,te){return ZH({baseThreshold:j,thresholdScale:de,maxScreenDistancePx:L,camera:G.camera,viewportHeightPx:Vn(),distance:De(te)})}function yt(){const j=kg(v.current),de=kg(R.current);return G.displayRecords.filter(L=>!(!L?.mesh?.visible||de.has(String(L?.partId||"").trim())||j.size&&!j.has(String(L?.partId||"").trim()))).map(L=>L.mesh)}function Te(){const j=yt();return j.length?Dg(G,G.raycaster.intersectObjects(j,!1)):[]}function rt(j){const de=kg(v.current),L=kg(R.current);for(const te of j){const fe=te?.object?.userData?.partId;if(fe&&!L.has(String(fe||"").trim())&&!(de.size&&!de.has(String(fe||"").trim())))return fe}return null}function Re(j){const de=Number(j?.faceIndex),L=j?.object?.userData?.faceIds,te=Number.isInteger(de)?Number(L?.[de]):NaN;if(!Number.isInteger(te))return null;const fe=I.current?.faceReferenceByRowIndex?.get?.(te)||null,ae=String(fe?.id||"").trim(),he=Y.current;return!ae||he.size&&!he.has(ae)?null:fe}function Fe(j){const de=Number(j?.index),L=j?.object?.userData?.edgeIds,te=Number.isInteger(de)?Math.floor(de/2):NaN,fe=Number.isInteger(te)?Number(L?.[te]):NaN;if(!Number.isInteger(fe))return null;const ae=I.current?.edgeReferenceByRowIndex?.get?.(fe)||null,he=String(ae?.id||"").trim(),ot=K.current;return!he||ot.size&&!ot.has(he)?null:ae}function on(j){const de=Number(j?.index),L=j?.object?.userData?.vertexIds,te=Number.isInteger(de)?Number(L?.[de]):NaN;if(!Number.isInteger(te))return null;const fe=I.current?.vertexReferenceByRowIndex?.get?.(te)||null,ae=String(fe?.id||"").trim(),he=J.current;return!ae||he.size&&!he.has(ae)?null:fe}function ht(j){if(!(Array.isArray(A.current)?A.current:[]).length)return null;for(const ae of wA(j)){const he=Re(ae);if(he)return he}if(!G.facePickMesh)return null;const de=Dg(G,G.raycaster.intersectObject(G.facePickMesh,!1));if(!de.length)return null;const L=wA(j);let te=de;const fe=Number(L[0]?.distance);if(Number.isFinite(fe)){const ae=Math.max(EP,fe*SP);te=de.filter(he=>Number(he?.distance)<=fe+ae)}for(const ae of te.length?te:de){const he=Re(ae);if(he)return he}return null}function jt(j,de,L,{thresholdScale:te=1,maxScreenDistancePx:fe=m1}={}){if(!(Array.isArray(N.current)?N.current:[]).length||!G.edgePickLines)return null;const he=xe(G.edgePickThreshold||1,te,fe,j);G.raycaster?.params?.Line&&(G.raycaster.params.Line.threshold=he);let ot=Dg(G,G.raycaster.intersectObject(G.edgePickLines,!1));const It=Number(j?.[0]?.distance);if(Number.isFinite(It)){const Ne=Math.max(xA,he*yA);ot=ot.filter(Et=>Number(Et?.distance)<=It+Ne)}const Pt=EA(ot,Ne=>wt(Ne,de,L));if(!Pt)return null;const Ke=wt(Pt,de,L);if(Number.isFinite(Ke)&&Ke>fe)return null;const en=Fe(Pt);return en?{reference:en,screenDistance:Ke}:null}function qt(j,de,L,{thresholdScale:te=1,maxScreenDistancePx:fe=SA}={}){if(!(Array.isArray(P.current)?P.current:[]).length||!G.vertexPickPoints)return null;const he=xe(G.vertexPickThreshold||1,te,fe,j);G.raycaster?.params?.Points&&(G.raycaster.params.Points.threshold=he);let ot=Dg(G,G.raycaster.intersectObject(G.vertexPickPoints,!1));const It=Number(j?.[0]?.distance);if(Number.isFinite(It)){const Ne=Math.max(xA,he*yA);ot=ot.filter(Et=>Number(Et?.distance)<=It+Ne)}const Pt=EA(ot,Ne=>wt(Ne,de,L));if(!Pt)return null;const Ke=wt(Pt,de,L);if(Number.isFinite(Ke)&&Ke>fe)return null;const en=on(Pt);return en?{reference:en,screenDistance:Ke}:null}function sn(j,de){const L=Array.isArray(j?.pickData?.adjacentSelectors)?j.pickData.adjacentSelectors:[];if(!L.length)return!1;const te=String(de?.displaySelector||"").trim(),fe=String(de?.normalizedSelector||"").trim();return L.includes(te)||L.includes(fe)}function Mn(j,de){const L=Array.isArray(de?.pickData?.adjacentSelectors)?de.pickData.adjacentSelectors:[];if(!L.length)return!1;const te=String(j?.displaySelector||"").trim(),fe=String(j?.normalizedSelector||"").trim();return L.includes(te)||L.includes(fe)}function fn(j,de){const L=Array.isArray(j?.pickData?.adjacentSelectors)?j.pickData.adjacentSelectors:[],te=Array.isArray(de?.pickData?.adjacentSelectors)?de.pickData.adjacentSelectors:[];if(!L.length||!te.length)return!1;const fe=new Set(L);return te.some(ae=>fe.has(ae))}function Bt(j,de,L,{hover:te=!1}={}){const fe=Array.isArray(A.current)?A.current:[],ae=Array.isArray(N.current)?N.current:[],he=Array.isArray(P.current)?P.current:[],ot=fe.length>0,It=ae.length>0,Pt=he.length>0;if(!ot&&!It&&!Pt)return null;const Ke=ht(j),Ne=jt(j,de,L,{thresholdScale:Ke?e8:1,maxScreenDistancePx:te?Ke?CP:vP:Ke?wP:m1}),Et=qt(j,de,L,{maxScreenDistancePx:te?r8:SA});if(Et){const Pe=te?i8:o8,En=Ne&&Mn(Ne.reference,Et.reference),Se=Ke&&fn(Ke,Et.reference);if(!Ke&&!Ne||(En||Se)&&Number(Et.screenDistance)<=Pe)return Et.reference.id}if(Ke&&Ne){const Pe=te?n8:t8;return sn(Ke,Ne.reference)&&Number(Ne.screenDistance)<=Pe?Ne.reference.id:Ke.id}return Ne?.reference?.id||Ke?.id||Et?.reference?.id||null}function dt(j,de,{hover:L=!1,preferTopology:te=!1}={}){Ve(j,de);const fe=Te(),ae=b.current;if(te){const he=Bt(fe,j,de,{hover:L});if(he)return he}return ae===si.PARTS||ae===si.ASSEMBLY?rt(fe):ae===si.AUTO?Bt(fe,j,de,{hover:L})||rt(fe):null}function qe(j,de,L=""){return ze(L)?String(be.hoveredReferenceId||"").trim()||dt(j,de,{hover:!0}):dt(j,de)}function Vt(j=""){return j==="touch"||j==="pen"||W}function We(j=""){return Vt(j)?l8:a8}function ze(j=""){return!Vt(j)}function Ze(j){return j instanceof Node?!!(D?.contains(j)||$&&(j===$||$.contains?.(j))):!1}function vt(j){return Ze(j.target)}function Tn(j){return vt(j)||re.active||Ee.active}function pe(j){const de=j||"";Q.style.cursor=de?"pointer":"",be.hoveredReferenceId!==de&&(be.hoveredReferenceId=de,C.current?.(de))}function Xe(){be.rafId&&(window.cancelAnimationFrame(be.rafId),be.rafId=0),be.lastX=NaN,be.lastY=NaN,Q.style.cursor="",be.hoveredReferenceId&&(be.hoveredReferenceId="",C.current?.(""))}function He(){Ie&&(window.clearTimeout(Ie),Ie=0)}function Rn(j,de={}){T.current?.(j||"",de)}function xn(j,de={}){if(He(),!_e){Rn(j,de);return}Ie=window.setTimeout(()=>{Ie=0,Rn(j,de)},c8)}function ue(){if(be.rafId=0,G.interactionState.active){Xe();return}be.lastX=be.x,be.lastY=be.y,pe(dt(be.x,be.y,{hover:!0}))}function Rt(j,de){be.x=j,be.y=de,!(Number.isFinite(be.lastX)&&Number.isFinite(be.lastY)&&Math.hypot(j-be.lastX,de-be.lastY)de&&(re.blocked=!0,re.moved=!0,Tt())}function Qt(j){if(vt(j)){if(j.button===0){re.active||Ae(j)||we(j)?Tt():Zt(j);return}j.button===2&&(qn(j),(Z.active||Ee.active||se(j)||we(j))&&Tt())}}function In(j){if(vt(j)){if(j.button===0){re.active||Ae(j)||we(j)?Tt():Zt(j);return}j.button===2&&(qn(j),(Z.active||Ee.active||se(j)||we(j))&&Tt())}}function gr(j){Tn(j)&&(vr(j),(we(j)||Ee.active&&Ae(j))&&Tt())}function lo(j){Tn(j)&&(vr(j),(we(j)||Ee.active&&Ae(j))&&Tt())}function Mt(j){j.button===0?ct():j.button===2&&(re.active=!1)}function gt(j){j.button===0?ct():j.button===2&&wr(j)}function Sn(j){if(!Ze(j.target)){Xe();return}if(Ee.active&&!se(j)&&ct(),(we(j)||Ee.active&&Ae(j))&&Tt(),vr(j),G.interactionState.active){Xe();return}const de=We(Z.pointerType||j.pointerType);if(Z.active&&Math.hypot(j.clientX-Z.x,j.clientY-Z.y)>de&&(Z.active=!1),!ze(j.pointerType)){Xe();return}Rt(j.clientX,j.clientY)}function On(){Xe(),(Z.active||Ee.active||re.active)&&Tt(),Z.active=!1,Z.pointerType="",Z.referenceId="",ct()}function Kr(j){if(j.button!==0){j.button===2&&Ze(j.target)&&(qn(j),(Z.active||Ee.active||se(j)||we(j))&&Tt());return}if(Ze(j.target)){if(we(j)||Ae(j)){Tt();return}Zt(j),Z.active=!0,Z.x=j.clientX,Z.y=j.clientY,Z.pointerType=j.pointerType||"",Z.referenceId=String(ze(Z.pointerType)?be.hoveredReferenceId||dt(j.clientX,j.clientY,{hover:!0})||"":dt(j.clientX,j.clientY)||"").trim()}}function Xr(j){if(j.button===0?ct():j.button===2&&(re.active=!1),j.button!==0||!Z.active&&!Ze(j.target))return;const de=We(Z.pointerType||j.pointerType),L=Math.hypot(j.clientX-Z.x,j.clientY-Z.y);if(!Z.active||L>de){Z.active=!1,Z.pointerType="",Z.referenceId="";return}const te=String(Z.referenceId||"").trim();Z.active=!1,Z.pointerType="",Z.referenceId="";const fe=te||qe(j.clientX,j.clientY,j.pointerType||"");xn(fe||"",{multiSelect:!!j.shiftKey})}function Co(j){if(!Ze(j.target))return;He();const de=qe(j.clientX,j.clientY,j.pointerType||"");k.current?.(de||"",{multiSelect:!!j.shiftKey})}function br(j){vt(j)&&(j.preventDefault(),j.stopPropagation(),He(),oe.consumeSuppression(),re.startedInScene||ut())}return Q.addEventListener("pointerdown",Qt,!0),Q.addEventListener("pointermove",gr,!0),Q.addEventListener("pointerup",Mt,!0),document.addEventListener("mousedown",In,!0),document.addEventListener("mousemove",lo,!0),document.addEventListener("mouseup",gt,!0),document.addEventListener("contextmenu",br,!0),Q.addEventListener("pointermove",Sn),Q.addEventListener("pointerleave",On),Q.addEventListener("pointerdown",Kr),Q.addEventListener("pointerup",Xr),_e&&Q.addEventListener("dblclick",Co),()=>{Q.removeEventListener("pointerdown",Qt,!0),Q.removeEventListener("pointermove",gr,!0),Q.removeEventListener("pointerup",Mt,!0),document.removeEventListener("mousedown",In,!0),document.removeEventListener("mousemove",lo,!0),document.removeEventListener("mouseup",gt,!0),document.removeEventListener("contextmenu",br,!0),Q.removeEventListener("pointermove",Sn),Q.removeEventListener("pointerleave",On),Q.removeEventListener("pointerdown",Kr),Q.removeEventListener("pointerup",Xr),_e&&Q.removeEventListener("dblclick",Co),oe.clear(),He(),Xe(),Q.style.cursor=""}},[r,t,o,e,n,S])}const f8="modulepreload",m8=function(e){return"/"+e},vA={},_o=function(t,n,r){let o=Promise.resolve();if(n&&n.length>0){let l=function(u){return Promise.all(u.map(d=>Promise.resolve(d).then(m=>({status:"fulfilled",value:m}),m=>({status:"rejected",reason:m}))))};document.getElementsByTagName("link");const s=document.querySelector("meta[property=csp-nonce]"),a=s?.nonce||s?.getAttribute("nonce");o=l(n.map(u=>{if(u=m8(u),u in vA)return;vA[u]=!0;const d=u.endsWith(".css"),m=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${m}`))return;const p=document.createElement("link");if(p.rel=d?"stylesheet":f8,d||(p.as="script"),p.crossOrigin="",p.href=u,a&&p.setAttribute("nonce",a),document.head.appendChild(p),d)return new Promise((g,x)=>{p.addEventListener("load",g),p.addEventListener("error",()=>x(new Error(`Unable to preload CSS for ${u}`)))})}))}function i(s){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=s,window.dispatchEvent(a),!a.defaultPrevented)throw s}return o.then(s=>{for(const a of s||[])a.status==="rejected"&&i(a.reason);return t().catch(i)})};function _w(e){return e instanceof Element?!!e.closest("input, textarea, select, [contenteditable=''], [contenteditable='true'], [role='textbox']"):!1}function MP({alpha:e=!0,antialias:t=!0,powerPreference:n="high-performance",preserveDrawingBuffer:r=!1,logarithmicDepthBuffer:o=!0}={}){return{alpha:e,antialias:t,powerPreference:n,preserveDrawingBuffer:r,logarithmicDepthBuffer:o}}function p8(e={}){return{...MP(e),antialias:!1,powerPreference:"default",logarithmicDepthBuffer:!1}}function h8(e,{allowFallback:t=!1,isRecoverableError:n=()=>!0,...r}={}){try{return new e.WebGLRenderer(MP(r))}catch(o){if(!t||!n(o))throw o;return new e.WebGLRenderer(p8(r))}}function g8({idlePixelRatioCap:e=2,interactionPixelRatioCap:t=1,preservePixelRatio:n=!1,screenSpaceLineMaterialCount:r=null,screenSpaceLineMaterials:o=null}={}){return n||(r!=null&&Number.isFinite(Number(r))?Number(r):Number(o?.size||0))>0?e:t}const b8=1,y8=60,p1=60/y8;function h1(e){const t=Number(e);return Number.isFinite(t)?t:null}function x8(e,t){const n=h1(e),r=h1(t);return n===null||r===null||r<=0||n<=r?null:Math.min((n-r)/1e3,b8)}function IP(e,t,n){if(!e||typeof e.update!="function")return!1;if(!e.autoRotate)return n&&(n.orbitControlsLastTimestamp=0),e.update();const r=h1(t),o=x8(r,n?.orbitControlsLastTimestamp);return n&&(n.orbitControlsLastTimestamp=r??0),o===null?e.update():e.update(o)}function S8(e){return h8(e,{allowFallback:!0,isRecoverableError:yP})}function E8({mountRef:e,runtimeRef:t,previewModeRef:n,setError:r,setViewerReadyTick:o,viewerTheme:i,syncDrawingCanvasSize:s,renderDrawingOverlay:a,emitPerspectiveChange:l,setActiveViewPlaneFace:u,activeViewPlaneFaceRef:d,stepCameraTransition:m,stepKeyboardOrbit:p,getActiveViewPlaneFaceId:g,cancelCameraTransition:x,clearKeyboardOrbitState:y,isTrackpadLikeWheelEvent:S,getKeyboardOrbitCommand:b,getKeyboardOrbitAxes:I,applyOrbitDelta:A,getViewerThemeValue:N,getPixelRatioCap:P,applySceneBackground:R,applyCameraFrameInsets:v,frameInsetsRef:C,applyInitialPerspective:T,updateGridHelper:k,clearSceneGroup:z,disposeSceneObject:Y,disposeTexture:K,syncViewPlaneOrientation:J,BASE_VIEWER_THEME:G,DEFAULT_LIGHTING:Q,DEFAULT_DAMPING_FACTOR:D,DEFAULT_ZOOM_SPEED:$,COARSE_POINTER_ZOOM_SPEED:ie,INTERACTION_PIXEL_RATIO_CAP:W,IDLE_PIXEL_RATIO_CAP:Z,INTERACTION_IDLE_DELAY_MS:Ee,TRACKPAD_PINCH_ZOOM_SPEED:re,COARSE_POINTER_PINCH_ZOOM_SPEED:be,ACCELERATED_WHEEL_ZOOM_SPEED:_e,KEYBOARD_ORBIT_NUDGE_RAD:Ie,defaultGridRadius:oe,sceneScaleMode:me,floorMode:se,onManualCameraInteraction:Ae,onViewportResize:we,onContextLost:ct,onContextRestored:ut,onInitializationError:Tt,preserveInteractionPixelRatio:Ve=!1,runtimeResetToken:St=0}){f.useEffect(()=>{t.current&&(t.current.preserveInteractionPixelRatio=Ve===!0)},[Ve,t,St]),f.useEffect(()=>{let wt=!1,Vn=()=>{};async function De(){const[xe,{OrbitControls:yt},{Line2:Te},{LineGeometry:rt},{LineSegments2:Re},{LineSegmentsGeometry:Fe},{LineMaterial:on}]=await Promise.all([_o(()=>import("./vendor-three-SYzIooV9.js").then(ne=>ne.T),[]),_o(()=>import("./vendor-three-SYzIooV9.js").then(ne=>ne.c),[]),_o(()=>import("./vendor-three-SYzIooV9.js").then(ne=>ne.g),[]),_o(()=>import("./vendor-three-SYzIooV9.js").then(ne=>ne.f),[]),_o(()=>import("./vendor-three-SYzIooV9.js").then(ne=>ne.e),[]),_o(()=>import("./vendor-three-SYzIooV9.js").then(ne=>ne.L),[]),_o(()=>import("./vendor-three-SYzIooV9.js").then(ne=>ne.d),[])]);if(wt||!e.current)return;const ht=e.current,qt=(typeof window.matchMedia=="function"?window.matchMedia("(pointer: coarse)"):null)?.matches??!1,sn=()=>Math.max((window.devicePixelRatio||1)|0,1),Mn=sn(),fn=()=>qt?ie:$,Bt=()=>qt?be:re,dt=ne=>ne*(sn()/Mn),qe=ht.clientWidth||800,Vt=ht.clientHeight||640,We=new xe.Scene,ze=(ne,ye=qe,it=Vt)=>{if(!ne)return;const ft=Math.max(ye,1)/Math.max(it,1);if(ne.isPerspectiveCamera)ne.aspect=ft;else if(ne.isOrthographicCamera){const xt=Math.max(Number(ne.userData?.cadHalfHeight)||120,.001);ne.left=-xt*ft,ne.right=xt*ft,ne.top=xt,ne.bottom=-xt}ne.updateProjectionMatrix?.()},Ze=new xe.PerspectiveCamera(48,qe/Vt,.1,5e4),vt=new xe.OrthographicCamera(-120,120,120,-120,.1,5e4);vt.userData.cadHalfHeight=120;const Tn=Ze;Tn.up.set(0,0,1),Tn.position.set(180,-180,120),vt.up.copy(Tn.up),vt.position.copy(Tn.position),ze(Ze,qe,Vt),ze(vt,qe,Vt);const pe=S8(xe);pe.outputColorSpace=xe.SRGBColorSpace,pe.toneMapping=xe.ACESFilmicToneMapping,pe.toneMappingExposure=N(i,"toneMappingExposure",Q.toneMappingExposure),pe.localClippingEnabled=!0,pe.shadowMap.enabled=!0,pe.shadowMap.type=xe.PCFSoftShadowMap,pe.setPixelRatio(P(Z)),pe.setSize(qe,Vt),ht.innerHTML="",ht.appendChild(pe.domElement);const Xe=new yt(Tn,pe.domElement);Xe.enableDamping=!0,Xe.dampingFactor=D,Xe.rotateSpeed=1,Xe.panSpeed=1.35,Xe.zoomSpeed=fn(),"zoomToCursor"in Xe&&(Xe.zoomToCursor=!0);const He=new xe.HemisphereLight(N(i,"hemisphereSky",Q.hemisphereSky),N(i,"hemisphereGround",Q.hemisphereGround),N(i,"hemisphereIntensity",Q.hemisphereIntensity));We.add(He);const Rn=new xe.AmbientLight("#ffffff",0);We.add(Rn);const xn=new xe.DirectionalLight(N(i,"keyLightColor",Q.keyLightColor),N(i,"keyLightIntensity",Q.keyLightIntensity));xn.position.set(240,-150,340),xn.castShadow=!0,xn.shadow.mapSize.set(2048,2048),xn.shadow.bias=-25e-5,xn.shadow.normalBias=.024,We.add(xn);const ue=new xe.DirectionalLight(N(i,"fillLightColor",Q.fillLightColor),N(i,"fillLightIntensity",Q.fillLightIntensity));ue.position.set(120,80,210),We.add(ue);const Rt=new xe.DirectionalLight(N(i,"rimLightColor",Q.rimLightColor),N(i,"rimLightIntensity",Q.rimLightIntensity));Rt.position.set(-260,240,180),We.add(Rt);const Zt=new xe.SpotLight("#ffffff",0,0,Math.PI/6);Zt.position.set(160,-120,140),Zt.visible=!1,Zt.castShadow=!1,Zt.shadow.mapSize.set(1024,1024),Zt.shadow.bias=-25e-5,Zt.shadow.normalBias=.01,We.add(Zt),We.add(Zt.target);const qn=new xe.PointLight("#ffffff",0,0);qn.position.set(-120,80,140),qn.visible=!1,qn.castShadow=!1,We.add(qn);const fi=null,Ct=new xe.Group,wr=new xe.Group,vr=new xe.Group,Qt=new xe.Group,In=new xe.Group,gr=new xe.Group;We.add(Ct),We.add(wr),We.add(vr),We.add(Qt),We.add(In),We.add(gr);const lo=new xe.Raycaster,Mt=new xe.Vector2,gt={active:!1,pixelRatioCap:Z,pixelRatio:P(Z),renderQueued:!1,renderQueuedAt:0,renderFallbackTimerId:0,restoreTimerId:0},Sn={pressedKeys:new Set,directionCounts:{left:0,right:0,up:0,down:0},lastFrameTime:0},On=new Set,Kr=()=>On.size+Number(t.current?.cadScene?.runtime?.screenSpaceLineMaterials?.size||0),Xr=()=>{const ne=ht.clientWidth||qe,ye=ht.clientHeight||Vt;for(const it of On)it?.resolution?.set?.(ne,ye);t.current?.cadScene?.runtime?.syncScreenSpaceLineMaterials?.(ne,ye)},Co=ne=>{ne?.resolution?.set&&(On.add(ne),ne.resolution.set(ht.clientWidth||qe,ht.clientHeight||Vt))},br=ne=>{ne&&On.delete(ne)},j=ne=>{ne.preventDefault(),y(Sn),r("WebGL context was lost. Restoring CAD Viewer..."),ct?.()},de=()=>{r(""),ut?.()},L=ne=>{const ye=P(ne);Math.abs(gt.pixelRatioCap-ne)<1e-4&&Math.abs((gt.pixelRatio||0)-ye)<1e-4||(gt.pixelRatioCap=ne,gt.pixelRatio=ye,pe.setPixelRatio(ye),pe.setSize(ht.clientWidth||qe,ht.clientHeight||Vt,!1),Xr(),s(t.current),a())};let te=0;const fe=()=>{if(gt.renderQueued){const ne=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();if(gt.renderQueuedAt&&ne-gt.renderQueuedAt<120)return;window.cancelAnimationFrame(te),gt.renderQueued=!1,gt.renderQueuedAt=0}gt.renderQueued=!0,gt.renderQueuedAt=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),te=window.requestAnimationFrame(ae),gt.renderFallbackTimerId&&window.clearTimeout(gt.renderFallbackTimerId),gt.renderFallbackTimerId=window.setTimeout(()=>{gt.renderQueued&&(window.cancelAnimationFrame(te),ae(typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()))},120),t.current&&(t.current.rafId=te)};function ae(ne){gt.renderQueued=!1,gt.renderQueuedAt=0,gt.renderFallbackTimerId&&(window.clearTimeout(gt.renderFallbackTimerId),gt.renderFallbackTimerId=0);const ye=m(t.current,ne),it=p(t.current,ne),ft=IP(Xe,ne,t.current);(ye||it)&&l(t.current),pe.render(We,t.current?.camera||Tn);const xt=!!t.current?.previewOrbitEnabled;if(!xt){const _r=g(t.current);_r!==d.current&&(d.current=_r,u(_r)),J(t.current)}(ye||it||ft||gt.active||xt)&&fe()}const he=()=>{gt.restoreTimerId&&(window.clearTimeout(gt.restoreTimerId),gt.restoreTimerId=0),gt.active=!0,L(g8({idlePixelRatioCap:Z,interactionPixelRatioCap:W,preservePixelRatio:t.current?.preserveInteractionPixelRatio===!0,screenSpaceLineMaterialCount:Kr()})),fe()},ot=()=>{gt.restoreTimerId&&window.clearTimeout(gt.restoreTimerId),gt.restoreTimerId=window.setTimeout(()=>{gt.restoreTimerId=0,gt.active=!1,Xe.enableDamping=!0,Xe.dampingFactor=D,Xe.zoomSpeed=fn(),L(Z),fe()},Ee)},It=()=>{const ne=ht.clientWidth||800,ye=ht.clientHeight||640;L(gt.pixelRatioCap),pe.setSize(ne,ye),ze(Ze,ne,ye),ze(vt,ne,ye),v?.(t.current,C?.current,{updateProjection:!1}),Xr(),s(t.current),a(),t.current?.onViewportResize?.(),fe()};window.addEventListener("resize",It);const Pt=typeof ResizeObserver=="function"?new ResizeObserver(()=>{It()}):null;Pt?.observe(ht);let Ke=null;const en=()=>{const ne=t.current;return!ne?.camera||!ne?.controls?.target?null:ne.camera.position.distanceTo(ne.controls.target)},Ne=()=>{Ke=en(),x(t.current),he()},Et=()=>{l(t.current),fe()},Pe=()=>{const ne=en();if(Number.isFinite(Ke)&&Number.isFinite(ne)){const ye=Math.max(Math.abs(Ke)*.002,1e-4);Math.abs(ne-Ke)>ye&&t.current?.onManualCameraInteraction?.("zoom")}Ke=null,ot()},En=ne=>{t.current?.onManualCameraInteraction?.("wheel"),x(t.current),Xe.enableDamping=!1,Xe.zoomSpeed=dt(S(ne)?Bt():_e),he()},Se={passive:!0,capture:!0};Xe.addEventListener("start",Ne),Xe.addEventListener("change",Et),Xe.addEventListener("end",Pe),pe.domElement.addEventListener("wheel",En,Se),pe.domElement.addEventListener("webglcontextlost",j,!1),pe.domElement.addEventListener("webglcontextrestored",de,!1);const Yr=ne=>{if(n.current||ne.defaultPrevented||ne.ctrlKey||ne.metaKey||ne.altKey||_w(ne.target))return;const ye=b(ne);if(ye){if(Sn.pressedKeys.has(ye.keyId)){ne.preventDefault();return}Sn.pressedKeys.add(ye.keyId),Sn.directionCounts[ye.direction]+=1,Sn.lastFrameTime=0,x(t.current),he(),A(t.current,(ye.direction==="right"?1:ye.direction==="left"?-1:0)*Ie,(ye.direction==="down"?1:ye.direction==="up"?-1:0)*Ie),l(t.current),fe(),ne.preventDefault()}},Kt=ne=>{const ye=b(ne);if(!ye||!Sn.pressedKeys.delete(ye.keyId))return;Sn.directionCounts[ye.direction]=Math.max(0,Sn.directionCounts[ye.direction]-1);const it=I(Sn);!it.azimuth&&!it.polar&&(Sn.lastFrameTime=0,ot()),ne.preventDefault()},X=()=>{Sn.pressedKeys.size&&(y(Sn),ot())},At=()=>{document.visibilityState!=="visible"&&X()};t.current={THREE:xe,scene:We,camera:Tn,perspectiveCamera:Ze,orthographicCamera:vt,projection:"perspective",syncCameraViewport:ze,renderer:pe,Line2:Te,LineGeometry:rt,LineSegments2:Re,LineSegmentsGeometry:Fe,LineMaterial:on,controls:Xe,stageGroup:Ct,modelGroup:wr,edgesGroup:vr,facePickGroup:Qt,edgePickGroup:In,vertexPickGroup:gr,facePickMesh:null,edgePickLines:null,vertexPickPoints:null,edgePickObjects:[],displayRecords:[],modelBounds:null,modelRadius:1,activeModelKey:"",sceneScaleMode:me,raycaster:lo,pointer:Mt,hemisphereLight:He,ambientLight:Rn,keyLight:xn,fillLight:ue,rimLight:Rt,spotLight:Zt,pointLight:qn,axesHelper:fi,sceneBackgroundTexture:null,environmentTexture:null,environmentTextureUrl:"",gridConfig:null,gridHelper:null,floorMode:se,hasVisibleModel:!1,edgePickThreshold:1.5,vertexPickThreshold:.9,cameraTransition:null,previewOrbitEnabled:!1,orbitControlsLastTimestamp:0,preserveInteractionPixelRatio:Ve===!0,interactionState:gt,keyboardOrbitState:Sn,onResize:It,resizeObserver:Pt,rafId:te,requestRender:fe,beginInteraction:he,scheduleIdleQuality:ot,applyCameraFrameInsets:v,frameInsetsRef:C,onManualCameraInteraction:Ae,onViewportResize:we,registerScreenSpaceLineMaterial:Co,unregisterScreenSpaceLineMaterial:br},s(t.current),a(),R(t.current,i),v?.(t.current,C?.current),T?.(t.current),window.addEventListener("keydown",Yr),window.addEventListener("keyup",Kt),window.addEventListener("blur",X),document.addEventListener("visibilitychange",At),fe(),k(t.current,i,oe,0,me,se),o(ne=>ne+1),Vn=()=>{const ne=t.current;ne&&(ne.interactionState.restoreTimerId&&window.clearTimeout(ne.interactionState.restoreTimerId),ne.interactionState.renderFallbackTimerId&&window.clearTimeout(ne.interactionState.renderFallbackTimerId),x(ne,{scheduleIdle:!1}),window.cancelAnimationFrame(ne.rafId),window.removeEventListener("resize",ne.onResize),ne.resizeObserver?.disconnect(),ne.controls.removeEventListener("start",Ne),ne.controls.removeEventListener("change",Et),ne.controls.removeEventListener("end",Pe),ne.renderer.domElement.removeEventListener("wheel",En,Se),ne.renderer.domElement.removeEventListener("webglcontextlost",j,!1),ne.renderer.domElement.removeEventListener("webglcontextrestored",de,!1),window.removeEventListener("keydown",Yr),window.removeEventListener("keyup",Kt),window.removeEventListener("blur",X),document.removeEventListener("visibilitychange",At),ne.controls.dispose(),z(ne.stageGroup),z(ne.modelGroup),z(ne.edgesGroup),z(ne.facePickGroup),z(ne.edgePickGroup),z(ne.vertexPickGroup),Y(ne.gridHelper),Y(ne.axesHelper),K(ne.sceneBackgroundTexture),K(ne.environmentTexture),ne.renderer.dispose(),ht.contains(ne.renderer.domElement)&&ht.removeChild(ne.renderer.domElement),t.current=null)}}return De().catch(xe=>{wt||(r(Aw(xe)),Tt?.(xe))}),()=>{wt=!0,Vn()}},[St])}function w8({themeSettings:e={},displaySettings:t=null}={}){const n=fr(e),r=So(t);return{themeSettings:n,displaySettings:r,displayMode:r.mode,clipSettings:r.clip}}const v8=2,C8=1.25,M8=140,mp=.14,CA=4.5,I8=1.6,A8=1e3,N8=10,_8=14,T8=2.4,R8=Math.PI/32,MA=Math.PI*.42,IA=.02,P8=.994,Tw=280,O8=.9999,k8=.02,D8=.999,j8=.999,sy=Object.freeze({EASE_IN_OUT_CUBIC:"ease-in-out-cubic",EASE_IN_OUT_SINE:"ease-in-out-sine"}),L8=Object.freeze({x:[1,0,0],y:[0,1,0],z:[0,0,1]}),AP=gu,Sa=Object.freeze([0,0,1]),F8="cad-z-up-v1",z8="cad-z-up-robot-framing-v2",Ky=[2.1,-1.65,1.08],AA={direction:Ky,up:Sa},B8="cad-glass-surface pointer-events-auto absolute z-30 inline-flex h-8 w-fit items-center gap-0.5 rounded-md border border-sidebar-border p-1 text-sidebar-foreground shadow-sm",Tx="grid size-6 shrink-0 place-items-center rounded-sm text-sidebar-foreground/70 transition hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/45 disabled:pointer-events-none disabled:opacity-50",NP="7.5rem",V8="0.5rem",$8="6.875rem",G8=10,U8=800,NA=10,W8=.84,ym={toneMappingExposure:1.08,hemisphereSky:"#d3dde6",hemisphereGround:"#090c16",hemisphereIntensity:1.62,keyLightColor:"#d6e0ea",keyLightIntensity:.82,fillLightColor:"#6b7f95",fillLightIntensity:.46,rimLightColor:"#6db6e8",rimLightIntensity:.04},H8="#f59e0b",K8=1.35,Rw=[{id:"z",label:"Z",title:"Jump to top view",direction:[0,0,1],up:[0,1,0]},{id:"zNeg",label:"-Z",title:"Jump to bottom view",direction:[0,0,-1],up:[0,1,0]},{id:"yNeg",label:"-Y",title:"Jump to front view",direction:[0,-1,0],up:Sa},{id:"y",label:"Y",title:"Jump to back view",direction:[0,1,0],up:Sa},{id:"x",label:"X",title:"Jump to right view",direction:[1,0,0],up:Sa},{id:"xNeg",label:"-X",title:"Jump to left view",direction:[-1,0,0],up:Sa}],X8=Object.fromEntries(Rw.map(e=>[e.id,e]));function Xc(e){return String(e?.selectorType||"").trim()}function g1(e){return Xc(e)==="occurrence"?String(e?.normalizedSelector||e?.displaySelector||"").trim():String(e?.occurrenceId||"").trim()}function b1(e,t){const n=g1(e),r=String(t||"").trim();return!!(n&&r&&(n===r||n.startsWith(`${r}.`)))}function _P(e){return Xc(e)==="shape"?String(e?.normalizedSelector||e?.displaySelector||"").trim():String(e?.shapeId||"").trim()}function Y8(e,t,n=""){const r=_P(e),o=String(t||"").trim();if(!r||!o||r!==o)return!1;const i=String(n||"").trim();return!i||b1(e,i)}function q8(e){const t=String(e||"").trim();if(!t.startsWith(Ap))return"";const n=t.slice(Ap.length),r=":occurrence:",o=n.lastIndexOf(r);return o>=0?n.slice(o+r.length).trim():""}function Z8(e,t,n=1e-4){if(!e||!t)return!1;for(const r of["x","y","z"]){const o=e[r],i=t[r];if(!Array.isArray(o)||!Array.isArray(i)||o.length!==3||i.length!==3)return!1;for(let s=0;s<3;s+=1)if(Math.abs((o[s]||0)-(i[s]||0))>n)return!1}return!0}function J8(e){if(!e?.THREE||!e?.camera)return null;const t=e.camera.quaternion.clone().invert(),n=(r,o,i)=>{const s=new e.THREE.Vector3(r,o,i).applyQuaternion(t);return[s.x,s.y,s.z]};return{x:n(1,0,0),y:n(0,1,0),z:n(0,0,1)}}function Q8(e,t,{directionDotThreshold:n=D8,upDotThreshold:r=j8}={}){if(!e?.THREE||!e?.camera||!e?.controls||!t||!Array.isArray(t.direction)||!Array.isArray(t.up))return!1;const o=e.camera.position.clone().sub(e.controls.target),i=new e.THREE.Vector3(...t.direction),s=e.camera.up.clone(),a=new e.THREE.Vector3(...t.up);return o.lengthSq()<=1e-8||i.lengthSq()<=1e-8||s.lengthSq()<=1e-8||a.lengthSq()<=1e-8?!1:(o.normalize(),i.normalize(),s.normalize(),a.normalize(),o.dot(i)>=n&&s.dot(a)>=r)}function Rx(e,t=1){return(Array.isArray(e)||ArrayBuffer.isView(e))&&e.length>=t&&e.length%t===0}function TP(e){return Array.isArray(e?.parts)?e.parts.filter(t=>Ar(t?.vertexCount)>0&&Ar(t?.triangleCount)>0):[]}function e6(e){const t=TP(e),n=t.map(r=>String(r?.color||"").trim().toLowerCase()).filter(Boolean);return n.length?n.length!==t.length||new Set(n).size>1:!1}function t6(e=[]){return(Array.isArray(e)?e:[]).map(t=>[String(t?.partId||"").trim(),String(t?.mesh?.uuid||""),String(t?.geometry?.uuid||"")].join(":")).join("|")}function n6(e,t){return(e?.base||null)===(t?.base||null)&&(e?.runtime||null)===(t?.runtime||null)}function od(e,t){e(n=>n6(n,t)?n:t)}function _A(e){const t=e?.current;!t?.rafId||typeof window>"u"||(window.cancelAnimationFrame(t.rafId),t.rafId=0)}function RP(e,t){const n=t?.explodedViewMatrix?.elements;return!e?.Vector3||!n||n.length<16?e?.Vector3?new e.Vector3:null:new e.Vector3(Ar(n[12]),Ar(n[13]),Ar(n[14]))}function r6(e,t,n){const r=Br(n,0,1);return(t?.translation?.isVector3?t.translation.clone():new e.Vector3(0,0,Ar(t?.distance))).multiplyScalar(r)}function TA(e){return String(e?.partId||e?.record?.partId||"").trim()||String(e?.groupKey||"").trim()}function o6(e,t,n,{previousStates:r=[],previousTransitionProgress:o=1,useCurrentTranslations:i=!0}={}){if(!e?.THREE)return[];const s=e.THREE,a=new Map,l=new Map;if(i)for(const u of Array.isArray(r)?r:[]){if(!u?.record)continue;const d=eP(s,u,o);if(d){a.has(u.record)||a.set(u.record,d);const m=TA(u);m&&!l.has(m)&&l.set(m,d)}}return(Array.isArray(t)?t:[]).map(u=>({...u,fromTranslation:i?a.get(u.record)||l.get(TA(u))||RP(s,u.record):new s.Vector3,translation:r6(s,u,n),matrix:new s.Matrix4}))}function i6(e=[],t=[]){const n=new Set((Array.isArray(t)?t:[]).map(r=>r?.record).filter(Boolean));for(const r of Array.isArray(e)?e:[])r&&!n.has(r)&&(r.explodedViewMatrix=null)}function s6(e=[]){for(const t of Array.isArray(e)?e:[]){const n=t?.fromTranslation,r=t?.translation;if(!n?.isVector3||!r?.isVector3||n.distanceToSquared(r)>1e-8)return!0}return!1}function nc(e,t=100){const n=Number(e);return Number.isFinite(n)?Br(n,G8,U8):t}function jg(e){return`${Math.round(nc(e))}%`}function Pw(e){if(!e?.camera?.position||!e?.controls?.target)return null;const t=e.camera.position.distanceTo(e.controls.target);return Number.isFinite(t)&&t>1e-6?t:null}function Ow(e){const t=e?.camera?.isOrthographicCamera?e.camera:e?.orthographicCamera;if(!t?.isOrthographicCamera)return null;const n=Number(t.userData?.cadHalfHeight);if(Number.isFinite(n)&&n>1e-6)return n;const r=Math.abs((Number(t.top)||0)-(Number(t.bottom)||0))/2;return Number.isFinite(r)&&r>1e-6?r:null}function Dp(e){if(e?.camera?.isOrthographicCamera){const n=Ow(e);return n&&(e.zoomBaseHalfHeight=n),n}const t=Pw(e);return t&&(e.zoomBaseDistance=t),t}function a6(e){const t=e?.camera;if(!t)return 100;const n=Number.isFinite(Number(t.zoom))&&Number(t.zoom)>0?Number(t.zoom):1;if(t.isOrthographicCamera){const s=Ow(e);if(!s)return nc(n*100);const a=Number(e.zoomBaseHalfHeight),l=Number.isFinite(a)&&a>1e-6?a:Dp(e)||s;return nc(l/s*n*100)}const r=Pw(e);if(!r)return nc(n*100);const o=Number(e.zoomBaseDistance),i=Number.isFinite(o)&&o>1e-6?o:Dp(e)||r;return nc(i/r*n*100)}function RA(e,t){if(!e?.THREE||!e?.camera||!e?.controls?.target)return!1;const n=nc(t)/100,r=e.camera;if(tu(e,{scheduleIdle:!1}),Lp(e.keyboardOrbitState),r.isOrthographicCamera){const o=Ow(e)||1,i=Number(e.zoomBaseHalfHeight),s=Number.isFinite(i)&&i>1e-6?i:o;e.zoomBaseHalfHeight=s,r.zoom=n*(o/s),r.updateProjectionMatrix?.(),jp(e)}else{const o=e.controls.target,i=r.position.clone().sub(o),s=i.lengthSq()>1e-8?i.normalize():new e.THREE.Vector3(...Ky).normalize(),a=Pw(e)||s.length()||1,l=Number(e.zoomBaseDistance),u=Number.isFinite(l)&&l>1e-6?l:a;e.zoomBaseDistance=u;const d=Number.isFinite(Number(e.controls.minDistance))?Number(e.controls.minDistance):.01,m=Number.isFinite(Number(e.controls.maxDistance))&&Number(e.controls.maxDistance)>0?Number(e.controls.maxDistance):Number.POSITIVE_INFINITY,p=Br(u/n,d,m);r.position.copy(o.clone().add(s.multiplyScalar(p))),r.zoom=1,r.updateProjectionMatrix?.(),jp(e)}return r.lookAt(e.controls.target),e.controls.update?.(),e.scheduleIdleQuality?.(),e.requestRender?.(),!0}function l6({zoomPercent:e,onZoomPercentChange:t,onZoomReset:n}){const[r,o]=f.useState(!1),[i,s]=f.useState(jg(e)),a=f.useRef(!1);f.useEffect(()=>{r||s(jg(e))},[r,e]);const l=()=>{const d=Number(String(i||"").replace(/%/g,"").trim());if(o(!1),!Number.isFinite(d)||d<=0){s(jg(100)),t?.(100);return}t?.(nc(d))},u=d=>{t?.(nc(Math.round(e)+d))};return c.jsxs("div",{className:"flex h-6 items-center gap-0.5",style:{width:$8},"aria-label":"Zoom controls",onPointerDown:d=>{d.stopPropagation()},children:[c.jsx("button",{type:"button","aria-label":"Zoom out",title:"Zoom out",className:Tx,onClick:d=>{d.stopPropagation(),u(-NA)},children:c.jsx(PE,{className:"size-3",strokeWidth:2.25,"aria-hidden":"true"})}),c.jsx("input",{type:"text",inputMode:"numeric","aria-label":"Zoom level percent",className:"h-6 w-8 min-w-0 rounded-sm border border-transparent bg-transparent px-0 text-center text-xs font-medium tabular-nums text-sidebar-foreground outline-none transition focus-visible:border-ring focus-visible:bg-sidebar-accent/40 focus-visible:ring-2 focus-visible:ring-ring/35",value:i,onFocus:d=>{const m=d.currentTarget;a.current=!0,o(!0),s(String(Math.round(e))),window.requestAnimationFrame(()=>{m.select(),a.current=!1})},onMouseUp:d=>{a.current&&(d.preventDefault(),d.currentTarget.select(),a.current=!1)},onClick:d=>{String(d.currentTarget.value||"").includes("%")&&d.currentTarget.select()},onChange:d=>{s(d.target.value)},onBlur:l,onKeyDown:d=>{d.key==="Enter"?(d.preventDefault(),l()):d.key==="Escape"&&(d.preventDefault(),o(!1),s(jg(e)),d.currentTarget.blur())}}),c.jsx("button",{type:"button","aria-label":"Zoom in",title:"Zoom in",className:Tx,onClick:d=>{d.stopPropagation(),u(NA)},children:c.jsx(OE,{className:"size-3",strokeWidth:2.25,"aria-hidden":"true"})}),c.jsx("button",{type:"button","aria-label":"Reset zoom",title:"Reset zoom",className:Tx,onClick:d=>{d.stopPropagation(),n?.()},children:c.jsx(ws,{className:"size-3",strokeWidth:2.1,"aria-hidden":"true"})})]})}function PA(e,t="0px"){return typeof e=="number"&&Number.isFinite(e)?`${e}px`:String(e||"").trim()||t}function c6({zoomPercent:e,onZoomPercentChange:t,onZoomReset:n,viewPlaneOffsetRight:r=16,viewPlaneOffsetBottom:o=16}){return c.jsx("div",{className:B8,style:{right:PA(r,"16px"),bottom:`calc(${PA(o,"16px")} + ${NP} + ${V8})`},"aria-label":"Zoom controls",onPointerDown:i=>{i.stopPropagation()},children:c.jsx(l6,{zoomPercent:e,onZoomPercentChange:t,onZoomReset:n})})}function Px(e,t,n){if(!(!e?.THREE||!Array.isArray(e.displayRecords))){rW(e.THREE,t,n);for(const r of e.displayRecords)tc(e.THREE,r);e.modelGroup?.updateMatrixWorld?.(!0),e.edgesGroup?.updateMatrixWorld?.(!0),e.topologyDisplayEdgeTransformByRecord===!0&&X2(e,e.displayRecords),e.requestRender?.()}}function u6(e){return typeof window>"u"?1:Math.min(window.devicePixelRatio||1,e)}function PP(e,t=Er.CAD){return X$(e,t)}function d6(e,t=Er.CAD){const n=Math.max(K$(t),qs(t).minModelRadius);return PP(e,t)/n}function Ox(e,t={},n=1){e?.position?.set?.((Number(t.x)||0)*n,(Number(t.y)||0)*n,(Number(t.z)||0)*n)}function OA(e,t=1){const n=Number(e);return Number.isFinite(n)&&n>0?n*t:0}function f6(e,t={},n,r=Er.CAD){const o=d6(n,r);Ox(e?.keyLight,t.directional?.position,o),Ox(e?.spotLight,t.spot?.position,o),Ox(e?.pointLight,t.point?.position,o),e?.spotLight&&(e.spotLight.distance=OA(t.spot?.distance,o)),e?.pointLight&&(e.pointLight.distance=OA(t.point?.distance,o))}function kx(e,t,n={},r,o,i=Er.CAD){f6(t,n,r,i),e&&o&&t?.keyLight?.shadow?.camera&&u1(e,t,o,i)}function Dx(e,t,n,r,o=0,i=Bn.STAGE,s=Er.CAD){if(!e?.THREE||!e?.stageGroup||(fs(e.stageGroup),i!==Bn.STAGE))return;const a=s,l=tU(r,a),u=PP(r,a);e.stageGroup.add(JG(e.THREE,t,n,l,o,0));const d=QG(e.THREE,n,u,l,o,a);d&&e.stageGroup.add(d);const m=eU(e.THREE,n,l,o);m&&e.stageGroup.add(m)}function m6(e){return e.ctrlKey||e.deltaMode===0&&Math.abs(e.deltaY)<20}function OP(e={}){const t=n=>{const r=Number(n);return Number.isFinite(r)?Math.max(0,r):0};return{top:t(e?.top),right:t(e?.right),bottom:t(e?.bottom),left:t(e?.left)}}function Au(e,t={}){const n=e?.renderer?.domElement,r=Math.max(1,n?.clientWidth||n?.parentElement?.clientWidth||1),o=Math.max(1,n?.clientHeight||n?.parentElement?.clientHeight||1),i=OP(t),s=Br(i.left,0,Math.max(r-1,0)),a=Br(i.right,0,Math.max(r-s-1,0)),l=Br(i.top,0,Math.max(o-1,0)),u=Br(i.bottom,0,Math.max(o-l-1,0)),d=Math.max(1,r-s-a),m=Math.max(1,o-l-u),p=s+d/2,g=l+m/2;return{width:r,height:o,top:l,right:a,bottom:u,left:s,framedWidth:d,framedHeight:m,aspect:d/m,offsetNdcX:p/r*2-1,offsetNdcY:1-g/o*2}}function p6(e,t={}){const n=e?.renderer?.domElement,r=Au(e,t),o=Math.max(1,n?.width||r.width),i=Math.max(1,n?.height||r.height),s=o/Math.max(r.width,1),a=i/Math.max(r.height,1),l=Math.round(r.left*s),u=Math.round(r.top*a),d=Math.round(r.right*s),m=Math.round(r.bottom*a);return{x:l,y:u,width:Math.max(1,o-l-d),height:Math.max(1,i-u-m)}}function Md(e,t={},{updateProjection:n=!0}={}){const r=e?.camera;if(!r?.projectionMatrix?.elements)return;const o=Au(e,t),i=(o.right-o.left)/2,s=(o.bottom-o.top)/2;(Math.abs(i)>1e-6||Math.abs(s)>1e-6)&&typeof r.setViewOffset=="function"?r.setViewOffset(o.width,o.height,i,s,o.width,o.height):typeof r.clearViewOffset=="function"?r.clearViewOffset():n&&r.updateProjectionMatrix(),r.projectionMatrixInverse?.copy&&r.projectionMatrixInverse.copy(r.projectionMatrix).invert()}function jp(e,{updateProjection:t=!1}={}){typeof e?.applyCameraFrameInsets=="function"&&e.applyCameraFrameInsets(e,e.frameInsetsRef?.current,{updateProjection:t})}function h6(e,t,n,r=e.aspect){const o=Math.max(t*AP,qs(n).minModelRadius),i=e.fov*Math.PI/360,s=Math.atan(Math.tan(i)*Math.max(r,.001)),a=Math.max(Math.min(i,s),.001);return o/Math.sin(a)}function kP(e){return ul(e?.projection||(e?.camera?.isOrthographicCamera?yo.ORTHOGRAPHIC:yo.PERSPECTIVE))}function g6(e,t,n){for(const r of[e?.perspectiveCamera,e?.orthographicCamera].filter(Boolean))r.near=t,r.far=n,r.updateProjectionMatrix?.()}function DP(e,t,n={},r=AP){const o=Math.max(e*r,qs(t).minModelRadius),i=Math.max(Number(n.aspect)||1,.001),s=Math.max(Number(n.height)||1,1),a=Math.max(Number(n.framedHeight)||s,1);return o/Math.min(i,1)*(s/a)}function Xy(e,t,n=null){const r=e?.orthographicCamera;if(!r?.isOrthographicCamera)return!1;const o=n||Au(e,e?.frameInsetsRef?.current),i=Math.max(Number(t)||0,.001),s=Number(r.userData?.cadHalfHeight),a=Number(r.left),l=Number(r.right),u=Number(r.top),d=Number(r.bottom);return r.userData.cadHalfHeight=i,e.syncCameraViewport?.(r,o.width,o.height),Math.abs((Number.isFinite(s)?s:0)-i)>1e-6||Math.abs((Number.isFinite(a)?a:0)-Number(r.left))>1e-6||Math.abs((Number.isFinite(l)?l:0)-Number(r.right))>1e-6||Math.abs((Number.isFinite(u)?u:0)-Number(r.top))>1e-6||Math.abs((Number.isFinite(d)?d:0)-Number(r.bottom))>1e-6}function b6(e,t,n,r=null){const o=r||Au(e,e?.frameInsetsRef?.current);return Xy(e,DP(t,n,o),o)}function kA(e,t,n,r){const o=e?.camera,i=o?.isPerspectiveCamera?o:e?.perspectiveCamera||o,s=h6(i,t,n,r.aspect);return o?.isOrthographicCamera?b6(e,t,n,r):o?.updateProjectionMatrix?.(),Md(e,e?.frameInsetsRef?.current,{updateProjection:!1}),s}function kw(e,t,{scheduleIdle:n=!0,requestRender:r=!0}={}){if(!e?.camera||!e?.controls)return!1;const o=ul(t),i=o===yo.ORTHOGRAPHIC?e.orthographicCamera:e.perspectiveCamera;if(!i)return!1;const s=e.camera,a=s?.isPerspectiveCamera&&e.controls?.target?s.position.distanceTo(e.controls.target)*Math.tan(Math.max(Number(s.fov)||48,.001)*Math.PI/360)/Math.max(Number(s.zoom)||1,.001):null;s!==i&&(i.position.copy(s.position),i.up.copy(s.up),i.near=s.near,i.far=s.far,i.zoom=Number.isFinite(s.zoom)&&s.zoom>0?s.zoom:1,e.camera=i,e.controls.object=i),e.projection=o;const l=Au(e,e.frameInsetsRef?.current);if(i.isOrthographicCamera&&s!==i){const d=Number(s?.userData?.cadHalfHeight),m=Number.isFinite(a)&&a>0?a:d;Number.isFinite(m)&&m>0?Xy(e,m,l):e.syncCameraViewport?.(i,l.width,l.height)}else e.syncCameraViewport?.(i,l.width,l.height);Md(e,e.frameInsetsRef?.current,{updateProjection:!1});const u=e.controls.autoRotate;return e.controls.autoRotate=!1,e.controls.update?.(),e.controls.autoRotate=u,n&&e.scheduleIdleQuality?.(),r&&e.requestRender?.(),!0}function y6(e){return e<=0?0:e>=1?1:e<.5?4*e*e*e:1-(-2*e+2)**3/2}function x6(e){return e<=0?0:e>=1?1:-(Math.cos(Math.PI*e)-1)/2}function S6(e,t=sy.EASE_IN_OUT_CUBIC){return t===sy.EASE_IN_OUT_SINE?x6(e):y6(e)}function E6(e){return!e?.camera||!e?.controls?null:{position:[e.camera.position.x,e.camera.position.y,e.camera.position.z],target:[e.controls.target.x,e.controls.target.y,e.controls.target.z],up:[e.camera.up.x,e.camera.up.y,e.camera.up.z],zoom:e.camera.zoom,projection:kP(e)}}function jx(e,{modelKey:t="",sceneScaleMode:n=""}={}){return J5(E6(e),{modelKey:t,sceneScaleMode:n,coordinateSystem:y1(n)})}function y1(e){return Mu(e)===Er.URDF?z8:F8}function w6(e){if(!e)return null;if(e.key==="ArrowLeft")return{direction:"left",keyId:"ArrowLeft"};if(e.key==="ArrowRight")return{direction:"right",keyId:"ArrowRight"};if(e.key==="ArrowUp")return{direction:"up",keyId:"ArrowUp"};if(e.key==="ArrowDown")return{direction:"down",keyId:"ArrowDown"};const t=String(e.key||"").toLowerCase();return t==="a"||e.code==="KeyA"?{direction:"left",keyId:e.code||"KeyA"}:t==="d"||e.code==="KeyD"?{direction:"right",keyId:e.code||"KeyD"}:t==="w"||e.code==="KeyW"?{direction:"up",keyId:e.code||"KeyW"}:t==="s"||e.code==="KeyS"?{direction:"down",keyId:e.code||"KeyS"}:null}function jP(e){return{azimuth:(e.directionCounts.right>0?1:0)-(e.directionCounts.left>0?1:0),polar:(e.directionCounts.down>0?1:0)-(e.directionCounts.up>0?1:0)}}function Lp(e){e&&(e.pressedKeys.clear(),e.directionCounts.left=0,e.directionCounts.right=0,e.directionCounts.up=0,e.directionCounts.down=0,e.lastFrameTime=0)}function LP(e,t,n){if(!e?.THREE||!e?.camera||!e?.controls||Math.abs(t)<1e-6&&Math.abs(n)<1e-6)return!1;const r=new e.THREE.Vector3().copy(e.camera.position).sub(e.controls.target),o=r.length();if(!Number.isFinite(o)||o<=1e-6)return!1;const i=new e.THREE.Vector3(...Sa).normalize(),s=r.clone().divideScalar(o),a=Math.max(Number.isFinite(e.controls.minPolarAngle)?e.controls.minPolarAngle:0,IA),l=Math.min(Number.isFinite(e.controls.maxPolarAngle)?e.controls.maxPolarAngle:Math.PI,Math.PI-IA),u=Math.acos(Br(s.dot(i),-1,1)),m=Br(u+n,a,l)-u,p=Number.isFinite(e.controls.minAzimuthAngle)?e.controls.minAzimuthAngle:-1/0,g=Number.isFinite(e.controls.maxAzimuthAngle)?e.controls.maxAzimuthAngle:1/0;if(Number.isFinite(p)||Number.isFinite(g)){const x=Math.atan2(r.y,r.x);t=Br(R6(x+t,x),p,g)-x}if(Math.abs(t)>1e-6&&r.applyAxisAngle(i,t),Math.abs(m)>1e-6){let x=new e.THREE.Vector3().crossVectors(i,r).normalize();x.lengthSq()<=1e-9&&(x=new e.THREE.Vector3(1,0,0)),r.applyAxisAngle(x,m)}return e.camera.position.copy(e.controls.target).add(r),e.camera.up.set(...Sa),e.camera.lookAt(e.controls.target),!0}function v6(e,t){const n=e?.keyboardOrbitState;if(!n)return!1;const r=jP(n);if(!r.azimuth&&!r.polar)return n.lastFrameTime=0,!1;if(!n.lastFrameTime)return n.lastFrameTime=t,!1;const o=Br((t-n.lastFrameTime)/1e3,0,.05);return n.lastFrameTime=t,LP(e,r.azimuth*MA*o,r.polar*MA*o)}function tu(e,{scheduleIdle:t=!0}={}){e?.cameraTransition&&(e.cameraTransition=null,e.controls&&(e.controls.enableDamping=!0,e.controls.dampingFactor=mp),t&&e.scheduleIdleQuality?.())}function Cb(e,t,{scheduleIdle:n=!0}={}){const r=Bs(t);return!e?.camera||!e?.controls||!r?!1:(tu(e,{scheduleIdle:!1}),Lp(e.keyboardOrbitState),Object.prototype.hasOwnProperty.call(r,"projection")&&kw(e,r.projection,{scheduleIdle:!1}),e.camera.position.set(...r.position),e.controls.target.set(...r.target),e.camera.up.set(...r.up),Number.isFinite(r.zoom)&&r.zoom>0&&(e.camera.zoom=r.zoom,e.camera.updateProjectionMatrix?.(),jp(e)),e.camera.lookAt(e.controls.target),e.controls.update(),n&&e.scheduleIdleQuality?.(),e.requestRender?.(),!0)}function FP(e,t,{durationMs:n=Tw,easing:r=sy.EASE_IN_OUT_CUBIC,orthographicHalfHeight:o=null,resetZoomBaselineOnComplete:i=!1}={}){const s=Bs(t);if(!e?.THREE||!e?.camera||!e?.controls||!s)return!1;tu(e,{scheduleIdle:!1}),Lp(e.keyboardOrbitState),Object.prototype.hasOwnProperty.call(s,"projection")&&kw(e,s.projection,{scheduleIdle:!1});const a=new e.THREE.Vector3(...s.position),l=new e.THREE.Vector3(...s.target),u=new e.THREE.Vector3(...s.up),d=Number.isFinite(s.zoom)&&s.zoom>0?s.zoom:e.camera.zoom,m=e.camera?.isOrthographicCamera?Number(e.camera.userData?.cadHalfHeight):null,p=e.camera?.isOrthographicCamera?Number(o):null;return![a.x,a.y,a.z,l.x,l.y,l.z,u.x,u.y,u.z,d].every(Number.isFinite)||u.lengthSq()<=1e-6?!1:(e.cameraTransition={startTime:performance.now(),durationMs:n,startPosition:e.camera.position.clone(),endPosition:a,startTarget:e.controls.target.clone(),endTarget:l,startUp:e.camera.up.clone(),endUp:u.normalize(),startZoom:e.camera.zoom,endZoom:d,startOrthographicHalfHeight:m,endOrthographicHalfHeight:p,resetZoomBaselineOnComplete:i,easing:r},e.controls.enableDamping=!1,e.beginInteraction?.(),e.requestRender?.(),!0)}function C6(e){if(!Array.isArray(e)&&!ArrayBuffer.isView(e))return null;const t=Ar(e[0]),n=Ar(e[1]),r=Ar(e[2]);return{min:[t,n,r],max:[t,n,r]}}function M6(e,t){const n=String(t||"").trim();return!n||!e?null:e.referenceMap?.get?.(n)||e.faceReferenceMap?.get?.(n)||e.edgeReferenceMap?.get?.(n)||e.referenceByDisplaySelector?.get?.(n)||e.referenceByNormalizedSelector?.get?.(n)||null}function I6(e,t=[]){const n=[];for(const r of Ja(t)){const o=M6(e,r),i=o?.pickData?.bbox||o?.bbox||null,s=Op([i])||C6(o?.pickData?.center||o?.center);s&&n.push(s)}return Op(n)}function A6(e,t=[]){const n=new Map;if(!e?.Vector3)return n;for(const r of Array.isArray(t)?t:[]){const o=RP(e,r);o?.isVector3&&o.lengthSq()>1e-12&&n.set(r,o)}return n}function N6(e,t=[]){const n=Ja(t);return!n.length||!Array.isArray(e?.displayRecords)?null:oU(e.displayRecords,{partIds:new Set(n),translationByRecord:A6(e?.THREE,e.displayRecords)})}function Lx(e,t,n,{animate:r=!0,modelOffset:o=null,resetZoomBaseline:i=!1}={}){if(!e?.THREE||!e?.camera||!e?.controls)return!1;const s=Op([t]);if(!s)return!1;const a=Au(e,e.frameInsetsRef?.current),l=aU(e.THREE,{camera:e.camera,controls:e.controls,bounds:s,modelOffset:o,frameAspect:a.aspect,minRadius:qs(n).minModelRadius,padding:gu,defaultDirection:Ky,viewUp:e.camera.up?.toArray?.()||Sa});if(!l)return!1;const u={position:l.position.toArray(),target:l.target.toArray(),up:l.up.toArray(),zoom:1,projection:kP(e)},d=e.camera.isOrthographicCamera?DP(l.radius,n,a,gu):null;if(r)return FP(e,u,{durationMs:Tw,easing:sy.EASE_IN_OUT_CUBIC,orthographicHalfHeight:d,resetZoomBaselineOnComplete:i});e.camera.isOrthographicCamera&&d&&Xy(e,d,a);const m=Cb(e,u);return m&&(i&&Dp(e),e.onZoomChange?.(e)),m}function _6(e,t){const n=e?.cameraTransition;if(!n||!e?.THREE||!e?.camera||!e?.controls)return!1;const r=Math.max(n.durationMs,1),o=Br((t-n.startTime)/r,0,1),i=S6(o,n.easing),s=new e.THREE.Vector3().lerpVectors(n.startPosition,n.endPosition,i),a=new e.THREE.Vector3().lerpVectors(n.startTarget,n.endTarget,i),l=new e.THREE.Vector3().lerpVectors(n.startUp,n.endUp,i);e.camera.position.copy(s),e.controls.target.copy(a),l.lengthSq()>1e-6&&e.camera.up.copy(l.normalize());const u=Number(n.startOrthographicHalfHeight),d=Number(n.endOrthographicHalfHeight);let m=!1;if(e.camera?.isOrthographicCamera&&Number.isFinite(u)&&Number.isFinite(d)&&d>0){const p=u+(d-u)*i;Xy(e,p),jp(e),m=!0}return Number.isFinite(n.startZoom)&&Number.isFinite(n.endZoom)&&(e.camera.zoom=n.startZoom+(n.endZoom-n.startZoom)*i,e.camera.updateProjectionMatrix?.(),m||jp(e)),e.camera.lookAt(a),o>=1?(n.resetZoomBaselineOnComplete&&Dp(e),e.onZoomChange?.(e),e.cameraTransition=null,e.controls.enableDamping=!0,e.controls.dampingFactor=mp,e.scheduleIdleQuality?.(),!1):!0}function DA(e,t){if(!e?.THREE||!e?.camera||!e?.controls||!t||!Array.isArray(t.direction)||t.direction.length!==3||!Array.isArray(t.up)||t.up.length!==3)return!1;const n=e.controls.target.clone(),r=new e.THREE.Vector3().copy(e.camera.position).sub(n),o=Math.max(e.controls.minDistance||1,1),i=r.length(),s=Br(Number.isFinite(i)&&i>1e-6?i:o,e.controls.minDistance||.01,e.controls.maxDistance||1/0),a=new e.THREE.Vector3(...t.direction);if(a.lengthSq()<1e-6)return!1;const l=new e.THREE.Vector3(...t.up);if(l.lengthSq()<1e-6)return!1;a.normalize(),l.normalize();const u=new e.THREE.Vector3(...Sa).normalize();if(Math.abs(a.dot(u))>=O8){let d=l.clone().addScaledVector(u,-l.dot(u));d.lengthSq()<1e-6&&(d=new e.THREE.Vector3(0,1,0).addScaledVector(u,-u.y)),d.lengthSq()<1e-6&&(d=new e.THREE.Vector3(1,0,0)),d.normalize();const m=a.dot(u)>=0?1:-1;a.addScaledVector(d,-m*k8).normalize(),l.copy(u)}return e.cameraTransition={startTime:performance.now(),durationMs:Tw,startPosition:e.camera.position.clone(),endPosition:n.clone().add(a.multiplyScalar(s)),startTarget:n.clone(),endTarget:n.clone(),startUp:e.camera.up.clone(),endUp:l},e.controls.enableDamping=!1,e.beginInteraction?.(),e.requestRender?.(),!0}function T6(e){if(!e?.THREE||!e?.camera||!e?.controls)return"";const t=new e.THREE.Vector3().copy(e.camera.position).sub(e.controls.target);if(t.lengthSq()<1e-6)return"";t.normalize();let n="",r=-1/0;for(const o of Rw){const i=new e.THREE.Vector3(...o.direction).normalize(),s=t.dot(i);s>r&&(r=s,n=o.id)}return r>=P8?n:""}function Yy(e){if(!e)return;for(;e.children?.length;)Yy(e.children[0]);typeof e.userData?.beforeDispose=="function"&&(e.userData.beforeDispose(e),delete e.userData.beforeDispose),e.parent?.remove(e),e.geometry?.userData?.cadSceneCachedGeometry!==!0&&e.geometry?.dispose?.();const t=Array.isArray(e.material)?e.material:[e.material];for(const n of t)n?.map?.dispose?.(),n?.alphaMap?.dispose?.(),n?.dispose?.()}function fs(e){for(;e.children.length;)Yy(e.children[0])}function x1(e=null,t=null){const n=Number.isFinite(Number(t?.edgeThickness))?Number(t.edgeThickness):Yn.edgeThickness;return Number.isFinite(Number(e?.thickness))?Br(Number(e.thickness),.5,6):n}function Fx(e=null,t=null){return Number.isFinite(Number(e?.highlightThickness))?Br(Number(e.highlightThickness),.5,6):Math.max(x1(e,t)*yU,2)}function zx(e=null){return Number.isFinite(Number(e?.highlightOpacity))?Br(Number(e.highlightOpacity),0,1):1}function Bx(e=null){return String(e?.highlightColor||Qb).trim()||Qb}function Vx(e,t){if(!e||!t||!Number.isFinite(Number(e.clientX))||!Number.isFinite(Number(e.clientY)))return!1;const n=t.getBoundingClientRect();return e.clientX>=n.left&&e.clientX<=n.right&&e.clientY>=n.top&&e.clientY<=n.bottom}function zP(e,t){if(!t)return;for(;t.children?.length;){const r=t.children[0];t.remove(r),zP(e,r)}typeof t.userData?.beforeDispose=="function"&&(t.userData.beforeDispose(t),delete t.userData.beforeDispose);const n=Array.isArray(t.material)?t.material:[t.material];if(t.userData?.disposeGeometry!==!1&&t.geometry?.dispose?.(),t.userData?.disposeMaterial!==!1)for(const r of n)r?.dispose?.()}function Ur(e,t){for(t===e?.urdfPosePickerGuideGroup&&(e.urdfPosePickerHoverCellMesh=null,e.urdfPosePickerHoverCellOutline=null);t?.children?.length;){const n=t.children[t.children.length-1];n&&(t.remove(n),zP(e,n))}t&&(t.visible=!1)}function Br(e,t,n){return Math.min(Math.max(e,t),n)}function R6(e,t){let n=e;for(;n-t>Math.PI;)n-=Math.PI*2;for(;n-t<-Math.PI;)n+=Math.PI*2;return n}function P6(e){return String(rh(e)?.token||"").trim()}function Hm(e){if(!Array.isArray(e)||e.length<3)return null;const t=e.slice(0,3).map(n=>Number(n));return t.every(n=>Number.isFinite(n))?t:null}function jA(e){if(!e||typeof e!="object")return null;const t=Hm(e.position);if(!t)return null;const n=e.axes&&typeof e.axes=="object"?e.axes:{};return{position:t,axes:{x:Hm(n.x),y:Hm(n.y),z:Hm(n.z)}}}function O6(e){return[...new Set((Array.isArray(e)?e:[e]).map(t=>String(t||"").trim()).filter(Boolean))]}function k6(e,t,n){const r=new Set(O6(t)),o=String(n||"").trim();if(!r.size&&!o)return[];const i=[],s=new Set;for(const a of Array.isArray(e)?e:[]){const l=String(a?.id||"").trim();if(!l||s.has(l))continue;const u=r.has(l),d=o===l;if(!u&&!d)continue;const m=jA(a.fixedEndpoint),p=jA(a.movingEndpoint);!m&&!p||(s.add(l),i.push({id:l,fixed:m,moving:p,selected:u,hovered:d}))}return i}function D6(e,t,{color:n,opacity:r,radius:o,renderOrder:i}){const s=new e.SphereGeometry(o,18,10),a=new e.MeshBasicMaterial({color:n,transparent:r<.999,opacity:r,depthTest:!1,depthWrite:!1,toneMapped:!1}),l=new e.Mesh(s,a);return l.position.set(t[0],t[1],t[2]),l.renderOrder=i,l}function LA(e,t,n,r){const o=Hm(n);if(!o)return;const i=Math.hypot(o[0],o[1],o[2]);if(i<=1e-8)return;const s=o.map(a=>a/i);e.push(t[0]-s[0]*r,t[1]-s[1]*r,t[2]-s[2]*r,t[0]+s[0]*r,t[1]+s[1]*r,t[2]+s[2]*r)}function j6(e,t,n,{color:r,opacity:o,markerRadius:i,axisLength:s,lineWidth:a,renderOrder:l}){const u=n.fixed?.position||null,d=n.moving?.position||null,m=u||d;if(!m)return;const p=[];u&&d&&Math.hypot(u[0]-d[0],u[1]-d[1],u[2]-d[2])>Math.max(i*.25,.01)&&p.push(...u,...d);const g=n.fixed?.axes||n.moving?.axes||{};if(LA(p,m,g.z||[0,0,1],s),LA(p,m,g.x||[1,0,0],s*.62),p.length){const x=iu(e,p,{color:r,opacity:o,lineWidth:a,renderOrder:l,depthTest:!1,depthWrite:!1});x&&t.add(x)}t.add(D6(e.THREE,m,{color:r,opacity:o,radius:i,renderOrder:l+1}))}function L6(e,t,n,r=0,o=Er.CAD,i=Bn.STAGE,s={}){return mU(e,t,n,r,o,i,{disposeSceneObject:Yy,floorSettings:s})}const F6=f.forwardRef(function({meshData:t,modelKey:n,renderFormat:r="",perspective:o=null,perspectiveRef:i=null,projection:s=yo.PERSPECTIVE,showEdges:a,recomputeNormals:l,theme:u=Yn,themeSettings:d=null,floorModeOverride:m="",previewMode:p=!1,showViewPlane:g=!0,viewPlaneOffsetRight:x=16,viewPlaneOffsetBottom:y=16,viewPlaneHeader:S=null,compactViewPlane:b=!1,viewportFrameInsets:I=null,isLoading:A=!1,pickMode:N=si.AUTO,renderPartsIndividually:P=!1,scale:R="",sceneScaleMode:v=Er.CAD,pickableParts:C=[],hiddenPartIds:T=[],selectedPartIds:k=[],hoveredPartId:z="",assemblyMates:Y=[],selectedMateIds:K=[],hoveredMateId:J="",hoveredReferenceId:G="",selectedReferenceIds:Q=[],selectorRuntime:D=null,displayEdgeRuntime:$=null,stepParameters:ie=null,pickableFaces:W=[],pickableEdges:Z=[],pickableVertices:Ee=[],surfaceLineFaceId:re="",focusedPartId:be="",displaySettings:_e=null,drawingEnabled:Ie=!1,drawingTool:oe=Jt.FREEHAND,drawingStrokes:me=[],onDrawingStrokesChange:se,onPerspectiveChange:Ae,onProjectionChange:we,onDisplayModeChange:ct,onHoverReferenceChange:ut,onActivateReference:Tt,onDoubleActivateReference:Ve,onContextReference:St,onViewerAlertChange:wt,onStepModuleTransformDetectedChange:Vn,urdfPosePicker:De=null},xe){const yt=ie,Te=Mu(R||v),rt=ul(s),Re=t?.geometrySource&&typeof t.geometrySource=="object"?t.geometrySource:t,Fe=H$(Te),on=f.useMemo(()=>OP(I),[I?.top,I?.right,I?.bottom,I?.left]),ht=f.useRef(null),jt=f.useRef(null),qt=f.useRef(null),sn=f.useRef(null),Mn=f.useRef(Array.isArray(me)?me:[]),fn=f.useRef(se),Bt=f.useRef(Ae),dt=f.useRef(wt),qe=f.useRef(Vn),Vt=f.useRef(De),We=f.useRef(null),ze=f.useRef(null),Ze=f.useRef(rt),vt=f.useRef(0),Tn=f.useRef(0),pe=f.useRef(null),Xe=f.useRef({rafId:0,progress:0,modelKey:"",recordKey:"",states:[],transitionProgress:0}),He=f.useRef(on),Rn=f.useRef(""),xn=f.useRef({modelKey:"",sceneScaleMode:"",offset:null,floorZ:null}),ue=f.useRef(Ws(null)),Rt=f.useRef(D),Zt=f.useRef($),qn=f.useRef([]),[fi,Ct]=f.useState(null),[wr,vr]=f.useState(null),[Qt,In]=f.useState(!1),[gr,lo]=f.useState(""),[Mt,gt]=f.useState(0),[Sn,On]=f.useState(0),[Kr,Xr]=f.useState(""),[Co,br]=f.useState(L8),[j,de]=f.useState(100),[L,te]=f.useState(null),[fe,ae]=f.useState(!1),he=f.useRef(""),ot=f.useRef(!1),It=f.useRef(p),Pt=f.useRef(o),Ke=f.useRef(n),en=f.useRef(Te),Ne=fi?.base===D?fi.runtime:D,Et=wr?.base===$?wr.runtime:$,Pe=u||Yn,En=f.useMemo(()=>w8({themeSettings:d,displaySettings:_e}),[d,_e]),Se=En.themeSettings,Yr=En.displaySettings,Kt=En.displayMode,X=Yr.exploded,At=f.useMemo(()=>TP(t).length,[t]),ne=X.enabled&&At>1,ye=P||ne,it=r===B.STEP,ft=f.useMemo(()=>a2(Yr),[Yr]),xt=ml(Kt),_r=$y(Kt),Ti=Gy(Kt),Ra=f.useMemo(()=>UG({edgeColor:ft?.color,themeSettings:Se,viewerTheme:Pe}),[ft,Se,Pe]),Pa=f.useMemo(()=>{const w=Number.isFinite(Number(ft?.opacity))?Br(Number(ft.opacity),0,1):Pe?.edgeOpacity??Yn.edgeOpacity??W8;return Math.max(w,.9)},[ft,Pe]),Cr=f.useMemo(()=>{const w={...ft,enabled:_r?!0:ft.enabled,depthTest:Ti?!1:ft.depthTest};return xt?{...w,contrastMode:"manual",color:Ra,opacity:Pa}:w},[ft,_r,Ti,Ra,Pa,xt]),Xt=f.useMemo(()=>Ja(be),[be]),os=f.useMemo(()=>new Set(Xt),[Xt]),kn=f.useMemo(()=>new Set(Ja(T)),[T]),Tr=f.useMemo(()=>{const w=Ja(T);if(!w.length)return Cr;const V=[...new Set([...Ja(Cr?.excludePartIds),...w])];return{...Cr,excludePartIds:V}},[T,Cr]),Ri=En.clipSettings,Zn=(Se.floor||{}).enabled===!0?Bn.STAGE:Bn.NONE,qr=m?WG(m,Zn):Zn,mi=f.useCallback((w,V,q,ce=0,ge=Er.CAD,et=Bn.STAGE)=>L6(w,V,q,ce,ge,et,Se.floor),[Se.floor]),Jn=a&&it&&qV(Kt,Cr),ar=yx({edgesVisible:Jn,wireframeMode:xt,cadEdgeSource:it,displayEdgeRuntime:Et,selectorRuntime:Ne,edgeSettings:Cr}),Mr=Jn&&!ar&&!it&&kV(t),pi=Jn&&!ar&&it,co=DV({edgesVisible:Jn,topologyDisplayEdgesVisible:ar,displayEdgesVisible:Mr,wireframeMode:xt}),Qs=!!(xt||Jn||ar||Mr||pi||co),Lr=N===si.PARTS||N===si.ASSEMBLY||N===si.AUTO&&Array.isArray(C)&&C.length>0||Array.isArray(T)&&T.length>0||Xt.length>0,ko=f.useRef({viewerTheme:Pe,edgeSettings:Cr,hiddenPartIds:Lr?T:[],hoveredPartId:Lr?z:"",focusedPartId:Lr?Xt:[],selectedPartIds:Lr?k:[],showEdges:co,displayMode:Kt});f.useLayoutEffect(()=>{ko.current={viewerTheme:Pe,edgeSettings:Cr,hiddenPartIds:Lr?T:[],hoveredPartId:Lr?z:"",focusedPartId:Lr?Xt:[],selectedPartIds:Lr?k:[],showEdges:co,displayMode:Kt}},[Kt,co,Xt,T,Tr,z,Lr,k,Pe,Cr]);const is=String(re||"").trim(),Mo=f.useCallback(w=>{const V=String(w?.partId||"").trim();return V&&kn.has(V)||!V&&kn.has("__model__")?!1:RU(w,os)},[os,kn]),uo=f.useMemo(()=>(Array.isArray(W)?W:[]).filter(Mo),[W,Mo]),wc=f.useMemo(()=>(Array.isArray(Z)?Z:[]).filter(Mo),[Z,Mo]),hl=f.useMemo(()=>(Array.isArray(Ee)?Ee:[]).filter(Mo),[Ee,Mo]),Pi=f.useMemo(()=>{if(Ne?.referenceMap instanceof Map){const V=new Map;for(const[q,ce]of Ne.referenceMap.entries())Mo(ce)&&V.set(q,ce);return V}const w=new Map;for(const V of[...uo,...wc,...hl]){const q=String(V?.id||"").trim();q&&w.set(q,V)}return w},[Ne,wc,uo,hl,Mo]),Do=f.useMemo(()=>new Set(uo.map(w=>String(w?.id||"").trim()).filter(Boolean)),[uo]),Ns=(w=pe.current)=>{const V=qt.current;if(!V)return null;const q=w?.renderer?.domElement,ce=q?.width||jt.current?.clientWidth||1,ge=q?.height||jt.current?.clientHeight||1;return(V.width!==ce||V.height!==ge)&&(V.width=ce,V.height=ge),V},_s=()=>{const w=Ns();w&&pI(w,Mn.current,sn.current)};Pt.current=o,Ke.current=n,en.current=Te,f.useLayoutEffect(()=>{He.current=on;const w=pe.current;w&&(Md(w,on),w.requestRender?.())},[on.top,on.right,on.bottom,on.left,Mt]);const Qo=w=>{vt.current+=1;try{return w()}finally{vt.current=Math.max(0,vt.current-1)}},Dn=f.useCallback((w=pe.current)=>{if(!w?.camera){de(q=>q===100?q:100);return}const V=Math.round(a6(w));de(q=>Math.abs(q-V)<.5?q:V)},[]),$r=(w=pe.current)=>{const V=Ke.current;if(!hH(w,V))return;const q=jx(w,{modelKey:V,sceneScaleMode:en.current});if(q){if(Dn(w),vt.current>0){ze.current=q;return}HR(ze.current,q)||(ze.current=q,Bt.current?.(q))}},ea=(w=pe.current)=>{if(ot.current){if(w?.cameraTransition){In(!1);return}ot.current=!1}const V=w?.THREE?!Q8(w,AA):!1;In(q=>q===V?q:V)},tn=(w=pe.current)=>{const V=J8(w);V&&(br(q=>Z8(q,V)?q:V),ea(w))},Zr=f.useCallback((w=pe.current)=>{const V=nI(i?i.current:void 0,Pt.current);return rI(V,{modelKey:Ke.current,sceneScaleMode:en.current,coordinateSystem:y1(en.current),requireModelKey:!0,requireSceneScaleMode:!0,requireCoordinateSystem:!0})?Qo(()=>Cb(w,V,{scheduleIdle:!1})):!1},[i]),Rr=f.useCallback(w=>{const V=pe.current;RA(V,w)&&(Dn(V),$r(V),tn(V))},[Dn,tn]),Qn=f.useCallback(({animate:w=!0}={})=>{const V=pe.current,q=Lx(V,V?.modelBounds||t?.bounds,en.current,{animate:w,modelOffset:xn.current.offset,resetZoomBaseline:!0});return q&&!w&&(Dn(V),$r(V),tn(V)),q?!0:RA(V,100)?(Dn(V),$r(V),tn(V),!0):!1},[t?.bounds,Dn,tn]),ei=(w,V,q="",ce=null)=>{const ge=pe.current;if(!ge?.raycaster||!ge?.camera||!Ne?.faceReferenceByRowIndex)return null;const et=String(q||is).trim(),Nt=V.getBoundingClientRect(),je=Nt.width||1,Je=Nt.height||1;ge.pointer.x=(w.clientX-Nt.left)/je*2-1,ge.pointer.y=-((w.clientY-Nt.top)/Je)*2+1,ge.raycaster.setFromCamera(ge.pointer,ge.camera);const Lt=(ge.displayRecords||[]).map(wn=>wn?.mesh).filter(wn=>wn?.visible&&wn.userData?.faceIds instanceof Uint32Array),gn=Lt.length?ge.raycaster.intersectObjects(Lt,!1):[],lr=ge.facePickMesh?ge.raycaster.intersectObject(ge.facePickMesh,!1):[],cr=gn.length?gn.map(wn=>({intersection:wn,source:"model"})):lr.map(wn=>({intersection:wn,source:"proxy"}));for(const{intersection:wn,source:$n}of cr){const er=Number(wn?.faceIndex),ur=Number.isInteger(er)?Number(wn?.object?.userData?.faceIds?.[er]):NaN;if(!Number.isInteger(ur))continue;const bn=Ne.faceReferenceByRowIndex.get(ur)||null,nn=String(bn?.id||"").trim();if(!nn)continue;if(et){if(nn!==et)continue}else if(Do.size&&!Do.has(nn))continue;const Jr=bn?.pickData?.surface||{};if(EH.has(String(Jr.type||"").trim()))return null;const Or=$n==="model"&&ge.modelGroup?ge.modelGroup.worldToLocal(wn.point.clone()):wn.object.worldToLocal(wn.point.clone()),kr=[Or.x,Or.y,Or.z],Gn=Jr.type==="CYLINDRICAL_SURFACE"&&Array.isArray(ce)?ce[0]/Math.max(Number(Jr.radius)||1,1):null,Qr=IH(Jr,kr,Gn);return Qr?{screenPoint:iI(w,V),surfaceLine:{referenceId:nn,selector:String(bn?.displaySelector||"").trim(),normalizedSelector:String(bn?.normalizedSelector||"").trim(),faceToken:P6(bn?.copyText),partId:String(bn?.partId||"").trim(),surfaceType:String(Jr.type||"").trim(),startPoint:kr,endPoint:kr,startUv:Qr,endUv:Qr}}:null}return null},Oi=(w,V,q)=>{const ce=String(q?.referenceId||"").trim();if(!ce)return null;const ge=ei(w,V,ce,q?.startUv);return ge?{screenPoint:ge.screenPoint,surfaceLine:{...q,endPoint:ge.surfaceLine.endPoint,endUv:ge.surfaceLine.endUv}}:null},Pr=(w,V)=>!w?.raycaster||!w?.modelGroup||!V?.active?null:y2(w,V),ti=w=>{const V=Vt.current,q=pe.current,ce=q?.renderer?.domElement||jt.current;if(!V?.active||It.current||!q?.raycaster||!q?.camera||!ce||!Vx(w,ce))return q&&(q.urdfPosePickerPointerNdc=null,Mg(q,V),ce?.style&&(ce.style.cursor="auto"),q.requestRender?.()),ae(!1),te(Je=>Je&&null),null;const ge=ce.getBoundingClientRect(),et=ge.width||1,Nt=ge.height||1;q.pointer.x=(w.clientX-ge.left)/et*2-1,q.pointer.y=-((w.clientY-ge.top)/Nt)*2+1,q.urdfPosePickerPointerNdc={x:q.pointer.x,y:q.pointer.y},q.raycaster.setFromCamera(q.pointer,q.camera);const je=Pr(q,V);return Mg(q,V),ce.style&&(ce.style.cursor=je?.point?"pointer":"crosshair"),ae(!!je?.point),te(Je=>{if(!je?.point)return Je&&null;const Lt=je.point;return Array.isArray(Je)&&Math.hypot(Je[0]-Lt[0],Je[1]-Lt[1],Je[2]-Lt[2])<.001?Je:Lt}),q.requestRender?.(),je},jo=w=>{const V=Vt.current,q=pe.current,ce=q?.renderer?.domElement||jt.current;if(!V?.active||!q?.raycaster||!q?.camera||!q?.modelGroup||!ce)return!1;const ge=ce.getBoundingClientRect(),et=ge.width||1,Nt=ge.height||1;q.pointer.x=(w.clientX-ge.left)/et*2-1,q.pointer.y=-((w.clientY-ge.top)/Nt)*2+1,q.urdfPosePickerPointerNdc={x:q.pointer.x,y:q.pointer.y},q.raycaster.setFromCamera(q.pointer,q.camera);const je=Pr(q,V);return je?(ae(!0),te(je.point),V.onPickPoint?.({point:je.point,source:je.source}),!0):(ae(!1),!1)},Tu=w=>{const V=Vt.current,ce=pe.current?.renderer?.domElement||jt.current;!V?.active||It.current||w.button!==0||!Vx(w,ce)||(We.current={pointerId:w.pointerId,x:w.clientX,y:w.clientY})},Nf=w=>{ti(w)},Ru=w=>{const V=We.current;We.current=null;const q=Vt.current,ge=pe.current?.renderer?.domElement||jt.current;!q?.active||It.current||!V||V.pointerId!==w.pointerId||!Vx(w,ge)||Math.hypot(w.clientX-V.x,w.clientY-V.y)>8||jo(w)},$e=()=>{const w=pe.current;We.current=null,w&&(w.urdfPosePickerPointerNdc=null,Mg(w,Vt.current),w.renderer?.domElement?.style&&(w.renderer.domElement.style.cursor="auto"),w.requestRender?.()),ae(!1)},ki=()=>{const w=pe.current;We.current=null,w&&(w.urdfPosePickerPointerNdc=null,Mg(w,Vt.current),w.renderer?.domElement?.style&&(w.renderer.domElement.style.cursor="auto"),w.requestRender?.()),ae(!1),te(V=>V&&null)},hi=w=>{const V=pe.current,q=X8[w];if(!V||!q)return!1;he.current=q.id,Xr(q.id);const ce=DA(V,q);return ce&&(ot.current=!1,In(!0)),ce},Pu=()=>{const w=pe.current;if(!w)return!1;he.current="",Xr("");const V=DA(w,AA);return V&&(ot.current=!0,In(!1)),V};f.useImperativeHandle(xe,()=>({async captureScreenshot({filename:w="cad-screenshot.png",mode:V="download"}={}){const q=pe.current;if(!q?.renderer||!q?.scene||!q?.camera)throw new Error("CAD Viewer not ready");_s();const ce=kH(q,qt.current,{backgroundColor:V==="clipboard"?PH(q.renderer.domElement):"",crop:p6(q,He.current)});if(V==="clipboard")return await tw(ce);const ge=await ce;return nw(ge,{filename:w})},getPerspective(){return jx(pe.current,{modelKey:n,sceneScaleMode:Te})},setPerspective(w,V={}){return V?.animate?FP(pe.current,w,V):Cb(pe.current,w)},resetZoom(){return Qn({animate:!0})},zoomToFit({animate:w=!0}={}){const V=pe.current,q=Lx(V,V?.modelBounds||t?.bounds,en.current,{animate:w,modelOffset:xn.current.offset,resetZoomBaseline:!0});return q&&!w&&($r(V),tn(V)),q},zoomToFitSelection({partIds:w=[],referenceIds:V=[],animate:q=!0}={}){const ce=pe.current,ge=Op([I6(Ne,V),N6(ce,w)]),et=Lx(ce,ge,en.current,{animate:q,modelOffset:xn.current.offset,resetZoomBaseline:!1});return et&&!q&&($r(ce),tn(ce)),et},focusViewPreset(w){return hi(w)}}),[Ne,t?.bounds,n,Te,Qn,Dn,tn]),f.useEffect(()=>{It.current=p},[p]),f.useEffect(()=>{fn.current=se},[se]),f.useEffect(()=>{Bt.current=Ae},[Ae]),f.useEffect(()=>{const w=pe.current;if(w)return w.onZoomChange=Dn,Dn(w),()=>{w.onZoomChange===Dn&&(w.onZoomChange=null)}},[Dn,Mt]),f.useEffect(()=>{dt.current=wt},[wt]),f.useEffect(()=>{qe.current=Vn},[Vn]),f.useEffect(()=>{Vt.current=De},[De]),f.useEffect(()=>{Ct(null)},[n,D]),f.useEffect(()=>{vr(null)},[n,$]),f.useEffect(()=>{Rt.current=Ne},[Ne]),f.useEffect(()=>{Zt.current=Et},[Et]),f.useEffect(()=>{ue.current=Ri;const w=pe.current;w?.THREE&&($c(w,Ri),w.requestRender?.())},[Mt,t?.bounds,Ri.axis,Ri.enabled,Ri.invert,Ri.offset]),f.useEffect(()=>{if(De?.active)return;const w=pe.current;w&&(w.urdfPosePickerPointerNdc=null,w.renderer?.domElement?.style&&(w.renderer.domElement.style.cursor="auto")),ae(!1),te(null)},[De?.active]),f.useEffect(()=>{Mn.current=Array.isArray(me)?me:[],Tn.current=Math.max(Tn.current,hV(Mn.current)),_s()},[me]);const _f=f.useCallback(()=>{Rn.current="",ze.current=null,ot.current=!1,dt.current?.(null),In(!1),On(w=>w+1)},[]),gl=f.useCallback(w=>{dt.current?.(jH(w))},[]);E8({mountRef:jt,runtimeRef:pe,previewModeRef:It,setError:lo,setViewerReadyTick:gt,viewerTheme:Pe,syncDrawingCanvasSize:Ns,renderDrawingOverlay:_s,emitPerspectiveChange:$r,setActiveViewPlaneFace:Xr,activeViewPlaneFaceRef:he,stepCameraTransition:_6,stepKeyboardOrbit:v6,getActiveViewPlaneFaceId:T6,cancelCameraTransition:tu,clearKeyboardOrbitState:Lp,isTrackpadLikeWheelEvent:m6,getKeyboardOrbitCommand:w6,getKeyboardOrbitAxes:jP,applyOrbitDelta:LP,getViewerThemeValue:Eb,getPixelRatioCap:u6,applySceneBackground:Ig,applyCameraFrameInsets:Md,frameInsetsRef:He,applyInitialPerspective:Zr,updateGridHelper:mi,clearSceneGroup:fs,disposeSceneObject:Yy,disposeTexture:cp,syncViewPlaneOrientation:tn,BASE_VIEWER_THEME:Yn,DEFAULT_LIGHTING:ym,DEFAULT_DAMPING_FACTOR:mp,DEFAULT_ZOOM_SPEED:CA,COARSE_POINTER_ZOOM_SPEED:I8,INTERACTION_PIXEL_RATIO_CAP:C8,IDLE_PIXEL_RATIO_CAP:v8,INTERACTION_IDLE_DELAY_MS:M8,TRACKPAD_PINCH_ZOOM_SPEED:_8,COARSE_POINTER_PINCH_ZOOM_SPEED:T8,ACCELERATED_WHEEL_ZOOM_SPEED:N8,KEYBOARD_ORBIT_NUDGE_RAD:R8,defaultGridRadius:Fe,sceneScaleMode:Te,floorMode:qr,onInitializationError:gl,onContextRestored:_f,preserveInteractionPixelRatio:Qs,runtimeResetToken:Sn}),f.useEffect(()=>{const w=pe.current;w&&(w.sceneScaleMode=Te)},[Te]),f.useEffect(()=>{const w=pe.current;if(!w)return;const V=Ze.current;Ze.current=rt,kw(w,rt,V!==rt?{scheduleIdle:!1,requestRender:!1}:void 0)&&($r(w),tn(w))},[rt,Mt]),f.useEffect(()=>{const w=pe.current;if(!w)return;Ig(w,Pe,Se.background),w.renderer.toneMappingExposure=Math.max(Se.lighting.toneMappingExposure,.05),w.hemisphereLight.visible=Se.lighting.hemisphere.enabled,w.hemisphereLight.color.set(Se.lighting.hemisphere.skyColor),w.hemisphereLight.groundColor.set(Se.lighting.hemisphere.groundColor),w.hemisphereLight.intensity=Se.lighting.hemisphere.intensity,w.ambientLight.visible=Se.lighting.ambient.enabled,w.ambientLight.color.set(Se.lighting.ambient.color),w.ambientLight.intensity=Se.lighting.ambient.intensity,w.keyLight.visible=Se.lighting.directional.enabled,w.keyLight.color.set(Se.lighting.directional.color),w.keyLight.intensity=Se.lighting.directional.intensity;const V=Ya(Pe,"fillLightIntensity",ym.fillLightIntensity);w.fillLight.visible=V>1e-4,w.fillLight.color.set(Eb(Pe,"fillLightColor",ym.fillLightColor)),w.fillLight.intensity=Math.max(V,0);const q=Ya(Pe,"rimLightIntensity",ym.rimLightIntensity);w.rimLight.visible=q>1e-4,w.rimLight.color.set(Eb(Pe,"rimLightColor",ym.rimLightColor)),w.rimLight.intensity=Math.max(q,0),w.spotLight.visible=Se.lighting.spot.enabled,w.spotLight.color.set(Se.lighting.spot.color),w.spotLight.intensity=Se.lighting.spot.intensity,w.spotLight.angle=Se.lighting.spot.angle,w.pointLight.visible=Se.lighting.point.enabled,w.pointLight.color.set(Se.lighting.point.color),w.pointLight.intensity=Se.lighting.point.intensity,kx(w.THREE,w,Se.lighting,w.modelRadius??w.gridRadius??Fe,w.modelBounds,Te),Ag(w),w.keyLight.castShadow=w.keyLight.visible,w.spotLight.castShadow=!1;const ce={...Se.materials,envMapIntensity:Se.materials.envMapIntensity*(Se.environment.enabled?Se.environment.intensity:0)};for(const ge of w.displayRecords||[])gU(w.THREE,ge,ce,{displayMode:Kt});w.gridConfig=null,mi(w,Pe,w.gridRadius??Fe,w.gridFloorZ??0,Te,qr),Ag(w),w.hasVisibleModel?Dx(w,Pe,Se,w.gridRadius??Fe,w.gridFloorZ??0,qr,Te):fs(w.stageGroup),w.requestRender()},[Fe,Kt,Se,Te,qr,Mt,Pe,mi]),f.useEffect(()=>{const w=pe.current;if(!w?.THREE||!w?.scene)return;let V=!1;const q=Se.environment,ce=()=>{w.scene.environment=null,cp(w.environmentTexture),w.environmentTexture=null,w.environmentTextureUrl=""},ge=()=>{ce(),Ig(w,Pe,Se.background),w.requestRender()};return(async()=>{if(!q.enabled){dt.current?.(null),ge();return}const Nt=_I(q.presetId),je=String(Nt?.url||"").trim();if(!je){dt.current?.(null),ge();return}if(!w.environmentTexture||w.environmentTextureUrl!==je){const Je=new w.THREE.TextureLoader;typeof Je.setCrossOrigin=="function"&&Je.setCrossOrigin("anonymous");const Lt=await Je.loadAsync(je);if(V){Lt.dispose?.();return}Lt.mapping=w.THREE.EquirectangularReflectionMapping,Lt.colorSpace=w.THREE.SRGBColorSpace,Lt.needsUpdate=!0,cp(w.environmentTexture),w.environmentTexture=Lt,w.environmentTextureUrl=je}w.scene.environment=w.environmentTexture,dt.current?.(null),w.scene.environmentRotation?.set&&w.scene.environmentRotation.set(0,q.rotationY,0),q.useAsBackground?(w.scene.background=w.environmentTexture,w.scene.backgroundRotation?.set&&w.scene.backgroundRotation.set(0,q.rotationY,0)):Ig(w,Pe,Se.background),w.requestRender()})().catch(Nt=>{V||(ge(),dt.current?.({severity:"warning",summary:"Environment unavailable",title:"Environment preset could not be loaded",message:`Failed to load ${String(_I(q.presetId)?.label||"the selected environment preset")}.`,resolution:"The viewer fell back to the current background settings. Check the network connection or choose another preset."}),console.error("Failed to apply environment texture",Nt))}),()=>{V=!0}},[Mt,Pe,Se.background,Se.environment]),f.useEffect(()=>{const w=pe.current;w&&(w.interactionState.restoreTimerId&&(window.clearTimeout(w.interactionState.restoreTimerId),w.interactionState.restoreTimerId=0),Lp(w.keyboardOrbitState),w.previewOrbitEnabled=!!p,w.orbitControlsLastTimestamp=0,w.controls.autoRotate=!!p,w.controls.autoRotateSpeed=p1,w.controls.enabled=!0,w.controls.enableDamping=!0,w.controls.dampingFactor=mp,p?(tu(w,{scheduleIdle:!1}),w.beginInteraction?.()):w.scheduleIdleQuality(),w.requestRender())},[p,Mt]);const Di=!!(De?.active&&!p),bl=Di?fe?"pointer":"crosshair":void 0;return f.useEffect(()=>{const w=pe.current;!De?.active||!w?.controls||(w.controls.enabled=!0,w.controls.enableDamping=!0,w.controls.dampingFactor=mp,w.requestRender())},[De?.active,Mt]),f.useEffect(()=>{const V=pe.current?.renderer?.domElement;if(!Di||!V)return;const q=ge=>{ti(ge)},ce=()=>{ki()};return V.addEventListener("pointermove",q,{passive:!0}),V.addEventListener("pointerleave",ce),()=>{V.removeEventListener("pointermove",q),V.removeEventListener("pointerleave",ce)}},[Di,Mt]),f.useEffect(()=>{const w=pe.current;if(!w)return;const{THREE:V,modelGroup:q,edgesGroup:ce,facePickGroup:ge,edgePickGroup:et,vertexPickGroup:Nt}=w,je=()=>{tu(w),w.cadScene?.dispose?.(),w.cadScene=null,fs(w.stageGroup),fs(q),fs(ce),fs(ge),fs(et),fs(Nt),w.facePickMesh=null,w.edgePickLines=null,w.vertexPickPoints=null,w.edgePickObjects=[],w.topologyDisplayEdgeLine=null,w.topologyDisplayEdgeTransformByRecord=!1,w.displayRecords=[],w.hasVisibleModel=!1,w.activeModelKey="",w.requestRender()};if(A){je(),lo("");return}if(!t||!Rx(t.vertices,3)||!Rx(t.indices,3)){je();return}je();const{controls:Je}=w,gn=Se.materials.cycleColors===!0&&Array.isArray(Se.materials.fillColors)&&Se.materials.fillColors.length>1&&Array.isArray(t?.parts)&&t.parts.length>0,lr=!xt&&Se.materials?.overrideSourceColors!==!0&&e6(t),cr=ye||gn||lr||Array.isArray(C)&&C.length>0&&(N===si.PARTS||N===si.ASSEMBLY||N===si.AUTO),wn=ye?Array.isArray(t?.parts)?t.parts:[]:gn||lr?t.parts:C,$n={...Se.materials,envMapIntensity:Se.materials.envMapIntensity*(Se.environment.enabled?Se.environment.intensity:0)},er=yt?.definition?{...yt,selectorRuntime:D}:null,ur=xt?{...Se,edges:{...Cr,enabled:!0}}:Mr||pi?{...Se,edges:{...Cr}}:{...Se,edges:{enabled:!1}},bn=pH(V,t,{theme:ur,displayMode:Kt,applyDisplayModeEdgePolicy:!ar,scale:Te,baseTheme:Pe,materialSettings:$n,recomputeNormals:l,silhouette:ar&&ft.silhouette===!0,parts:cr?wn:[],renderPartsIndividually:ye,stepParameters:er,parameterSetup:!1,edgeRendering:{mode:"screen-space",Line2:w.Line2,LineGeometry:w.LineGeometry,LineSegments2:w.LineSegments2,LineSegmentsGeometry:w.LineSegmentsGeometry,LineMaterial:w.LineMaterial,wireframeEdgeColor:Ra},selection:cr?ko.current:{...ko.current,hiddenPartIds:[],hoveredPartId:"",focusedPartId:[],selectedPartIds:[]},clip:ue.current,callbacks:{faceIdsForPart:ss=>Iw(ss,D),faceIdsForMesh:()=>hP(t,D),onWarning:ss=>{dt.current?.({severity:"warning",compact:!0,title:ss?.title||"CAD scene warning",message:ss?.message||"The CAD scene renderer reported a warning."})}}});q.add(bn.modelGroup),ce.add(bn.edgesGroup),w.cadScene=bn,w.displayRecords=bn.displayRecords,w.hasVisibleModel=!0,w.activeModelKey=n||"";const nn=bx({selectorRuntime:D,displayEdgeRuntime:$,displayRecords:er?w.displayRecords:[],transformDisplayEdges:!1}),Jr=ne||WI({transformDetected:nn.transformCount>0,topologyDisplayEdgesVisible:ar,displayEdgeRuntime:$,displayRecords:w.displayRecords}),Or=Jr?null:bx({selectorRuntime:null,displayEdgeRuntime:$,displayRecords:er?w.displayRecords:[]}).transformedDisplayEdgeRuntime,kr=nn.transformedSelectorRuntime;od(Ct,kr?{base:D,runtime:kr}:null),od(vr,Or?{base:$,runtime:Or}:null),qe.current?.(nn.transformCount>0);const Gn=nn.selectorRuntime,Qr=Jr?$:Or||nn.topologyRuntime;w.topologyDisplayEdgeTransformByRecord=Jr,Tg(w,Qr,{visible:ar,edgeSettings:Tr,focusedPartIds:Xt,viewerTheme:Pe,dimmedOpacity:Vm,transformByRecord:Jr,displayRecords:w.displayRecords,syncClip:ss=>$c(ss,ue.current)});const Lo=bn.bounds||t.bounds,ta=Array.isArray(Lo?.min)?Lo.min:[0,0,0],Ou=Array.isArray(Lo?.max)?Lo.max:[0,0,0],yl=new V.Vector3((Ar(ta[0])+Ar(Ou[0]))/2,(Ar(ta[1])+Ar(Ou[1]))/2,(Ar(ta[2])+Ar(Ou[2]))/2),fo=xn.current;(fo.modelKey!==n||fo.sceneScaleMode!==Te||!fo.offset)&&(fo.modelKey=n||"",fo.sceneScaleMode=Te,fo.offset=new V.Vector3(-yl.x,-yl.y,-yl.z),fo.floorZ=Cx(Lo,fo.offset,Te));const ni=fo.offset,Oa=Number.isFinite(Number(fo.floorZ))?Number(fo.floorZ):Cx(Lo,ni,Te),{radius:ji}=u1(V,w,Lo,Te);kx(V,w,Se.lighting,ji,Lo,Te),mi(w,Pe,ji,Oa,Te,qr),Ag(w),Dx(w,Pe,Se,ji,w.gridFloorZ??0,qr,Te),q.position.copy(ni),ce.position.copy(ni),ge.position.copy(ni),et.position.copy(ni),Nt.position.copy(ni),ge.updateMatrixWorld(!0),et.updateMatrixWorld(!0),Nt.updateMatrixWorld(!0),Ix(w,Gn,ni,{clearSceneGroup:fs}),$c(w,ue.current);const na=ko.current;if(Ng(V,w.displayRecords,cr?na:{...na,hiddenPartIds:[],hoveredPartId:"",focusedPartId:[],selectedPartIds:[]}),q.updateMatrixWorld(!0),ce.updateMatrixWorld(!0),g6(w,Math.max(ji/1200,.01),Math.max(ji*600,2e3)),Md(w,He.current,{updateProjection:!1}),Je.minDistance=Math.max(ji/2200,.02),Je.maxDistance=Math.max(ji*140,50),Je.zoomSpeed=CA,w.edgePickThreshold=Math.max(ji/320,.65),Rn.current!==(n||"")){const ss=nI(i?i.current:void 0,o),vc=rI(ss,{modelKey:n,sceneScaleMode:Te,coordinateSystem:y1(Te),requireModelKey:!0,requireSceneScaleMode:!0,requireCoordinateSystem:!0});Qo(()=>{if(!vc||!Cb(w,ss,{scheduleIdle:!1})){tu(w);const xl=Au(w,He.current),ka=w.camera,Sl=kA(w,ji,Te,xl),Sh=new V.Vector3(...Ky).normalize();ka.zoom=1,ka.up.set(...Sa),kA(w,ji,Te,xl),Md(w,He.current,{updateProjection:!1}),ka.position.copy(Sh.multiplyScalar(Sl)),Je.target.set(0,0,0),ka.lookAt(Je.target),Je.update(),w.requestRender()}}),Dp(w),Dn(w),Rn.current=n||"",ze.current=jx(w,{modelKey:n,sceneScaleMode:Te})}lo(""),w.requestRender()},[Re,n,o,i,Mr,pi,ar,l,A,Mt,N,ye,ne,C,D,$,Kt,Te,qr,Pe,Se.lighting,Se.materials,Se.environment,ft,Tr,Cr,Dn,Ra,mi]),f.useEffect(()=>{const w=pe.current;if(!w?.THREE||A||!ye||!Array.isArray(t?.parts)||!Array.isArray(w.displayRecords)||!w.displayRecords.length)return;const V=new Map(t.parts.map(et=>[String(et?.id||""),et]).filter(([et])=>et));let q=!1;for(const et of w.displayRecords){const Nt=V.get(String(et?.partId||""));Nt&&(et.baseTransform=$2(t,Nt,ye),et.partBounds=Nt.bounds,et.partCenter=uP(w.THREE,Nt.bounds),tc(w.THREE,et,w.modelRadius||1),q=!0)}if(!q)return;const{radius:ce}=u1(w.THREE,w,t.bounds,Te);kx(w.THREE,w,Se.lighting,ce,t.bounds,Te);const ge=Number.isFinite(Number(xn.current.floorZ))?Number(xn.current.floorZ):Cx(t.bounds,w.modelGroup?.position,Te);mi(w,Pe,ce,ge,Te,qr),Ag(w),Dx(w,Pe,Se,ce,w.gridFloorZ??0,qr,Te),w.requestRender()},[t?.parts,t?.bounds,A,ye,Te,Se,qr,Pe,Mt,mi]),f.useEffect(()=>{const w=pe.current;w&&(Ng(w.THREE,w.displayRecords,ko.current),w.requestRender())},[Mt,Lr,co,Xt,T,z,N,C,k,Pe,Cr,Kt]),f.useEffect(()=>{const w=pe.current,V=yt?.definition||null,q=V?.module||null,ce=[];qn.current=ce;const ge=()=>{for(;ce.length;){const je=ce.pop();try{je?.()}catch(Je){console.error("STEP parameter cleanup failed",Je)}}};if(!w?.THREE||!V||A||!t)return ge;const et=ey(V,{meshData:t,selectorRuntime:Rt.current}),Nt=kp({runtime:w,stepModuleRuntime:yt,features:et,effects:ny(w.THREE,{meshData:t,features:et,runtime:w,effectsByPartId:new Map}),cleanup:je=>{typeof je=="function"&&ce.push(je)}});try{q?.setup?.(Nt)}catch(je){dt.current?.({severity:"warning",compact:!0,title:"STEP parameter setup failed",message:je instanceof Error?je.message:String(je)}),console.error("STEP parameter setup failed",je)}return()=>{ge();try{q?.dispose?.(Nt)}catch(je){console.error("STEP parameter dispose failed",je)}}},[Mt,A,t,n,D,yt?.definition,yt?.sourceUrl]),f.useEffect(()=>{const w=pe.current;if(!w?.THREE||!Array.isArray(w.displayRecords)||!w.displayRecords.length)return;const V=yt?.definition||null,q=V?.module||null;if(!V||A||!t){qe.current?.(!1),od(Ct,null),od(vr,null),w.topologyDisplayEdgeTransformByRecord=ne,G2(w.displayRecords);for(const er of w.displayRecords)tc(w.THREE,er,w.modelRadius||1);Ng(w.THREE,w.displayRecords,ko.current);const $n=yx({edgesVisible:Jn,wireframeMode:xt,cadEdgeSource:it,displayEdgeRuntime:$,selectorRuntime:D,edgeSettings:Cr});Tg(w,$||D,{visible:$n,edgeSettings:Tr,focusedPartIds:Xt,viewerTheme:Pe,dimmedOpacity:Vm,transformByRecord:ne,displayRecords:w.displayRecords,syncClip:er=>$c(er,ue.current)}),w.requestRender?.();return}let ce=!1;const ge=ey(V,{meshData:t,selectorRuntime:Rt.current}),et=new Map,Nt=ny(w.THREE,{meshData:t,features:ge,runtime:w,effectsByPartId:et,onTransformEffect:()=>{ce=!0}}),je=kp({runtime:w,stepModuleRuntime:yt,features:ge,effects:Nt,cleanup:$n=>{typeof $n=="function"&&qn.current.push($n)}});try{q?.update?.(je),q?.render?.(je)}catch($n){dt.current?.({severity:"warning",compact:!0,title:"STEP parameter update failed",message:$n instanceof Error?$n.message:String($n)}),console.error("STEP parameter update failed",$n)}U2(w.THREE,w.displayRecords,et);const Je=ne||WI({transformDetected:ce,topologyDisplayEdgesVisible:ar,displayEdgeRuntime:$,displayRecords:w.displayRecords}),Lt=bx({selectorRuntime:D,displayEdgeRuntime:$,displayRecords:ce?w.displayRecords:[],transformDisplayEdges:!Je}),gn=yx({edgesVisible:Jn,wireframeMode:xt,cadEdgeSource:it,displayEdgeRuntime:Je?$:Lt.displayEdgeRuntime,selectorRuntime:Lt.selectorRuntime,edgeSettings:Cr});qe.current?.(Lt.transformCount>0);const lr=Lt.transformedSelectorRuntime,cr=Je?null:Lt.transformedDisplayEdgeRuntime;od(Ct,lr?{base:D,runtime:lr}:null),od(vr,cr?{base:$,runtime:cr}:null);for(const $n of w.displayRecords)tc(w.THREE,$n,w.modelRadius||1);Ng(w.THREE,w.displayRecords,ko.current),w.topologyDisplayEdgeTransformByRecord=Je,Tg(w,Je?$:Lt.topologyRuntime,{visible:gn,edgeSettings:Tr,focusedPartIds:Xt,viewerTheme:Pe,dimmedOpacity:Vm,transformByRecord:Je,displayRecords:w.displayRecords,syncClip:$n=>$c($n,ue.current)}),w.modelGroup?.updateMatrixWorld?.(!0),w.edgesGroup?.updateMatrixWorld?.(!0);const wn=Lt.selectorRuntime;dA(w,t,wn),Ix(w,wn,xn.current.offset,{clearSceneGroup:fs}),w.requestRender?.()},[Cr,Jn,xt,it,Xt,co,Mt,Pe,T,Tr,z,ne,A,t,n,Lr,N,C,k,D,$,yt]),f.useEffect(()=>{const w=pe.current,V=Xe.current,q=Array.isArray(V.states)?V.states:[],ce=Br(V.transitionProgress,0,1);if(_A(Xe),!w?.THREE||A||!Array.isArray(w.displayRecords)||!w.displayRecords.length){V.progress=0,V.modelKey="",V.recordKey="",V.states=[],V.transitionProgress=0;return}const ge=n||"",et=`${ge}:${t6(w.displayRecords)}`,Nt=V.modelKey!==ge,je=ne?1:0,Je=w.modelBounds||t?.bounds,Lt=nW(w.THREE,w.displayRecords,Je,X);if(V.modelKey=ge,V.recordKey=et,!Lt.length){oW(w.displayRecords);for(const wn of w.displayRecords)tc(w.THREE,wn);X2(w,w.displayRecords),w.requestRender?.(),V.progress=0,V.states=[],V.transitionProgress=0;return}const gn=o6(w,Lt,je,{previousStates:q,previousTransitionProgress:ce,useCurrentTranslations:!Nt});if(i6(w.displayRecords,gn),!s6(gn)){V.progress=je,V.states=gn,V.transitionProgress=1,Px(w,gn,1);return}const lr=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();V.states=gn,V.transitionProgress=0,Px(w,gn,0);const cr=wn=>{const $n=Number.isFinite(Number(wn))?Number(wn):Date.now(),er=Br(($n-lr)/A8,0,1),ur=iW(er);V.progress=je>0?ur:1-ur,V.transitionProgress=ur,Px(w,gn,ur),er<1?V.rafId=window.requestAnimationFrame(cr):(V.rafId=0,V.progress=je,V.transitionProgress=1,V.states=gn)};return V.rafId=window.requestAnimationFrame(cr),()=>{_A(Xe)}},[ne,X,A,t?.bounds,Re,n,Xt.length,Te,Se,Mt]),f.useEffect(()=>{const w=pe.current;!w?.THREE||!w?.edgePickGroup||!w?.facePickGroup||!w?.vertexPickGroup||(dA(w,t,Ne),Ix(w,Ne,xn.current.offset,{clearSceneGroup:fs}),$c(w,ue.current))},[Ne,t,n,Mt]),f.useEffect(()=>{const w=pe.current;if(!w?.THREE||!w?.edgesGroup)return;const V=w.topologyDisplayEdgeTransformByRecord===!0;Tg(w,V?$||D:Et||Ne,{visible:ar,edgeSettings:Tr,focusedPartIds:Xt,viewerTheme:Pe,dimmedOpacity:Vm,transformByRecord:V,displayRecords:w.displayRecords,syncClip:q=>$c(q,ue.current)})},[Et,Ne,$,Mt,Pe,Xt,Tr,D,ar,Cr]),f.useEffect(()=>{const w=pe.current;if(!w?.THREE||!w?.edgesGroup)return;const{THREE:V,edgesGroup:q}=w;(!w.surfaceLineGroup||w.surfaceLineGroup.parent!==q)&&(w.surfaceLineGroup=new V.Group,w.surfaceLineGroup.renderOrder=21,q.add(w.surfaceLineGroup));const ce=w.surfaceLineGroup;Ur(w,ce);const ge=(Array.isArray(me)?me:[]).filter(QR);if(!ge.length)return()=>{Ur(w,ce)};const et=Math.max(x1(ft,Pe)*1.6,1.8),Nt=Math.max(w.modelRadius||0,1)*8e-4+.02;for(const je of ge){const Je=je?.surfaceLine,Lt=String(Je?.referenceId||"").trim(),gn=Pi.get(Lt)||Ne?.referenceMap?.get(Lt)||null;if(!gn)continue;const lr=_H(gn,Je,{offset:Nt});if(!lr.length)continue;const cr=iu(w,lr,{color:pV,opacity:.98,lineWidth:et,renderOrder:22,depthTest:!0,depthWrite:!1});cr&&ce.add(cr)}return ce.visible=ce.children.length>0,w.requestRender(),()=>{Ur(w,ce)}},[Ne,me,ft,Pi,Mt,Pe]),f.useEffect(()=>{const w=pe.current;if(!w?.THREE||!w?.edgesGroup)return;const{THREE:V,edgesGroup:q}=w;(!w.bendGuideGroup||w.bendGuideGroup.parent!==q)&&(w.bendGuideGroup=new V.Group,w.bendGuideGroup.renderOrder=15,q.add(w.bendGuideGroup));const ce=w.bendGuideGroup;if(Ur(w,ce),A||!t||!Rx(t.guide_line_segments,6))return()=>{Ur(w,ce)};const ge=iu(w,t.guide_line_segments,{color:H8,opacity:.98,lineWidth:Math.max(x1(ft,Pe)*K8,1.4),renderOrder:16,depthTest:!1,depthWrite:!1});return ge&&ce.add(ge),ce.visible=ce.children.length>0,w.requestRender(),()=>{Ur(w,ce)}},[A,t,n,ft,Mt,Pe]),f.useEffect(()=>{const w=pe.current;if(!w?.THREE||!w?.edgesGroup)return;const{THREE:V,edgesGroup:q}=w;(!w.urdfPosePickerGuideGroup||w.urdfPosePickerGuideGroup.parent!==q)&&(w.urdfPosePickerGuideGroup=new V.Group,w.urdfPosePickerGuideGroup.renderOrder=28,q.add(w.urdfPosePickerGuideGroup));const ce=w.urdfPosePickerGuideGroup;if(Ur(w,ce),!De?.active)return()=>{Ur(w,ce)};if(!Hs(w,De))return()=>{Ur(w,ce)};const et=z$(w,De);et&&ce.add(et);const Nt=B$(w,De);Nt&&ce.add(Nt);const je=V$(w,De);return je&&ce.add(je),ce.visible=ce.children.length>0,w.requestRender(),()=>{Ur(w,ce)}},[De?.active,De?.center,L,fe,Mt]),f.useEffect(()=>{const w=pe.current;if(!w?.THREE||!w?.edgesGroup)return;const{THREE:V,edgesGroup:q}=w;(!w.partHighlightGroup||w.partHighlightGroup.parent!==q)&&(w.partHighlightGroup=new V.Group,w.partHighlightGroup.renderOrder=22,q.add(w.partHighlightGroup));const ce=w.partHighlightGroup;Ur(w,ce);const ge=[],et=new Set,Nt=je=>{const Je=String(je||"").trim();!Je||kn.has(Je)||et.has(Je)||(et.add(Je),ge.push(Je))};for(const je of Ja(k))Nt(je);for(const je of Ja(z))Nt(je);if(ar&&ge.length){const je={...Tr,thickness:Fx(ft,Pe),highlightPartIds:ge,highlightColor:Bx(ft),highlightOpacity:zx(ft),highlightRenderOrder:26},Je=w.topologyDisplayEdgeTransformByRecord===!0&&$?Y2(w,$,{edgeSettings:je,viewerTheme:Pe,displayRecords:w.displayRecords}):dw(w,Et||Ne,je,Pe);Je&&ce.add(Je)}return ce.visible=ce.children.length>0,w.requestRender(),()=>{Ur(w,ce)}},[Et,Ne,$,ft,Tr,kn,Mt,Pe,z,n,k,ar,Cr]),f.useEffect(()=>{const w=pe.current;if(!w?.THREE||!w?.edgesGroup)return;const{THREE:V,edgesGroup:q}=w;(!w.mateOverlayGroup||w.mateOverlayGroup.parent!==q)&&(w.mateOverlayGroup=new V.Group,w.mateOverlayGroup.renderOrder=27,q.add(w.mateOverlayGroup));const ce=w.mateOverlayGroup;if(Ur(w,ce),A||!t)return()=>{Ur(w,ce)};const ge=k6(Y,K,J);if(!ge.length)return()=>{Ur(w,ce)};const et=Number.isFinite(Number(w.modelRadius))&&Number(w.modelRadius)>0?Number(w.modelRadius):1,Nt=Bx(ft),je=zx(ft),Je=Br(et*.012,.55,4.5),Lt=Br(et*.07,Je*3.2,18),gn=Math.max(Fx(ft,Pe),2.6);for(const lr of ge)j6(w,ce,lr,{color:Nt,opacity:lr.selected?je:Math.min(je,.82),markerRadius:lr.hovered&&!lr.selected?Je*.9:Je,axisLength:Lt,lineWidth:lr.selected?gn:Math.max(gn*.86,2.2),renderOrder:lr.selected?28:27});return ce.visible=ce.children.length>0,w.requestRender(),()=>{Ur(w,ce)}},[Y,ft,J,A,t,n,K,Mt,Pe]),f.useEffect(()=>{const w=pe.current;if(!w?.THREE||!w?.edgesGroup||!w?.modelGroup)return;const{THREE:V,edgesGroup:q,modelGroup:ce}=w;(!w.referenceHighlightGroup||w.referenceHighlightGroup.parent!==q)&&(w.referenceHighlightGroup=new V.Group,w.referenceHighlightGroup.renderOrder=25,q.add(w.referenceHighlightGroup));const ge=w.referenceHighlightGroup;(!w.referenceFaceFillGroup||w.referenceFaceFillGroup.parent!==ce)&&(w.referenceFaceFillGroup=new V.Group,w.referenceFaceFillGroup.renderOrder=24,ce.add(w.referenceFaceFillGroup));const et=w.referenceFaceFillGroup;Ur(w,ge),Ur(w,et);const Nt=Fx(ft,Pe),je=Nt,Je=Bx(ft),Lt=zx(ft),gn=new Map,lr=Array.isArray(Ne?.references)?Ne.references:Ne?.referenceMap instanceof Map?[...Ne.referenceMap.values()]:[],cr=(er,{hovered:ur=!1}={})=>{const bn=String(er||"").trim();if(!bn)return;const nn=gn.get(bn);if(nn){nn.hovered=nn.hovered||ur;return}gn.set(bn,{hovered:ur})},wn=(er,{hovered:ur=!1}={})=>{const bn=String(er||"").trim(),nn=Pi.get(bn)||Ne?.referenceMap?.get(bn)||null;if(!nn){const Or=q8(bn);if(Or)for(const kr of lr){const Gn=Xc(kr);(Gn==="face"||Gn==="edge"||Gn==="vertex")&&b1(kr,Or)&&cr(kr?.id,{hovered:ur})}return}const Jr=Xc(nn);if(Jr==="occurrence"){const Or=g1(nn);for(const kr of lr){const Gn=Xc(kr);(Gn==="face"||Gn==="edge"||Gn==="vertex")&&b1(kr,Or)&&cr(kr?.id,{hovered:ur})}return}if(Jr==="shape"){const Or=_P(nn),kr=g1(nn);for(const Gn of lr){const Qr=Xc(Gn);(Qr==="face"||Qr==="edge"||Qr==="vertex")&&Y8(Gn,Or,kr)&&cr(Gn?.id,{hovered:ur})}return}cr(bn,{hovered:ur})};for(const er of Array.isArray(Q)?Q:[])wn(er);const $n=String(G||"").trim();$n&&wn($n,{hovered:!0});for(const[er,ur]of gn.entries()){const bn=Pi.get(er)||Ne?.referenceMap?.get(er)||null;if(!bn)continue;const nn=Xc(bn);if(nn!=="face"&&nn!=="edge"&&nn!=="vertex")continue;const Jr=!!ur?.hovered;if(nn==="vertex"){const Gn=CU(w,V,bn,{color:bU,opacity:Jr?.96:.88});Gn&&ge.add(Gn);continue}const Or=Je,kr=nn==="edge"?j2(Ne,bn):vU(Ne,bn);if(kr?.length){const Gn=nn==="edge"&&Ne?.edges?.[bn.rowIndex]?.visibilityClass||"",Qr=Jr?je:Nt,Lo=iu(w,kr,{color:Or,opacity:Lt,lineWidth:Qr,renderOrder:26,depthTest:nn!=="edge",depthWrite:!1,depthBias:Yb(Qr,{visibilityClass:Gn})});Lo&&ge.add(Lo)}if(nn==="face"){const Gn=EU(w,V,bn)||SU(w,V,Ne,bn);if(Gn){const Qr=Lt,Lo=new V.MeshBasicMaterial({color:Or,transparent:Qr<.999,opacity:Qr,depthTest:!0,depthWrite:!1,polygonOffset:!0,polygonOffsetFactor:-2,polygonOffsetUnits:-2,side:V.DoubleSide,toneMapped:!1}),ta=new V.Mesh(Gn,Lo);ta.renderOrder=25,et.add(ta)}}}return ge.visible=ge.children.length>0,et.visible=et.children.length>0,w.requestRender(),()=>{Ur(w,ge),Ur(w,et)}},[Ne,G,Pi,Q,Mt,Pe,ft]),YH({drawingCanvasRef:qt,drawingDraftRef:sn,drawingStrokesRef:Mn,drawingChangeRef:fn,drawingIdRef:Tn,drawingEnabled:Ie,drawingTool:oe,meshData:t,previewMode:p,viewerReadyTick:Mt,renderDrawingOverlay:_s,redrawDrawingCanvas:pI,buildDrawingPoint:iI,distanceToStrokeInPixels:sV,strokeLengthInPixels:rV,drawingToolNeedsTwoPoints:iV,buildFillStrokeAtPoint:RV,buildSurfaceLineAnchor:ei,updateSurfaceLineAnchor:Oi,drawingEraseThresholdPx:uV,drawingMinPointDistancePx:lV,drawingMinStrokeLengthPx:cV}),d8({runtimeRef:pe,mountRef:ht,sceneMountRef:jt,drawingCanvasRef:qt,previewMode:p,pickMode:N,selectorRuntime:Ne,pickableFaces:uo,pickableEdges:wc,pickableVertices:hl,hiddenPartIds:T,focusedPartId:Xt,onHoverReferenceChange:ut,onActivateReference:Tt,onDoubleActivateReference:Ve,onContextReference:St,viewerReadyTick:Mt}),c.jsxs("div",{ref:ht,className:"relative h-full w-full",style:bl?{cursor:bl}:void 0,onPointerDownCapture:Tu,onPointerMoveCapture:Nf,onPointerUpCapture:Ru,onPointerCancelCapture:$e,onPointerLeave:ki,children:[c.jsx("div",{className:"h-full w-full",ref:jt}),c.jsx("canvas",{ref:qt,className:"absolute inset-0 z-10 h-full w-full touch-none",style:{pointerEvents:Ie&&!p&&t?"auto":"none",cursor:Ie&&!p&&t?oe===Jt.ERASE?"cell":oe===Jt.FILL?"copy":"crosshair":"default"},"aria-hidden":"true"}),g&&!p&&!A&&t?c.jsx(c6,{zoomPercent:j,onZoomPercentChange:Rr,onZoomReset:()=>{Qn({animate:!0})},viewPlaneOffsetRight:x,viewPlaneOffsetBottom:y}):null,c.jsx(Nw,{showViewPlane:g,previewMode:p,isLoading:A,meshData:t,viewPlaneOffsetRight:x,viewPlaneOffsetBottom:y,viewPlaneSize:NP,viewPlaneHeader:S,compact:b,activeViewPlaneFace:Kr,viewPlaneFaces:Rw,viewPlaneOrientation:Co,viewerTheme:Pe,activateViewPlaneFace:hi,activateDefaultViewPlane:Pu}),gr?c.jsx("p",{className:"cad-glass-popover pointer-events-none absolute left-4 top-24 z-20 rounded-[10px] border border-[var(--ui-error-bg)] px-4 py-3 text-sm text-[var(--ui-error-text)] shadow-[var(--ui-shadow-soft)] sm:top-20",children:gr}):null]})}),zs=1,FA=.08,zA=20,BA=12,VA=1.12,Lg=1e-6,$A=1e3,z6=.001,Mb=1e-9,B6=.35,V6=10,$6=160,G6=Object.freeze({x:[1,0,0],y:[0,1,0],z:[0,0,1]}),U6=Object.freeze([{id:"x+",title:"Fit 2D view",direction:[1,0,0]},{id:"x-",title:"Fit 2D view",direction:[-1,0,0]},{id:"y+",title:"Fit 2D view",direction:[0,1,0]},{id:"y-",title:"Fit 2D view",direction:[0,-1,0]}]),W6=Object.freeze({format:"dxf-2d"});function $x(e,t,n){return Math.min(Math.max(e,t),n)}function Ci(e,t=0){const n=Number(e);return Number.isFinite(n)?n:t}function Km(e){return!Array.isArray(e)||e.length<2?[0,0]:[Ci(e[0]),Ci(e[1])]}function Dw(e,t,n=z6){return Math.abs(e[0]-t[0])<=n&&Math.abs(e[1]-t[1])<=n}function xm(e){return`${Math.round(e[0]*$A)}:${Math.round(e[1]*$A)}`}function H6(e){return[...e].reverse()}function BP(e){return e.length>1&&Dw(e[0],e[e.length-1])?e.slice(0,-1):e}function K6(e){const t=[];for(const n of e)t.length&&Dw(t[t.length-1],n)||t.push(n);return BP(t)}function Fg(e){const t=Ci(e)%360;return t<0?t+360:t}function X6(e,t,n){const r=Math.abs(n);return r>=360-Mb?!0:n>=0?(Fg(e)-Fg(t)+360)%360<=r+Mb:(Fg(t)-Fg(e)+360)%360<=r+Mb}function Gx(e,t,n){const r=Ci(n)*Math.PI/180;return[e[0]+t*Math.cos(r),e[1]+t*Math.sin(r)]}function Y6(e){const t=Km(e?.center),n=Math.max(Ci(e?.radius),0),r=Ci(e?.startAngleDeg),o=Ci(e?.sweepAngleDeg),i=r+o,s=[Gx(t,n,r),Gx(t,n,i)];for(const a of[0,90,180,270])X6(a,r,o)&&s.push(Gx(t,n,a));return s}function GA(e){if(!e.length)return null;const t=e.map(r=>r[0]),n=e.map(r=>r[1]);return{minX:Math.min(...t),minY:Math.min(...n),maxX:Math.max(...t),maxY:Math.max(...n)}}function Ux(e,t){return t?e?{minX:Math.min(e.minX,t.minX),minY:Math.min(e.minY,t.minY),maxX:Math.max(e.maxX,t.maxX),maxY:Math.max(e.maxY,t.maxY)}:t:e}function q6(e,t){const n=Math.max(Math.abs(e),.01),r=$x(1-B6/n,-1,1),o=r<=-1?Math.PI/8:$x(2*Math.acos(r),Math.PI/64,Math.PI/10);return $x(Math.ceil(Math.max(Math.abs(t),Math.PI/36)/o),V6,$6)}function VP(e,t,n,r){const o=Ci(n)*Math.PI/180,i=Ci(r)*Math.PI/180,s=q6(t,i),a=[];for(let l=0;l<=s;l+=1){const u=l/s,d=o+i*u;a.push([e[0]+t*Math.cos(d),e[1]+t*Math.sin(d)])}return a}function Z6(e,t){return BP(VP(e,t,0,360))}function J6(e){const t=e?.geometry||{},n=Array.isArray(t.lines)?t.lines:[],r=Array.isArray(t.arcs)?t.arcs:[],o=Array.isArray(t.circles)?t.circles:[],i=[],s=[];let a=null;for(const l of n){const u=Km(l?.start),d=Km(l?.end);a=Ux(a,GA([u,d])),!(String(l?.kind||"").trim().toLowerCase()==="bend"||Dw(u,d))&&i.push({points:[u,d]})}for(const l of r){const u=Km(l?.center),d=Math.max(Ci(l?.radius),0);if(d<=0)continue;a=Ux(a,GA(Y6(l)));const m=VP(u,d,Ci(l?.startAngleDeg),Ci(l?.sweepAngleDeg));String(l?.kind||"").trim().toLowerCase()!=="bend"&&i.push({points:m})}for(const l of o){const u=Km(l?.center),d=Math.max(Ci(l?.radius),0);d<=0||(a=Ux(a,{minX:u[0]-d,minY:u[1]-d,maxX:u[0]+d,maxY:u[1]+d}),String(l?.kind||"").trim().toLowerCase()!=="bend"&&s.push(Z6(u,d)))}return{cutPrimitives:i,cutCircleLoops:s,rawBounds:a}}function Q6(e){const{cutPrimitives:t,cutCircleLoops:n,rawBounds:r}=J6(e),o=[];if(t.length){const i=new Map,s=new Set,a=(l,u)=>{const d=i.get(l);if(d){d.push(u);return}i.set(l,[u])};t.forEach((l,u)=>{const d=xm(l.points[0]),m=xm(l.points[l.points.length-1]);a(d,{index:u,reverse:!1}),a(m,{index:u,reverse:!0})});for(let l=0;l!s.has(b));if(!g.length)return{loops:[],rawBounds:r};const x=g[0];s.add(x.index);const y=t[x.index].points,S=x.reverse?H6(y):y;if(u=u.concat(S.slice(1)),m=xm(S[S.length-1]),p+=1,p>t.length+4)return{loops:[],rawBounds:r}}u=K6(u),u.length>=3&&o.push(u)}}for(const i of n)i.length>=3&&o.push(i);return{loops:o,rawBounds:r}}function zg(e){const t=Math.round(Ci(e)*1e6)/1e6;return Math.abs(t){const o=r.map(a=>e9(a,n));if(o.length<3)return"";const[i,...s]=o;return[`M ${zg(i[0])} ${zg(i[1])}`,...s.map(a=>`L ${zg(a[0])} ${zg(a[1])}`),"Z"].join(" ")}).filter(Boolean).join(" ")}function Wx(e,t){return typeof window>"u"?t:window.getComputedStyle(document.documentElement).getPropertyValue(e).trim()||t}function n9(){return{background:Wx("--ui-app-bg","#f3f4f6"),cutStroke:Wx("--ui-text","#111827"),bendStroke:Wx("--ui-accent","#b45309")}}function r9(e,t){const n=Math.max(Number(e?.width)||0,zs),r=Math.max(Number(e?.height)||0,zs),o=Math.max(Number(t?.width)||0,1),i=Math.max(Number(t?.height)||0,1),s=n*(1+FA*2),a=r*(1+FA*2),l=s/Math.max(a,zs),u=o/i;let d=s,m=a;return l>u?m=d/u:d=m*u,{x:(n-d)/2,y:(r-m)/2,width:Math.max(d,zs),height:Math.max(m,zs)}}function o9(e,t){const n=Math.max(t.width/zA,zs),r=Math.max(t.height/zA,zs),o=Math.max(t.width*BA,zs),i=Math.max(t.height*BA,zs);return{x:Number(e.x)||0,y:Number(e.y)||0,width:Math.min(Math.max(Number(e.width)||t.width,n),o),height:Math.min(Math.max(Number(e.height)||t.height,r),i)}}function i9(e,t){return Math.abs((Number(e?.x)||0)-(Number(t?.x)||0)){if(typeof e.toBlob=="function"){e.toBlob(r=>{if(r){t(r);return}n(new Error("Failed to encode screenshot"))},"image/png");return}try{const o=e.toDataURL("image/png").split(",")[1]||"",i=Uint8Array.from(atob(o),s=>s.charCodeAt(0));t(new Blob([i],{type:"image/png"}))}catch(r){n(r instanceof Error?r:new Error("Failed to encode screenshot"))}})}async function a9(e,{width:t,height:n,backgroundColor:r}){const i=new XMLSerializer().serializeToString(e),s=new Blob([i],{type:"image/svg+xml;charset=utf-8"}),a=URL.createObjectURL(s);try{const l=await new Promise((m,p)=>{const g=new Image;g.onload=()=>m(g),g.onerror=()=>p(new Error("Failed to render DXF screenshot")),g.src=a}),u=document.createElement("canvas");u.width=t,u.height=n;const d=u.getContext("2d");if(!d)throw new Error("Failed to create screenshot canvas");return d.fillStyle=r,d.fillRect(0,0,t,n),d.drawImage(l,0,0,t,n),await s9(u)}finally{URL.revokeObjectURL(a)}}const l9=f.forwardRef(function({dxfData:t,modelKey:n,themeSettings:r=null,showViewPlane:o=!0,viewPlaneOffsetRight:i=16,viewPlaneOffsetBottom:s="1rem",viewPlaneHeader:a=null,onViewerAlertChange:l},u){const d=f.useRef(null),m=f.useRef(null),p=f.useRef(null),g=f.useRef(n),[x,y]=f.useState({width:0,height:0}),[S,b]=f.useState({x:0,y:0,width:1,height:1}),I=n9(),A=Uy(r?.materials||{},0),N=Math.max(Number(t?.bounds?.width)||0,zs),P=Math.max(Number(t?.bounds?.height)||0,zs),R=f.useMemo(()=>{try{return t9(t)}catch{return""}},[t]),v=f.useMemo(()=>r9({width:N,height:P},x),[P,N,x.height,x.width]);f.useEffect(()=>{l?.(null)},[n,l]),f.useEffect(()=>{const z=d.current;if(!z||typeof ResizeObserver!="function")return;const Y=new ResizeObserver(K=>{const J=K[0];J&&y(G=>{const Q=J.contentRect.width,D=J.contentRect.height;return G.width===Q&&G.height===D?G:{width:Q,height:D}})});return Y.observe(z),()=>Y.disconnect()},[]),f.useEffect(()=>{const z=g.current!==n;g.current=n,b(Y=>!z&&i9(Y,v)?Y:v)},[v.height,v.width,v.x,v.y,n]),f.useEffect(()=>{const z=()=>{p.current=null};return window.addEventListener("pointerup",z),window.addEventListener("pointercancel",z),()=>{window.removeEventListener("pointerup",z),window.removeEventListener("pointercancel",z)}},[]),f.useImperativeHandle(u,()=>({async captureScreenshot({filename:z="cad-screenshot.png",mode:Y="download"}={}){const K=d.current,J=m.current;if(!K||!J)throw new Error("CAD Viewer not ready");const G=K.getBoundingClientRect(),Q=Math.max(window.devicePixelRatio||1,1),D=Math.max(1,Math.round(G.width*Q)),$=Math.max(1,Math.round(G.height*Q)),ie=a9(J,{width:D,height:$,backgroundColor:I.background});if(Y==="clipboard")return await tw(ie);const W=await ie;return nw(W,{filename:z})}}),[I.background]);const C=z=>{z.button===0&&(z.currentTarget.setPointerCapture?.(z.pointerId),p.current={clientX:z.clientX,clientY:z.clientY})},T=z=>{const Y=p.current,K=d.current?.getBoundingClientRect();if(!Y||!K||!K.width||!K.height)return;const J=z.clientX-Y.clientX,G=z.clientY-Y.clientY;p.current={clientX:z.clientX,clientY:z.clientY},b(Q=>({...Q,x:Q.x-J/K.width*Q.width,y:Q.y-G/K.height*Q.height}))},k=z=>{const Y=d.current?.getBoundingClientRect();if(!Y||!Y.width||!Y.height)return;z.preventDefault();const K=(z.clientX-Y.left)/Y.width,J=(z.clientY-Y.top)/Y.height,G=z.deltaY>0?VA:1/VA;b(Q=>{const D=Q.width*G,$=Q.height*G,ie=Q.x+Q.width*K,W=Q.y+Q.height*J;return o9({x:ie-D*K,y:W-$*J,width:D,height:$},v)})};return c.jsxs("div",{ref:d,className:"absolute inset-0 touch-none select-none",onPointerDown:C,onPointerMove:T,onDoubleClick:()=>{b(v)},onWheel:k,children:[c.jsxs("svg",{ref:m,className:"h-full w-full",viewBox:`${S.x} ${S.y} ${S.width} ${S.height}`,xmlns:"http://www.w3.org/2000/svg",children:[c.jsx("rect",{x:S.x,y:S.y,width:S.width,height:S.height,fill:I.background}),R?c.jsx("path",{d:R,fill:A,fillOpacity:"0.96",fillRule:"evenodd",stroke:"none"}):null,Array.isArray(t?.paths)?t.paths.map((z,Y)=>{const K=z?.kind==="bend";return c.jsx("path",{d:String(z?.d||""),fill:"none",stroke:K?I.bendStroke:I.cutStroke,strokeDasharray:K?"8 6":void 0,strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:K?1.5:1.75,vectorEffect:"non-scaling-stroke"},`${z?.layer||"path"}:${Y}`)}):null,Array.isArray(t?.circles)?t.circles.map((z,Y)=>{const K=z?.kind==="bend";return c.jsx("circle",{cx:Number(z?.cx)||0,cy:Number(z?.cy)||0,r:Math.max(Number(z?.r)||0,0),fill:"none",stroke:K?I.bendStroke:I.cutStroke,strokeDasharray:K?"8 6":void 0,strokeWidth:K?1.5:1.75,vectorEffect:"non-scaling-stroke"},`${z?.layer||"circle"}:${Y}`)}):null]}),c.jsx(Nw,{showViewPlane:o,previewMode:!1,isLoading:!1,meshData:t?W6:null,viewPlaneOffsetRight:i,viewPlaneOffsetBottom:s,activeViewPlaneFace:"z+",viewPlaneFaces:U6,viewPlaneOrientation:G6,viewerTheme:null,variant:"2d",viewPlaneHeader:a,activateViewPlaneFace:()=>{b(v)},activateDefaultViewPlane:()=>{b(v)}})]})}),qa=Object.freeze([0,0,1]),UA=Object.freeze([0,1,0]),$P=Object.freeze({front:Object.freeze({name:"front",direction:Object.freeze([0,-1,0]),up:qa}),back:Object.freeze({name:"back",direction:Object.freeze([0,1,0]),up:qa}),right:Object.freeze({name:"right",direction:Object.freeze([1,0,0]),up:qa}),left:Object.freeze({name:"left",direction:Object.freeze([-1,0,0]),up:qa}),top:Object.freeze({name:"top",direction:Object.freeze([0,0,1]),up:UA}),bottom:Object.freeze({name:"bottom",direction:Object.freeze([0,0,-1]),up:UA}),iso:Object.freeze({name:"iso",direction:Object.freeze([1,-1,.8]),up:qa}),isometric:Object.freeze({name:"iso",direction:Object.freeze([1,-1,.8]),up:qa}),side:Object.freeze({name:"side",direction:Object.freeze([1,0,0]),up:qa})}),pp="iso",c9=Object.freeze(["preset","position","target","up","zoom","direction","name"]);function GP(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Bg(e,{fieldName:t="camera vector",required:n=!1,nonZero:r=!1,strict:o=!0}={}){if(e==null){if(n&&o)throw new Error(`${t} must be a three-number array`);return null}if(!Array.isArray(e)||e.length<3){if(o)throw new Error(`${t} must be a three-number array`);return null}const i=[Number(e[0]),Number(e[1]),Number(e[2])];if(!i.every(Number.isFinite)){if(o)throw new Error(`${t} must contain only finite numbers`);return null}if(r&&i[0]**2+i[1]**2+i[2]**2<=1e-12){if(o)throw new Error(`${t} must not be the zero vector`);return null}return i}function u9(e,t=1,{fieldName:n="camera.zoom",strict:r=!1}={}){if(e==null||e==="")return t;const o=Number(e);if(Number.isFinite(o)&&o>0)return o;if(r)throw new Error(`${n} must be a positive finite number`);return t}function WA(e){return{name:e.name,direction:[...e.direction],up:[...e.up]}}function HA(e,{presets:t=$P,strict:n=!0}={}){const r=String(e||pp).trim().toLowerCase();if(t[r])return WA(t[r]);const o=r.split(":").map(i=>Number(i));if(o.length>=2&&o.every(Number.isFinite)){const i=o[0]*Math.PI/180,s=o[1]*Math.PI/180,a=Math.cos(s);return{name:`${o[0]}:${o[1]}`,direction:[Math.sin(i)*a,-Math.cos(i)*a,Math.sin(s)],up:[...qa]}}if(n)throw new Error(`Unknown camera preset: ${e}`);return WA(t[pp])}function d9(e,{strict:t=!0}={}){const n=String(e||"").trim();if(!n.startsWith("{"))return null;try{const r=JSON.parse(n);if(!GP(r))throw new Error("camera JSON must be an object");return r}catch(r){if(t){const o=r instanceof Error?r.message:String(r);throw new Error(`Invalid camera JSON: ${o}`)}return null}}function f9(e){const t=Object.keys(e).filter(n=>!c9.includes(n));if(t.length)throw new Error(`Unsupported camera fields: ${t.join(", ")}`)}function m9(e=pp,{presets:t=$P,strict:n=!0}={}){const o=(typeof e=="string"?d9(e,{strict:n}):null)||e;if(!GP(o)){const p=HA(o||pp,{presets:t,strict:n});return{sourceKind:"string",name:p.name,preset:p.name,direction:p.direction,position:null,target:null,up:p.up,zoom:1,hasExplicitPosition:!1,hasExplicitTarget:!1,hasExplicitUp:!1,hasExplicitZoom:!1}}f9(o);const i=o.preset??pp,s=HA(i,{presets:t,strict:n}),a=Bg(o.direction,{fieldName:"camera.direction",nonZero:!0,strict:n})||s.direction,l=Bg(o.position,{fieldName:"camera.position",strict:n}),u=Bg(o.target,{fieldName:"camera.target",strict:n}),d=Bg(o.up,{fieldName:"camera.up",nonZero:!0,strict:n})||s.up||[...qa],m=Object.prototype.hasOwnProperty.call(o,"zoom");return{sourceKind:"object",name:String(o.name||s.name||"custom"),preset:s.name,direction:a,position:l,target:u,up:d,zoom:u9(o.zoom,1,{strict:n,fieldName:"camera.zoom"}),hasExplicitPosition:Object.prototype.hasOwnProperty.call(o,"position"),hasExplicitTarget:Object.prototype.hasOwnProperty.call(o,"target"),hasExplicitUp:Object.prototype.hasOwnProperty.call(o,"up"),hasExplicitZoom:m}}const p9=/^#(?:[0-9a-fA-F]{3}){1,2}$/,h9=50,g9="#132232",UP="#8dc5ff",b9=Object.freeze(["feature","tangent","seam","degenerate"]),S1=Object.freeze({feature:Object.freeze({opacity:1,thickness:1.15}),tangent:Object.freeze({opacity:.5,thickness:1.15}),seam:Object.freeze({opacity:.85,thickness:1.15}),degenerate:Object.freeze({opacity:1,thickness:0})}),ff=Object.freeze({enabled:!0,contrastMode:"manual",color:g9,thickness:1,classes:S1,highlightColor:UP,highlightOpacity:1,highlightThickness:3,silhouette:!1,silhouetteScale:0}),ah=Object.freeze({...ff,enabled:!1});function WP(e,t,n){return Math.min(Math.max(e,t),n)}function Ft(e,t,n=-1/0,r=1/0){const o=Number(e);return Number.isFinite(o)?WP(o,n,r):t}function yr(e,t){const n=String(e||"").trim();return p9.test(n)?n.length===4?`#${n[1]}${n[1]}${n[2]}${n[2]}${n[3]}${n[3]}`.toLowerCase():n.toLowerCase():t}function y9(e,t=Oe?.materials?.defaultColor||"#ffffff"){const r=(Array.isArray(e)?e:[e]).map(o=>yr(o,"")).filter(Boolean).slice(0,h9);return r.length?r:[yr(t,"#ffffff")]}function x9(e,t="#000000"){const n=yr(e,t),r=n.length===4?`#${n[1]}${n[1]}${n[2]}${n[2]}${n[3]}${n[3]}`:n,o=i=>{const s=parseInt(r.slice(i,i+2),16)/255;return s<=.03928?s/12.92:((s+.055)/1.055)**2.4};return{r:o(1),g:o(3),b:o(5)}}function S9(e,t="#000000"){const n=x9(e,t);return .2126*n.r+.7152*n.g+.0722*n.b}function Ps(e,t=!1){return typeof e=="boolean"?e:t}function E9(e,t="solid"){const n=String(e||"").trim().toLowerCase();return["solid","linear","radial","transparent"].includes(n)?n:t}function w9(e,t="multiply"){const n=String(e||"").trim().toLowerCase();return["multiply","blend"].includes(n)?n:t}function v9(e,t="manual"){const n=String(e||"").trim().toLowerCase();return["auto","manual"].includes(n)?n:t}function C9(e={},t=S1){const n=e&&typeof e=="object"?e:{};return Object.fromEntries(b9.map(r=>{const o=n[r]&&typeof n[r]=="object"?n[r]:{},i=t?.[r]||S1[r],s=o.enabled===!1;return[r,{opacity:Ft(o.opacity,i.opacity,0,1),thickness:s?0:Ft(o.thickness,i.thickness,0,6)}]}))}const Ii=Object.freeze({STAGE:"stage",GRID:"grid",NONE:"none"}),No=Object.freeze({SYSTEM:"system",LIGHT:"light",DARK:"dark"}),M9=Object.freeze(Object.values(No));function ay(e,t=No.SYSTEM){const n=String(e||"").trim().toLowerCase();return M9.includes(n)?n:t}const HP=Object.freeze([Object.freeze(["edges","color"]),Object.freeze(["background","solidColor"]),Object.freeze(["background","linearStart"]),Object.freeze(["background","linearEnd"]),Object.freeze(["background","radialInner"]),Object.freeze(["background","radialOuter"]),Object.freeze(["floor","color"]),Object.freeze(["floor","gridCenterColor"]),Object.freeze(["floor","gridCellColor"]),Object.freeze(["lighting","directional","color"]),Object.freeze(["lighting","spot","color"]),Object.freeze(["lighting","point","color"]),Object.freeze(["lighting","ambient","color"]),Object.freeze(["lighting","hemisphere","skyColor"]),Object.freeze(["lighting","hemisphere","groundColor"])]);function E1(e,t){return t.reduce((n,r)=>n&&typeof n=="object"?n[r]:void 0,e)}function KP(e,t,n){let r=e;for(let o=0;o{const l=parseInt(r.slice(a,a+2),16),u=parseInt(o.slice(a,a+2),16);return Math.round(l+(u-l)*i).toString(16).padStart(2,"0")};return`#${s(1)}${s(3)}${s(5)}`}function O9(e,t){const n=Array.isArray(e)?e:[],r=Array.isArray(t)?t:[],o=Math.max(n.length,r.length);return Object.freeze(o?Array.from({length:o},(i,s)=>{const a=n[s]||n.at(-1)||"#ffffff",l=r[s]||r.at(-1)||a;return bs(a,l)}):["#ffffff"])}function Js(e,t={}){const n=yr(e,"#f1f5f9"),r=S9(n)>=.36;return{gridCenterColor:r?bs(n,"#0f172a",.48):bs(n,"#f8fafc",.46),gridCellColor:r?bs(n,"#475569",.26):bs(n,"#cbd5e1",.22),gridOpacity:Ft(t.opacity,KA.gridOpacity,0,1),gridDensity:Ft(t.density,KA.gridDensity,YP,qP)}}const Ki=Object.freeze({materials:{defaultColor:cy[0],fillColors:cy,cycleColors:!1,overrideSourceColors:!1,tintMode:"blend",tintStrength:0,saturation:1.18,contrast:1.12,brightness:1.02,roughness:.58,metalness:.02,clearcoat:.12,clearcoatRoughness:.42,opacity:1,envMapIntensity:.42,emissiveIntensity:.02},edges:{...ff},background:{type:"linear",solidColor:"#edf5fb",linearStart:"#fbfdff",linearEnd:"#b8cadb",linearAngle:135,radialInner:"#ffffff",radialOuter:"#b3c4d4"},floor:{mode:Ii.STAGE,color:"#edf3f8",roughness:.7,reflectivity:.14,shadowOpacity:.16,horizonBlend:.18,...Js("#edf3f8",{opacity:.2})},environment:{enabled:!0,presetId:"studio-hdri-43",intensity:.32,rotationY:-.25,useAsBackground:!1},lighting:{toneMappingExposure:1.16,directional:{enabled:!0,color:"#ffffff",intensity:1.16,position:{x:-210,y:260,z:270}},spot:{enabled:!0,color:"#f4fbff",intensity:.52,angle:.74,distance:0,position:{x:190,y:210,z:170}},point:{enabled:!0,color:"#ffe2ba",intensity:.28,distance:0,position:{x:-240,y:110,z:-210}},ambient:{enabled:!0,color:"#ffffff",intensity:.4},hemisphere:{enabled:!0,skyColor:"#ffffff",groundColor:"#d6e2ee",intensity:1.12}}}),Kn=Object.freeze({materials:{defaultColor:cy[0],fillColors:cy,cycleColors:!1,overrideSourceColors:!1,tintMode:"blend",tintStrength:0,saturation:1.2,contrast:1.14,brightness:1.06,roughness:.54,metalness:.02,clearcoat:.14,clearcoatRoughness:.4,opacity:1,envMapIntensity:.5,emissiveIntensity:.03},edges:{...ah},background:{type:"linear",solidColor:"#081b2d",linearStart:"#18304a",linearEnd:"#030914",linearAngle:135,radialInner:"#174267",radialOuter:"#030914"},floor:{mode:Ii.STAGE,color:"#0a2238",roughness:.38,reflectivity:.1,shadowOpacity:.42,horizonBlend:.1,...Js("#0a2238",{opacity:.22})},environment:{enabled:!0,presetId:"studio-hdri-43",intensity:.18,rotationY:-.25,useAsBackground:!1},lighting:{toneMappingExposure:1.22,directional:{enabled:!0,color:"#ffffff",intensity:1.42,position:{x:-210,y:260,z:270}},spot:{enabled:!0,color:"#70c4ff",intensity:.24,angle:.74,distance:0,position:{x:190,y:210,z:170}},point:{enabled:!0,color:"#9bd0ff",intensity:.36,distance:0,position:{x:-240,y:110,z:-210}},ambient:{enabled:!0,color:"#c6d8ea",intensity:.24},hemisphere:{enabled:!0,skyColor:"#ffffff",groundColor:"#020713",intensity:.98}}}),Wl=Object.freeze({...Kn,materials:{...Kn.materials,defaultColor:XA[0],fillColors:XA},background:{...Kn.background,solidColor:"#151617",linearStart:"#2a2b2d",linearEnd:"#070809",radialInner:"#303133",radialOuter:"#070809"},floor:{...Kn.floor,color:"#171819",...Js("#171819",{opacity:.22})}}),YA=O9(Kn.materials.fillColors,Wl.materials.fillColors),Fl=Object.freeze({...Kn,materials:{...Kn.materials,defaultColor:YA[0],fillColors:YA},edges:{...ff},background:{...Kn.background,solidColor:bs(Kn.background.solidColor,Wl.background.solidColor),linearStart:bs(Kn.background.linearStart,Wl.background.linearStart),linearEnd:bs(Kn.background.linearEnd,Wl.background.linearEnd),radialInner:bs(Kn.background.radialInner,Wl.background.radialInner),radialOuter:bs(Kn.background.radialOuter,Wl.background.radialOuter)},floor:{...Kn.floor,color:bs(Kn.floor.color,Wl.floor.color),...Js(bs(Kn.floor.color,Wl.floor.color),{opacity:.22})}}),k9=Object.freeze({materials:{...Kn.materials,defaultColor:hp[0],fillColors:hp,cycleColors:!1},edges:{...ah},background:{type:"radial",solidColor:"#04131f",linearStart:"#07253a",linearEnd:"#0b8edc",linearAngle:128,radialInner:"#0b8edc",radialOuter:"#02070c"},floor:{mode:Ii.STAGE,color:"#06324f",roughness:.58,reflectivity:.2,shadowOpacity:.3,horizonBlend:.18,...Js("#06324f",{opacity:.24})},environment:Kn.environment,lighting:Kn.lighting}),D9=Object.freeze({materials:{...Kn.materials,defaultColor:gp[0],fillColors:gp,cycleColors:!1},edges:{...ah},background:{type:"radial",solidColor:"#281323",linearStart:"#7a1a52",linearEnd:"#301426",linearAngle:140,radialInner:"#7f1a55",radialOuter:"#25101f"},floor:{mode:Ii.STAGE,color:"#4a1833",roughness:.56,reflectivity:.2,shadowOpacity:.26,horizonBlend:.22,...Js("#4a1833",{opacity:.24})},environment:Kn.environment,lighting:Kn.lighting}),j9=Object.freeze({materials:{...Kn.materials,defaultColor:bp[0],fillColors:bp,cycleColors:!1},edges:{...ah},background:{type:"linear",solidColor:"#f3eadc",linearStart:"#f7ead8",linearEnd:"#c88d5d",linearAngle:162,radialInner:"#f7ead8",radialOuter:"#b06c43"},floor:{mode:Ii.STAGE,color:"#d4a070",roughness:.72,reflectivity:.14,shadowOpacity:.34,horizonBlend:.12,...Js("#d4a070",{opacity:.18})},environment:Kn.environment,lighting:Kn.lighting}),L9=Object.freeze({materials:{...Ki.materials,defaultColor:Kl[0],fillColors:Kl,cycleColors:!0},edges:{...ah},background:{type:"linear",solidColor:"#dff7f7",linearStart:"#fff4d6",linearEnd:"#47c5d6",linearAngle:152,radialInner:"#fff8e8",radialOuter:"#1a8fb5"},floor:{mode:Ii.STAGE,color:"#f2d59b",roughness:.74,reflectivity:.18,shadowOpacity:.2,horizonBlend:.2,...Js("#f2d59b",{opacity:.18})},environment:{enabled:!0,presetId:"studio-hdri-12",intensity:.36,rotationY:-.18,useAsBackground:!1},lighting:{toneMappingExposure:1.18,directional:{enabled:!0,color:"#fff7df",intensity:1.3,position:{x:-220,y:280,z:250}},spot:{enabled:!0,color:"#e4fbff",intensity:.36,angle:.72,distance:0,position:{x:190,y:210,z:170}},point:{enabled:!0,color:"#ffd08a",intensity:.24,distance:0,position:{x:-240,y:110,z:-210}},ambient:{enabled:!0,color:"#fff8e6",intensity:.34},hemisphere:{enabled:!0,skyColor:"#bff8ff",groundColor:"#f2d59b",intensity:1.04}}}),F9=Object.freeze({materials:{...Kn.materials,defaultColor:yp[0],fillColors:yp,cycleColors:!1},edges:{...P9},background:{type:"radial",solidColor:"#020403",linearStart:"#031109",linearEnd:"#000000",linearAngle:180,radialInner:"#062414",radialOuter:"#000201"},floor:{mode:Ii.GRID,color:"#020403",roughness:.58,reflectivity:.12,shadowOpacity:.35,horizonBlend:0,gridCenterColor:ZP,gridCellColor:"#0c3d22",gridOpacity:.34,gridDensity:1.15},environment:Kn.environment,lighting:Kn.lighting}),Sm="#f0f4f9",qA="#e2e9f0",ZA=Object.freeze({...Ki,background:{...Ki.background,type:"solid",solidColor:Sm,linearStart:Sm,linearEnd:Sm,radialInner:Sm,radialOuter:Sm},edges:{...ff},floor:{...Ki.floor,color:qA,...Js(qA,{opacity:.2})},environment:{...Ki.environment,enabled:!1},lighting:{...Ki.lighting,hemisphere:{...Ki.lighting.hemisphere,groundColor:"#c7d5e3"}}}),JA="#202832",z9=Object.freeze({...Fl,edges:{...ff,color:"#1c2836"},background:{...Fl.background,solidColor:"#181f28",linearStart:"#242e3a",linearEnd:"#0c1016",radialInner:"#293443",radialOuter:"#0c1016"},floor:{...Fl.floor,color:JA,...Js(JA,{opacity:.22})},lighting:{...Fl.lighting,spot:{...Fl.lighting.spot,color:"#b3d4f2"},point:{...Fl.lighting.point,color:"#bfd8f0"},ambient:{...Fl.lighting.ambient,color:"#dfe7f0"},hemisphere:{...Fl.lighting.hemisphere,groundColor:"#333d4b"}}}),Lw=mf(ZA,No.SYSTEM,jw(ZA,z9)),B9=mf(k9,No.DARK),V9=mf(D9,No.DARK),$9=mf(j9,No.LIGHT),G9=mf(L9,No.LIGHT),U9=mf(F9,No.DARK),uy=Object.freeze([{id:"workbench",label:"Workbench",description:"Balanced CAD workbench lighting with system-aware light and dark canvas colors.",preview:{background:"#f0f4f9",modelColor:"#b6c4ce",accentColor:"#4ea7d8"},settings:Lw},{id:"blue",label:"Blue",description:"Single cyan fill against deep-navy CAD lighting.",preview:{background:hp[0],modelColor:hp[0],accentColor:hp[0]},settings:B9},{id:"pink",label:"Magenta",description:"Single saturated magenta fill against a near-black studio backdrop.",preview:{background:gp[0],modelColor:gp[0],accentColor:gp[0]},settings:V9},{id:"clay-sunrise",label:"Clay",description:"Single warm clay fill with a soft presentation stage.",preview:{background:bp[0],modelColor:bp[0],accentColor:bp[0]},settings:$9},{id:"beach",label:"Beach",description:"Two-color aqua-and-coral fill with warm beach presentation lighting.",preview:{background:`linear-gradient(135deg, ${Kl[0]} 0%, ${Kl[0]} 50%, ${Kl[1]} 50%, ${Kl[1]} 100%)`,modelColor:Kl[0],accentColor:Kl[1]},settings:G9},{id:"terminal",label:"Terminal",description:"Single terminal-green fill with green CAD edge linework and a dark grid floor.",preview:{background:yp[0],modelColor:yp[0],accentColor:yp[0]},settings:U9}]),W9=Object.freeze({cinematic:"workbench",light:"workbench",dark:"workbench",charcoal:"workbench",darkoal:"workbench","dark-2":"workbench"}),H9="workbench",JP=Object.freeze(uy.find(e=>e.id===H9)||uy[0]),Oe=Object.freeze(JP.settings),K9=new Set(_9.map(e=>e.id)),X9=Object.freeze({defaultColor:"#aeb9c3",tintStrength:.28,saturation:.42,contrast:1.02,brightness:.94,roughness:.46,metalness:.02,clearcoat:.18,clearcoatRoughness:.34,opacity:1,envMapIntensity:.58}),Y9=Object.freeze({defaultColor:"#aeb9c3",tintMode:"blend",tintStrength:.08,saturation:1,contrast:1.04,brightness:1.02,roughness:.46,metalness:.02,clearcoat:.18,clearcoatRoughness:.34,opacity:1,envMapIntensity:.58,emissiveIntensity:.06}),q9=Object.freeze({defaultColor:"#aeb9c3",tintMode:"blend",tintStrength:0,saturation:1.34,contrast:1.02,brightness:.82,roughness:.76,metalness:0,clearcoat:0,clearcoatRoughness:.72,opacity:1,envMapIntensity:.08,emissiveIntensity:.01}),Z9=Object.freeze({defaultColor:"#bcc8d4",tintMode:"blend",tintStrength:0,saturation:1.18,contrast:1.07,brightness:1.04,roughness:.58,metalness:.02,clearcoat:.12,clearcoatRoughness:.42,opacity:1,envMapIntensity:.42,emissiveIntensity:.02}),J9=Object.freeze({defaultColor:"#748899",tintMode:"blend",tintStrength:0,saturation:1.18,contrast:1.07,brightness:1.04,roughness:.58,metalness:.02,clearcoat:.12,clearcoatRoughness:.42,opacity:1,envMapIntensity:.42,emissiveIntensity:.02}),Q9=Object.freeze({defaultColor:"#556c7f",tintMode:"blend",tintStrength:0,saturation:1.18,contrast:1.12,brightness:1.02,roughness:.58,metalness:.02,clearcoat:.12,clearcoatRoughness:.42,opacity:1,envMapIntensity:.42,emissiveIntensity:.02}),eK=Object.freeze({enabled:!1,color:"#8fa1b5",thickness:1}),tK=Object.freeze({enabled:!0,color:"#8fa1b5",thickness:1.65}),nK=Object.freeze({enabled:!1,color:"#8fa1b5",thickness:1}),rK=Object.freeze({enabled:!1,color:"#8fa1b5",thickness:1}),QP=Object.freeze({solidColor:"#050711",linearStart:"#02040b",linearEnd:"#252f47",linearAngle:90,radialInner:"#171d30",radialOuter:"#02040b"}),oK=QP,iK=Object.freeze({solidColor:"#0a0f18",linearStart:"#08111c",linearEnd:"#1f2c3d",linearAngle:90,radialInner:"#182337",radialOuter:"#08111c"}),sK=Object.freeze({mode:Ii.STAGE,color:"#141a29",roughness:.62,reflectivity:.22,shadowOpacity:.24,horizonBlend:.28}),aK=Object.freeze({mode:Ii.STAGE,color:"#141a29",roughness:.62,reflectivity:.06,shadowOpacity:.24,horizonBlend:.12}),lK=Object.freeze({mode:Ii.STAGE,color:"#121a24",roughness:.86,reflectivity:.06,shadowOpacity:.24,horizonBlend:.28}),cK=Object.freeze({enabled:!0,presetId:"studio-hdri-43",intensity:.46,rotationY:-.35,useAsBackground:!1}),uK=Object.freeze({enabled:!1,presetId:"studio-hdri-43",intensity:0,rotationY:-.35,useAsBackground:!1}),dK=Object.freeze({toneMappingExposure:1.2,directional:{enabled:!0,color:"#f1f6fb",intensity:2.45,position:{x:-190,y:300,z:210}},spot:{enabled:!0,color:"#dbeafe",intensity:1.34,angle:.72,distance:0,position:{x:160,y:245,z:126}},point:{enabled:!0,color:"#8fb6d8",intensity:.34,distance:0,position:{x:-260,y:95,z:-220}},ambient:{enabled:!0,color:"#1e293b",intensity:.2},hemisphere:{enabled:!0,skyColor:"#dbe7f3",groundColor:"#070a14",intensity:.68}}),fK=Object.freeze({toneMappingExposure:1.03,directional:{enabled:!0,color:"#f1f6fb",intensity:1.28,position:{x:-190,y:300,z:210}},spot:{enabled:!0,color:"#dbeafe",intensity:.18,angle:.72,distance:0,position:{x:160,y:245,z:126}},point:{enabled:!0,color:"#8fb6d8",intensity:.08,distance:0,position:{x:-260,y:95,z:-220}},ambient:{enabled:!0,color:"#1e293b",intensity:.42},hemisphere:{enabled:!0,skyColor:"#dbe7f3",groundColor:"#070a14",intensity:.92}});function mK(e){const t=String(e||"").trim();return K9.has(t)?t:Oe.environment.presetId}function Hx(e,t){return{x:Ft(e?.x,t.x,-5e3,5e3),y:Ft(e?.y,t.y,-5e3,5e3),z:Ft(e?.z,t.z,-5e3,5e3)}}function eO(e,t){return typeof t=="number"?Math.abs((Number(e)||0)-t)<1e-6:t&&typeof t=="object"?!e||typeof e!="object"?!1:Object.entries(t).every(([n,r])=>eO(e[n],r)):e===t}function id(e,t){return t.some(n=>eO(e,n))}function pK(e){const t=id(e?.materials,[X9,Y9,q9,Z9,J9,Q9,Ki.materials]),n=id(e?.edges,[eK,tK,nK,rK,Ki.edges]),r=id(e?.floor,[sK,aK,lK,Ki.floor]),o=id(e?.environment,[cK,uK,Ki.environment,Lw.environment]),i=id(e?.background,[QP,oK,iK,Ki.background]),s=id(e?.lighting,[dK,fK,Ki.lighting]);return t&&n&&i&&r&&o&&s}function Xd(e={}){const t=e&&typeof e=="object"?e:{},n=t.materials&&typeof t.materials=="object"?t.materials:{},r=t.background&&typeof t.background=="object"?t.background:{},o=t.environment&&typeof t.environment=="object"?t.environment:{},i=t.floor&&typeof t.floor=="object"?t.floor:{},s=t.edges&&typeof t.edges=="object"?t.edges:{},a=t.lighting&&typeof t.lighting=="object"?t.lighting:{},l=!!(t.materials&&typeof t.materials=="object"),u=l&&!Object.hasOwn(n,"tintMode"),d=l&&!Object.hasOwn(n,"emissiveIntensity"),m=yr(n.defaultColor||n.tintColor,Oe.materials.defaultColor),p=y9(n.fillColors,m),g=yr(i.color,Oe.floor?.color||"#141416"),x=Js(g),S={colorMode:ay(t.colorMode,Oe?.colorMode||No.SYSTEM),materials:{defaultColor:p[0]||m,fillColors:p,cycleColors:Ps(n.cycleColors,Oe.materials.cycleColors||!1),overrideSourceColors:Ps(n.overrideSourceColors,Oe.materials.overrideSourceColors||!1),tintMode:w9(n.tintMode,u?"multiply":Oe.materials.tintMode),tintStrength:Ft(n.tintStrength,Oe.materials.tintStrength,0,1),saturation:Ft(n.saturation,Oe.materials.saturation,0,2.5),contrast:Ft(n.contrast,Oe.materials.contrast,0,2.5),brightness:Ft(n.brightness,Oe.materials.brightness,0,2),roughness:Ft(n.roughness,Oe.materials.roughness,0,1),metalness:Ft(n.metalness,Oe.materials.metalness,0,1),clearcoat:Ft(n.clearcoat,Oe.materials.clearcoat,0,1),clearcoatRoughness:Ft(n.clearcoatRoughness,Oe.materials.clearcoatRoughness,0,1),opacity:Ft(n.opacity,Oe.materials.opacity,0,1),envMapIntensity:Ft(n.envMapIntensity,Oe.materials.envMapIntensity,0,4),emissiveIntensity:Ft(n.emissiveIntensity,d?0:Oe.materials.emissiveIntensity,0,2)},edges:{enabled:Ps(s.enabled,Oe.edges.enabled),contrastMode:v9(s.contrastMode,Oe.edges.contrastMode),color:yr(s.color,Oe.edges.color),thickness:Ft(s.thickness,Oe.edges.thickness,.5,6),classes:C9(s.classes,Oe.edges.classes),highlightColor:yr(s.highlightColor,Oe.edges.highlightColor||UP),highlightOpacity:Ft(s.highlightOpacity,Oe.edges.highlightOpacity||1,0,1),highlightThickness:Ft(s.highlightThickness,Oe.edges.highlightThickness||3,.5,6),silhouette:Ps(s.silhouette,Oe.edges.silhouette||!1),silhouetteScale:Ft(s.silhouetteScale,Oe.edges.silhouetteScale||.004,0,.04)},background:{type:E9(r.type,Oe.background.type),solidColor:yr(r.solidColor,Oe.background.solidColor),linearStart:yr(r.linearStart,Oe.background.linearStart),linearEnd:yr(r.linearEnd,Oe.background.linearEnd),linearAngle:Ft(r.linearAngle,Oe.background.linearAngle,-360,360),radialInner:yr(r.radialInner,Oe.background.radialInner),radialOuter:yr(r.radialOuter,Oe.background.radialOuter)},floor:{mode:N9(i.mode,Oe.floor?.mode||Ii.STAGE),color:g,roughness:Ft(i.roughness,Oe.floor?.roughness??.72,0,1),reflectivity:Ft(i.reflectivity,Oe.floor?.reflectivity??.12,0,1),shadowOpacity:Ft(i.shadowOpacity,Oe.floor?.shadowOpacity??.45,0,1),horizonBlend:Ft(i.horizonBlend,Oe.floor?.horizonBlend??0,0,1),gridCenterColor:yr(i.gridCenterColor??i.gridCenter,x.gridCenterColor),gridCellColor:yr(i.gridCellColor??i.gridCell,x.gridCellColor),gridOpacity:Ft(i.gridOpacity,x.gridOpacity,0,1),gridDensity:Ft(i.gridDensity,x.gridDensity,YP,qP)},environment:{enabled:Ps(o.enabled,Oe.environment.enabled),presetId:mK(o.presetId),intensity:Ft(o.intensity,Oe.environment.intensity,0,4),rotationY:Ft(o.rotationY,Oe.environment.rotationY,-Math.PI*2,Math.PI*2),useAsBackground:Ps(o.useAsBackground,Oe.environment.useAsBackground)},lighting:{toneMappingExposure:Ft(a.toneMappingExposure,Oe.lighting.toneMappingExposure,.05,6),directional:{enabled:Ps(a.directional?.enabled,Oe.lighting.directional.enabled),color:yr(a.directional?.color,Oe.lighting.directional.color),intensity:Ft(a.directional?.intensity,Oe.lighting.directional.intensity,0,20),position:Hx(a.directional?.position,Oe.lighting.directional.position)},spot:{enabled:Ps(a.spot?.enabled,Oe.lighting.spot.enabled),color:yr(a.spot?.color,Oe.lighting.spot.color),intensity:Ft(a.spot?.intensity,Oe.lighting.spot.intensity,0,20),angle:Ft(a.spot?.angle,Oe.lighting.spot.angle,.01,Math.PI/2),distance:Ft(a.spot?.distance,Oe.lighting.spot.distance,0,5e3),position:Hx(a.spot?.position,Oe.lighting.spot.position)},point:{enabled:Ps(a.point?.enabled,Oe.lighting.point.enabled),color:yr(a.point?.color,Oe.lighting.point.color),intensity:Ft(a.point?.intensity,Oe.lighting.point.intensity,0,20),distance:Ft(a.point?.distance,Oe.lighting.point.distance,0,5e3),position:Hx(a.point?.position,Oe.lighting.point.position)},ambient:{enabled:Ps(a.ambient?.enabled,Oe.lighting.ambient.enabled),color:yr(a.ambient?.color,Oe.lighting.ambient.color),intensity:Ft(a.ambient?.intensity,Oe.lighting.ambient.intensity,0,20)},hemisphere:{enabled:Ps(a.hemisphere?.enabled,Oe.lighting.hemisphere.enabled),skyColor:yr(a.hemisphere?.skyColor,Oe.lighting.hemisphere.skyColor),groundColor:yr(a.hemisphere?.groundColor,Oe.lighting.hemisphere.groundColor),intensity:Ft(a.hemisphere?.intensity,Oe.lighting.hemisphere.intensity,0,20)}}};return S.modeColors=I9(t.modeColors,S),!Object.hasOwn(t,"colorMode")&&!Object.hasOwn(t,"modeColors")&&pK(S)?Xd(XP(Lw)):S}function hK(e=Oe){return Xd(JSON.parse(JSON.stringify(e)))}function gK(e){const t=String(e||"").trim(),n=W9[t]||t;return uy.some(r=>r.id===n)?n:""}function bK(e){const t=gK(e);return uy.find(n=>n.id===t)||JP}function yK(e){return hK(bK(e).settings)}function xK(e){return yK(e)}function SK(e={},{prefersDark:t=!1,systemFallback:n=No.LIGHT}={}){const r=ay(e?.colorMode,Oe?.colorMode||No.SYSTEM);return r===No.SYSTEM?t===!0||ay(n,No.LIGHT)===No.DARK?No.DARK:No.LIGHT:r}function EK(e={},t={}){const n=Xd(e),r=SK(n,t),o=XP(n);return o.colorMode=r,A9(o,n.modeColors?.[r]),Xd(o)}function wK(e={},{defaultThemeId:t="workbench"}={}){return typeof e.appearance=="string"?{themeId:e.appearance,settings:null}:e.appearance&&typeof e.appearance=="object"&&!Array.isArray(e.appearance)?{themeId:t,settings:e.appearance}:{themeId:t,settings:null}}function vK(e={},{defaultThemeId:t="workbench"}={}){const n=wK(e,{defaultThemeId:t}),r=xK(n.themeId||t),o=Xd(n.settings||r);return typeof e.appearance=="string"?EK(o,{prefersDark:!1}):o}const Ds=Object.freeze({resolutionScale:2,interactionResolutionScale:1.25,detail:1.25,normalSmoothing:1,modelColors:!0,shadows:!0,ambientOcclusion:!0,rimLight:!0}),Xm=Object.freeze({resolutionScale:Object.freeze({min:.5,max:5,step:.05}),interactionResolutionScale:Object.freeze({min:.25,max:4,step:.05}),detail:Object.freeze({min:.25,max:8,step:.05}),normalSmoothing:Object.freeze({min:.25,max:5,step:.05})}),QA=96,CK=.75;function Vg(e,t,{min:n=-1/0,max:r=1/0}={}){const o=Number(e),i=Number.isFinite(o)?o:t;return Math.min(Math.max(i,n),r)}function $g(e,t){return typeof e=="boolean"?e:t}function Ms(e={}){const t=e&&typeof e=="object"?e:{};return{resolutionScale:Vg(t.resolutionScale,Ds.resolutionScale,Xm.resolutionScale),interactionResolutionScale:Vg(t.interactionResolutionScale,Ds.interactionResolutionScale,Xm.interactionResolutionScale),detail:Vg(t.detail,Ds.detail,Xm.detail),normalSmoothing:Vg(t.normalSmoothing,Ds.normalSmoothing,Xm.normalSmoothing),modelColors:$g(t.modelColors,Ds.modelColors),shadows:$g(t.shadows,Ds.shadows),ambientOcclusion:$g(t.ambientOcclusion,Ds.ambientOcclusion),rimLight:$g(t.rimLight,Ds.rimLight)}}function Gg(e={},{interaction:t=!1}={}){const n=Ms(e);return t?n.interactionResolutionScale:n.resolutionScale}function tO(e={},{interaction:t=!1}={}){const n=Ms(e);if(!t)return n;const r=e&&typeof e=="object"?e:{},o=Number.isFinite(Number(r.stepBudget))?Math.max(1,Math.floor(Number(r.stepBudget))):QA;return{...n,detail:Math.min(n.detail,CK),stepBudget:Math.min(o,QA),shadows:!1,ambientOcclusion:!1}}function MK(e,t){const n=Ms(e),r=Ms(t);return Object.keys(Ds).every(o=>n[o]===r[o])}const IK=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;function Yd(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ai(e,t=""){return String(e??t).trim()||t}function Qa(e,t=0){const n=Number(e);return Number.isFinite(n)?n:t}function AK(e,t,n){return Math.min(Math.max(e,t),n)}function nO(e){const t=Ai(e,"number").toLowerCase();return["number","boolean","enum","select","color","string","button"].includes(t)?t==="select"?"enum":t:"number"}function NK(e){return(Array.isArray(e)?e:[]).map(t=>{if(Yd(t)){const r=Ai(t.value);return r?{value:r,label:Ai(t.label,r)}:null}const n=Ai(t);return n?{value:n,label:n}:null}).filter(Boolean)}function bu(e,t){const n=nO(e?.type);if(n==="boolean")return t===!0;if(n==="color"){const i=Ai(t,Ai(e?.defaultValue,"#ffffff"));return IK.test(i)?i:"#ffffff"}if(n==="enum"){const i=Array.isArray(e?.options)?e.options:[],s=Ai(t,i[0]?.value||"");return i.some(a=>a.value===s)?s:i[0]?.value||""}if(n==="string")return String(t??"");if(n==="button")return Math.max(0,Math.floor(Qa(t,0)));const r=Qa(e?.min,0),o=Math.max(Qa(e?.max,r),r);return AK(Qa(t,Qa(e?.defaultValue,r)),r,o)}function _K(e,t){const n=Yd(t)?t:{},r=nO(n.type),o=Qa(n.min,0),i=Math.max(Qa(n.max,r==="number"?1:o),o),s=NK(n.options||n.values),a=r==="boolean"?!1:r==="color"?"#ffffff":r==="enum"?s[0]?.value||"":r==="string"?"":0;return{id:e,type:r,label:Ai(n.label,e),description:Ai(n.description),unit:Ai(n.unit),min:o,max:i,step:Math.max(Qa(n.step,r==="number"?.01:1),0),defaultValue:bu({type:r,min:o,max:i,options:s},n.default??n.defaultValue??a),options:s}}function TK(e){return(Array.isArray(e)?e.map(n=>[n?.id,n]):Object.entries(Yd(e)?e:{})).map(([n,r])=>_K(Ai(n),r)).filter(n=>n.id)}function RK(e){return Object.fromEntries((Array.isArray(e)?e:[]).filter(t=>t?.id).map(t=>[t.id,t]))}function qd(e,t={}){const n=e?.parameterMap||{};return Object.fromEntries(Object.values(n).map(r=>[r.id,bu(r,Yd(t)&&Object.hasOwn(t,r.id)?t[r.id]:r.defaultValue)]))}function PK(e){return(Array.isArray(e)?e.map(n=>[n?.id,n]):Object.entries(Yd(e)?e:{})).map(([n,r])=>{const o=Yd(r)?r:{},i=Ai(n);return i?{id:i,label:Ai(o.label,i),description:Ai(o.description),duration:Math.max(Qa(o.duration??o.durationSeconds,1),.001),loop:o.loop!==!1,update:typeof o.update=="function"?o.update:null,raw:o}:null}).filter(Boolean)}function Zo(e){return Array.isArray(e)}function hc(e,t=0){const n=Number(e);return Number.isFinite(n)?n:t}function li(e){return Zo(e)?e.some(t=>li(t)):!!e}function Fw(e,t){const n=[];for(const r of e)Zo(r)?n.push(...r):n.push(r);return n.length===0&&n.push(0),n.length===1?Array.from({length:t},()=>hc(n[0])):Array.from({length:t},(r,o)=>hc(n[o],0))}function ir(e=0,t=void 0){return Fw(t===void 0?[e]:[e,t],2)}function Jo(e=0,t=void 0,n=void 0){return Fw(t===void 0&&n===void 0?[e]:[e,t,n],3)}function zw(e=0,t=void 0,n=void 0,r=void 0){return Fw(t===void 0&&n===void 0&&r===void 0?[e]:[e,t,n,r],4)}function Gi(e,t){return Zo(e)?e.map(n=>t(n)):t(e)}function pl(e,t,n){if(Zo(e)&&Zo(t)){const r=Math.max(e.length,t.length);return Array.from({length:r},(o,i)=>n(e[i]??0,t[i]??0))}return Zo(e)?e.map(r=>n(r,t)):Zo(t)?t.map(r=>n(e,r)):n(e,t)}function Eo(e,t){return pl(e,t,(n,r)=>n+r)}function ln(e,t){return pl(e,t,(n,r)=>n-r)}function lt(e,t){return pl(e,t,(n,r)=>n*r)}function Zi(e,t){return pl(e,t,(n,r)=>n/r)}function rO(e){return Gi(e,t=>-t)}function dy(e){return Gi(e,Math.abs)}function oO(e,t){return pl(e,t,Math.min)}function Fp(e,t){return pl(e,t,Math.max)}function Sd(e,t,n){return oO(Fp(e,t),n)}function w1(e,t,n){return Eo(lt(e,ln(1,n)),lt(t,n))}function OK(e,t,n){const r=Sd(Zi(ln(n,e),ln(t,e)),0,1);return lt(lt(r,r),ln(3,lt(2,r)))}function Bw(e,t){return pl(e,t,(n,r)=>n-r*Math.floor(n/r))}function zr(e){return Zo(e)?Math.hypot(...e):Math.abs(e)}function Ln(e,t){const n=Zo(e)?e:[e],r=Zo(t)?t:[t],o=Math.max(n.length,r.length);let i=0;for(let s=0;s1e-12?Zi(e,t):lt(e,0)}function iO(e){const t={x:0,y:1,z:2,w:3,r:0,g:1,b:2,a:3,s:0,t:1,p:2,q:3};return String(e||"").split("").map(n=>t[n])}function Vr(e,t){const n=iO(t);if(!n.length||n.some(i=>i===void 0))throw new Error(`Unsupported GLSL member access: .${t}`);const r=Zo(e)?e:[e],o=n.map(i=>r[i]??0);return o.length===1?o[0]:o}function kK(e,t,n){if(!Zo(e))throw new Error(`Cannot assign .${t} on a scalar value`);const r=iO(t),o=Zo(n)?n:[n];return r.forEach((i,s)=>{if(i===void 0)throw new Error(`Unsupported GLSL member assignment: .${t}`);e[i]=hc(o[s],o[0]??0)}),e}function sO(e,t,n,r,o){const i=(o-r)/(n-t);return(e-t)*i+r}function DK(e,t,n,r,o){return Math.min(Math.max(sO(e,t,n,r,o),r),o)}function jK(e,t){return(e-t)/(e+t)}function LK(e,t,n){return e*Math.cos(n)+t*Math.sin(n)}function qy(e,t){if(Zo(e)||Zo(t))return pl(e,t,qy);const n=t*.5,r=t*.25,o=Bw(e+n,t);return r-Math.abs(o-n)}function Zy(e,t){return Eo(qy(e,t),lt(t,.25))}function aO(e,t){return qy(ln(e,lt(t,.5)),t)}function v1(e,t){return Eo(aO(e,t),lt(t,.25))}function lh(e,t){return ln(Bw(Eo(e,lt(t,.5)),t),lt(t,.5))}function tN(e,t,n){const r=Math.max(n,0),o=Fp(Eo(ir(e,t),r),0);return Math.min(-r,Math.max(e,t))+zr(o)}function nN(e,t,n){return Math.max(Math.max(e,t),(e+t+n)*.7071067811865476)}function rN(e,t,n){const r=Math.max(n,1e-6)*.5;return r*Math.log(Math.exp(e/r)+Math.exp(t/r))}function oN(e,t,n,r){const o=Math.max(n,0),i=Math.max(r,1e-6),s=Fp(Eo(ir(e,t),o),0);return Math.min(-o,Math.max(e,t))+Math.pow(Math.pow(s[0],i)+Math.pow(s[1],i),1/i)}function iN(e,t,n){const r=Math.max(e,t),o=Math.max(n,0);if(o<=0)return r;const i=e+t-Math.sqrt(e*e+t*t),s=Math.min(Math.max((r+o)/o,0),1),a=s*s*(3-2*s);return r<-o?r:w1(r,i,a)}const nt={float:(e=0)=>hc(e),int:(e=0)=>Math.trunc(hc(e)),bool:(e=!1)=>li(e),vec2:ir,vec3:Jo,vec4:zw,abs:dy,min:oO,max:Fp,clamp:Sd,mix:w1,smoothstep:OK,mod:Bw,length:zr,dot:Ln,cross:eN,normalize:Id,sin:e=>Gi(e,Math.sin),cos:e=>Gi(e,Math.cos),tan:e=>Gi(e,Math.tan),atan:(...e)=>e.length>=2?Math.atan2(e[0],e[1]):Gi(e[0],Math.atan),pow:(e,t)=>pl(e,t,Math.pow),sqrt:e=>Gi(e,Math.sqrt),exp:e=>Gi(e,Math.exp),log:e=>Gi(e,Math.log),floor:e=>Gi(e,Math.floor),ceil:e=>Gi(e,Math.ceil),fract:e=>Gi(e,t=>t-Math.floor(t)),sign:e=>Gi(e,Math.sign),implicit_clamp01:e=>Sd(e,0,1),implicit_linear_map:sO,implicit_ramp:DK,implicit_two_body_field:jK,implicit_two_body_polar:LK,implicit_triangle_wave_even:qy,implicit_triangle_wave_even_positive:Zy,implicit_triangle_wave_odd:aO,implicit_triangle_wave_odd_positive:v1,implicit_repeat_centered:lh,implicit_intersect_sharp:(e,t)=>Math.max(e,t),implicit_union_sharp:(e,t)=>Math.min(e,t),implicit_intersect_round:tN,implicit_union_round:(e,t,n)=>-tN(-e,-t,n),implicit_intersect_chamfer:nN,implicit_union_chamfer:(e,t,n)=>-nN(-e,-t,n),implicit_intersect_exp:rN,implicit_union_exp:(e,t,n)=>-rN(-e,-t,n),implicit_intersect_lp_norm:oN,implicit_union_lp_norm:(e,t,n,r)=>-oN(-e,-t,n,r),implicit_intersect_rvachev:iN,implicit_union_rvachev:(e,t,n)=>-iN(-e,-t,n),implicit_plane2:(e,t,n)=>Ln(ln(e,t),Id(n)),implicit_line_segment2:(e,t,n)=>{const r=ln(n,t),o=Ln(r,r);if(o<1e-12)return zr(ln(e,t));const i=Sd(Ln(ln(e,t),r)/o,0,1);return zr(ln(e,Eo(t,lt(i,r))))},implicit_sphere:(e,t,n)=>zr(ln(e,t))-n,implicit_box_centered:(e,t,n)=>{const r=ln(dy(ln(e,n)),lt(t,.5));return zr(Fp(r,0))+Math.min(Math.max(r[0],Math.max(r[1],r[2])),0)},implicit_plane:(e,t,n)=>Ln(ln(e,t),Id(n)),implicit_line_segment:(e,t,n)=>{const r=ln(n,t),o=Ln(r,r);if(o<1e-12)return zr(ln(e,t));const i=Sd(Ln(ln(e,t),r)/o,0,1);return zr(ln(e,Eo(t,lt(i,r))))},implicit_torus:(e,t,n)=>{const r=ir(zr(Vr(e,"xy"))-t,Vr(e,"z"));return zr(r)-n},implicit_axis:(e,t,n)=>{const r=zr(n);if(r<1e-12)return zr(ln(e,t));const o=Zi(n,r),i=ln(e,t);return zr(ln(i,lt(Ln(i,o),o)))},implicit_cylinder:(e,t,n,r)=>nt.implicit_axis(e,t,n)-r,implicit_cylinder_capped:(e,t,n,r)=>{const o=ln(n,t),i=nt.implicit_cylinder(e,t,o,r),s=-nt.implicit_plane(e,t,o),a=nt.implicit_plane(e,n,o);return Math.max(i,Math.max(s,a))},implicit_capsule:(e,t,n,r)=>nt.implicit_line_segment(e,t,n)-r,implicit_cone_capsule:(e,t,n,r,o)=>{const i=ln(n,t),s=Ln(i,i);if(s<1e-12)return nt.implicit_sphere(e,t,r);const a=Sd(Ln(ln(e,t),i)/s,0,1),l=w1(r,o,a);return zr(ln(e,Eo(t,lt(a,i))))-l},implicit_cone:(e,t,n,r)=>{const o=zr(n);if(o<1e-12)return zr(ln(e,t));const i=Zi(n,o),s=ln(e,t),a=Ln(s,i);return zr(ln(s,lt(a,i)))-a*Math.tan(r)},implicit_cone_capped:(e,t,n,r,o)=>{const i=ln(n,t),s=zr(i);if(s<1e-12)return nt.implicit_sphere(e,t,r);const a=Math.atan2(Math.abs(o-r),s),l=rMath.abs(e+n*t*.5)-t*.5,implicit_rotate_axis:(e,t,n,r)=>{const o=Id(n),i=ln(e,t),s=Math.cos(r),a=Math.sin(r);return Eo(Eo(Eo(t,lt(i,s)),lt(eN(o,i),a)),lt(o,Ln(o,i)*(1-s)))},implicit_remap_cylindrical:(e,t)=>{const n=zr(Vr(e,"xy")),r=Math.atan2(e[1],e[0]);return Jo(n,r*(t/(Math.PI*2)),e[2])},implicit_tpms_gyroid:(e,t,n)=>{const r=lt(e,Zi(Math.PI*2,t)),o=Vr(r,"yzx");return Ln(n,lt(nt.sin(r),nt.cos(o)))*(t[0]+t[1]+t[2])/18},implicit_tpms_schwarz:(e,t,n,r)=>{const o=lt(e,Zi(Math.PI*2,t)),i=Vr(o,"yzx"),s=Eo(Jo(-(1-r)),lt(nt.sin(o),r));return Ln(n,lt(nt.cos(i),s))*(t[0]+t[1]+t[2])/36},implicit_diamond:()=>0};nt.implicit_tpms_diamond=(e,t,n,r)=>{const o=lt(e,Zi(Math.PI*2,t)),i=Vr(o,"yzx"),s=Vr(o,"zxy"),a=nt.sin(o),l=nt.cos(i),u=nt.cos(s),d=1-r,m=d*a[0]*a[1]*a[2],p=Ln(n,lt(lt(a,l),Eo(lt(u,d),Jo(r))));return(m+p)*(t[0]+t[1]+t[2])/(6*2.8284271247461903*2)};nt.implicit_tpms_lidinoid=(e,t,n,r)=>{const o=lt(e,Zi(Math.PI*2,t)),i=Vr(o,"yzx"),s=Vr(o,"zxy"),a=nt.cos(lt(2,o)),l=Vr(a,"yzx"),u=1-r,d=Ln(n,lt(lt(nt.sin(s),nt.cos(i)),Eo(lt(nt.sin(lt(2,o)),u),Jo(r)))),m=u*Ln(a,l);return(d-m)*(t[0]+t[1]+t[2])/72};nt.implicit_tpms_neovius=(e,t,n,r)=>{const o=lt(e,Zi(Math.PI*2,t)),i=lt(nt.cos(o),n),s=-Ln(i,Jo(1)),a=(1-r)*(4/3)*i[0]*i[1]*i[2];return(s-a)*(t[0]+t[1]+t[2])/(6*(26/3))};nt.implicit_tpms_split_p=(e,t,n,r,o)=>{const i=lt(e,Zi(Math.PI*2,t)),s=Vr(i,"yzx"),a=Vr(i,"zxy"),l=nt.sin(lt(2,i)),u=nt.cos(lt(2,i)),d=-n*Ln(lt(lt(l,nt.cos(s)),nt.sin(a)),Jo(1)),m=r*Ln(lt(l,u),Jo(1)),p=o*Ln(u,Jo(1));return(d+m+p)*(t[0]+t[1]+t[2])/36};nt.implicit_tpms_iwp=(e,t,n)=>{const r=lt(e,Zi(Math.PI*2,t)),o=Vr(r,"yzx"),i=2*Ln(lt(lt(n,nt.cos(r)),nt.cos(o)),Jo(1)),s=Ln(nt.cos(lt(2,r)),Jo(1));return(i-s)*(t[0]+t[1]+t[2])/48};nt.implicit_cubic_grid=(e,t)=>{const n=Zy(e,t);return Math.min(n[0],Math.min(n[1],n[2]))};nt.implicit_square_honeycomb=(e,t)=>{const n=Zy(Vr(e,"xy"),t);return Math.min(n[0],n[1])};nt.implicit_square_honeycomb_reinforced=(e,t,n,r,o)=>{const i=Vr(e,"xy"),s=Zy(i,t),a=Math.min(s[0],s[1]),l=lh(i,t),u=Math.PI*n;let d=Math.abs(nt.implicit_plane2(l,ir(0),ir(Math.cos(u),Math.sin(u))));if(o>.5){const m=Math.PI*r,p=Math.abs(nt.implicit_plane2(l,ir(0),ir(Math.cos(m),Math.sin(m))));d=Math.min(d,p)}return Math.min(a,d)};nt.implicit_square_diagonal_honeycomb=(e,t)=>{const n=ir(t[0]+t[1]),r=lh(Vr(e,"xy"),n),o=Math.abs(nt.implicit_plane2(r,ir(0),ir(t[1],t[0]))),i=Math.abs(nt.implicit_plane2(r,ir(0),ir(t[1],-t[0])));return Math.min(o,i)};nt.implicit_octet_honeycomb=(e,t)=>{const n=Vr(e,"xy"),r=nt.implicit_square_honeycomb(e,t),o=v1(n,t),i=Math.min(o[0],o[1]),s=zr(t)*.5,a=ir((n[0]+n[1])/1.4142135623730951,(n[0]-n[1])/1.4142135623730951),l=v1(a,ir(s));return Math.min(Math.min(r,i),Math.min(l[0],l[1]))};nt.implicit_hexagonal_honeycomb=(e,t,n)=>{const r=Vr(e,"xy"),o=lt(t,.5),i=lt(t,.25),s=ir(0,(1-n)*o[1]),a=ir(o[0],n*o[1]),l=dy(lh(r,t)),u=ir(l[0]-o[0],o[1]-l[1]),d=Math.min(nt.implicit_line_segment2(l,s,ir(0,t[1])),Math.min(nt.implicit_line_segment2(l,s,a),nt.implicit_line_segment2(l,s,ir(-a[0],a[1])))),m=Math.min(nt.implicit_line_segment2(u,s,ir(0,t[1])),Math.min(nt.implicit_line_segment2(u,s,a),nt.implicit_line_segment2(u,s,ir(-a[0],a[1]))));return l[0]{const n=dy(lh(Vr(e,"xy"),t)),r=lt(t,.5),o=lt(t,.25),i=ir(0,1),s=Id(ir(t[1],t[0])),a=Id(ir(t[1],-t[0])),l=Math.min(Math.abs(Ln(n,i)),Math.min(Math.abs(Ln(n,s)),Math.abs(Ln(n,a)))),u=ln(n,r),d=Math.min(Math.abs(Ln(u,i)),Math.min(Math.abs(Ln(u,s)),Math.abs(Ln(u,a))));return n[1]=","==","!=","&&","||","+=","-=","*=","/=","++","--"];function zK(e){return String(e||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"")}function BK(e){const t=[],n=zK(e);let r=0;for(;rn.startsWith(l,r));if(a){t.push({type:"operator",value:a}),r+=a.length;continue}t.push({type:"punct",value:o}),r+=1}return t}class VK{constructor(t){this.tokens=t,this.index=0}peek(t=0){return this.tokens[this.index+t]||null}consume(t=null){const n=this.peek();if(!n)throw new Error(`Expected ${t||"token"}, reached end of GLSL source`);if(t!==null&&n.value!==t)throw new Error(`Expected ${t}, got ${n.value}`);return this.index+=1,n}match(t){return this.peek()?.value===t?(this.index+=1,!0):!1}skipQualifiers(){for(;Kx.has(this.peek()?.value);)this.consume()}parseProgram(){const t=[],n=new Map;for(;this.peek();){this.skipQualifiers();const r=this.peek()?.value;if(!Em.has(r)&&r!=="void"){this.consume();continue}this.consume();const o=this.consume().value;if(this.match("(")){const i=[];if(!this.match(")")){do{this.skipQualifiers();const s=this.consume().value,a=this.consume().value;i.push({type:s,name:a})}while(this.match(","));this.consume(")")}n.set(o,{name:o,params:i,returnType:r,body:this.parseBlock()})}else{let i={type:"literal",value:0};this.match("=")&&(i=this.parseExpression()),this.consume(";"),t.push({type:"var",varType:r,name:o,init:i})}}return{globals:t,functions:n}}parseBlock(){this.consume("{");const t=[];for(;this.peek()&&this.peek().value!=="}";)t.push(this.parseStatement());return this.consume("}"),{type:"block",body:t}}parseStatement(){if(this.peek()?.value==="{")return this.parseBlock();if(this.match(";"))return{type:"empty"};if(this.match("return")){const n=this.parseExpression();return this.consume(";"),{type:"return",expression:n}}if(this.match("if")){this.consume("(");const n=this.parseExpression();this.consume(")");const r=this.parseStatement(),o=this.match("else")?this.parseStatement():null;return{type:"if",condition:n,consequent:r,alternate:o}}if(this.match("for")){this.consume("(");const n=this.parseForPart(";");this.consume(";");const r=this.peek()?.value===";"?null:this.parseExpression();this.consume(";");const o=this.peek()?.value===")"?null:this.parseExpression();return this.consume(")"),{type:"for",init:n,condition:r,update:o,body:this.parseStatement()}}if(Em.has(this.peek()?.value)||Kx.has(this.peek()?.value)&&Em.has(this.peek(1)?.value)){const n=this.parseVariableDeclaration();return this.consume(";"),n}const t=this.parseExpression();return this.consume(";"),{type:"expr",expression:t}}parseForPart(){return Em.has(this.peek()?.value)||Kx.has(this.peek()?.value)&&Em.has(this.peek(1)?.value)?this.parseVariableDeclaration():this.peek()?.value===";"?{type:"empty"}:{type:"expr",expression:this.parseExpression()}}parseVariableDeclaration(){this.skipQualifiers();const t=this.consume().value,n=this.consume().value;let r={type:"literal",value:lO(t)};return this.match("=")&&(r=this.parseExpression()),{type:"var",varType:t,name:n,init:r}}parseExpression(){return this.parseAssignment()}parseAssignment(){const t=this.parseTernary(),n=this.peek()?.value;return["=","+=","-=","*=","/="].includes(n)?(this.consume(),{type:"assign",op:n,left:t,right:this.parseAssignment()}):t}parseTernary(){const t=this.parseLogicalOr();if(!this.match("?"))return t;const n=this.parseExpression();return this.consume(":"),{type:"ternary",condition:t,consequent:n,alternate:this.parseExpression()}}parseLogicalOr(){let t=this.parseLogicalAnd();for(;this.match("||");)t={type:"binary",op:"||",left:t,right:this.parseLogicalAnd()};return t}parseLogicalAnd(){let t=this.parseEquality();for(;this.match("&&");)t={type:"binary",op:"&&",left:t,right:this.parseEquality()};return t}parseEquality(){let t=this.parseComparison();for(;["==","!="].includes(this.peek()?.value);)t={type:"binary",op:this.consume().value,left:t,right:this.parseComparison()};return t}parseComparison(){let t=this.parseAdditive();for(;["<",">","<=",">="].includes(this.peek()?.value);)t={type:"binary",op:this.consume().value,left:t,right:this.parseAdditive()};return t}parseAdditive(){let t=this.parseMultiplicative();for(;["+","-"].includes(this.peek()?.value);)t={type:"binary",op:this.consume().value,left:t,right:this.parseMultiplicative()};return t}parseMultiplicative(){let t=this.parseUnary();for(;["*","/"].includes(this.peek()?.value);)t={type:"binary",op:this.consume().value,left:t,right:this.parseUnary()};return t}parseUnary(){return this.match("+")?this.parseUnary():this.match("-")?{type:"unary",op:"-",argument:this.parseUnary()}:this.match("!")?{type:"unary",op:"!",argument:this.parseUnary()}:this.match("++")?{type:"update",op:"++",argument:this.parseUnary(),prefix:!0}:this.match("--")?{type:"update",op:"--",argument:this.parseUnary(),prefix:!0}:this.parsePostfix()}parsePostfix(){let t=this.parsePrimary();for(;;){if(this.match(".")){t={type:"member",object:t,property:this.consume().value};continue}if(this.match("(")){const n=[];if(!this.match(")")){do n.push(this.parseExpression());while(this.match(","));this.consume(")")}t={type:"call",callee:t,args:n};continue}if(this.match("++")){t={type:"update",op:"++",argument:t,prefix:!1};continue}if(this.match("--")){t={type:"update",op:"--",argument:t,prefix:!1};continue}break}return t}parsePrimary(){const t=this.consume();if(t.type==="number")return{type:"literal",value:t.value};if(t.value==="true"||t.value==="false")return{type:"literal",value:t.value==="true"};if(t.value==="("){const n=this.parseExpression();return this.consume(")"),n}if(t.type==="identifier")return{type:"identifier",name:t.value};throw new Error(`Unexpected GLSL token: ${t.value}`)}}function lO(e){return e==="bool"?!1:e==="vec2"?ir(0):e==="vec3"?Jo(0):e==="vec4"?zw(0):0}class cO extends Error{constructor(t){super("return"),this.value=t}}class sN{constructor(t=null){this.parent=t,this.values=new Map}has(t){return this.values.has(t)||!!this.parent?.has(t)}get(t){if(this.values.has(t))return this.values.get(t);if(this.parent)return this.parent.get(t);throw new Error(`Unknown GLSL identifier: ${t}`)}set(t,n){if(this.values.has(t)){this.values.set(t,Ib(n));return}if(this.parent?.has(t)){this.parent.set(t,n);return}this.values.set(t,Ib(n))}define(t,n){this.values.set(t,Ib(n))}}function Ib(e){return Zo(e)?[...e]:e}function Ab(e,t){return t==="int"?Math.trunc(hc(e)):t==="float"?hc(e):t==="bool"?li(e):t==="vec2"?ir(e):t==="vec3"?Jo(e):t==="vec4"?zw(e):e}function $K(e,t,n){switch(e){case"+":return Eo(t,n);case"-":return ln(t,n);case"*":return lt(t,n);case"/":return Zi(t,n);case"<":return t":return t>n;case"<=":return t<=n;case">=":return t>=n;case"==":return t===n;case"!=":return t!==n;case"&&":return li(t)&&li(n);case"||":return li(t)||li(n);default:throw new Error(`Unsupported GLSL operator: ${e}`)}}function C1(e,t,n){if(e.type==="identifier")return{get:()=>t.get(e.name),set:r=>(t.set(e.name,r),r)};if(e.type==="member"){const r=C1(e.object,t);return{get:()=>Vr(r.get(),e.property),set:o=>{const i=r.get();return kK(i,e.property,o),r.set(i),o}}}throw new Error("Unsupported GLSL assignment target")}function io(e,t,n){switch(e.type){case"literal":return Ib(e.value);case"identifier":return t.get(e.name);case"member":return Vr(io(e.object,t,n),e.property);case"unary":{const r=io(e.argument,t,n);return e.op==="-"?rO(r):e.op==="!"?!li(r):r}case"update":{const r=C1(e.argument,t),o=r.get(),i=e.op==="++"?Eo(o,1):ln(o,1);return r.set(i),e.prefix?i:o}case"binary":return e.op==="&&"?li(io(e.left,t,n))&&li(io(e.right,t,n)):e.op==="||"?li(io(e.left,t,n))||li(io(e.right,t,n)):$K(e.op,io(e.left,t,n),io(e.right,t,n));case"ternary":return li(io(e.condition,t,n))?io(e.consequent,t,n):io(e.alternate,t,n);case"assign":{const r=C1(e.left,t),o=io(e.right,t,n),i=r.get(),s=e.op==="="?o:e.op==="+="?Eo(i,o):e.op==="-="?ln(i,o):e.op==="*="?lt(i,o):Zi(i,o);return r.set(s)}case"call":{const r=e.callee.type==="identifier"?e.callee.name:"",o=e.args.map(i=>io(i,t,n));return nt[r]?nt[r](...o):n.call(r,o)}default:throw new Error(`Unsupported GLSL expression node: ${e.type}`)}}function Yc(e,t,n){switch(e.type){case"empty":return;case"block":for(const r of e.body)Yc(r,t,n);return;case"var":t.define(e.name,Ab(io(e.init,t,n),e.varType));return;case"expr":io(e.expression,t,n);return;case"return":throw new cO(io(e.expression,t,n));case"if":li(io(e.condition,t,n))?Yc(e.consequent,t,n):e.alternate&&Yc(e.alternate,t,n);return;case"for":{Yc(e.init,t,n);for(let r=0;r<1e4;r+=1){if(e.condition&&!li(io(e.condition,t,n)))return;Yc(e.body,t,n),e.update&&io(e.update,t,n)}throw new Error("GLSL for-loop exceeded exporter safety limit")}default:throw new Error(`Unsupported GLSL statement node: ${e.type}`)}}function GK(e){const t=String(e||"").trim();if(!t)throw new Error("Implicit CAD model has no GLSL source");return`${t} float implicit_distance(vec3 p) { return sdf(p); } `}function UK(e,t,n){const r=new VK(BK(t)).parseProgram();if(!r.functions.has(n))throw new Error(`Implicit CAD GLSL source did not define ${n}`);const o=new sN;for(const[s,a]of Object.entries({PI:Math.PI,TWO_PI:Math.PI*2}))o.define(s,a);for(const[s,a]of Object.entries(e?.uniforms||{}))o.define(s,Ab(a?.value,a?.type));const i={call(s,a){const l=r.functions.get(s);if(!l)throw new Error(`Unknown GLSL function: ${s}`);const u=new sN(o);l.params.forEach((d,m)=>{u.define(d.name,Ab(a[m],d.type))});try{Yc(l.body,u,i)}catch(d){if(d instanceof cO)return Ab(d.value,l.returnType);throw d}return lO(l.returnType)}};for(const s of r.globals)Yc(s,o,i);return i}function uO(e){const t=GK(e?.glslSource||e?.distanceSource),n=UK(e,t,"implicit_distance");return(r,o,i)=>hc(n.call("implicit_distance",[Jo(r,o,i)]),1e6)}const dO="implicit.js/0.1.0",M1="implicit",xp=Object.freeze({min:[-50,-50,-50],max:[50,50,50]}),Nb=Object.freeze([4,8,16,32,64,128,256,512]),WK=5,HK=9,KK=32,Vw="#f4f4f5",I1=/^#(?:[0-9a-fA-F]{3}){1,2}$/,XK=/^[A-Za-z_][A-Za-z0-9_]*$/,aN=Object.freeze(new Set(["float","int","bool","vec2","vec3","vec4"])),fO=Object.freeze({number:"float",boolean:"bool",color:"vec3",button:"int"});function gc(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ts(e,t=0){const n=Number(e);return Number.isFinite(n)?n:t}function Ym(e,t){const n=Number(e);return Number.isFinite(n)&&n>0?n:t}function lN(e,t){const n=Array.isArray(e)||ArrayBuffer.isView(e)?e:[];return[0,1,2].map(r=>ts(n[r],t[r]||0))}function YK(e,t,n=[]){const r=Array.isArray(e)||ArrayBuffer.isView(e)?e:[];return Array.from({length:t},(o,i)=>ts(r[i],n[i]||0))}function $w(e,t=xp){const n=Ym(e,null),r=n?{min:[-n,-n,-n],max:[n,n,n]}:Array.isArray(e)&&e.length>=2?{min:e[0],max:e[1]}:gc(e)?e:t,o=lN(r.min,xp.min),i=lN(r.max,xp.max);for(let s=0;s<3;s+=1)if(i[s]<=o[s]){const a=(o[s]+i[s])/2;o[s]=a-.5,i[s]=a+.5}return{min:o,max:i}}function zp(e){return{min:[...e.min],max:[...e.max]}}function qK(e){return e==null||String(e).trim().toLowerCase()==="auto"?!1:!(gc(e)&&e.auto===!0)}function mO(e){return[e.max[0]-e.min[0],e.max[1]-e.min[1],e.max[2]-e.min[2]]}function cN(e,t,n){const r=Math.max(ts(n,0),.25);return $w({min:[e[0]-r,e[1]-r,e[2]-r],max:[t[0]+r,t[1]+r,t[2]+r]})}function uN(e,t,n){const o=mO(t).map(d=>d/Math.max(n-1,1)),i=Math.max(Math.min(...o)*.35,.002),s=[1/0,1/0,1/0],a=[-1/0,-1/0,-1/0];let l=0,u=!1;for(let d=0;di||(l+=1,s[0]=Math.min(s[0],y),s[1]=Math.min(s[1],g),s[2]=Math.min(s[2],m),a[0]=Math.max(a[0],y),a[1]=Math.max(a[1],g),a[2]=Math.max(a[2],m),S<=0&&(x===0||p===0||d===0||x===n-1||p===n-1||d===n-1)&&(u=!0))}}}return{hitCount:l,hitMin:s,hitMax:a,boundaryTouch:u,step:o,threshold:i}}function ZK(e,t){const n=e.parameters.filter(o=>o.type==="number").filter(o=>!pO(o)).reduce((o,i)=>{const s=Math.abs(ts(t[i.id],0));return Math.max(o,s)},1),r=Math.max(n*3,4);return Nb.find(o=>o>=r)||Nb[Nb.length-1]}function JK(e,t,n){let r=null;try{r=uO(e)}catch{return zp(xp)}let o=null;const i=ZK(t,n.params);for(const s of Nb.filter(a=>a>=i)){const a=$w(s),l=uN(r,a,WK);if(!l.hitCount)continue;const u=Math.max(Math.max(...l.step)*1.5,s*.06,.5);if(o=cN(l.hitMin,l.hitMax,u),!l.boundaryTouch)break}if(!o)return zp(xp);for(let s=0;s<1;s+=1){const a=uN(r,o,HK);if(!a.hitCount)break;const l=Math.max(Math.max(...a.step)*1.1,Math.max(...mO(o))*.025,.25);o=cN(a.hitMin,a.hitMax,l)}return o}function pO(e){const t=String(e?.unit||"").trim().toLowerCase();if(t==="deg"||t==="rad")return!0;const n=`${e?.id||""} ${e?.label||""}`.toLowerCase();return["angle","phase","rotation","rotate","orbit","spin","yaw","pitch","roll"].some(r=>n.includes(r))}function QK(e,t,n){const r=e.parameters.filter(o=>!pO(o)).filter(o=>fO[o.type]).filter(o=>o.type!=="color").map(o=>{const i=t[o.id];return typeof i=="number"?`${o.id}:${Number.isFinite(i)?i.toPrecision(8):"0"}`:typeof i=="boolean"?`${o.id}:${i?"1":"0"}`:`${o.id}:${String(i??"")}`}).join(";");return`${n.length}:${r}`}function e7(e,t,n){return e?e.map.has(t)?zp(e.map.get(t)):n&&e.last?zp(e.last):null:null}function t7(e,t,n){if(!e)return;const r=zp(n);for(e.map.set(t,r),e.last=r;e.map.size>KK;){const o=e.map.keys().next().value;e.map.delete(o)}}function n7(e,t,n,r,o){if(qK(e))return{bounds:$w(e),source:"explicit"};const i=QK(n,r.params,t.glslSource),s=e7(o,i,r.animationState.playing);if(s)return{bounds:s,source:"auto"};const a=JK(t,n,r);return t7(o,i,a),{bounds:a,source:"auto"}}function hO(e,t=Vw){const n=String(e||"").trim();return I1.test(n)?n:t}function r7(e,t=Vw){const n=hO(e,t),r=n.length===4?`${n[1]}${n[1]}${n[2]}${n[2]}${n[3]}${n[3]}`:n.slice(1);return[parseInt(r.slice(0,2),16)/255,parseInt(r.slice(2,4),16)/255,parseInt(r.slice(4,6),16)/255]}function js(e,t){return typeof e=="function"?e(t):e}function o7(){const e={};return{color:hO(e.color,Vw),roughness:Math.min(Math.max(ts(e.roughness,.75),0),1),metalness:Math.min(Math.max(ts(e.metalness,.02),0),1)}}function i7(e){return typeof e=="function"?e():gc(e)?e.default!==void 0?typeof e.default=="function"?e.default():e.default:e.model!==void 0?typeof e.model=="function"?e.model():e.model:e:e}function s7(e,t={}){const n=js(e,t),r=gc(n)&&Object.hasOwn(n,"value")?js(n.value,t):n,o=gc(n)?String(n.type||n.kind||"").trim().toLowerCase():"",i=aN.has(o)?o:typeof r=="boolean"?"bool":typeof r=="number"?"float":typeof r=="string"&&I1.test(r)?"vec3":Array.isArray(r)||ArrayBuffer.isView(r)?`vec${Math.min(Math.max(r.length,2),4)}`:"";if(!aN.has(i))return null;if(i==="bool")return{type:i,value:r===!0};if(i==="int")return{type:i,value:Math.trunc(ts(r,0))};if(i==="float")return{type:i,value:ts(r,0)};if(typeof r=="string"&&I1.test(r))return{type:i,value:r7(r)};const s=Number(i.slice(3)),a=Array.from({length:s},()=>0);return{type:i,value:YK(r,s,a)}}function a7(e=[],t={}){return Object.fromEntries(e.map(n=>{const r=String(n?.id||"").trim();if(!XK.test(r)||r.startsWith("gl_"))throw new Error(`Implicit CAD param "${r}" is not a valid GLSL uniform identifier.`);const o=fO[n.type];if(!o)return null;const i=s7({type:o,value:t[n.id]});return i?[r,i]:null}).filter(Boolean))}function l7(e,t={}){return String(js(e.glsl??e.glslSource,t)||"").trim()}function c7(e={}){return{activeId:String(e?.activeId||"").trim(),playing:e?.playing===!0,elapsedSec:Math.max(ts(e?.elapsedSec??e?.elapsed,0),0),speed:Math.min(Math.max(ts(e?.speed,1),.1),5)}}function u7(e,t){const n=Array.isArray(e?.animations)?e.animations:[];if(!n.length)return null;const r=String(t||"").trim();return n.find(o=>o.id===r)||n[0]||null}function d7(e,t={},n={}){const r=qd(e,t),o=c7(n),i=u7(e,o.activeId),s=Math.max(Number(i?.duration)||0,.001),a=Math.min(o.elapsedSec,s),l=i?Math.min(Math.max(a/s,0),1):0;return{...r,params:r,parameterValues:r,animation:i,animationState:{...o,activeId:i?.id||o.activeId,duration:i?.duration||0,loop:i?.loop!==!1},elapsed:a,elapsedSec:a,duration:i?.duration||0,progress:l,cycle:s>0?a/s:0,t:a,time:a}}function f7(e,t,n={},r={},{sourceUrl:o="",autoBoundsCache:i=null}={}){const s=d7(t,n,r),a=e;if(!gc(a))throw new Error("Implicit CAD module must export an object, or a function returning an object.");const l=a7(t.parameters,s.params),u=l7(a,s);if(!u)throw new Error("Implicit CAD module must export GLSL code in glsl.");const d=n7(js(a.bounds,s),{glslSource:u,uniforms:l},t,s,i),m=d.bounds,p=[m.max[0]-m.min[0],m.max[1]-m.min[1],m.max[2]-m.min[2]],g=[(m.min[0]+m.max[0])/2,(m.min[1]+m.max[1])/2,(m.min[2]+m.max[2])/2],x=Math.max(Math.hypot(p[0],p[1],p[2])/2,.001),y=js(a.render,s),S=gc(y)?y:{},b=Ym(js(S.epsilon,s),Math.max(x*7e-4,.002)),I=Ym(js(S.normalEpsilon,s),Math.max(b*2.5,x*.001)),A=Math.min(Math.max(ts(js(S.stepScale,s),.45),.05),1),N=Ym(js(S.maxStep,s),Math.max(x*.035,b*10));return{schema:String(a.schema||dO),kind:M1,name:String(a.name||a.title||"Implicit CAD").trim()||"Implicit CAD",description:String(a.description||"").trim(),units:String(a.units||"mm").trim()||"mm",sourceUrl:String(o||a.sourceUrl||"").trim(),parameters:t.parameters,parameterMap:t.parameterMap,defaultParameterValues:t.defaultParameterValues,parameterValues:s.params,animations:t.animations,animationState:s.animationState,glslSource:u,distanceSource:u,colorSource:/\bvec3\s+color\s*\(/.test(u)?u:"",uniforms:l,uniformSignature:Object.entries(l).map(([P,R])=>`${P}:${R.type}`).sort().join(";"),bounds:m,boundsSource:d.source,center:g,size:p,radius:x,material:o7(),background:{},maxSteps:Math.max(16,Math.min(Math.floor(ts(js(S.steps,s),192)),768)),maxDistance:Ym(js(S.maxDistance,s),x*8),stepScale:A,maxStep:N,epsilon:b,normalEpsilon:I}}function m7(e,{sourceUrl:t=""}={}){const n=i7(e);if(!gc(n))throw new Error("Implicit CAD module must export an object, or a function returning an object.");if(n.kind===M1&&n.glslSource&&Array.isArray(n.parameters))return n.definition?n:{...n,definition:null};const r=TK(n.params),o=RK(r),i={map:new Map,last:null},s={schema:String(n.schema||dO),kind:M1,name:String(n.name||n.title||"Implicit CAD").trim()||"Implicit CAD",description:String(n.description||"").trim(),units:String(n.units||"mm").trim()||"mm",sourceUrl:String(t||n.sourceUrl||"").trim(),parameters:r,parameterMap:o,defaultParameterValues:{},animations:PK(n.animations),buildModel(l={},u={}){return f7(n,s,l,u,{sourceUrl:t,autoBoundsCache:i})}};return s.defaultParameterValues=qd(s,n.values||{}),{...s.buildModel(s.defaultParameterValues),definition:s}}function pf(e,{sourceUrl:t=""}={}){return m7(e,{sourceUrl:t})}const nl={sceneBackground:"#09090b",surface:"#f4f4f5",surfaceRoughness:.92,surfaceMetalness:.03},p7=/^#(?:[0-9a-fA-F]{3}){1,2}$/;function h7(e,t,n){return e?.[t]??nl[t]??n}function zl(e,t,n){return Math.min(Math.max(e,t),n)}function g7(e={},t=nl.surface){const n=Array.isArray(e.fillColors)?e.fillColors:[];return String(n[0]||e.defaultColor||t||nl.surface)}function Gw(e,t){const n=String(t||"").trim();if(!p7.test(n))return null;const r=n.length===4?`#${n[1]}${n[1]}${n[2]}${n[2]}${n[3]}${n[3]}`:n;return new e.Color(r)}function dN(e,t,n={},{applyTint:r=!0}={}){const o=(t||new e.Color("#ffffff")).clone(),i=zl(Number(n.tintStrength)||0,0,1);if(r&&i>0){const u=Gw(e,n.defaultColor||n.tintColor)||new e.Color("#ffffff");n.tintMode==="blend"?o.lerp(u,i):o.lerp(o.clone().multiply(u),i)}const s=zl(Number(n.saturation)||1,0,2.5);if(Math.abs(s-1)>1e-4){const u={};o.getHSL(u),o.setHSL(u.h,zl(u.s*s,0,1),u.l)}const a=zl(Number(n.contrast)||1,0,2.5),l=zl(Number(n.brightness)||1,0,2);return o.r=zl(((o.r-.5)*a+.5)*l,0,1),o.g=zl(((o.g-.5)*a+.5)*l,0,1),o.b=zl(((o.b-.5)*a+.5)*l,0,1),o}function b7(e,{hasVertexColors:t=!1,sourceColor:n=null,materialSettings:r={},fallbackColor:o=nl.surface,forceFill:i=!1}={}){if(i||!n){const s=Gw(e,g7(r,o))||new e.Color(o||nl.surface);return dN(e,s,r,{applyTint:!1})}return t?new e.Color("#ffffff"):dN(e,n,r)}const _b="#0b1020",Jy=48,fN=1.25,A1=1.42,y7=25,x7=.45,S7=.75,E7=.015,Tb="workbench";function Xx(e,t,n){return Math.min(Math.max(e,t),n)}function Be(e,t=0){const n=Number(e);return Number.isFinite(n)?n:t}function w7(e){return[Xx(Number(e?.r)||0,0,1),Xx(Number(e?.g)||0,0,1),Xx(Number(e?.b)||0,0,1)]}function v7(e){const t=String(e||"").trim().toLowerCase();return t==="linear"?1:t==="radial"?2:0}function C7(e,t=180){const n=Number(e);return(Number.isFinite(n)?n:t)*Math.PI/180}function M7(e={}){return Object.entries(e).map(([t,n])=>`uniform ${n.type} ${t};`).sort().join(` `)}const Ir=Object.freeze({toneMappingExposure:1.16,directional:{color:"#ffffff",intensity:1.16,position:{x:-210,y:260,z:270}},spot:{color:"#f4fbff",intensity:.52,position:{x:190,y:210,z:170}},point:{color:"#ffe2ba",intensity:.28,position:{x:-240,y:110,z:-210}},ambient:{color:"#ffffff",intensity:.4},hemisphere:{skyColor:"#ffffff",groundColor:"#d6e2ee",intensity:1.12},environmentAmbientScale:1,rimColor:"#6db6e8",rimIntensity:.08,floorShadowOpacity:.16});function I7(e){const t=Math.min(Math.max(Be(e,0),0),1);return t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function wi(e,t,n){const r=rl(e,n),o=Math.max(Be(t,0),0);return r.map(i=>I7(i)*o)}function au(e,t){const n=e&&typeof e=="object"?e:t,r=Be(n?.x,t.x),o=Be(n?.y,t.y),i=Be(n?.z,t.z),s=Math.hypot(r,o,i);return s>1e-9?[r/s,o/s,i/s]:au(t,{x:0,y:0,z:1})}function gO(e){const t=[e.max[0]-e.min[0],e.max[1]-e.min[1],e.max[2]-e.min[2]];return Math.max(Math.hypot(t[0],t[1],t[2])*1.2,.001)}function Uw(e,t=null,{estimate:n=!0}={}){const r=`${e.bounds.min.join(",")}|${e.bounds.max.join(",")}`;if(t?.implicitFloorBounds){if(t.implicitFloorBoundsKey===r)return t.implicitFloorBounds;const i=t.implicitFloorDeclaredBounds;if(i){const s=[...e.bounds.min,...e.bounds.max],a=Math.max(Be(e.radius,1),1e-6);let l=0;for(let u=0;u<6;u+=1)l=Math.max(l,Math.abs(Be(i[u],0)-Be(s[u],0)));if(l=0;n-=1){const r=e[n];if(!/\s/.test(r))return r}return""}function R7(e,t){for(let n=t;n=0?e.indexOf(")",o):-1;return o>=0&&o=t}function k7(e,t){const n=e[t-1];if(n!=="+"&&n!=="-")return!1;const r=e[t-2];return r!=="e"&&r!=="E"?!1:/[0-9.]/.test(e[t-3]||"")}const mN=/\b(?:int|uint)\s+([A-Za-z_]\w*)/g;function D7(e){const t=new Set;let n;for(mN.lastIndex=0;(n=mN.exec(e))!==null;)t.add(n[1]);return t}function j7(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]!=="=")return"";const r=e[n-1];if(r!=="="&&r!=="!"&&r!=="<"&&r!==">")return"";let o=n-2;for(;o>=0&&/\s/.test(e[o]);)o-=1;let i=o;for(;i>=0&&N1(e[i]);)i-=1;return e.slice(i+1,o+1)}function L7(e,t,n,r){const o=T7(e,t),i=R7(e,n);if(o==="."||i==="."||N1(o)||N1(i)||i==="["||o==="["||o&&!/[+\-*/=(,{?:]/.test(o)||i&&!/[,);}\]+\-*/?:]/.test(i)||k7(e,t))return!1;const s=j7(e,t);if(s&&r?.has(s)||O7(e,t))return!1;const a=P7(e,t);return!/\b(?:int|ivec[234]|uint|uvec[234])\b/.test(a)}function F7(e){const t=String(e||""),n=D7(t);let r="",o=0;for(;o16e3?9:t>8e3?11:t>4e3?17:y7}function U7(e,t){for($s.set(e,t);$s.size>$7;)$s.delete($s.keys().next().value)}function xO(e){if(e?.frameBounds?.min&&e?.frameBounds?.max)return e.frameBounds;const t=Bp(e);return $s.get(Ww(e,t))||null}function*SO(e,t,n){let r=null;try{r=uO(e)}catch{return t}const o=G7(e),i=B7(t),s=i.map(x=>x/Math.max(o-1,1)),a=Math.max(Math.min(...s)*x7,Be(e?.epsilon,.002)*12,.01),l=[1/0,1/0,1/0],u=[-1/0,-1/0,-1/0];let d=0;try{for(let x=0;xa||(d+=1,l[0]=Math.min(l[0],y),l[1]=Math.min(l[1],b),l[2]=Math.min(l[2],A),u[0]=Math.max(u[0],y),u[1]=Math.max(u[1],b),u[2]=Math.max(u[2],A))}yield}}}catch{return t}if(!d)return t;const m=Math.max(Math.max(...s)*S7,Math.max(...i)*E7,Be(e?.epsilon,.002)*20,.25),p=V7(l,u,m),g={min:p.min.map((x,y)=>Math.max(x,t.min[y])),max:p.max.map((x,y)=>Math.min(x,t.max[y]))};return U7(n,g),g}function EO(e){const t=Bp(e);if(e?.frameBounds?.min&&e?.frameBounds?.max)return e.frameBounds;const n=Ww(e,t);if($s.has(n)){const i=$s.get(n);return $s.delete(n),$s.set(n,i),i}const r=SO(e,t,n);let o=r.next();for(;!o.done;)o=r.next();return o.value||t}const Ug=new Map;async function W7(e){const t=Bp(e);if(e?.frameBounds?.min&&e?.frameBounds?.max)return e.frameBounds;const n=Ww(e,t);if($s.has(n))return $s.get(n);if(Ug.has(n))return Ug.get(n);const r=(async()=>{const o=()=>typeof performance<"u"?performance.now():Date.now(),i=SO(e,t,n);let s=o(),a=i.next();for(;!a.done;)o()-s>=10&&(await new Promise(l=>setTimeout(l,0)),s=o()),a=i.next();return a.value||t})().finally(()=>{Ug.delete(n)});return Ug.set(n,r),r}function qm(e,t){const n=Array.isArray(e)||ArrayBuffer.isView(e)?e:t;return[0,1,2].map(r=>Be(n?.[r],t[r]||0))}function H7(e){return Math.hypot(e[0],e[1],e[2])}function Ad(e,t=[1,0,0]){const n=qm(e,t),r=H7(n);return r>1e-9?n.map(o=>o/r):Ad(t,[1,0,0])}function lu(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function pN(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function wO(e,t){return[e[0]-t[0],e[1]-t[1],e[2]-t[2]]}function hN(e,t,n){return[e[0]+t[0]*n,e[1]+t[1]*n,e[2]+t[2]*n]}function vO(e){const t=[];for(const n of[e.min[0],e.max[0]])for(const r of[e.min[1],e.max[1]])for(const o of[e.min[2],e.max[2]])t.push([n,r,o]);return t}function K7(e,t){const n=Ad(e,[1,-1,.8]);let r=Ad(t,[0,0,1]);Math.abs(lu(n,r))>.96&&(r=Math.abs(n[2])>.8?[0,1,0]:[0,0,1]);const o=Ad(pN(r,n),[1,0,0]),i=Ad(pN(n,o),[0,0,1]);return{zAxis:n,right:o,screenUp:i}}function X7(e,t,n,r,o=A1,i=1){const s=Math.tan(Jy*Math.PI/360),a=Math.max(Be(r,4/3),.05),l=Math.max(Be(o,A1),1.05),u=Math.max(Be(i,1),.05);let d=0;for(const m of vO(e)){const p=wO(m,t),g=Math.abs(lu(p,n.right)),x=Math.abs(lu(p,n.screenUp)),y=lu(p,n.zAxis);d=Math.max(d,y+Math.max(g/(s*a),x/s)*l*u)}return Math.max(d,.001)}function Y7(e,t,n,r,o,i){const s=Math.tan(Jy*Math.PI/360),a=Math.max(Be(o,4/3),.05),l=Math.max(Be(i,1),.05);let u=1/0,d=-1/0,m=1/0,p=-1/0;for(const g of vO(e)){const x=wO(g,t),y=Math.max(r-lu(x,n.zAxis),.001),S=lu(x,n.right)*l/(y*s*a),b=lu(x,n.screenUp)*l/(y*s);u=Math.min(u,S),d=Math.max(d,S),m=Math.min(m,b),p=Math.max(p,b)}return{x:(u+d)/2,y:(m+p)/2}}function q7(e,t,n,r,o,i){const s=Y7(e,t,n,r,o,i),a=Math.tan(Jy*Math.PI/360),l=Math.max(Be(o,4/3),.05),u=Math.max(Be(i,1),.05),d=s.x*r*a*l/u,m=s.y*r*a/u;return hN(hN(t,n.right,d),n.screenUp,m)}function Z7(e,t="iso",{zoom:n=fN,width:r=4,height:o=3,frameMargin:i=A1,estimateFrameBounds:s=!0}={}){const a=m9(t,{strict:!0}),l=s?EO(e):xO(e)||Bp(e),u=Bp(e),d=z7(l||u);let m=qm(a.target,d);const p=a.hasExplicitZoom?a.zoom:Math.max(Be(n,fN),.05),g=a.position?[a.position[0]-m[0],a.position[1]-m[1],a.position[2]-m[2]]:qm(a.direction,[1,-1,.8]),x=Ad(g,[1,-1,.8]),y=K7(x,a.up),S=Math.max(Be(r,4)/Math.max(Be(o,3),1),.05),b=X7(l,m,y,S,i,p),I=Math.max(b,Math.max(Be(e?.radius,1),.001)*.45);!a.position&&!a.hasExplicitTarget&&(m=q7(l,m,y,I,S,p));const A=a.position?qm(a.position,[m[0]+x[0]*I,m[1]+x[1]*I,m[2]+x[2]*I]):[m[0]+x[0]*I,m[1]+x[1]*I,m[2]+x[2]*I];return{label:a.name,preset:a.preset,target:m,position:A,direction:x,up:qm(a.up,[0,0,1]),zoom:p,fov:Jy,bounds:u,frameBounds:l}}function J7(e){const t=Math.max(16,Math.min(Math.floor(Be(e.maxSteps,192)),768)),n=e.uniforms&&typeof e.uniforms=="object"?e.uniforms:{},r=M7(n),o=F7(e.glslSource||e.distanceSource),i=/\bvec3\s+color\s*\(\s*vec3\s+\w+\s*,\s*vec3\s+\w+\s*\)/.test(o);return` precision highp float; uniform vec2 uResolution; uniform vec3 uCameraPosition; uniform mat4 uCameraWorld; uniform mat4 uProjectionInverse; uniform vec3 uBoundsMin; uniform vec3 uBoundsMax; uniform vec3 uSurfaceColor; uniform vec3 uBackgroundColor; uniform vec3 uBackgroundColorA; uniform vec3 uBackgroundColorB; uniform float uBackgroundMode; uniform float uBackgroundAngle; uniform float uBackgroundAlpha; uniform float uUseProceduralColor; uniform float uHitEpsilon; uniform float uNormalEpsilon; uniform float uMaxDistance; uniform float uStepScale; uniform float uMaxStep; uniform float uStepBudget; uniform float uShadowStrength; uniform float uAmbientOcclusionStrength; uniform float uRimStrength; uniform float uExposure; uniform vec3 uHemiSky; uniform vec3 uHemiGround; uniform vec3 uAmbientLight; uniform vec3 uKeyColor; uniform vec3 uKeyDir; uniform vec3 uFillColor; uniform vec3 uFillDir; uniform vec3 uBounceColor; uniform vec3 uBounceDir; uniform vec3 uRimColor; uniform float uFloorEnabled; uniform float uFloorShadowOpacity; uniform float uFloorZ; uniform vec2 uFloorCenter; uniform float uFloorFadeRadius; ${r} varying vec2 vUv; const int IMPLICIT_MAX_STEPS = ${t}; float implicit_clamp01(float value) { return clamp(value, 0.0, 1.0); } float implicit_linear_map(float value, float inMin, float inMax, float outMin, float outMax) { float slope = (outMax - outMin) / (inMax - inMin); return (value - inMin) * slope + outMin; } float implicit_ramp(float value, float inMin, float inMax, float outMin, float outMax) { return clamp(implicit_linear_map(value, inMin, inMax, outMin, outMax), outMin, outMax); } float implicit_two_body_field(float a, float b) { return (a - b) / (a + b); } float implicit_two_body_polar(float a, float b, float angle) { return a * cos(angle) + b * sin(angle); } float implicit_triangle_wave_even(float value, float period) { float halfPeriod = period * 0.5; float quarterPeriod = period * 0.25; float wrapped = mod(value + halfPeriod, period); return quarterPeriod - abs(wrapped - halfPeriod); } vec2 implicit_triangle_wave_even(vec2 value, vec2 period) { return vec2( implicit_triangle_wave_even(value.x, period.x), implicit_triangle_wave_even(value.y, period.y) ); } vec3 implicit_triangle_wave_even(vec3 value, vec3 period) { return vec3( implicit_triangle_wave_even(value.x, period.x), implicit_triangle_wave_even(value.y, period.y), implicit_triangle_wave_even(value.z, period.z) ); } float implicit_triangle_wave_even_positive(float value, float period) { return implicit_triangle_wave_even(value, period) + period * 0.25; } vec2 implicit_triangle_wave_even_positive(vec2 value, vec2 period) { return vec2( implicit_triangle_wave_even_positive(value.x, period.x), implicit_triangle_wave_even_positive(value.y, period.y) ); } vec3 implicit_triangle_wave_even_positive(vec3 value, vec3 period) { return vec3( implicit_triangle_wave_even_positive(value.x, period.x), implicit_triangle_wave_even_positive(value.y, period.y), implicit_triangle_wave_even_positive(value.z, period.z) ); } float implicit_triangle_wave_odd(float value, float period) { return implicit_triangle_wave_even(value - period * 0.5, period); } vec2 implicit_triangle_wave_odd(vec2 value, vec2 period) { return vec2( implicit_triangle_wave_odd(value.x, period.x), implicit_triangle_wave_odd(value.y, period.y) ); } vec3 implicit_triangle_wave_odd(vec3 value, vec3 period) { return vec3( implicit_triangle_wave_odd(value.x, period.x), implicit_triangle_wave_odd(value.y, period.y), implicit_triangle_wave_odd(value.z, period.z) ); } float implicit_triangle_wave_odd_positive(float value, float period) { return implicit_triangle_wave_odd(value, period) + period * 0.25; } vec2 implicit_triangle_wave_odd_positive(vec2 value, vec2 period) { return vec2( implicit_triangle_wave_odd_positive(value.x, period.x), implicit_triangle_wave_odd_positive(value.y, period.y) ); } vec3 implicit_triangle_wave_odd_positive(vec3 value, vec3 period) { return vec3( implicit_triangle_wave_odd_positive(value.x, period.x), implicit_triangle_wave_odd_positive(value.y, period.y), implicit_triangle_wave_odd_positive(value.z, period.z) ); } vec2 implicit_repeat_centered(vec2 p, vec2 period) { return mod(p + period * 0.5, period) - period * 0.5; } vec3 implicit_repeat_centered(vec3 p, vec3 period) { return mod(p + period * 0.5, period) - period * 0.5; } float implicit_intersect_sharp(float a, float b) { return max(a, b); } float implicit_union_sharp(float a, float b) { return min(a, b); } float implicit_intersect_round(float a, float b, float radius) { float k = max(radius, 0.0); vec2 q = max(vec2(a, b) + k, 0.0); return min(-k, max(a, b)) + length(q); } float implicit_union_round(float a, float b, float radius) { return -implicit_intersect_round(-a, -b, radius); } float implicit_intersect_chamfer(float a, float b, float radius) { return max(max(a, b), (a + b + radius) * 0.7071067811865476); } float implicit_union_chamfer(float a, float b, float radius) { return -implicit_intersect_chamfer(-a, -b, radius); } float implicit_intersect_exp(float a, float b, float radius) { float k = max(radius, 1.0e-6) * 0.5; return k * log(exp(a / k) + exp(b / k)); } float implicit_union_exp(float a, float b, float radius) { return -implicit_intersect_exp(-a, -b, radius); } float implicit_intersect_lp_norm(float a, float b, float radius, float normPower) { float k = max(radius, 0.0); float p = max(normPower, 1.0e-6); vec2 q = max(vec2(a, b) + k, 0.0); return min(-k, max(a, b)) + pow(pow(q.x, p) + pow(q.y, p), 1.0 / p); } float implicit_union_lp_norm(float a, float b, float radius, float normPower) { return -implicit_intersect_lp_norm(-a, -b, radius, normPower); } float implicit_intersect_rvachev(float a, float b, float radius) { float sharp = max(a, b); float k = max(radius, 0.0); if (k <= 0.0) { return sharp; } float r0 = a + b - sqrt(a * a + b * b); float t = clamp((sharp + k) / k, 0.0, 1.0); float s = t * t * (3.0 - 2.0 * t); return sharp < -k ? sharp : mix(sharp, r0, s); } float implicit_union_rvachev(float a, float b, float radius) { return -implicit_intersect_rvachev(-a, -b, radius); } float implicit_plane2(vec2 p, vec2 origin, vec2 normal) { vec2 n = normalize(normal); return dot(p - origin, n); } float implicit_line_segment2(vec2 p, vec2 a, vec2 b) { vec2 segment = b - a; float segmentLengthSq = dot(segment, segment); if (segmentLengthSq < 1.0e-12) { return length(p - a); } float t = clamp(dot(p - a, segment) / segmentLengthSq, 0.0, 1.0); return length(p - (a + t * segment)); } float implicit_sphere(vec3 p, vec3 center, float radius) { return length(p - center) - radius; } float implicit_box_centered(vec3 p, vec3 size, vec3 center) { vec3 q = abs(p - center) - size * 0.5; return length(max(q, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0); } float implicit_plane(vec3 p, vec3 origin, vec3 normal) { vec3 n = normalize(normal); return dot(p - origin, n); } float implicit_line_segment(vec3 p, vec3 a, vec3 b) { vec3 segment = b - a; float segmentLengthSq = dot(segment, segment); if (segmentLengthSq < 1.0e-12) { return length(p - a); } float t = clamp(dot(p - a, segment) / segmentLengthSq, 0.0, 1.0); return length(p - (a + t * segment)); } float implicit_torus(vec3 p, float majorRadius, float minorRadius) { vec2 q = vec2(length(p.xy) - majorRadius, p.z); return length(q) - minorRadius; } float implicit_axis(vec3 p, vec3 origin, vec3 direction) { float directionLength = length(direction); if (directionLength < 1.0e-12) { return length(p - origin); } vec3 axis = direction / directionLength; vec3 toPoint = p - origin; return length(toPoint - dot(toPoint, axis) * axis); } float implicit_cylinder(vec3 p, vec3 origin, vec3 direction, float radius) { return implicit_axis(p, origin, direction) - radius; } float implicit_cylinder_capped(vec3 p, vec3 a, vec3 b, float radius) { vec3 axis = b - a; float side = implicit_cylinder(p, a, axis, radius); float capA = -implicit_plane(p, a, axis); float capB = implicit_plane(p, b, axis); return max(side, max(capA, capB)); } float implicit_capsule(vec3 p, vec3 a, vec3 b, float radius) { return implicit_line_segment(p, a, b) - radius; } float implicit_cone_capsule(vec3 p, vec3 a, vec3 b, float radiusA, float radiusB) { vec3 axis = b - a; float axisLengthSq = dot(axis, axis); if (axisLengthSq < 1.0e-12) { return implicit_sphere(p, a, radiusA); } float t = clamp(dot(p - a, axis) / axisLengthSq, 0.0, 1.0); float radius = mix(radiusA, radiusB, t); return length(p - (a + t * axis)) - radius; } float implicit_cone(vec3 p, vec3 apex, vec3 direction, float halfAngle) { float directionLength = length(direction); if (directionLength < 1.0e-12) { return length(p - apex); } vec3 axis = direction / directionLength; vec3 toPoint = p - apex; float axial = dot(toPoint, axis); float perpendicular = length(toPoint - axial * axis); return perpendicular - axial * tan(halfAngle); } float implicit_cone_capped(vec3 p, vec3 a, vec3 b, float radiusA, float radiusB) { vec3 axis = b - a; float axisLength = length(axis); if (axisLength < 1.0e-12) { return implicit_sphere(p, a, radiusA); } float halfAngle = atan(abs(radiusB - radiusA), axisLength); float coneDistance = radiusA < radiusB ? implicit_cone(p, a, axis, halfAngle) - radiusA : implicit_cone(p, b, -axis, halfAngle) - radiusB; float capA = -implicit_plane(p, a, axis); float capB = implicit_plane(p, b, axis); return max(coneDistance, max(capA, capB)); } float implicit_shell(float distanceValue, float thickness, float bias) { float halfThickness = thickness * 0.5; return abs(distanceValue + bias * halfThickness) - halfThickness; } vec3 implicit_rotate_axis(vec3 p, vec3 origin, vec3 direction, float angle) { vec3 k = normalize(direction); vec3 local = p - origin; float c = cos(angle); float s = sin(angle); return origin + local * c + cross(k, local) * s + k * dot(k, local) * (1.0 - c); } vec3 implicit_remap_cylindrical(vec3 p, float circumference) { float radial = length(p.xy); float theta = atan(p.y, p.x); return vec3(radial, theta * (circumference / 6.283185307179586), p.z); } float implicit_tpms_gyroid(vec3 p, vec3 period, vec3 drop) { vec3 xyz = p * (6.283185307179586 / period); vec3 yzx = xyz.yzx; float field = dot(drop, sin(xyz) * cos(yzx)); return field * (period.x + period.y + period.z) / 18.0; } float implicit_tpms_schwarz(vec3 p, vec3 period, vec3 drop, float gyroidBlend) { vec3 xyz = p * (6.283185307179586 / period); vec3 yzx = xyz.yzx; vec3 mixTerm = vec3(-(1.0 - gyroidBlend)) + sin(xyz) * gyroidBlend; float field = dot(drop, cos(yzx) * mixTerm); return field * (period.x + period.y + period.z) / 36.0; } float implicit_tpms_diamond(vec3 p, vec3 period, vec3 drop, float gyroidBlend) { vec3 xyz = p * (6.283185307179586 / period); vec3 yzx = xyz.yzx; vec3 zxy = xyz.zxy; vec3 sinXyz = sin(xyz); vec3 cosYzx = cos(yzx); vec3 cosZxy = cos(zxy); float blendFactor = 1.0 - gyroidBlend; float term1 = blendFactor * sinXyz.x * sinXyz.y * sinXyz.z; float term2 = dot(drop, sinXyz * cosYzx * (cosZxy * blendFactor + vec3(gyroidBlend))); return (term1 + term2) * (period.x + period.y + period.z) / (6.0 * 2.8284271247461903 * 2.0); } float implicit_tpms_lidinoid(vec3 p, vec3 period, vec3 drop, float gyroidBlend) { vec3 xyz = p * (6.283185307179586 / period); vec3 yzx = xyz.yzx; vec3 zxy = xyz.zxy; vec3 cos2Xyz = cos(2.0 * xyz); vec3 cos2Yzx = cos2Xyz.yzx; float blendFactor = 1.0 - gyroidBlend; float term1 = dot(drop, sin(zxy) * cos(yzx) * (sin(2.0 * xyz) * blendFactor + vec3(gyroidBlend))); float term2 = blendFactor * dot(cos2Xyz, cos2Yzx); return (term1 - term2) * (period.x + period.y + period.z) / 72.0; } float implicit_tpms_neovius(vec3 p, vec3 period, vec3 drop, float schwarzBlend) { vec3 xyz = p * (6.283185307179586 / period); vec3 cosDrop = cos(xyz) * drop; float term1 = -dot(cosDrop, vec3(1.0)); float term2 = (1.0 - schwarzBlend) * (4.0 / 3.0) * cosDrop.x * cosDrop.y * cosDrop.z; return (term1 - term2) * (period.x + period.y + period.z) / (6.0 * (26.0 / 3.0)); } float implicit_tpms_split_p(vec3 p, vec3 period, float lidinoidBlend, float gyroidOctave, float schwarzOctave) { vec3 xyz = p * (6.283185307179586 / period); vec3 yzx = xyz.yzx; vec3 zxy = xyz.zxy; vec3 sin2Xyz = sin(2.0 * xyz); vec3 cos2Xyz = cos(2.0 * xyz); float term1 = -lidinoidBlend * dot(sin2Xyz * cos(yzx) * sin(zxy), vec3(1.0)); float term2 = gyroidOctave * dot(sin2Xyz * cos2Xyz, vec3(1.0)); float term3 = schwarzOctave * dot(cos2Xyz, vec3(1.0)); return (term1 + term2 + term3) * (period.x + period.y + period.z) / 36.0; } float implicit_tpms_iwp(vec3 p, vec3 period, vec3 drop) { vec3 xyz = p * (6.283185307179586 / period); vec3 yzx = xyz.yzx; float term1 = 2.0 * dot(drop * cos(xyz) * cos(yzx), vec3(1.0)); float term2 = dot(cos(2.0 * xyz), vec3(1.0)); return (term1 - term2) * (period.x + period.y + period.z) / 48.0; } float implicit_cubic_grid(vec3 p, vec3 size) { vec3 d = implicit_triangle_wave_even_positive(p, size); return min(d.x, min(d.y, d.z)); } float implicit_square_honeycomb(vec3 p, vec2 size) { vec2 d = implicit_triangle_wave_even_positive(p.xy, size); return min(d.x, d.y); } float implicit_square_honeycomb_reinforced(vec3 p, vec2 size, float rotation, float rotation2, float hasRotation2) { vec2 pxy = p.xy; vec2 grid = implicit_triangle_wave_even_positive(pxy, size); float squareGrid = min(grid.x, grid.y); vec2 repeated = implicit_repeat_centered(pxy, size); float angle = 3.141592653589793 * rotation; float diagonal = abs(implicit_plane2(repeated, vec2(0.0), vec2(cos(angle), sin(angle)))); if (hasRotation2 > 0.5) { float angle2 = 3.141592653589793 * rotation2; float diagonal2 = abs(implicit_plane2(repeated, vec2(0.0), vec2(cos(angle2), sin(angle2)))); diagonal = min(diagonal, diagonal2); } return min(squareGrid, diagonal); } float implicit_square_diagonal_honeycomb(vec3 p, vec2 size) { vec2 period = vec2(size.x + size.y); vec2 repeated = implicit_repeat_centered(p.xy, period); float positive = abs(implicit_plane2(repeated, vec2(0.0), vec2(size.y, size.x))); float negative = abs(implicit_plane2(repeated, vec2(0.0), vec2(size.y, -size.x))); return min(positive, negative); } float implicit_octet_honeycomb(vec3 p, vec2 size) { vec2 pxy = p.xy; float square = implicit_square_honeycomb(p, size); vec2 oddGrid = implicit_triangle_wave_odd_positive(pxy, size); float planeGrid = min(oddGrid.x, oddGrid.y); float diagonalPeriod = length(size) * 0.5; vec2 rotated = vec2((pxy.x + pxy.y) / 1.4142135623730951, (pxy.x - pxy.y) / 1.4142135623730951); vec2 diagonal = implicit_triangle_wave_odd_positive(rotated, vec2(diagonalPeriod)); return min(min(square, planeGrid), min(diagonal.x, diagonal.y)); } float implicit_hexagonal_honeycomb(vec3 p, vec2 size, float setback) { vec2 pxy = p.xy; vec2 halfSize = size * 0.5; vec2 quarterSize = size * 0.25; vec2 starCenter = vec2(0.0, (1.0 - setback) * halfSize.y); vec2 transition = vec2(halfSize.x, setback * halfSize.y); vec2 folded = abs(implicit_repeat_centered(pxy, size)); vec2 reflected = vec2(folded.x - halfSize.x, halfSize.y - folded.y); float foldedStar = min( implicit_line_segment2(folded, starCenter, vec2(0.0, size.y)), min( implicit_line_segment2(folded, starCenter, transition), implicit_line_segment2(folded, starCenter, vec2(-transition.x, transition.y)) ) ); float reflectedStar = min( implicit_line_segment2(reflected, starCenter, vec2(0.0, size.y)), min( implicit_line_segment2(reflected, starCenter, transition), implicit_line_segment2(reflected, starCenter, vec2(-transition.x, transition.y)) ) ); return folded.x < quarterSize.x ? foldedStar : reflectedStar; } float implicit_triangular_honeycomb(vec3 p, vec2 size) { vec2 folded = abs(implicit_repeat_centered(p.xy, size)); vec2 halfSize = size * 0.5; vec2 quarterSize = size * 0.25; vec2 normalH = vec2(0.0, 1.0); vec2 normalP60 = normalize(vec2(size.y, size.x)); vec2 normalN60 = normalize(vec2(size.y, -size.x)); float foldedStar = min( abs(dot(folded, normalH)), min(abs(dot(folded, normalP60)), abs(dot(folded, normalN60))) ); vec2 shifted = folded - halfSize; float shiftedStar = min( abs(dot(shifted, normalH)), min(abs(dot(shifted, normalP60)), abs(dot(shifted, normalN60))) ); return folded.y < quarterSize.y ? foldedStar : shiftedStar; } ${o} float implicit_distance(vec3 p) { return sdf(p); } vec3 implicit_color(vec3 p, vec3 normal) { ${i?"return clamp(color(p, normal), vec3(0.0), vec3(1.0));":"return vec3(1.0);"} } float implicit_scene_sdf(vec3 p) { return implicit_distance(p); } vec2 implicit_ray_slab(float origin, float direction, float boundsMin, float boundsMax) { if (abs(direction) < 1.0e-8) { return origin < boundsMin || origin > boundsMax ? vec2(1.0, -1.0) : vec2(-1.0e20, 1.0e20); } float invDirection = 1.0 / direction; float nearPlane = (boundsMin - origin) * invDirection; float farPlane = (boundsMax - origin) * invDirection; return vec2(min(nearPlane, farPlane), max(nearPlane, farPlane)); } vec2 implicit_ray_bounds(vec3 origin, vec3 direction, vec3 boundsMin, vec3 boundsMax) { vec2 x = implicit_ray_slab(origin.x, direction.x, boundsMin.x, boundsMax.x); vec2 y = implicit_ray_slab(origin.y, direction.y, boundsMin.y, boundsMax.y); vec2 z = implicit_ray_slab(origin.z, direction.z, boundsMin.z, boundsMax.z); float tMin = max(max(x.x, y.x), z.x); float tMax = min(min(x.y, y.y), z.y); return vec2(tMin, tMax); } vec3 implicit_estimate_normal(vec3 p) { float e = uNormalEpsilon; vec2 k = vec2(1.0, -1.0); return normalize( k.xyy * implicit_scene_sdf(p + k.xyy * e) + k.yyx * implicit_scene_sdf(p + k.yyx * e) + k.yxy * implicit_scene_sdf(p + k.yxy * e) + k.xxx * implicit_scene_sdf(p + k.xxx * e) ); } float implicit_ambient_occlusion(vec3 p, vec3 normal) { float occlusion = 0.0; float scale = 1.0; for (int sampleIndex = 1; sampleIndex <= 5; sampleIndex += 1) { float distanceAlongNormal = 0.018 * float(sampleIndex) * uMaxDistance; float sampled = implicit_scene_sdf(p + normal * distanceAlongNormal); occlusion += (distanceAlongNormal - sampled) * scale; scale *= 0.58; } // Gentler floor than a typical raymarcher: the mesh viewer has no SSAO, so // heavy AO reads as "implicit models render darker". return clamp(1.0 - 0.045 * occlusion, 0.62, 1.0); } float implicit_soft_shadow(vec3 origin, vec3 direction, float maxDistance) { // Tight penumbra and a higher floor keep self-shadowing close to the mesh // viewer's crisp PCF shadows instead of dimming broad surface areas. float shadow = 1.0; float t = uHitEpsilon * 8.0; for (int shadowStep = 0; shadowStep < 28; shadowStep += 1) { if (t >= maxDistance) { break; } float h = implicit_scene_sdf(origin + direction * t); if (h < uHitEpsilon) { return 0.32; } shadow = min(shadow, 22.0 * h / t); t += clamp(h, uHitEpsilon * 3.0, maxDistance * 0.08); } return clamp(shadow, 0.32, 1.0); } vec3 implicit_srgb_to_linear(vec3 c) { c = clamp(c, vec3(0.0), vec3(1.0)); vec3 low = c / 12.92; vec3 high = pow((c + 0.055) / 1.055, vec3(2.4)); return mix(low, high, step(vec3(0.04045), c)); } vec3 implicit_linear_to_srgb(vec3 c) { c = clamp(c, vec3(0.0), vec3(1.0)); vec3 low = c * 12.92; vec3 high = 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055; return mix(low, high, step(vec3(0.0031308), c)); } // THREE.js ACESFilmicToneMapping port so implicit shading matches the mesh // viewer's renderer output transform. vec3 implicit_rrt_odt_fit(vec3 v) { vec3 a = v * (v + 0.0245786) - 0.000090537; vec3 b = v * (0.983729 * v + 0.4329510) + 0.238081; return a / b; } vec3 implicit_aces_tone_map(vec3 color) { const mat3 acesInput = mat3( vec3(0.59719, 0.07600, 0.02840), vec3(0.35458, 0.90834, 0.13383), vec3(0.04823, 0.01566, 0.83777) ); const mat3 acesOutput = mat3( vec3(1.60475, -0.10208, -0.00327), vec3(-0.53108, 1.10813, -0.07276), vec3(-0.07367, -0.00605, 1.07602) ); color *= 1.0 / 0.6; color = acesInput * color; color = implicit_rrt_odt_fit(color); color = acesOutput * color; return clamp(color, vec3(0.0), vec3(1.0)); } // Sharper than implicit_soft_shadow so the stage shadow stays a tight contact // shadow like the mesh viewer's PCF shadow map instead of a broad blob. float implicit_floor_shadow(vec3 origin, vec3 direction, float maxDistance) { float shadow = 1.0; float t = uHitEpsilon * 8.0; for (int shadowStep = 0; shadowStep < 32; shadowStep += 1) { if (t >= maxDistance) { break; } float h = implicit_scene_sdf(origin + direction * t); if (h < uHitEpsilon) { return 0.0; } shadow = min(shadow, 30.0 * h / t); t += clamp(h, uHitEpsilon * 3.0, maxDistance * 0.05); } return clamp(shadow, 0.0, 1.0); } // Stage-floor shadow matte for rays that miss the model, matching the mesh // viewer's shadow-catcher plane under the part. vec3 implicit_floor_shadowed_background(vec3 backgroundColor, vec3 rayOrigin, vec3 rayDirection) { float shadowStrength = clamp(uShadowStrength, 0.0, 1.0); if (uFloorEnabled < 0.5 || shadowStrength < 0.001 || rayDirection.z > -1.0e-5) { return backgroundColor; } float tFloor = (uFloorZ - rayOrigin.z) / rayDirection.z; if (tFloor <= 0.0) { return backgroundColor; } vec3 floorPoint = rayOrigin + rayDirection * tFloor; float fade = 1.0 - smoothstep(uFloorFadeRadius * 0.5, uFloorFadeRadius, length(floorPoint.xy - uFloorCenter)); if (fade < 0.002) { return backgroundColor; } vec3 shadowOrigin = vec3(floorPoint.xy, uFloorZ + max(uHitEpsilon * 6.0, uFloorFadeRadius * 0.0001)); float lit = implicit_floor_shadow(shadowOrigin, uKeyDir, uFloorFadeRadius * 1.5); float occlusion = clamp(1.0 - lit, 0.0, 1.0); float strength = occlusion * fade * clamp(uFloorShadowOpacity, 0.0, 1.0) * shadowStrength; return backgroundColor * (1.0 - strength); } vec3 implicit_background_color(vec2 uv) { if (uBackgroundMode < 0.5) { return uBackgroundColor; } if (uBackgroundMode < 1.5) { vec2 direction = normalize(vec2(cos(uBackgroundAngle), sin(uBackgroundAngle))); float t = dot(uv - vec2(0.5), direction) * 0.7071067811865476 + 0.5; return mix(uBackgroundColorA, uBackgroundColorB, clamp(t, 0.0, 1.0)); } float radial = smoothstep(0.0, 0.72, length(uv - vec2(0.5))); return mix(uBackgroundColorA, uBackgroundColorB, radial); } vec3 implicit_ray_direction(vec2 uv) { vec2 ndc = uv * 2.0 - 1.0; vec4 clip = vec4(ndc, -1.0, 1.0); vec4 view = uProjectionInverse * clip; view = vec4(view.xy, -1.0, 0.0); return normalize((uCameraWorld * view).xyz); } void main() { vec3 rayOrigin = uCameraPosition; vec2 screenUv = gl_FragCoord.xy / uResolution; vec3 backgroundColor = implicit_background_color(screenUv); vec3 rayDirection = implicit_ray_direction(screenUv); vec2 boundsHit = implicit_ray_bounds(rayOrigin, rayDirection, uBoundsMin, uBoundsMax); float t = max(boundsHit.x, 0.0); float tEnd = min(boundsHit.y, uMaxDistance); if (boundsHit.x > boundsHit.y || tEnd < 0.0) { gl_FragColor = vec4(implicit_floor_shadowed_background(backgroundColor, rayOrigin, rayDirection), uBackgroundAlpha); return; } bool hit = false; float previousT = t; vec3 p = rayOrigin; for (int stepIndex = 0; stepIndex < IMPLICIT_MAX_STEPS; stepIndex += 1) { if (float(stepIndex) >= uStepBudget) { break; } previousT = t; p = rayOrigin + rayDirection * t; float distanceValue = implicit_scene_sdf(p); float hitEpsilon = max(uHitEpsilon, t * 0.00028); if (distanceValue < hitEpsilon) { hit = true; break; } float stepDistance = max(distanceValue * uStepScale, uHitEpsilon * 0.25); t += min(stepDistance, uMaxStep); if (t > tEnd) { break; } } if (!hit) { gl_FragColor = vec4(implicit_floor_shadowed_background(backgroundColor, rayOrigin, rayDirection), uBackgroundAlpha); return; } float refineNear = previousT; float refineFar = t; for (int refineIndex = 0; refineIndex < 5; refineIndex += 1) { float mid = (refineNear + refineFar) * 0.5; float midDistance = implicit_scene_sdf(rayOrigin + rayDirection * mid); if (midDistance > 0.0) { refineNear = mid; } else { refineFar = mid; } } p = rayOrigin + rayDirection * refineFar; vec3 normal = implicit_estimate_normal(p); vec3 viewDirection = normalize(rayOrigin - p); float shadowStrength = clamp(uShadowStrength, 0.0, 1.0); float shadow = 1.0; if (shadowStrength > 0.001) { shadow = mix( 1.0, implicit_soft_shadow(p + normal * uHitEpsilon * 4.0, uKeyDir, uMaxDistance * 0.55), shadowStrength ); } float ambientOcclusionStrength = clamp(uAmbientOcclusionStrength, 0.0, 1.0); float ao = 1.0; if (ambientOcclusionStrength > 0.001) { ao = mix(1.0, implicit_ambient_occlusion(p, normal), ambientOcclusionStrength); } vec3 sourceColor = clamp(implicit_color(p, normal), vec3(0.0), vec3(1.0)); vec3 surfaceColor = implicit_srgb_to_linear(mix(uSurfaceColor, sourceColor, clamp(uUseProceduralColor, 0.0, 1.0))); // Match the mesh viewer's light rig: hemisphere + ambient indirect terms, // key/fill/bounce directional terms with a Lambert 1/pi factor, then the // same ACES filmic tone mapping and sRGB encode THREE.js applies. vec3 irradiance = (mix(uHemiGround, uHemiSky, normal.z * 0.5 + 0.5) + uAmbientLight) * ao; irradiance += uKeyColor * clamp(dot(normal, uKeyDir), 0.0, 1.0) * shadow; irradiance += uFillColor * clamp(dot(normal, uFillDir), 0.0, 1.0); irradiance += uBounceColor * clamp(dot(normal, uBounceDir), 0.0, 1.0); vec3 color = surfaceColor * irradiance * 0.3183098861837907; float rim = pow(1.0 - clamp(dot(normal, viewDirection), 0.0, 1.0), 2.4); color += uRimColor * rim * clamp(uRimStrength, 0.0, 1.0); color = implicit_aces_tone_map(color * uExposure); color = implicit_linear_to_srgb(color); gl_FragColor = vec4(color, 1.0); } `}function CO(e){const t=pf(e);return[t.maxSteps,t.uniformSignature||"",t.glslSource].join(` ---implicit-cad-shader-key--- `)}function Q7(){return` varying vec2 vUv; void main() { vUv = uv; gl_Position = vec4(position.xy, 0.0, 1.0); } `}function eX(e,t){const n=pf(t),r=Object.fromEntries(Object.entries(n.uniforms||{}).map(([a,l])=>[a,{value:N7(e,l)}])),o={},i=Uw(n,o,{estimate:!1}),s=new e.ShaderMaterial({name:"ImplicitCadRaymarchMaterial",depthTest:!1,depthWrite:!1,transparent:!0,uniforms:{uResolution:{value:new e.Vector2(1,1)},uCameraPosition:{value:new e.Vector3},uCameraWorld:{value:new e.Matrix4},uProjectionInverse:{value:new e.Matrix4},uBoundsMin:{value:new e.Vector3(...n.bounds.min)},uBoundsMax:{value:new e.Vector3(...n.bounds.max)},uSurfaceColor:{value:new e.Vector3(...rl(n.material.color,"#f4f4f5"))},uBackgroundColor:{value:new e.Vector3(...rl(n.background.color,_b))},uBackgroundColorA:{value:new e.Vector3(...rl(n.background.color,_b))},uBackgroundColorB:{value:new e.Vector3(...rl(n.background.color,_b))},uBackgroundMode:{value:0},uBackgroundAngle:{value:Math.PI},uBackgroundAlpha:{value:n.background.transparent?0:1},uUseProceduralColor:{value:n.colorSource?1:0},uHitEpsilon:{value:n.epsilon},uNormalEpsilon:{value:n.normalEpsilon},uMaxDistance:{value:n.maxDistance},uStepScale:{value:n.stepScale},uMaxStep:{value:n.maxStep},uStepBudget:{value:n.maxSteps},uShadowStrength:{value:1},uAmbientOcclusionStrength:{value:1},uRimStrength:{value:1},uExposure:{value:Ir.toneMappingExposure},uHemiSky:{value:new e.Vector3(...wi(Ir.hemisphere.skyColor,Ir.hemisphere.intensity,"#ffffff"))},uHemiGround:{value:new e.Vector3(...wi(Ir.hemisphere.groundColor,Ir.hemisphere.intensity,"#d6e2ee"))},uAmbientLight:{value:new e.Vector3(...wi(Ir.ambient.color,Ir.ambient.intensity,"#ffffff"))},uKeyColor:{value:new e.Vector3(...wi(Ir.directional.color,Ir.directional.intensity,"#ffffff"))},uKeyDir:{value:new e.Vector3(...au(Ir.directional.position,Ir.directional.position))},uFillColor:{value:new e.Vector3(...wi(Ir.spot.color,Ir.spot.intensity,"#f4fbff"))},uFillDir:{value:new e.Vector3(...au(Ir.spot.position,Ir.spot.position))},uBounceColor:{value:new e.Vector3(...wi(Ir.point.color,Ir.point.intensity,"#ffe2ba"))},uBounceDir:{value:new e.Vector3(...au(Ir.point.position,Ir.point.position))},uRimColor:{value:new e.Vector3(...wi(Ir.rimColor,Ir.rimIntensity,"#6db6e8"))},uFloorEnabled:{value:1},uFloorShadowOpacity:{value:Ir.floorShadowOpacity},uFloorZ:{value:i.min[2]},uFloorCenter:{value:new e.Vector2((i.min[0]+i.max[0])/2,(i.min[1]+i.max[1])/2)},uFloorFadeRadius:{value:gO(i)},...r},vertexShader:Q7(),fragmentShader:J7(n)});return Object.assign(s.userData,o),s}function tX(e,t,n){if(!t?.uniforms)return;const r=pf(n);t.uniforms.uBoundsMin&&t.uniforms.uBoundsMin.value.set(...r.bounds.min),t.uniforms.uBoundsMax&&t.uniforms.uBoundsMax.value.set(...r.bounds.max),t.uniforms.uMaxDistance&&(t.uniforms.uMaxDistance.value=r.maxDistance),bO(t,Uw(r,t.userData,{estimate:!1}));for(const[o,i]of Object.entries(r.uniforms||{}))_7(e,t.uniforms[o],i)}function gN({appearance:e=Tb,themeSettings:t=null}={}){return t&&typeof t=="object"&&!Array.isArray(t)?Xd(t):vK({appearance:e||Tb},{defaultThemeId:Tb})}function nX(e,t){const n=t?.lighting||{},r=Ir;e.uExposure&&(e.uExposure.value=Math.max(Be(n.toneMappingExposure,r.toneMappingExposure),.05));const o=n.hemisphere||r.hemisphere,i=o.enabled===!1?0:Be(o.intensity,r.hemisphere.intensity);if(e.uHemiSky&&e.uHemiSky.value.set(...wi(o.skyColor,i,r.hemisphere.skyColor)),e.uHemiGround&&e.uHemiGround.value.set(...wi(o.groundColor,i,r.hemisphere.groundColor)),e.uAmbientLight){const d=n.ambient||r.ambient,m=d.enabled===!1?0:Be(d.intensity,r.ambient.intensity),p=wi(d.color,m,r.ambient.color),g=t?.environment||{},x=g.enabled===!1?0:Math.max(Be(g.intensity,0),0)*r.environmentAmbientScale;e.uAmbientLight.value.set(p[0]+x,p[1]+x,p[2]+x)}const s=n.directional||r.directional;if(e.uKeyColor){const d=s.enabled===!1?0:Be(s.intensity,r.directional.intensity);e.uKeyColor.value.set(...wi(s.color,d,r.directional.color))}e.uKeyDir&&e.uKeyDir.value.set(...au(s.position,r.directional.position));const a=n.spot||r.spot;if(e.uFillColor){const d=a.enabled===!1?0:Be(a.intensity,r.spot.intensity);e.uFillColor.value.set(...wi(a.color,d,r.spot.color))}e.uFillDir&&e.uFillDir.value.set(...au(a.position,r.spot.position));const l=n.point||r.point;if(e.uBounceColor){const d=l.enabled===!1?0:Be(l.intensity,r.point.intensity);e.uBounceColor.value.set(...wi(l.color,d,r.point.color))}e.uBounceDir&&e.uBounceDir.value.set(...au(l.position,r.point.position)),e.uRimColor&&e.uRimColor.value.set(...wi(r.rimColor,r.rimIntensity,r.rimColor));const u=t?.floor||{};e.uFloorEnabled&&(e.uFloorEnabled.value=u.mode==="none"?0:1),e.uFloorShadowOpacity&&(e.uFloorShadowOpacity.value=Math.min(Math.max(Be(u.shadowOpacity,r.floorShadowOpacity),0),1))}function rX(e,t,n,{appearance:r=Tb,themeSettings:o=null,graphicsSettings:i=null,forceTransparent:s=!1}={}){const a=t?.uniforms;if(!a)return gN({appearance:r,themeSettings:o});const l=gN({appearance:r,themeSettings:o}),u=Ms(i),d=l.materials||{},m=Gw(e,n?.material?.color);a.uUseProceduralColor.value=n?.colorSource&&u.modelColors&&d.overrideSourceColors!==!0?1:0;const p=b7(e,{sourceColor:d.overrideSourceColors===!0?null:m,materialSettings:d,fallbackColor:d.defaultColor||nl.surface,forceFill:d.overrideSourceColors===!0});if(a.uSurfaceColor.value.set(...w7(p)),nX(a,l),n?.background?.color){const I=rl(n.background.color,nl.sceneBackground);return a.uBackgroundColor.value.set(...I),a.uBackgroundColorA.value.set(...I),a.uBackgroundColorB.value.set(...I),a.uBackgroundMode.value=0,a.uBackgroundAngle.value=Math.PI,a.uBackgroundAlpha.value=s||n.background.transparent?0:1,l}const g=l.background||{},x=v7(g.type),y=g.solidColor||h7(l,"sceneBackground",nl.sceneBackground),S=x===1?g.linearStart:x===2?g.radialInner:y,b=x===1?g.linearEnd:x===2?g.radialOuter:y;return a.uBackgroundColor.value.set(...rl(y,nl.sceneBackground)),a.uBackgroundColorA.value.set(...rl(S,y)),a.uBackgroundColorB.value.set(...rl(b,y)),a.uBackgroundMode.value=x,a.uBackgroundAngle.value=C7(g.linearAngle,180),a.uBackgroundAlpha.value=s||g.type==="transparent"?0:1,l}function oX(e,t,n=null){const r=e?.uniforms;if(!r)return Ms(n);const o=Ms(n),i=Math.max(o.detail,.001),s=Math.sqrt(i);if(r.uHitEpsilon&&(r.uHitEpsilon.value=Math.max(Be(t?.epsilon,.001)/s,1e-6)),r.uNormalEpsilon&&(r.uNormalEpsilon.value=Math.max(Be(t?.normalEpsilon,.001)*o.normalSmoothing/s,1e-6)),r.uStepScale&&(r.uStepScale.value=Math.max(Be(t?.stepScale,1)/i,.01)),r.uMaxStep&&(r.uMaxStep.value=Math.max(Be(t?.maxStep,1)/i,1e-6)),r.uStepBudget){const a=Math.max(Math.floor(Be(t?.maxSteps,192)),1),l=Math.floor(Be(n?.stepBudget,a));r.uStepBudget.value=Math.max(Math.min(l,a),1)}return r.uShadowStrength&&(r.uShadowStrength.value=o.shadows?1:0),r.uAmbientOcclusionStrength&&(r.uAmbientOcclusionStrength.value=o.ambientOcclusion?1:0),r.uRimStrength&&(r.uRimStrength.value=o.rimLight?1:0),o}function iX(e,t,n,r){t.updateMatrixWorld(!0),e.uniforms.uResolution.value.set(Math.max(n,1),Math.max(r,1)),e.uniforms.uCameraPosition.value.copy(t.position),e.uniforms.uCameraWorld.value.copy(t.matrixWorld),e.uniforms.uProjectionInverse.value.copy(t.projectionMatrixInverse)}function bN(e,t){const n=new e.Scene,r=pf(t),o=eX(e,t),i=new e.Mesh(new e.PlaneGeometry(2,2),o);return i.frustumCulled=!1,n.add(i),{scene:n,material:o,quad:i,shaderKey:CO(r),dispose(){i.geometry?.dispose?.(),o.dispose?.()}}}const sX=140,_1=.14,yN=4.5,aX=10,lX=14,xN=Math.PI/32,SN=Math.PI*.42,EN=.02,wN=Object.freeze([2.1,-1.65,1.08]),Ss=Object.freeze([0,0,1]),cX=.994,MO=280,uX=48,IO=8,dX=1.08,AO=400,fX="cad-glass-surface pointer-events-auto grid h-8 w-8 shrink-0 place-items-center rounded-full border border-sidebar-border text-sidebar-foreground/60 shadow-sm transition duration-150 hover:text-sidebar-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/45",Hw=[{id:"z",title:"Jump to top view",direction:[0,0,1],up:[0,1,0]},{id:"zNeg",title:"Jump to bottom view",direction:[0,0,-1],up:[0,1,0]},{id:"yNeg",title:"Jump to front view",direction:[0,-1,0],up:Ss},{id:"y",title:"Jump to back view",direction:[0,1,0],up:Ss},{id:"x",title:"Jump to right view",direction:[1,0,0],up:Ss},{id:"xNeg",title:"Jump to left view",direction:[-1,0,0],up:Ss}],mX=Object.fromEntries(Hw.map(e=>[e.id,e]));function Ea(e,t,n){return Math.min(Math.max(e,t),n)}function Ui(e,t=0){const n=Number(e);return Number.isFinite(n)?n:t}function pX(e){const t=Ea(e,0,1);return t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2}function hX(e){return e.ctrlKey||e.deltaMode===0&&Math.abs(e.deltaY)<20}function vN(e){if(!e)return null;if(e.key==="ArrowLeft")return{direction:"left",keyId:"ArrowLeft"};if(e.key==="ArrowRight")return{direction:"right",keyId:"ArrowRight"};if(e.key==="ArrowUp")return{direction:"up",keyId:"ArrowUp"};if(e.key==="ArrowDown")return{direction:"down",keyId:"ArrowDown"};const t=String(e.key||"").toLowerCase();return t==="a"||e.code==="KeyA"?{direction:"left",keyId:e.code||"KeyA"}:t==="d"||e.code==="KeyD"?{direction:"right",keyId:e.code||"KeyD"}:t==="w"||e.code==="KeyW"?{direction:"up",keyId:e.code||"KeyW"}:t==="s"||e.code==="KeyS"?{direction:"down",keyId:e.code||"KeyS"}:null}function NO(e){return{azimuth:(e.directionCounts.right>0?1:0)-(e.directionCounts.left>0?1:0),polar:(e.directionCounts.down>0?1:0)-(e.directionCounts.up>0?1:0)}}function gX(e){e&&(e.pressedKeys.clear(),e.directionCounts.left=0,e.directionCounts.right=0,e.directionCounts.up=0,e.directionCounts.down=0,e.lastFrameTime=0)}function _O(e,t,n){if(!e?.camera||!e?.controls||Math.abs(t)<1e-6&&Math.abs(n)<1e-6)return!1;const r=e.camera.position.clone().sub(e.controls.target),o=r.length();if(!Number.isFinite(o)||o<=1e-6)return!1;const i=new vs(...Ss).normalize(),s=r.clone().divideScalar(o),a=Math.max(Number.isFinite(e.controls.minPolarAngle)?e.controls.minPolarAngle:0,EN),l=Math.min(Number.isFinite(e.controls.maxPolarAngle)?e.controls.maxPolarAngle:Math.PI,Math.PI-EN),u=Math.acos(Ea(s.dot(i),-1,1)),m=Ea(u+n,a,l)-u;if(Math.abs(t)>1e-6&&r.applyAxisAngle(i,t),Math.abs(m)>1e-6){let p=new vs().crossVectors(i,r).normalize();p.lengthSq()<=1e-9&&(p=new vs(1,0,0)),r.applyAxisAngle(p,m)}return e.camera.position.copy(e.controls.target).add(r),e.camera.up.set(...Ss),e.camera.lookAt(e.controls.target),!0}function bX(e,t){const n=e?.keyboardOrbitState;if(!n)return!1;const r=NO(n);if(!r.azimuth&&!r.polar)return n.lastFrameTime=0,!1;if(!n.lastFrameTime)return n.lastFrameTime=t,!1;const o=Ea((t-n.lastFrameTime)/1e3,0,.05);return n.lastFrameTime=t,_O(e,r.azimuth*SN*o,r.polar*SN*o)}function yX(e={}){const t=n=>{const r=Number(n);return Number.isFinite(r)?Math.max(0,r):0};return{top:t(e?.top),right:t(e?.right),bottom:t(e?.bottom),left:t(e?.left)}}function fy(e,t={}){const n=e?.renderer?.domElement,r=Math.max(1,n?.clientWidth||n?.parentElement?.clientWidth||1),o=Math.max(1,n?.clientHeight||n?.parentElement?.clientHeight||1),i=yX(t),s=Ea(i.left,0,Math.max(r-1,0)),a=Ea(i.right,0,Math.max(r-s-1,0)),l=Ea(i.top,0,Math.max(o-1,0)),u=Ea(i.bottom,0,Math.max(o-l-1,0)),d=Math.max(1,r-s-a),m=Math.max(1,o-l-u),p=s+d/2,g=l+m/2;return{width:r,height:o,top:l,right:a,bottom:u,left:s,framedWidth:d,framedHeight:m,aspect:d/m,offsetNdcX:p/r*2-1,offsetNdcY:1-g/o*2}}function xX(e,t={}){const n=e?.renderer?.domElement,r=fy(e,t),o=Math.max(1,n?.width||r.width),i=Math.max(1,n?.height||r.height),s=o/Math.max(r.width,1),a=i/Math.max(r.height,1),l=Math.round(r.left*s),u=Math.round(r.top*a),d=Math.round(r.right*s),m=Math.round(r.bottom*a);return{x:l,y:u,width:Math.max(1,o-l-d),height:Math.max(1,i-u-m)}}function SX(e,t={},{updateProjection:n=!0}={}){const r=e?.camera;if(!r?.projectionMatrix?.elements)return;n&&r.updateProjectionMatrix();const{offsetNdcX:o,offsetNdcY:i}=fy(e,t);r.projectionMatrix.elements[8]-=o,r.projectionMatrix.elements[9]-=i,r.projectionMatrixInverse.copy(r.projectionMatrix).invert()}function EX(e){if(!e?.camera)return null;const t=e.camera.quaternion.clone().invert(),n=(r,o,i)=>{const s=new vs(r,o,i).applyQuaternion(t);return[s.x,s.y,s.z]};return{x:n(1,0,0),y:n(0,1,0),z:n(0,0,1)}}function wX(e,t){if(e===t)return!0;if(!e||!t)return!1;for(const n of["x","y","z"]){const r=e[n],o=t[n];if(!r||!o)return!1;for(let i=0;i<3;i+=1)if(Math.abs((r[i]||0)-(o[i]||0))>1e-4)return!1}return!0}function vX(e){if(!e?.camera||!e?.controls)return"";const t=e.camera.position.clone().sub(e.controls.target);if(t.lengthSq()<1e-6)return"";t.normalize();let n="",r=-1/0;for(const o of Hw){const s=new vs(...o.direction).normalize().dot(t);s>r&&(r=s,n=o.id)}return r>=cX?n:""}function CN(e,t=""){if(!e?.camera||!e?.controls)return null;const n=e.camera,r=e.controls.target;return{implicit:!0,cameraVersion:IO,modelKey:String(t||""),position:[n.position.x,n.position.y,n.position.z],target:[r.x,r.y,r.z],up:[n.up.x,n.up.y,n.up.z],fov:n.fov}}function MN(e,t,n=""){if(!e?.camera||!e?.controls||!t?.implicit||t.cameraVersion!==IO)return!1;const r=String(t.modelKey||"").trim(),o=String(n||"").trim();if(r&&o&&r!==o)return!1;const i=Array.isArray(t.position)?t.position:null,s=Array.isArray(t.target)?t.target:null,a=Array.isArray(t.up)?t.up:Ss;return!i||!s?!1:(e.camera.position.set(Ui(i[0],e.camera.position.x),Ui(i[1],e.camera.position.y),Ui(i[2],e.camera.position.z)),e.controls.target.set(Ui(s[0],e.controls.target.x),Ui(s[1],e.controls.target.y),Ui(s[2],e.controls.target.z)),e.camera.up.set(Ui(a[0],Ss[0]),Ui(a[1],Ss[1]),Ui(a[2],Ss[2])),e.camera.fov=Ui(t.fov,e.camera.fov),e.updateCameraFraming?.(),e.camera.lookAt(e.controls.target),e.controls.update(),e.requestRender?.(),!0)}function CX(e,t){if(!e?.camera||!e?.controls||!t)return!1;const n=new vs(...t.direction||[]),r=new vs(...t.up||[]);if(n.lengthSq()<1e-6||r.lengthSq()<1e-6)return!1;const o=e.controls.target.clone(),i=Ea(e.camera.position.distanceTo(o),e.controls.minDistance||.01,e.controls.maxDistance||1/0);return e.cameraTransition={startTime:performance.now(),durationMs:MO,startPosition:e.camera.position.clone(),endPosition:o.clone().add(n.normalize().multiplyScalar(i)),startUp:e.camera.up.clone(),endUp:r.normalize()},e.controls.enableDamping=!1,e.beginInteraction?.(),e.requestRender?.(),!0}function MX(e,t){const n=e?.cameraTransition;if(!n)return!1;const r=Ea((t-n.startTime)/n.durationMs,0,1),o=pX(r);return e.camera.position.lerpVectors(n.startPosition,n.endPosition,o),e.camera.up.lerpVectors(n.startUp,n.endUp,o).normalize(),n.endTarget&&e.controls.target.lerpVectors(n.startTarget,n.endTarget,o),e.camera.lookAt(e.controls.target),r>=1?(e.cameraTransition=null,e.controls.enableDamping=!0,e.controls.dampingFactor=_1,e.scheduleIdleQuality?.(),e.emitPerspectiveChange?.(),!1):!0}function IX(e,t){e.controls.target.set(...t.target),e.camera.position.set(...t.position),e.camera.up.set(...t.up),e.camera.fov=t.fov,e.camera.zoom=t.zoom,e.updateCameraFraming?.(),e.camera.lookAt(e.controls.target),e.controls.update(),e.emitPerspectiveChange?.(),e.requestRender?.()}function AX(e,t,{animate:n=!0,durationMs:r=AO}={}){return!e?.camera||!e?.controls||!t?!1:!n||r<=0?(IX(e,t),!0):(e.camera.fov=t.fov,e.camera.zoom=t.zoom,e.updateCameraFraming?.(),e.cameraTransition={startTime:performance.now(),durationMs:r,startPosition:e.camera.position.clone(),endPosition:new vs(...t.position),startUp:e.camera.up.clone(),endUp:new vs(...t.up).normalize(),startTarget:e.controls.target.clone(),endTarget:new vs(...t.target)},e.controls.enableDamping=!1,e.beginInteraction?.(),e.requestRender?.(),!0)}function IN(e){const t=e?.shaderScene,n=e?.renderer;if(!(!t||!n)){if(typeof n.compileAsync!="function"||!e.screenCamera){e.shaderSceneReady=!0;return}e.shaderSceneReady=!1,n.compileAsync(t.scene,e.screenCamera).catch(()=>{}).finally(()=>{e.shaderScene===t&&(e.shaderSceneReady=!0,e.requestRender?.())})}}function Wg(e){const t=e?.bounds;if(!Array.isArray(t?.min)||!Array.isArray(t?.max))return"";const n=Math.max(Ui(e?.radius,1),1e-6),r=Math.max(n*.02,1e-6);return[...t.min,...t.max].map(o=>Math.round(Ui(o,0)/r)).join(",")}function NX(e,t=null){return new Promise((n,r)=>{const o=e,i=t?document.createElement("canvas"):o;t&&(i.width=t.width,i.height=t.height,i.getContext("2d")?.drawImage(o,t.x,t.y,t.width,t.height,0,0,t.width,t.height)),i.toBlob(s=>{s?n(s):r(new Error("Failed to capture implicit CAD screenshot"))},"image/png")})}function sd(e,t,n){rX(gb,e?.shaderScene?.material,t,{themeSettings:n,graphicsSettings:tO(e?.graphicsSettings,{interaction:e?.previewOrbitEnabled===!0})})}function ad(e,t){oX(e?.shaderScene?.material,t,tO(e?.graphicsSettings,{interaction:e?.previewOrbitEnabled===!0}))}const _X=f.forwardRef(function({model:t,modelKey:n="",isLoading:r=!1,previewMode:o=!1,viewportFrameInsets:i={},viewPlaneOffsetRight:s=16,themeSettings:a=null,graphicsSettings:l=null,dynamicRenderActive:u=!1,perspective:d=null,perspectiveRef:m=null,onPerspectiveChange:p,onViewerAlertChange:g},x){const y=f.useRef(null),S=f.useRef(null),b=f.useRef(i),I=f.useRef(n),A=f.useRef(p),N=f.useRef(o),P=f.useMemo(()=>Ms(l),[l]),R=f.useRef(P),v=f.useRef(u===!0),[C,T]=f.useState(""),[k,z]=f.useState(""),[Y,K]=f.useState(null);f.useEffect(()=>{b.current=i;const oe=S.current;oe?.updateCameraFraming?.(),oe?.requestRender?.()},[i]),f.useEffect(()=>{A.current=p},[p]),f.useEffect(()=>{I.current=n},[n]),f.useEffect(()=>{N.current=o},[t,o,a]),f.useEffect(()=>{const oe=u===!0;v.current=oe;const me=S.current;me&&(me.dynamicRenderActive=oe,ad(me,t),me.requestRender?.())},[u,t]);const J=f.useCallback(()=>{const oe=CN(S.current,I.current);oe&&A.current?.(oe)},[]),G=f.useRef({attached:!0,lastFitKey:""}),[Q,D]=f.useState(!1),$=f.useCallback(oe=>{G.current.attached=oe,D(!oe)},[]),ie=f.useRef($);ie.current=$;const W=f.useCallback((oe="state",{animate:me=!0,force:se=!1,viewDirection:Ae=null,viewUp:we=null,durationMs:ct=AO}={})=>{const ut=S.current;if(!ut?.camera||!ut?.controls)return!1;const Tt=G.current;if(!se&&Tt.attached===!1)return!1;const Ve=ut.model||t;if(!Ve)return!1;const St=fy(ut,b.current),wt=ut.camera.position.clone().sub(ut.controls.target),Vn=Ae||(wt.lengthSq()>1e-9?wt.toArray():wN),De=Z7(Ve,{direction:Vn,up:we||ut.camera.up.toArray()},{width:St.framedWidth,height:St.framedHeight,zoom:1,frameMargin:dX,estimateFrameBounds:!1});return $(!0),Tt.lastFitKey=Wg(Ve),AX(ut,De,{animate:me,durationMs:ct})},[t,$]),Z=f.useRef(null);Z.current=W;const Ee=f.useCallback(oe=>{if(!oe||v.current)return;const me=G.current;if(me.attached===!1)return;const se=Wg(oe);!se||me.lastFitKey===se||Z.current?.("model")},[]),re=f.useCallback((oe,{force:me=!1}={})=>{const se=S.current,Ae=se?.shaderScene?.material;if(!se||!Ae||!oe||!me&&v.current)return;const we=Wg(oe);if(!me&&we&&se.refineBoundsKey===we)return;se.refineBoundsKey=we;const ct=se.refineToken=(se.refineToken||0)+1;A7(Ae,oe).then(()=>{S.current!==se||se.refineToken!==ct||se.shaderScene?.material===Ae&&(se.requestRender?.(),G.current.attached!==!1&&!v.current&&Z.current?.("refine"))}).catch(()=>{S.current===se&&se.refineBoundsKey===we&&(se.refineBoundsKey=null)})},[]),be=f.useRef(null);be.current=re;const _e=f.useCallback(oe=>{const me=mX[oe];return!me||!S.current?!1:(z(me.id),G.current.attached!==!1?W("viewport",{viewDirection:me.direction,viewUp:me.up,durationMs:MO}):CX(S.current,me))},[W]),Ie=f.useCallback(()=>S.current?(z(""),W("reset",{force:!0,viewDirection:wN,viewUp:Ss})):!1,[W]);return f.useImperativeHandle(x,()=>({async captureScreenshot({filename:oe="implicit-cad-screenshot.png",mode:me="download"}={}){const se=S.current,Ae=se?.renderer?.domElement;if(!Ae)throw new Error("Implicit CAD Viewer not ready");se.requestRender?.({immediate:!0});const we=NX(Ae,xX(se,b.current));if(me==="clipboard")return await tw(we);const ct=await we;return nw(ct,{filename:oe})},getPerspective(){return CN(S.current,I.current)},setPerspective(oe){return MN(S.current,oe,I.current)},focusViewPreset(oe){return _e(oe)}}),[_e]),f.useEffect(()=>{const oe=S.current;oe?.controls&&(oe.orbitControlsLastTimestamp=0,oe.previewOrbitEnabled=!!o,oe.controls.autoRotate=!!o,oe.controls.autoRotateSpeed=p1,sd(oe,t,a),ad(oe,t),o?oe.beginInteraction?.():oe.scheduleIdleQuality?.(),oe.requestRender?.())},[o]),f.useEffect(()=>{const oe=S.current;if(!oe||!t)return;oe.dynamicRenderActive=v.current;let me="";try{me=CO(t)}catch(we){const ct=we instanceof Error?we.message:String(we);T(ct),g?.({severity:"error",compact:!0,title:"Implicit CAD shader failed",message:ct});return}if(oe.shaderScene&&oe.shaderScene.shaderKey===me){oe.model=t,tX(gb,oe.shaderScene.material,t),oe.updateCameraFraming?.(),sd(oe,t,a),ad(oe,t),Ee(t),re(t),oe.requestRender?.();return}let se=null;try{se=bN(gb,t)}catch(we){const ct=we instanceof Error?we.message:String(we);T(ct),g?.({severity:"error",compact:!0,title:"Implicit CAD shader failed",message:ct});return}const Ae=oe.shaderScene;oe.shaderScene=se,oe.model=t,IN(oe),T(""),g?.(null),sd(oe,t,a),ad(oe,t),oe.updateCameraFraming?.(),Ee(t),re(t),oe.requestRender?.(),Ae?.dispose?.()},[Ee,t,P,g,re,a]),f.useEffect(()=>{sd(S.current,t,a),S.current?.requestRender?.()},[t,a]),f.useEffect(()=>{R.current=P;const oe=S.current;oe&&(oe.graphicsSettings=P,oe.dynamicRenderActive=v.current,sd(oe,t,a),ad(oe,t),oe.setPixelRatioCap?.(Gg(P,{interaction:N.current})),oe.requestRender?.())},[t,P,a]),f.useEffect(()=>{if(!y.current||!t)return;let oe=!1,me=0,se=0;const Ae=y.current,we=new X3({antialias:!0,alpha:!0,preserveDrawingBuffer:!0});we.setPixelRatio(Math.min(window.devicePixelRatio||1,R.current.resolutionScale)),we.setSize(Ae.clientWidth||800,Ae.clientHeight||640,!1),we.domElement.className="h-full w-full touch-none",Ae.innerHTML="",Ae.appendChild(we.domElement);let ct=null,ut=null,Tt=null,Ve=null;const St=()=>Math.max((window.devicePixelRatio||1)|0,1),wt=St(),Vn=ze=>ze*(St()/wt),De={pressedKeys:new Set,directionCounts:{left:0,right:0,up:0,down:0},lastFrameTime:0};try{ct=bN(gb,t),ut=new Y3(-1,1,1,-1,0,1),Tt=new q3(uX,1,.01,2e3),Tt.up.set(...Ss),Ve=new Z3(Tt,we.domElement),Ve.enableDamping=!0,Ve.dampingFactor=_1,Ve.rotateSpeed=1,Ve.panSpeed=1.35,Ve.zoomSpeed=yN,"zoomToCursor"in Ve&&(Ve.zoomToCursor=!0),T(""),g?.(null)}catch(ze){const Ze=ze instanceof Error?ze.message:String(ze);T(Ze),g?.({severity:"error",compact:!0,title:"Implicit CAD shader failed",message:Ze})}const xe={renderer:we,shaderScene:ct,screenCamera:ut,camera:Tt,controls:Ve,cameraTransition:null,renderQueued:!1,orbitControlsLastTimestamp:0,keyboardOrbitState:De,graphicsSettings:R.current,dynamicRenderActive:v.current,previewOrbitEnabled:!!o,model:t,shaderSceneReady:!1,requestRender:rt,beginInteraction:Re,scheduleIdleQuality:Fe,setPixelRatioCap:yt,updateCameraFraming:Te,emitPerspectiveChange:J};S.current=xe;function yt(ze){we.setPixelRatio(Math.min(window.devicePixelRatio||1,ze)),we.setSize(Ae.clientWidth||800,Ae.clientHeight||640,!1)}function Te(){if(!xe.camera||!xe.controls)return;const ze=xe.model||t,Ze=fy(xe,b.current);xe.camera.aspect=Ze.width/Ze.height,xe.camera.near=Math.max(ze.radius/1200,.01),xe.camera.far=Math.max(ze.radius*600,2e3),xe.camera.updateProjectionMatrix(),SX(xe,b.current,{updateProjection:!1}),xe.controls.minDistance=Math.max(ze.radius/2200,.02),xe.controls.maxDistance=Math.max(ze.radius*140,50)}function rt(ze={}){if(!oe){if(ze.immediate){on(performance.now());return}xe.renderQueued||(xe.renderQueued=!0,me=window.requestAnimationFrame(on))}}function Re(){se&&(window.clearTimeout(se),se=0),yt(Gg(R.current,{interaction:!0})),rt()}function Fe(){se&&window.clearTimeout(se),se=window.setTimeout(()=>{se=0,Ve.enableDamping=!0,Ve.dampingFactor=_1,Ve.zoomSpeed=yN,yt(Gg(R.current,{interaction:N.current})),rt()},sX)}function on(ze){if(oe)return;xe.renderQueued=!1;const Ze=MX(xe,ze),vt=bX(xe,ze),Tn=IP(Ve,ze,xe);if(vt&&J(),xe.shaderScene&&xe.shaderSceneReady!==!1&&xe.camera&&xe.screenCamera){const pe=we.domElement;iX(xe.shaderScene.material,xe.camera,pe.width||pe.clientWidth||1,pe.height||pe.clientHeight||1),we.render(xe.shaderScene.scene,xe.screenCamera)}if(!xe.previewOrbitEnabled){const pe=vX(xe);z(He=>He===pe?He:pe);const Xe=EX(xe);K(He=>wX(He,Xe)?He:Xe)}(Ze||vt||Tn||Ve?.autoRotate)&&rt()}function ht(){oe||(yt(Gg(R.current,{interaction:N.current})),Te(),G.current.attached!==!1&&Z.current?.("resize",{animate:!1}),rt())}const jt=()=>{xe.cameraTransition=null,ie.current(!1),Re()},qt=()=>{J(),rt()},sn=()=>{Fe()},Mn=ze=>{xe.cameraTransition=null,ie.current(!1),Ve.enableDamping=!1,Ve.zoomSpeed=Vn(hX(ze)?lX:aX),Re()},fn=ze=>{if(N.current||ze.defaultPrevented||ze.ctrlKey||ze.metaKey||ze.altKey||_w(ze.target))return;const Ze=vN(ze);if(Ze){if(De.pressedKeys.has(Ze.keyId)){ze.preventDefault();return}De.pressedKeys.add(Ze.keyId),De.directionCounts[Ze.direction]+=1,De.lastFrameTime=0,xe.cameraTransition=null,ie.current(!1),Re(),_O(xe,(Ze.direction==="right"?1:Ze.direction==="left"?-1:0)*xN,(Ze.direction==="down"?1:Ze.direction==="up"?-1:0)*xN),J(),rt(),ze.preventDefault()}},Bt=ze=>{const Ze=vN(ze);if(!Ze||!De.pressedKeys.delete(Ze.keyId))return;De.directionCounts[Ze.direction]=Math.max(0,De.directionCounts[Ze.direction]-1);const vt=NO(De);!vt.azimuth&&!vt.polar&&(De.lastFrameTime=0,Fe()),ze.preventDefault()},dt=()=>{De.pressedKeys.size&&(gX(De),Fe())},qe=()=>{document.visibilityState!=="visible"&&dt()},Vt=typeof ResizeObserver=="function"?new ResizeObserver(ht):null;Vt?.observe(Ae),window.addEventListener("resize",ht),Ve?.addEventListener("start",jt),Ve?.addEventListener("change",qt),Ve?.addEventListener("end",sn),we.domElement.addEventListener("wheel",Mn,{passive:!0,capture:!0}),window.addEventListener("keydown",fn),window.addEventListener("keyup",Bt),window.addEventListener("blur",dt),document.addEventListener("visibilitychange",qe),sd(xe,t,a),ad(xe,t),Te(),IN(xe);const We=m?.current||d;return MN(xe,We,n)?(ie.current(!1),G.current.lastFitKey=Wg(t)):Z.current?.("mount",{animate:!1,force:!0}),be.current?.(t),Ve&&(xe.orbitControlsLastTimestamp=0,Ve.autoRotate=!!o,Ve.autoRotateSpeed=p1),rt(),()=>{oe=!0,window.cancelAnimationFrame(me),se&&window.clearTimeout(se),Vt?.disconnect(),window.removeEventListener("resize",ht),Ve?.removeEventListener("start",jt),Ve?.removeEventListener("change",qt),Ve?.removeEventListener("end",sn),we.domElement.removeEventListener("wheel",Mn,{passive:!0,capture:!0}),window.removeEventListener("keydown",fn),window.removeEventListener("keyup",Bt),window.removeEventListener("blur",dt),document.removeEventListener("visibilitychange",qe),Ve?.dispose?.(),xe.shaderScene?.dispose?.(),we.dispose(),we.domElement.remove(),S.current===xe&&(S.current=null)}},[J,n,g,d,m,!!t]),c.jsxs("div",{className:"relative h-full w-full overflow-hidden bg-[#09090b]",children:[c.jsx("div",{ref:y,className:"absolute inset-0"}),!o&&!r&&t&&Q?c.jsx("button",{type:"button","aria-label":"Reset view",title:"Reset view",className:`${fX} absolute z-20`,style:{right:`calc(${Ui(s,16)}px + 2rem)`,bottom:"calc(1rem + 6.6rem)"},onClick:Ie,children:c.jsx(w3,{className:"h-3.5 w-3.5",strokeWidth:2,"aria-hidden":"true"})}):null,c.jsx(Nw,{showViewPlane:!0,previewMode:o,isLoading:r,meshData:t,viewPlaneOffsetRight:s,viewPlaneOffsetBottom:"1rem",compact:!1,activeViewPlaneFace:k,viewPlaneFaces:Hw,viewPlaneOrientation:Y,viewerTheme:a,activateViewPlaneFace:_e,activateDefaultViewPlane:Ie}),r?c.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-4 z-10 flex justify-center",children:c.jsx("div",{className:"rounded-md border border-border/70 bg-background/90 px-3 py-1.5 text-xs text-muted-foreground shadow-sm",children:"Loading implicit CAD"})}):null,C?c.jsx("div",{className:"pointer-events-none absolute inset-0 z-20 flex items-center justify-center p-4",children:c.jsx("div",{className:"max-w-lg rounded-md border border-destructive/40 bg-background/95 p-4 text-sm text-foreground shadow-lg",children:C})}):null]})}),TX=th("relative grid w-full gap-1 rounded-md border px-4 py-3 text-sm shadow-sm has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] has-[>svg]:gap-x-3 [&>svg]:size-4 [&>svg]:translate-y-0.5",{variants:{variant:{default:"bg-card text-card-foreground",destructive:"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",warning:"border-chart-5/45 bg-chart-5/10 text-foreground [&>svg]:text-chart-5"}},defaultVariants:{variant:"default"}});function Hg({className:e,variant:t,...n}){return c.jsx("div",{"data-slot":"alert",role:"alert",className:H(TX({variant:t}),e),...n})}function RX({className:e,...t}){return c.jsx("div",{"data-slot":"alert-title",className:H("col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",e),...t})}function PX({className:e,...t}){return c.jsx("div",{"data-slot":"alert-description",className:H("col-start-2 grid justify-items-start gap-1 text-muted-foreground text-sm [&_p]:leading-relaxed",e),...t})}function hf({...e}){return c.jsx(mz,{"data-slot":"dropdown-menu",...e})}const gf=f.forwardRef(function({...t},n){return c.jsx(dz,{ref:n,"data-slot":"dropdown-menu-trigger",...t})}),bf=f.forwardRef(function({className:t,sideOffset:n=4,...r},o){return c.jsx(nR,{children:c.jsx(fz,{ref:o,"data-slot":"dropdown-menu-content",sideOffset:n,className:H("cad-glass-popover z-50 min-w-32 origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border border-border bg-popover p-1 text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",t),...r})})});function Yo({className:e,inset:t,variant:n="default",...r}){return c.jsx(pz,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":n,className:H("relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden transition-colors data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive",e),...r})}function T1({className:e,inset:t,...n}){return c.jsx(gz,{"data-slot":"dropdown-menu-label","data-inset":t,className:H("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",e),...n})}function nu({className:e,...t}){return c.jsx(hz,{"data-slot":"dropdown-menu-separator",className:H("-mx-1 my-1 h-px bg-border",e),...t})}function TO({...e}){return c.jsx(bz,{"data-slot":"dropdown-menu-sub",...e})}function RO({className:e,inset:t,children:n,showChevron:r=!0,...o}){return c.jsxs(yz,{"data-slot":"dropdown-menu-sub-trigger","data-inset":t,className:H("flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden transition-colors data-[inset]:pl-8 focus:bg-accent focus:text-accent-foreground",e),...o,children:[n,r?c.jsx(Vd,{className:"ml-auto size-4"}):null]})}function PO({className:e,...t}){return c.jsx(nR,{children:c.jsx(xz,{"data-slot":"dropdown-menu-sub-content",className:H("cad-glass-popover z-50 min-w-32 origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border border-border bg-popover p-1 text-popover-foreground shadow-lg animate-in fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t})})}const OX=th("inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-[color,box-shadow] outline-none hover:bg-muted hover:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",{variants:{variant:{default:"bg-transparent",outline:"border border-input bg-transparent shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:hover:bg-input/50"},size:{default:"h-9 min-w-9 px-2",sm:"h-8 min-w-8 px-1.5",lg:"h-10 min-w-10 px-2.5"}},defaultVariants:{variant:"default",size:"default"}}),OO=f.createContext({size:"default",variant:"default"});function Kw({className:e,variant:t,size:n,children:r,...o}){return c.jsx(Sz,{"data-slot":"toggle-group","data-variant":t,"data-size":n,className:H("group/toggle-group flex w-fit items-center rounded-md data-[variant=outline]:shadow-xs",e),...o,children:c.jsx(OO.Provider,{value:{variant:t,size:n},children:r})})}function Vp({className:e,variant:t,size:n,...r}){const o=f.useContext(OO);return c.jsx(Ez,{"data-slot":"toggle-group-item","data-variant":o.variant||t,"data-size":o.size||n,className:H(OX({variant:o.variant||t,size:o.size||n}),"min-w-0 flex-1 shrink-0 rounded-none shadow-none first:rounded-l-md last:rounded-r-md focus:z-10 focus-visible:z-10 data-[variant=outline]:border-l-0 data-[variant=outline]:first:border-l",e),...r})}function Bi({children:e}){return c.jsx("span",{className:"min-w-0 truncate",children:e})}function R1({Item:e,Separator:t,itemClassName:n="text-xs",selected:r=!1,isolated:o=!1,hidden:i=!1,actionCount:s=1,copyReferenceDisabled:a=!1,selectDisabled:l=!1,showIsolate:u=!0,isolateDisabled:d=!1,showExitAllIsolate:m=!1,exitAllIsolateDisabled:p=!1,showHideOther:g=!0,hideOtherDisabled:x=!1,hideAllDisabled:y=!0,hideAllLabel:S="Show all",showVisibility:b=!0,visibilityDisabled:I=!1,showCameraActions:A=!1,resetZoomDisabled:N=!1,zoomToFitDisabled:P=!1,showHideAll:R=!1,showExpandCollapse:v=!1,expandSelectedDisabled:C=!0,collapseSelectedDisabled:T=!0,expandAllDisabled:k=!0,collapseAllDisabled:z=!0,onCopyReference:Y,onSelect:K,onIsolate:J,onExitAllIsolate:G,onHideOther:Q,onHideAll:D,onToggleVisibility:$,onResetZoom:ie,onZoomToFit:W,onExpandSelected:Z,onCollapseSelected:Ee,onExpandAll:re,onCollapseAll:be}){const _e=r?"Deselect":"Select",Ie=o?"Exit isolate":"Isolate",oe=i?"Reveal":"Hide";return c.jsxs(c.Fragment,{children:[c.jsx(e,{className:n,disabled:a,onSelect:Y,children:c.jsx(Bi,{children:"Copy Reference"})}),c.jsx(t,{}),c.jsx(e,{className:n,disabled:l,onSelect:K,children:c.jsx(Bi,{children:_e})}),u?c.jsx(e,{className:n,disabled:d,onSelect:J,children:c.jsx(Bi,{children:Ie})}):null,m?c.jsx(e,{className:n,disabled:p,onSelect:G,children:c.jsx(Bi,{children:"Exit all isolates"})}):null,g||R||b?c.jsx(t,{}):null,g?c.jsx(e,{className:n,disabled:x,onSelect:Q,children:c.jsx(Bi,{children:"Hide others"})}):null,R?c.jsx(e,{className:n,disabled:y,onSelect:D,children:c.jsx(Bi,{children:S})}):null,b?c.jsx(e,{className:n,disabled:I,onSelect:$,children:c.jsx(Bi,{children:oe})}):null,A?c.jsxs(c.Fragment,{children:[c.jsx(t,{}),c.jsx(e,{className:n,disabled:N,onSelect:ie,children:c.jsx(Bi,{children:"Reset Zoom"})}),c.jsx(e,{className:n,disabled:P,onSelect:W,children:c.jsx(Bi,{children:"Zoom To Fit"})})]}):null,v?c.jsxs(c.Fragment,{children:[c.jsx(t,{}),c.jsx(e,{className:n,disabled:C,onSelect:Z,children:c.jsx(Bi,{children:"Expand"})}),c.jsx(e,{className:n,disabled:T,onSelect:Ee,children:c.jsx(Bi,{children:"Collapse"})}),c.jsx(e,{className:n,disabled:k,onSelect:re,children:c.jsx(Bi,{children:"Expand all"})}),c.jsx(e,{className:n,disabled:z,onSelect:be,children:c.jsx(Bi,{children:"Collapse all"})})]}):null]})}const Xw=Object.freeze({}),P1=new Set;let sl={elapsedSec:0,parameterValues:Xw};function kX(){for(const e of P1)e()}function kO(e){return P1.add(e),()=>{P1.delete(e)}}function DX(e){const t=Number(e);return Number.isFinite(t)&&t>0?t:0}function jX(e){return e&&typeof e=="object"?e:Xw}function Yw(e){const t={elapsedSec:DX(e.elapsedSec),parameterValues:jX(e.parameterValues)};t.elapsedSec===sl.elapsedSec&&t.parameterValues===sl.parameterValues||(sl=t,kX())}function AN(){return sl}function NN(){return sl.elapsedSec}function Yx({elapsedSec:e,parameterValues:t}){Yw({elapsedSec:e,parameterValues:t===void 0?sl.parameterValues:t})}function qx(e){Yw({elapsedSec:e,parameterValues:sl.parameterValues})}function Bl({elapsedSec:e=0,parameterValues:t=Xw}={}){Yw({elapsedSec:e,parameterValues:t})}function Zx(){return sl.elapsedSec}function _N(){return sl.parameterValues}function LX(){return f.useSyncExternalStore(kO,AN,AN)}function FX(){return f.useSyncExternalStore(kO,NN,NN)}function zX({dxfMode:e=!1,pathPreviewMode:t=!1,topologySelectionPending:n=!1,topologySelectionUnavailable:r=!1,topologySelectionDeferred:o=!1,topologyPickingActive:i=!1,viewerMode:s="",assemblyPickingActive:a=!1,focusedPartIds:l=""}={}){return n||r||o||e||t?si.NONE:s==="assembly"&&!i&&(a||!String(l||"").trim())?si.ASSEMBLY:si.AUTO}const Jx=Object.freeze([]),TN=Object.freeze({error:{label:"Error",borderClassName:"border-destructive/45",iconClassName:"border-destructive/45 bg-destructive/10 text-destructive dark:text-red-300",labelClassName:"text-destructive dark:text-red-300"},warning:{label:"Warning",borderClassName:"border-amber-500/45",iconClassName:"border-amber-500/55 bg-amber-500/10 text-amber-500 dark:text-amber-300",labelClassName:"text-amber-500 dark:text-amber-300"}});function Wi(e){const t=Number(e);return Number.isFinite(t)&&t>0?t:0}function BX(e){return e?.severity==="warning"?TN.warning:TN.error}function VX(e,t){if(!e)return null;const n=8,r=typeof window<"u"?window.innerWidth:0,o=typeof window<"u"?window.innerHeight:0,i=Wi(t?.left)+n,s=Wi(t?.top)+n,a=r>0?Math.max(i,r-Wi(t?.right)-n):Number(e.x)||i,l=o>0?Math.max(s,o-Wi(t?.bottom)-n):Number(e.y)||s,u=Math.min(Math.max(Number(e.x)||i,i),a),d=Math.min(Math.max(Number(e.y)||s,s),l);return{position:"fixed",left:`${u}px`,top:`${d}px`,width:"1px",height:"1px"}}function $X({value:e,threeDimensionalAvailable:t=!1,onChange:n}){const r=e==="3d"&&t?"3d":"2d";return c.jsx("div",{className:"cad-glass-surface rounded-md border border-sidebar-border p-0.5 shadow-sm",children:c.jsxs(Kw,{type:"single",variant:"outline",size:"sm",value:r,onValueChange:o=>{o&&(o==="3d"&&!t||n?.(o))},className:"grid h-7 w-[5.5rem] grid-cols-2","aria-label":"DXF view mode",children:[c.jsx(Vp,{value:"2d",className:"!h-7 px-2 text-[11px] text-muted-foreground hover:text-foreground data-[state=on]:!bg-accent data-[state=on]:!text-foreground data-[state=on]:font-semibold",title:"Show DXF flat pattern",children:"2D"}),c.jsx(Vp,{value:"3d",disabled:!t,className:"!h-7 px-2 text-[11px] text-muted-foreground hover:text-foreground data-[state=on]:!bg-accent data-[state=on]:!text-foreground data-[state=on]:font-semibold",title:t?"Show DXF bend preview":"3D bend preview unavailable",children:"3D"})]})})}function GX({menu:e,positionStyle:t,onClose:n,onCopyReference:r,onSelect:o,onFocus:i,onExitAllIsolate:s,onHideOther:a,onHideAll:l,onHide:u,onReveal:d,onResetZoom:m,onZoomToFit:p,onExpandSelected:g,onCollapseSelected:x,onExpandAll:y,onCollapseAll:S}){if(!e||!t)return null;const b="text-xs",I=R=>{R?.(e),n?.()},A=e.selected===!0,N=e.hidden===!0,P=e.focused===!0;return c.jsxs(hf,{open:!0,onOpenChange:R=>{R||n?.()},children:[c.jsx(gf,{asChild:!0,children:c.jsx("button",{type:"button",tabIndex:-1,"aria-hidden":"true",className:"pointer-events-none fixed size-px opacity-0",style:t})}),c.jsx(bf,{align:"start",side:"bottom",sideOffset:4,className:"w-44",onContextMenu:R=>{R.preventDefault(),R.stopPropagation()},children:e.global===!0?c.jsxs(c.Fragment,{children:[e.showShowAll===!0?c.jsx(Yo,{className:b,onSelect:()=>I(l),children:"Show all"}):null,e.showShowAll===!0&&e.showCameraActions!==!1?c.jsx(nu,{}):null,e.showCameraActions!==!1?c.jsx(c.Fragment,{children:c.jsx(Yo,{className:b,disabled:e.resetZoomDisabled===!0,onSelect:()=>I(m),children:"Reset Zoom"})}):null,e.showCameraActions!==!1&&e.showExpandCollapse===!0?c.jsx(nu,{}):null,e.showShowAll===!0&&e.showCameraActions===!1&&e.showExpandCollapse===!0?c.jsx(nu,{}):null,e.showExpandCollapse===!0?c.jsxs(c.Fragment,{children:[c.jsx(Yo,{className:b,disabled:e.expandAllDisabled===!0,onSelect:()=>I(y),children:"Expand all"}),c.jsx(Yo,{className:b,disabled:e.collapseAllDisabled===!0,onSelect:()=>I(S),children:"Collapse all"})]}):null]}):c.jsx(R1,{Item:Yo,Separator:nu,itemClassName:b,selected:A,isolated:P,hidden:N,actionCount:e.actionCount,copyReferenceDisabled:!String(e.copyText||"").trim(),selectDisabled:e.selectDisabled===!0,showIsolate:e.showIsolate!==!1,isolateDisabled:e.isolateDisabled===!0,showExitAllIsolate:e.showExitAllIsolate===!0,exitAllIsolateDisabled:e.exitAllIsolateDisabled===!0,showHideOther:e.showHideOther!==!1,hideOtherDisabled:e.hideOtherDisabled===!0,showVisibility:e.showVisibility!==!1,showHideAll:e.showHideAll===!0,hideAllDisabled:e.hideAllDisabled===!0,hideAllLabel:String(e.hideAllLabel||"").trim()||"Show all",visibilityDisabled:e.visibilityDisabled===!0,showCameraActions:e.showCameraActions!==!1,resetZoomDisabled:e.resetZoomDisabled===!0,zoomToFitDisabled:e.zoomToFitDisabled===!0,showExpandCollapse:e.showExpandCollapse===!0,expandSelectedDisabled:e.expandSelectedDisabled!==!1,collapseSelectedDisabled:e.collapseSelectedDisabled!==!1,expandAllDisabled:e.expandAllDisabled!==!1,collapseAllDisabled:e.collapseAllDisabled!==!1,onCopyReference:()=>I(r),onSelect:()=>I(o),onIsolate:()=>I(i),onExitAllIsolate:()=>I(s),onHideOther:()=>I(a),onHideAll:()=>I(l),onToggleVisibility:()=>I(N?d:u),onResetZoom:()=>I(m),onZoomToFit:()=>I(p),onExpandSelected:()=>I(g),onCollapseSelected:()=>I(x),onExpandAll:()=>I(y),onCollapseAll:()=>I(S)})})]})}function UX({viewerRef:e,renderFormat:t,renderPartsIndividually:n=!1,selectedMeshData:r,selectedDxfData:o,selectedDxfMeshData:i,dxfViewMode:s="2d",onDxfViewModeChange:a,selectedImplicitModel:l,implicitDynamicRenderActive:u=!1,implicitGraphicsSettings:d=null,selectedKey:m,selectedDxfKey:p,missingFileRef:g="",viewerPerspective:x,viewerPerspectiveRef:y,themeSettings:S,previewMode:b,viewportFrameInsets:I,viewerLoading:A,viewerAlert:N,stepUpdateInProgress:P,referenceSelectionPending:R=!1,referenceSelectionUnavailable:v=!1,referenceSelectionDeferred:C=!1,viewPlaneOffsetRight:T=16,viewerMode:k,assemblyPickingActive:z=!1,assemblyParts:Y,hiddenPartIds:K,selectedPartIds:J,hoveredPartId:G,assemblyMates:Q=Jx,selectedMateIds:D=Jx,hoveredMateId:$="",hoveredReferenceId:ie,selectedReferenceIds:W,selectorRuntime:Z,displayEdgeRuntime:Ee,stepParameters:re=null,pickableFaces:be,pickableEdges:_e,pickableVertices:Ie,focusedPartIds:oe="",displaySettings:me=null,onProjectionChange:se,onDisplayModeChange:Ae,boundsAnimationActive:we=!1,drawToolActive:ct,drawingTool:ut,drawingStrokes:Tt,handleDrawingStrokesChange:Ve,handlePerspectiveChange:St,handleModelHoverChange:wt,handleModelReferenceActivate:Vn,handleModelReferenceDoubleActivate:De,handleModelReferenceContext:xe,viewerContextMenu:yt=null,onViewerContextMenuClose:Te,onViewerContextMenuCopyReference:rt,onViewerContextMenuSelect:Re,onViewerContextMenuFocus:Fe,onViewerContextMenuExitAllIsolate:on,onViewerContextMenuHideOther:ht,onViewerContextMenuHideAll:jt,onViewerContextMenuHide:qt,onViewerContextMenuReveal:sn,onViewerContextMenuResetZoom:Mn,onViewerContextMenuZoomToFit:fn,onViewerContextMenuExpandSelected:Bt,onViewerContextMenuCollapseSelected:dt,onViewerContextMenuExpandAll:qe,onViewerContextMenuCollapseAll:Vt,handleViewerAlertChange:We,handleStepModuleTransformDetectedChange:ze,selectionCount:Ze,copyButtonLabel:vt,handleCopySelection:Tn,handleScreenshotCopy:pe,urdfPosePicker:Xe=null}){const He=LX(),Rn=f.useMemo(()=>{if(!re?.animationState?.playing)return re;const En=He?.parameterValues;return!En||typeof En!="object"?re:{...re,parameterValues:En,animationState:{...re.animationState,elapsedSec:He.elapsedSec}}},[re,He]),xn="Viewer error. See the Issues section for details.",ue=t===B.DXF,Rt=t===B.GCODE,Zt=Hi(t),qn=t===B.IMPLICIT,Ct=df(t)||Rt,wr=!!i,vr=s==="3d"&&wr?"3d":"2d",Qt=ue&&vr==="3d"&&wr,In=Qt?i:r,gr=t===B.STEP&&!!me&&!ue&&!Ct,lo=gr?ul(me.projection):yo.PERSPECTIVE,Mt=Qt&&p||m,gt=!!Rn?.animationState?.playing,Sn=!!(we||gt),On=String(g||"").trim(),Kr=!!(R&&!ue&&!Zt&&!Ct),Xr=!!(v&&!ue&&!Zt&&!Ct),Co=!!(C&&In&&!ue&&!Zt&&!Ct),br=!!Xe?.active,j="Select target",de={left:`calc(${Math.max(Number(I?.left)||0,0)}px + 0.75rem)`,top:`calc(${Math.max(Number(I?.top)||0,0)}px + 0.75rem)`},L=!ue&&!Ct&&ct?"screenshot":!ue&&!Ct&&Ze>0?"selection":"",te=ue?c.jsx($X,{value:vr,threeDimensionalAvailable:wr,onChange:a}):null,fe={bottom:"1rem"},ae={left:`${Wi(I?.left)}px`,right:`${Wi(I?.right)}px`,top:`${Wi(I?.top)}px`,bottom:`${Wi(I?.bottom)}px`},he={left:`${Wi(I?.left)}px`,right:`${Wi(I?.right)}px`,bottom:`calc(${Wi(I?.bottom)}px + 1rem)`},ot={...fe,left:`calc(${Wi(I?.left)}px + 1rem)`,right:`calc(${Wi(I?.right)}px + 1rem)`},It=L==="screenshot"?"Copy Screenshot":vt,Pt=L==="screenshot"?"Copy screenshot to clipboard":vt,Ke=L==="screenshot"?A||!In:!1,en=qn?!!l:ue&&!Qt?!!o:!!In,Ne=N&&N.blocking!==!1&&(N.blocking||N.severity!=="warning"||!en)?N:null,Et=BX(Ne),Pe=f.useMemo(()=>VX(yt,I),[yt,I]);return f.useEffect(()=>{if(!br||typeof window>"u"||typeof document>"u")return;const En=Se=>{Se.defaultPrevented||Se.key!=="Escape"&&Se.key!=="Esc"&&Se.code!=="Escape"||(Se.preventDefault(),Se.stopPropagation(),Xe?.onCancel?.())};return window.addEventListener("keydown",En,!0),document.addEventListener("keydown",En,!0),()=>{window.removeEventListener("keydown",En,!0),document.removeEventListener("keydown",En,!0)}},[Xe,br]),c.jsxs("div",{className:"absolute inset-0",children:[qn?c.jsx(_X,{ref:e,model:l,modelKey:Mt,isLoading:A,previewMode:b,viewportFrameInsets:I,viewPlaneOffsetRight:T,themeSettings:S,graphicsSettings:d,dynamicRenderActive:u,perspective:x,perspectiveRef:y,onPerspectiveChange:St,onViewerAlertChange:We},`implicit:${Mt}`):ue&&!Qt?c.jsx(l9,{ref:e,dxfData:o,modelKey:p,themeSettings:S,viewPlaneOffsetRight:T,viewPlaneOffsetBottom:"1rem",viewPlaneHeader:te,onViewerAlertChange:We}):c.jsx(F6,{ref:e,meshData:In,modelKey:Mt,renderFormat:t,perspective:x,projection:lo,perspectiveRef:y,onProjectionChange:gr?se:void 0,onDisplayModeChange:gr?Ae:void 0,showEdges:!Rt,recomputeNormals:!1,themeSettings:S,displaySettings:gr?me:null,previewMode:ue?!1:b,showViewPlane:ue||Rt?!0:!b,scale:Zt?Er.URDF:Er.CAD,viewPlaneOffsetRight:T,viewPlaneOffsetBottom:"1rem",viewPlaneHeader:te,compactViewPlane:!1,viewportFrameInsets:I,isLoading:A,pickMode:Zt?si.NONE:zX({dxfMode:ue,pathPreviewMode:Ct,topologySelectionPending:Kr,topologySelectionUnavailable:Xr,topologySelectionDeferred:Co,topologyPickingActive:!!(be?.length||_e?.length||Ie?.length),viewerMode:k,assemblyPickingActive:z,focusedPartIds:oe}),renderPartsIndividually:Zt?!0:n||!!Rn?.definition,pickableParts:ue||Zt||Ct?Jx:Y,hiddenPartIds:ue||Ct?[]:K,selectedPartIds:ue||Ct?[]:J,hoveredPartId:ue||Ct?"":G,assemblyMates:ue||Ct?[]:Q,selectedMateIds:ue||Ct?[]:D,hoveredMateId:ue||Ct?"":$,hoveredReferenceId:ue||Ct?"":ie,selectedReferenceIds:ue||Ct?[]:W,selectorRuntime:ue||Ct?null:Z,displayEdgeRuntime:ue||Ct?null:Ee,stepParameters:ue||Ct?null:Rn,pickableFaces:ue||Ct?[]:be,pickableEdges:ue||Ct?[]:_e,pickableVertices:ue||Ct?[]:Ie,focusedPartId:ue||Ct?"":oe,boundsAnimationActive:Sn,drawingEnabled:!ue&&!Ct&&ct,drawingTool:ut,drawingStrokes:ue||Ct?[]:Tt,onDrawingStrokesChange:Ve,onPerspectiveChange:St,onHoverReferenceChange:wt,onActivateReference:Vn,onDoubleActivateReference:De,onContextReference:xe,onViewerAlertChange:We,onStepModuleTransformDetectedChange:ze,urdfPosePicker:Xe}),b?null:c.jsx(GX,{menu:yt,positionStyle:Pe,onClose:Te,onCopyReference:rt,onSelect:Re,onFocus:Fe,onExitAllIsolate:on,onHideOther:ht,onHideAll:jt,onHide:qt,onReveal:sn,onResetZoom:Mn,onZoomToFit:fn,onExpandSelected:Bt,onCollapseSelected:dt,onExpandAll:qe,onCollapseAll:Vt}),!b&&On?c.jsx("div",{className:"pointer-events-none absolute z-30 flex min-w-0 items-center justify-center px-4 py-4",style:ae,children:c.jsxs(Hg,{variant:"destructive",className:"cad-glass-popover pointer-events-auto w-full max-w-xl min-w-0 p-5 text-center shadow-lg",children:[c.jsx("p",{className:"col-start-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-destructive",children:"File does not exist"}),c.jsx(RX,{className:"col-start-1 mt-1 line-clamp-none text-lg text-foreground",children:"File does not exist"}),c.jsx(PX,{className:"col-start-1 mt-1 text-sm leading-6 text-muted-foreground",children:c.jsx("code",{className:"rounded-md bg-muted px-2 py-1 text-xs text-foreground",children:On})})]})}):null,!b&&Ne?c.jsx("div",{className:"pointer-events-none absolute z-30 flex min-w-0 items-center justify-center px-3 py-3 sm:px-4",style:ae,children:c.jsxs("div",{role:"alert","aria-label":xn,title:xn,className:H("cad-glass-popover pointer-events-auto flex w-full max-w-sm min-w-0 flex-col items-center gap-2 rounded-md border px-4 py-3 text-center shadow-md",Et.borderClassName),children:[c.jsx("span",{className:H("flex size-9 shrink-0 items-center justify-center rounded-full border",Et.iconClassName),children:c.jsx(v3,{className:"size-5",strokeWidth:2,"aria-hidden":"true"})}),c.jsxs("div",{className:"min-w-0 max-w-full",children:[c.jsx("span",{className:H("text-[10px] font-medium uppercase tracking-[0.08em]",Et.labelClassName),children:Et.label}),c.jsx("div",{className:"mt-1 line-clamp-2 min-w-0 max-w-full break-words text-sm font-medium leading-5 text-foreground",children:N.title||N.summary||"Viewer issue"}),N.message?c.jsx("p",{className:"mt-1 line-clamp-3 min-w-0 max-w-full break-words text-xs leading-5 text-muted-foreground",children:N.message}):null,N.resolution?c.jsx("p",{className:"mt-1 line-clamp-2 min-w-0 max-w-full break-words text-xs leading-5 text-muted-foreground",children:N.resolution}):null]})]})}):null,!b&&P?c.jsx("div",{className:"pointer-events-none absolute z-20 flex justify-center px-4",style:he,children:c.jsx(Hg,{role:"status",className:"cad-glass-popover w-auto px-3 py-1.5 text-[11px] font-medium text-popover-foreground shadow-sm",children:"STEP changed. Updating/regenerating references..."})}):null,!b&&!P&&Kr?c.jsx("div",{className:"pointer-events-none absolute z-20 flex justify-center px-4",style:he,children:c.jsx(Hg,{role:"status",className:"cad-glass-popover w-auto px-3 py-1.5 text-[11px] font-medium text-popover-foreground shadow-sm",children:"Preparing selectable topology..."})}):null,!b&&br?c.jsx(Qe,{type:"button",variant:"outline",size:"icon-xs",className:"cad-glass-popover pointer-events-auto absolute z-30 size-6 rounded-md border-sidebar-border p-0 text-popover-foreground shadow-sm",style:de,onClick:()=>{Xe?.onCancel?.()},"aria-label":"Exit Select Pose",title:"Exit Select Pose",children:c.jsx(eh,{className:"size-3.5",strokeWidth:2,"aria-hidden":"true"})}):null,!b&&br?c.jsx("div",{className:"pointer-events-none absolute z-20 flex justify-center px-4",style:he,children:c.jsx(Hg,{role:"status",className:"cad-glass-popover w-auto px-3 py-1.5 text-[11px] font-medium text-popover-foreground shadow-sm",children:j})}):null,!b&&L&&!P&&!Kr&&!Xr&&!Co?c.jsx("div",{className:"pointer-events-none absolute z-20 flex min-w-0 justify-center",style:ot,children:c.jsx(Qe,{type:"button",variant:"default",size:"sm",className:"pointer-events-auto h-9 w-fit min-w-0 max-w-[min(28rem,100%)] shrink overflow-hidden border border-primary/20 bg-primary/85 px-4 text-[12px] font-semibold text-primary-foreground shadow-lg shadow-black/20 hover:bg-primary/75 focus-visible:ring-primary/35 max-sm:w-full",disabled:Ke,onClick:()=>{if(L==="screenshot"){pe?.();return}Tn()},title:Pt,children:c.jsx("span",{className:"block min-w-0 max-w-full truncate",children:It})})}):null]})}const $p=2,RN=.2,PN=25,my=0,ON=0,kN=180,cu={UP:"up",DOWN:"down"},DN=1e3,WX=.35,HX=10,KX=160,jN=.04,Cn=.001,sc=.01,XX=6,YX=48,qX=.6;function Na(e,t,n){return Math.min(Math.max(e,t),n)}function Ji(e,t=0){const n=Number(e);return Number.isFinite(n)?n:t}function al(e,t,n=Cn){return Math.abs(e-t)<=n}function Nd(e){return!Array.isArray(e)||e.length<2?[0,0]:[Ji(e[0]),Ji(e[1])]}function qw(e,t,n=Cn){return Math.abs(e[0]-t[0])<=n&&Math.abs(e[1]-t[1])<=n}function wm(e){return`${Math.round(e[0]*DN)}:${Math.round(e[1]*DN)}`}function DO(e){return[...e].reverse()}function jO(e){return e.length>1&&qw(e[0],e[e.length-1])?e.slice(0,-1):e}function Qy(e){const t=[];for(const n of e)t.length&&qw(t[t.length-1],n)||t.push(n);return jO(t)}function LO(e,t){const n=Math.max(Math.abs(e),.01),r=Na(1-WX/n,-1,1),o=r<=-1?Math.PI/8:Na(2*Math.acos(r),Math.PI/64,Math.PI/10);return Na(Math.ceil(Math.max(Math.abs(t),Math.PI/36)/o),HX,KX)}function FO(e,t,n,r){const o=Ji(n)*Math.PI/180,i=Ji(r)*Math.PI/180,s=LO(t,i),a=[];for(let l=0;l<=s;l+=1){const u=l/s,d=o+i*u;a.push([e[0]+t*Math.cos(d),e[1]+t*Math.sin(d)])}return a}function ZX(e,t){const n=FO(e,t,0,360);return jO(n)}function O1(e){if(!Array.isArray(e)||e.length<3)return 0;let t=0;for(let n=0;nnew FS(i,s)),o=fR.isClockWise(r);return t&&!o||!t&&o?DO(n):n}function zO(e){const t=e?.geometry||{},n=Array.isArray(t.lines)?t.lines:[],r=Array.isArray(t.arcs)?t.arcs:[],o=Array.isArray(t.circles)?t.circles:[],i=[],s=[],a=[];for(const l of n){const u=Nd(l?.start),d=Nd(l?.end);if(String(l?.kind||"").trim().toLowerCase()==="bend"){a.push([u,d]);continue}qw(u,d)||i.push({points:[u,d]})}for(const l of r){const u=Nd(l?.center),d=Math.max(Ji(l?.radius),0);if(d<=0)continue;const m=String(l?.kind||"").trim().toLowerCase(),p=FO(u,d,Ji(l?.startAngleDeg),Ji(l?.sweepAngleDeg));if(m==="bend"){a.push([p[0],p[p.length-1]]);continue}i.push({points:p})}for(const l of o){const u=Nd(l?.center),d=Math.max(Ji(l?.radius),0);d<=0||String(l?.kind||"").trim().toLowerCase()==="bend"||s.push(ZX(u,d))}return{cutPrimitives:i,cutCircleLoops:s,bendLines:a}}function JX(e){const{cutPrimitives:t,cutCircleLoops:n,bendLines:r}=zO(e);if(!t.length&&!n.length)throw new Error("DXF preview requires cut-layer contour geometry");const o=new Map,i=new Set,s=[],a=(l,u)=>{const d=o.get(l);if(d){d.push(u);return}o.set(l,[u])};t.forEach((l,u)=>{const d=wm(l.points[0]),m=wm(l.points[l.points.length-1]);a(d,{index:u,reverse:!1}),a(m,{index:u,reverse:!0})});for(let l=0;l!i.has(b));if(!g.length)throw new Error("DXF preview requires closed cut contours");const x=g[0];i.add(x.index);const y=t[x.index].points,S=x.reverse?DO(y):y;if(u=u.concat(S.slice(1)),m=wm(S[S.length-1]),p+=1,p>t.length+4)throw new Error("DXF preview contour walk did not terminate")}u=Qy(u),u.length>=3&&s.push(u)}for(const l of n)l.length>=3&&s.push(l);if(!s.length)throw new Error("DXF preview could not resolve any closed cut contours");return{loops:s,bendLines:r}}function QX(e,t){const n=Nd(e?.[0]),r=Nd(e?.[1]),o=r[1]QX(t,n)).sort((t,n)=>{const r=t.x-n.x;return Math.abs(r)>Cn?r:t.yMin-n.yMin}).map((t,n)=>({...t,id:`bend-${n+1}`,index:n}))}function VO(e){const{bendLines:t}=zO(e);return BO(t)}function eY(e){for(const t of e){if(Math.abs(t.start[0]-t.end[0])>sc)throw new Error("DXF 3D bend preview currently requires vertical bend lines");if(Math.abs(t.end[1]-t.start[1])<=Cn)throw new Error("DXF bend line length is too small for preview bending")}}function Gp(e){return String(e||"").trim().toLowerCase()===cu.DOWN?cu.DOWN:cu.UP}function Up(e,t=my){const n=Na(Ji(t,my),ON,kN),r=Ji(e,n);return Na(r,ON,kN)}function py(e,t=$p){const n=Na(Ji(t,$p),RN,PN),r=Ji(e,n);return r<=0?n:Na(r,RN,PN)}function Rb(e,t){const n=VO(e),r=Array.isArray(t)?t:[];return n.map((o,i)=>{const s=r[i]&&typeof r[i]=="object"?r[i]:{};return{id:o.id,direction:Gp(s.direction),angleDeg:Up(s.angleDeg,my)}})}function LN(e,t,n){const r=t[0]-e[0];if(Math.abs(r)<=Cn)return[n,e[1]];const o=(n-e[0])/r;return[n,e[1]+(t[1]-e[1])*o]}function FN(e,t,n){const r=t[0]-e[0];if(Math.abs(r)<=Cn)return[n,e[1]];const o=(n-e[0])/r;return[n,e[1]+(t[1]-e[1])*o]}function tY(e,t){if(!e.length)return[];const n=[];for(let r=0;r=t-Cn,a=i[0]>=t-Cn;s?(a||n.push(LN(i,o,t)),n.push(o)):a&&n.push(LN(i,o,t))}return Qy(n)}function nY(e,t){if(!e.length)return[];const n=[];for(let r=0;rCn)return!1;const o=(e[0]-t[0])*(n[0]-t[0])+(e[1]-t[1])*(n[1]-t[1]);if(o<-Cn)return!1;const i=(n[0]-t[0])**2+(n[1]-t[1])**2;return o<=i+Cn}function iY(e,t){let n=!1;for(let r=0,o=t.length-1;re[1]!=s[1]>e[1]))continue;const l=s[0]+(e[1]-s[1])*(i[0]-s[0])/(i[1]-s[1]);e[0]({loop:r,index:o,parentIndex:-1,depth:-1,area:Math.abs(O1(r))}));for(let r=0;r=a||iY(i,u.loop)&&(s=l,a=u.area)}o.parentIndex=s}const n=r=>{const o=t[r];return o.depth>=0||(o.depth=o.parentIndex<0?0:n(o.parentIndex)+1),o.depth};for(let r=0;ra.parentIndex===r.index&&a.depth%2===1).map(a=>Zd(a.loop,{clockwise:!1}));n.push({index:n.length,transformIndex:0,leftX:i.minX,rightX:i.maxX,outerLoop:o,holeLoops:s,isLeftExterior:!0,isRightExterior:!0})}if(!n.length)throw new Error("DXF preview could not build flat extrusion geometry");return n}function $O(e,t,n){const r=e0(e);return r.maxX<=t+Cn||r.minX>=n-Cn?"outside":r.minX>=t-Cn&&r.maxX<=n+Cn?"inside":"intersects"}function lY(e,t,n,r){const o=t.map((i,s)=>{const a=n[s]||{direction:cu.UP,angleDeg:my},l=mY(a),u=Math.abs(l),d=Math.max(r*2*qX,Cn),m=d+r,p=u>1e-6?m*u/2:0;return{bendLine:i,angleRadians:l,insideRadius:d,neutralRadius:m,leftX:i.x-p,rightX:i.x+p}});for(let i=0;i{const s=Math.max(i.rightX-i.leftX,0),a=Math.abs(i.angleRadians),l=a>1e-6&&s>Cn?s/a:i.neutralRadius;return{...i,flatWidth:s,neutralRadius:l,insideRadius:Math.max(l-r,Cn)}})}function cY(e,t){for(const n of e)for(const r of t)if(!(r.rightX-r.leftX<=Cn)&&$O(n,r.leftX,r.rightX)!=="outside")throw new Error("DXF 3D bend preview does not support holes crossing bend radius bands")}function uY(e,t,n){const r=e0(e);cY(t,n);const o=[];let i=r.minX;for(let s=0;s<=n.length;s+=1){const a=n[s]||null,l=a?a.leftX:r.maxX;if(l-i<=Cn){a&&(i=Math.max(i,a.rightX));continue}const u=Zd(rY(e,i,l),{clockwise:!0});if(u.length<3){a&&(i=Math.max(i,a.rightX));continue}const d=[];for(const m of t){const p=$O(m,i,l);if(p==="inside"){d.push(Zd(m,{clockwise:!1}));continue}if(p==="intersects")throw new Error("DXF 3D bend preview does not support holes crossing bend lines")}o.push({index:o.length,transformIndex:s,leftX:i,rightX:l,outerLoop:u,holeLoops:d,isLeftExterior:al(i,r.minX),isRightExterior:al(l,r.maxX)}),a&&(i=Math.max(i,a.rightX))}if(!o.length)throw new Error("DXF preview could not build bendable strip geometry");return{strips:o,bounds:r}}function Zm(e,t,n,r,o){const i=e.length/3;e.push(...n,...r,...o),t.push(i,i+1,i+2)}function dY(e,t,n,r=!0){const o=t[0]-e[0],i=t[2]-e[2],s=n[0]-e[0],a=n[2]-e[2],l=i*s-o*a;return r&&l<0||!r&&l>0?[e,n,t]:[e,t,n]}function Qi(e,t){const[n,r,o]=t,i=e.elements;return[i[0]*n+i[4]*r+i[8]*o+i[12],i[1]*n+i[5]*r+i[9]*o+i[13],i[2]*n+i[6]*r+i[10]*o+i[14]]}function hy(e,t,n,r,o,i,s){const a=dY(Qi(n,r),Qi(n,o),Qi(n,i),s);Zm(e,t,a[0],a[1],a[2])}function GO(e,t,n,r,o,i,s,a=!1){const l=Qi(n,r),u=Qi(n,o),d=Qi(n,i),m=Qi(n,s);if(a){Zm(e,t,l,d,u),Zm(e,t,l,m,d);return}Zm(e,t,l,u,d),Zm(e,t,l,d,m)}function zN(e,t,n,r){return e.push(t,n,r),e.length/3-1}function Sp(e,t,n,r,o){const i=Qi(n,r),s=Qi(n,o),a=zN(e,i[0],i[1],i[2]),l=zN(e,s[0],s[1],s[2]);t.push(a,l)}function fY(e,t,n){return al(e[0],t[0],sc)?!!(al(e[0],n.leftX,sc)&&!n.isLeftExterior||al(e[0],n.rightX,sc)&&!n.isRightExterior):!1}function BN(e,t,n,r,o,i,s=()=>!1){for(let a=0;a!1){for(let a=0;aCn)i=l.clone().multiply(hY(s));else{const u=Qi(l,[a.start[0],0,a.start[1]]),d=Qi(l,[a.end[0],0,a.end[1]]);i=pY(u,d,s.angleRadians).clone().multiply(l)}n.push(i.clone())}return{transforms:n,bendTransforms:r,guideLineSegments:o}}function k1(e){const t=e.map(([r,o])=>[Math.min(r,o),Math.max(r,o)]).filter(([r,o])=>o-r>Cn).sort((r,o)=>r[0]-o[0]),n=[];for(const r of t){const o=n[n.length-1];if(o&&r[0]<=o[1]+Cn){o[1]=Math.max(o[1],r[1]);continue}n.push([...r])}return n}function $N(e,t){const n=[];for(let r=0;rCn&&n.push([o[1],i[1]])}return n}function bY(e,t){const n=[];for(const r of e)for(const o of t){const i=Math.max(r[0],o[0]),s=Math.min(r[1],o[1]);s-i>Cn&&n.push([i,s])}return k1(n)}function yY(e,t){const n=[],r=[];for(const s of e)al(s.rightX,t.leftX,sc)&&!s.isRightExterior&&n.push(...$N(s.outerLoop,t.leftX)),al(s.leftX,t.rightX,sc)&&!s.isLeftExterior&&r.push(...$N(s.outerLoop,t.rightX));const o=k1(n),i=k1(r);return o.length&&i.length?bY(o,i):o.length?o:i.length?i:[[t.bendLine.yMin,t.bendLine.yMax]].filter(([s,a])=>a-s>Cn)}function xY(e,t){return Na(LO(Math.max(e,Cn),t),XX,YX)}function Es(e,t,n,r){const o=(e.angleRadians<0?-1:1)*e.neutralRadius,i=t-o;return[e.leftX-i*Math.sin(r),o+i*Math.cos(r),n]}function GN(e,t,n,r,o,i,s,a,l,u){GO(e,t,n,Es(r,o,i,a),Es(r,o,i,l),Es(r,o,s,l),Es(r,o,s,a),u)}function UN(e,t,n,r,o,i,s,a,l){GO(e,t,n,Es(r,o,i,s),Es(r,o,i,a),Es(r,-o,i,a),Es(r,-o,i,s),l)}function WN(e,t,n,r,o,i,s,a){Sp(e,t,n,Es(r,o,i,s),Es(r,o,i,a))}function HN(e,t,n,r,o,i,s){Sp(e,t,n,Es(r,o,i,s),Es(r,-o,i,s))}function SY(e,t,n,r,o,i,s){const{bendProfile:a}=o,l=a.angleRadians;if(Math.abs(l)<=1e-6)return;const[u,d]=i;if(d-u<=Cn)return;const m=o.matrix,p=xY(a.neutralRadius+s,l),g=l<0,x=l>0,y=l<0;for(let S=0;SMath.abs(O1(l))-Math.abs(O1(a))),o=Zd(r[0]||[],{clockwise:!0});if(!o.length)throw new Error("DXF preview requires one outer contour");const i=r.slice(1).map(a=>Zd(a,{clockwise:!1})),s=BO(n);return eY(s),{loops:r,outerLoop:o,holeLoops:i,bendLines:s}}function CY(e,t,n=null){const{loops:r,outerLoop:o,holeLoops:i,bendLines:s}=vY(e),a=py(t,Ji(e?.defaultThicknessMm,$p)),l=Rb(e,n),u=a/2;let d,m,p,g;if(s.length){const R=e0(o),v=lY(R,s,l,u);({strips:d}=uY(o,i,v)),{transforms:g,bendTransforms:m,guideLineSegments:p}=gY(v,u)}else d=aY(r),g=[new qi().identity()],m=[],p=[];const x=[],y=[],S=[],b=[];for(const R of d){const v=g[R.transformIndex]||g[g.length-1]||new qi().identity(),C=R.outerLoop.map(([K,J])=>new FS(K,J)),T=R.holeLoops.map(K=>K.map(([J,G])=>new FS(J,G))),k=fR.triangulateShape(C,T),z=C.concat(...T);for(const K of k){const J=z[K[0]],G=z[K[1]],Q=z[K[2]];hy(x,y,v,[J.x,u,J.y],[G.x,u,G.y],[Q.x,u,Q.y],!0),hy(x,y,v,[J.x,-u,J.y],[G.x,-u,G.y],[Q.x,-u,Q.y],!1)}const Y=(K,J)=>fY(K,J,R);BN(x,y,v,R.outerLoop,u,-u,Y),VN(S,b,v,R.outerLoop,u,-u,Y);for(const K of R.holeLoops)BN(x,y,v,K,u,-u),VN(S,b,v,K,u,-u)}EY(x,y,S,b,d,m,u);const I=x.length/3,A=new Float32Array(x.length+S.length);A.set(x,0),A.set(S,x.length);const N=new Uint32Array(b.length);for(let R=0;Rsvg]:rotate-180",e),...n,children:[t,c.jsx(jy,{className:"size-4 shrink-0 text-[var(--ui-text-faint)]"})]})})}function AY({className:e,children:t,...n}){return c.jsx(Iz,{"data-slot":"accordion-content",className:"overflow-hidden text-sm",...n,children:c.jsx("div",{className:H("pb-0",e),children:t})})}function ch({className:e,viewportClassName:t,scrollbars:n="vertical",type:r,scrollHideDelay:o,children:i,...s}){const a=Array.isArray(n)?n:[n].filter(Boolean),l=a.includes("horizontal"),u=a.includes("vertical"),d=l?"overflow-x-auto":"overflow-x-hidden",m=u?"overflow-y-auto":"overflow-y-hidden";return c.jsx("div",{"data-slot":"scroll-area",className:H("relative",e),...s,children:c.jsx("div",{"data-slot":"scroll-area-viewport",className:H("size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1",d,m,t),children:c.jsx("div",{className:H("min-w-full",l?"w-max":"w-full"),children:i})})})}function NY({className:e,thumbClassName:t,...n}){return c.jsx(Az,{"data-slot":"switch",className:H("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border border-transparent bg-input shadow-xs transition-all outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input dark:data-[state=unchecked]:bg-input/80",e),...n,children:c.jsx(Nz,{"data-slot":"switch-thumb",className:H("pointer-events-none block size-4 rounded-full bg-background ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0",t)})})}const _Y=365,UO=240,Kg="min(28rem, calc(100vw - 0.75rem))",TY="min(24rem, calc(100vw - 0.75rem))",RY=["[&_[data-slot=input]]:!text-[11px]","[&_[data-slot=select-trigger]]:!text-[11px]","[&_[data-slot=color-picker-trigger]]:!text-[11px]"].join(" "),PY="px-3 py-2 text-sm font-normal text-sidebar-foreground/90",OY="py-1",kY="space-y-1 px-3 py-0.5",t0="space-y-2",DY=`${t0} py-3`,jY="space-y-1 px-3 py-0.5",LY="px-3 py-0.5",Nu="block min-w-0 truncate text-[11px] font-medium leading-4 text-muted-foreground",FY="px-3 py-1 text-[11px] font-normal leading-4 text-sidebar-foreground",zY="shrink-0 rounded bg-muted px-1.5 py-0.5 font-mono text-[10px] font-medium leading-none tabular-nums text-muted-foreground",BY=["h-7 w-20 shrink-0 rounded-md border border-input bg-transparent px-1.5 py-1 text-right text-[11px] font-medium leading-none tabular-nums text-foreground shadow-xs outline-none","m-0 box-border min-w-0 appearance-none transition-[color,box-shadow,border-color] placeholder:text-muted-foreground","focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:opacity-50 dark:bg-input/30"].join(" "),uh="h-7 px-2 text-[11px] text-muted-foreground hover:text-foreground",VY="size-7 text-muted-foreground hover:text-foreground",n0="!h-7 px-2 text-[11px] !text-foreground",$Y="h-7 px-2 !text-[11px] font-medium leading-none tabular-nums text-foreground",GY=["h-4 w-7 border shadow-none","data-[state=checked]:border-primary/75 data-[state=checked]:bg-primary","data-[state=unchecked]:!border-[rgb(115_125_140_/_0.52)] data-[state=unchecked]:!bg-[rgb(115_125_140_/_0.22)]","dark:data-[state=unchecked]:!border-[rgb(148_163_184_/_0.44)] dark:data-[state=unchecked]:!bg-[rgb(148_163_184_/_0.18)]"].join(" "),UY=["!size-3 shadow-sm","data-[state=checked]:!translate-x-3 data-[state=checked]:!bg-background","data-[state=unchecked]:!translate-x-0 data-[state=unchecked]:!bg-[rgb(115_125_140)]","dark:data-[state=unchecked]:!bg-[rgb(148_163_184)]"].join(" "),D1=["text-muted-foreground hover:text-foreground","data-[state=on]:!bg-accent data-[state=on]:!text-foreground data-[state=on]:font-semibold","data-[state=on]:ring-1 data-[state=on]:ring-inset data-[state=on]:ring-border/80","data-[state=on]:hover:!bg-accent data-[state=on]:hover:!text-foreground"].join(" "),Us=["h-4","[&_[data-slot=slider-track]]:h-px","[&_[data-slot=slider-track]]:rounded-none","[&_[data-slot=slider-track]]:bg-border","[&_[data-slot=slider-range]]:bg-primary","[&_[data-slot=slider-thumb]]:h-2.5","[&_[data-slot=slider-thumb]]:w-1.5","[&_[data-slot=slider-thumb]]:rounded-[1px]","[&_[data-slot=slider-thumb]]:border-primary","[&_[data-slot=slider-thumb]]:bg-background","[&_[data-slot=slider-thumb]]:shadow-none","[&_[data-slot=slider-thumb]]:ring-0","[&_[data-slot=slider-thumb]]:hover:border-primary/85","[&_[data-slot=slider-thumb]]:hover:ring-1","[&_[data-slot=slider-thumb]]:hover:ring-ring/25","[&_[data-slot=slider-thumb]]:focus-visible:ring-2","[&_[data-slot=slider-thumb]]:focus-visible:ring-ring/30"].join(" ");function ci({value:e,title:t,children:n,className:r,contentClassName:o,triggerClassName:i,triggerProps:s,...a}){return c.jsxs(MY,{value:e,className:H("border-border",r),...a,children:[c.jsx(IY,{className:H(PY,i),...s,children:t}),c.jsx(AY,{className:H(OY,o),children:n})]})}function bo({title:e,trailing:t=null,children:n,className:r,contentClassName:o,hideFirstSeparator:i=!0}){return c.jsxs("div",{className:H("py-2.5",i&&"first:pt-2 first:[&_.cad-sheet-subsection-separator]:hidden",r),children:[c.jsx("div",{className:"cad-sheet-subsection-separator mx-3 mb-2 h-px bg-border/60"}),c.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2 px-3 pb-1 text-[12px] font-normal leading-5 text-sidebar-foreground/80",children:[c.jsx("span",{className:"min-w-0 truncate",children:e}),t?c.jsx("span",{className:"shrink-0",children:t}):null]}),c.jsx("div",{className:H(t0,o),"data-file-sheet-row-stack":"",children:n})]})}function WY({title:e,children:t,className:n,contentClassName:r}){return c.jsxs("div",{className:H("py-1",n),"data-file-sheet-subsubsection":"",children:[c.jsx("div",{className:FY,children:e}),c.jsx("div",{className:H(t0,r),"data-file-sheet-row-stack":"",children:t})]})}function r0({children:e,className:t}){return c.jsx("div",{className:H(DY,t),"data-file-sheet-section-body":"","data-file-sheet-row-stack":"",children:e})}function cn({label:e,value:t,trailing:n,children:r,className:o,contentClassName:i,labelClassName:s,rowKind:a="control"}){return c.jsxs("div",{className:H(kY,o),"data-file-sheet-control-row":"","data-file-sheet-row-kind":a,children:[e!=null||t!=null||n!=null?c.jsxs("div",{className:"flex min-h-4 items-center justify-between gap-2",children:[e!=null?c.jsx("span",{className:H(Nu,s),children:e}):c.jsx("span",{}),n??(t!=null?c.jsx("span",{className:zY,children:t}):null)]}):null,c.jsx("div",{className:H("min-w-0",i),children:r})]})}function ui(e,{fallback:t=0,min:n=-1/0,max:r=1/0,integer:o=!1}={}){const s=String(e??"").trim().match(/[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?/i),a=Number.isFinite(Number(t))?Number(t):0,l=s?Number(s[0]):NaN,u=Number.isFinite(Number(n))?Number(n):-1/0,d=Number.isFinite(Number(r))?Number(r):1/0,m=Number.isFinite(l)?l:a,p=Math.min(Math.max(m,u),Math.max(u,d));return o?Math.round(p):p}function Zw({value:e,onValueCommit:t,disabled:n=!1,ariaLabel:r,inputMode:o="decimal",className:i,style:s}){const a=f.useRef(null),l=String(e??""),[u,d]=f.useState(l),[m,p]=f.useState(!1),g=f.useRef(!1),x=f.useRef(!1),y=m?u:l;f.useEffect(()=>{m||d(l)},[l,m]),f.useEffect(()=>{!m||!x.current||(x.current=!1,a.current?.select?.())},[m,y]);const S=b=>{b?.select?.(),typeof window<"u"&&window.requestAnimationFrame?.(()=>b?.select?.())};return c.jsx("input",{ref:a,type:"text",inputMode:o,value:y,disabled:n,"data-editing":m?"true":"false",onChange:b=>{d(b.target.value)},onFocus:b=>{x.current=!0,p(!0),S(b.currentTarget)},onClick:b=>{x.current=!0,p(!0),S(b.currentTarget)},onMouseUp:b=>{b.preventDefault()},onBlur:()=>{if(p(!1),g.current){g.current=!1;return}t?.(u)},onKeyDown:b=>{b.key==="Enter"&&b.currentTarget.blur(),b.key==="Escape"&&(g.current=!0,d(l),b.currentTarget.blur())},className:H(BY,i),style:{borderColor:m?"var(--ring)":void 0,...s},"aria-label":r})}function Ni({label:e,value:t,trailing:n,onValueCommit:r,valueInputProps:o,children:i,className:s,contentClassName:a,labelClassName:l}){const u=n??(r?c.jsx(Zw,{value:t,onValueCommit:r,...o}):null);return c.jsx(cn,{label:u?null:e,value:null,className:H(jY,s),contentClassName:H(u?"space-y-0":"space-y-1",a),labelClassName:l,rowKind:"slider",children:u?c.jsxs("div",{className:"grid min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-x-2","data-file-sheet-slider-input-row":"",children:[c.jsxs("div",{className:"min-w-0 pr-3",children:[e!=null?c.jsx("span",{className:H(Nu,"block h-3 leading-3",l),children:e}):null,c.jsx("div",{className:H("min-w-0",e!=null&&"-mt-0.5"),children:i})]}),u]}):i})}function HY({label:e,description:t,children:n,className:r,labelClassName:o}){return c.jsxs("div",{className:H(LY,r),"data-file-sheet-control-row":"","data-file-sheet-row-kind":"inline",children:[c.jsxs("div",{className:"flex min-h-7 max-w-full items-center justify-between gap-3",children:[c.jsx("span",{className:H(Nu,o),children:e}),c.jsx("span",{className:"shrink-0",children:n})]}),t?c.jsx("p",{className:"mt-0.5 max-w-[28rem] text-[11px] leading-4 text-muted-foreground",children:t}):null]})}function j1({checked:e,onCheckedChange:t,disabled:n=!1,ariaLabel:r,className:o}){return c.jsx(NY,{checked:e,disabled:n,onCheckedChange:t,className:H(GY,o),thumbClassName:UY,"aria-label":r})}function Mi({label:e,checked:t,onCheckedChange:n,disabled:r=!1,description:o,className:i,labelClassName:s,ariaLabel:a}){return c.jsx(HY,{label:e,description:o,className:i,labelClassName:s,children:c.jsx(j1,{checked:t,onCheckedChange:n,disabled:r,ariaLabel:a||e})})}function KY(e){const t=Number(e);return!Number.isFinite(t)||t<=0?_Y:Math.max(UO,t)}function xf({open:e,title:t,isDesktop:n,width:r,onOpenChange:o,onStartResize:i,bodyClassName:s,children:a}){const l=`min(${KY(r)}px, ${Kg})`,u=n?{width:l,flexBasis:l,minWidth:`min(${UO}px, ${Kg})`,maxWidth:Kg}:{width:TY,maxWidth:Kg},d=c.jsx(ch,{className:H("min-h-0 flex-1",RY,s),type:"auto",viewportClassName:"h-full",children:a});return n?e?c.jsxs("aside",{className:H("cad-glass-surface pointer-events-auto z-30 flex h-full max-w-[calc(100vw_-_0.75rem)] flex-col border-l border-sidebar-border text-sidebar-foreground",n?"relative shrink-0":"absolute inset-y-0 right-0 shadow-xl"),style:u,"aria-label":t,children:[n&&typeof i=="function"?c.jsx("button",{type:"button","aria-label":`Resize ${t} sidebar`,title:"Resize sidebar",onPointerDown:i,className:"group/file-sheet-resize absolute inset-y-0 -left-1.5 z-30 flex h-auto w-3 cursor-col-resize touch-none items-stretch justify-center rounded-none px-0 py-0 hover:bg-transparent",children:c.jsx("span",{className:"my-2 w-px rounded-full bg-transparent transition-colors group-hover/file-sheet-resize:bg-sidebar-border group-focus-visible/file-sheet-resize:bg-ring"})}):null,d]}):null:c.jsx(_R,{open:e,onOpenChange:o,children:c.jsxs(TR,{side:"right",showCloseButton:!1,className:"cad-glass-surface gap-0 p-0 text-sidebar-foreground",style:u,"aria-label":t,children:[c.jsxs(RR,{className:"sr-only",children:[c.jsx(PR,{children:t}),c.jsx(OR,{children:"Inspect and adjust the selected file."})]}),d]})})}const bt=Object.freeze({FILE_STATUS:"status",DXF:"dxf",GCODE_TOOLPATH:"toolpath",GCODE_FEATURES:"features",GCODE_STATS:"stats",GCODE_BOUNDS:"bounds",STEP_TREE:"tree",STEP_PARAMETERS:"parameters",ROBOT_SDF:"sdf",ROBOT_MOTION:"motion",ROBOT_JOINTS:"joints",IMPLICIT_GRAPHICS:"graphics",THEME_DISPLAY:"display",THEME_APPEARANCE:"appearance",FILE_METADATA:"metadata"}),ld=Object.freeze([bt.THEME_DISPLAY,bt.THEME_APPEARANCE]);function dh(e){return String(e||"").trim()}function L1(e){return Array.isArray(e)?[...new Set(e.map(dh).filter(Boolean))]:[]}function XY(e){return e==="plate"||e==="bends"?bt.DXF:e}function YY(e,t={}){const n=dh(e),r=t.isSdf===!0||n==="sdf",o=t.showJoints!==!1;switch(n){case"dxf":return[...t.hasFileStatus?[bt.FILE_STATUS]:[],bt.DXF,...ld,bt.FILE_METADATA];case"gcode":return[...t.hasFileStatus?[bt.FILE_STATUS]:[],bt.GCODE_TOOLPATH,bt.GCODE_FEATURES,bt.GCODE_STATS,bt.GCODE_BOUNDS,...ld,bt.FILE_METADATA];case"step":return[...t.hasFileStatus?[bt.FILE_STATUS]:[],bt.STEP_TREE,...t.hasStepModulePanel?[bt.STEP_PARAMETERS]:[],...ld,bt.FILE_METADATA];case"urdf":case"srdf":case"sdf":return[...t.hasFileStatus?[bt.FILE_STATUS]:[],...r?[bt.ROBOT_SDF]:[],...t.motionEnabled?[bt.ROBOT_MOTION]:[],...o?[bt.ROBOT_JOINTS]:[],...ld,bt.FILE_METADATA];case"mesh":return[...t.hasFileStatus?[bt.FILE_STATUS]:[],...ld,bt.FILE_METADATA];case"implicit":return[...t.hasFileStatus?[bt.FILE_STATUS]:[],...t.hasImplicitParameterPanel?[bt.STEP_PARAMETERS]:[],bt.IMPLICIT_GRAPHICS,...ld,bt.FILE_METADATA];default:return[]}}function qY(e,t={}){const n=dh(e),r=t.isSdf===!0||n==="sdf",o=t.showJoints!==!1;switch(n){case"dxf":return[...t.hasFileStatus?[bt.FILE_STATUS]:[],bt.DXF];case"gcode":return[...t.hasFileStatus?[bt.FILE_STATUS]:[],bt.GCODE_TOOLPATH];case"step":return[...t.hasFileStatus?[bt.FILE_STATUS]:[],bt.STEP_TREE,...t.hasStepModulePanel?[bt.STEP_PARAMETERS]:[]];case"urdf":case"srdf":case"sdf":return[...t.hasFileStatus?[bt.FILE_STATUS]:[],...r?[bt.ROBOT_SDF]:[],...t.motionEnabled?[bt.ROBOT_MOTION]:[],...o?[bt.ROBOT_JOINTS]:[]];case"mesh":return[...t.hasFileStatus?[bt.FILE_STATUS]:[]];case"implicit":return[...t.hasFileStatus?[bt.FILE_STATUS]:[],...t.hasImplicitParameterPanel?[bt.STEP_PARAMETERS]:[]];default:return[]}}function ma(e,t){const n=new Set(L1(t));return n.size?[...new Set(L1(e).map(XY).filter(r=>n.has(r)))]:[]}function ZY(e,t,n){const r=dh(n),o=ma(e,t);return!r||!L1(t).includes(r)||o.includes(r)?o:[...o,r]}function JY({isDesktop:e=!0,source:t="viewer"}={}){return e||dh(t)!=="viewer"}function Ks(e){return String(e||"").trim()}function QY(e){return Ks(e?.kind).toLowerCase()}function eq(e){if(!e||typeof e!="object")return null;const t=Ks(e.url);return t?{url:t,hash:Ks(e.hash),bytes:Number.isFinite(Number(e.bytes))&&Number(e.bytes)>=0?Number(e.bytes):0}:null}function tq(e,t){const n=e?.relations?.[t];if(!n||typeof n!="object")return null;const r=Ks(n.url);return r?{url:r,hash:Ks(n.hash),bytes:Number.isFinite(Number(n.bytes))&&Number(n.bytes)>=0?Number(n.bytes):0}:null}function Jw(e,t){const n=Ks(t).toLowerCase(),r=QY(e),o=or(e);return n==="urdf"&&r==="srdf"?tq(e,"urdf"):n===r||n===o||o===B.STEP&&["glb","topology","selectortopology","displayedgetopology"].includes(n)||r==="srdf"&&n==="srdf"?eq(e):null}function vn(e,t){return Ks(Jw(e,t)?.url)}function zt(e,t){return Ks(Jw(e,t)?.hash)}function WO(e,t){const n=Number(Jw(e,t)?.bytes);return Number.isFinite(n)&&n>=0?n:0}function Qw(e){return vn(e,Iu(e))}function F1(e){return zt(e,Iu(e))}function nq(e){return WO(e,Iu(e))}function gy(e){return vn(e,"topology")||vn(e,"glb")}function KN(e){return vn(e,"selectorTopology")||gy(e)}function XN(e){return vn(e,"displayEdgeTopology")||gy(e)}function Wp(e){return[zt(e,"urdf"),zt(e,"srdf"),zt(e,"sdf")].filter(Boolean).join(":")}function HO(e){return String(e?.kind==="assembly"?zt(e,"glb"):F1(e))}function rq(e){return zt(e,"selectorTopology")||Ks(e?.hash)}function qc(e){if(or(e)===B.STEP)return!!(vn(e,"glb")&&zt(e,"glb"));const t=Iu(e);return!!(vn(e,t)&&zt(e,t))}function Xg(e){return Ks(e?.kind).toLowerCase()===B.SDF?!!(vn(e,"sdf")&&zt(e,"sdf")):!!(vn(e,"urdf")&&zt(e,"urdf"))}function Qx(e){return!!(or(e)===B.STEP&&vn(e,"glb")&&zt(e,"selectorTopology"))}function YN(e){return!!(or(e)===B.STEP&&vn(e,"glb")&&zt(e,"displayEdgeTopology"))}function vm(e){return!!(vn(e,"dxf")&&zt(e,"dxf"))}function Yg(e){return!!(vn(e,"gcode")&&zt(e,"gcode"))}function oq(e){return or(e)===B.STEP?Ks(e?.moduleUrl):""}const ev=3,iq=Object.freeze(["missing_glb","missing_step_topology","missing_edge_topology","missing_surface_edge_attributes","missing_selector_topology","missing_source_path","missing_step_hash","stale_step_artifact","unsupported_step_topology"]),sq=new Set(iq),KO=/\.(step|stp)$/i;function Jd(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"")}function aq(e){return e?Array.isArray(e)?e:typeof e!="string"&&typeof e[Symbol.iterator]=="function"?Array.from(e):[e]:[]}function XO(e,t){const n=Jd(t);return n&&e.add(n),n}function qg(e,t){const n=XO(e,t);if(!KO.test(n))return;const r=n.lastIndexOf("/"),o=r>=0?`${n.slice(0,r)}/`:"",i=r>=0?n.slice(r+1):n;e.add(`${o}.${i}.glb`)}function lq(e,t){const n=Jd(e),r=Jd(t);return!!(n&&r&&n===r)}function qN(e,t){return t.some(n=>lq(e,n))}function tv(e){const t=Number(e?.failureCount||0);return Number.isFinite(t)&&t>0?Math.trunc(t):0}function cq(e=null,t=e?.artifact){const n=new Set;return qg(n,e?.file),qg(n,e?.rootRelativeFile),qg(n,t?.stepPath),KO.test(Jd(t?.sourcePath))&&qg(n,t?.sourcePath),XO(n,t?.glbPath),[...n]}function by({entry:e=null,artifact:t=e?.artifact,generationState:n=null,activeGenerationFiles:r=[]}={}){const o=cq(e,t);if(String(n?.status||"").trim().toLowerCase()==="loading"){const i=Jd(n?.file);if(!i||o.length===0||qN(i,o))return!0}return aq(r).map(Jd).filter(Boolean).some(i=>qN(i,o))}function uq({entry:e=null,artifact:t=e?.artifact,sourceFormat:n=B.STEP,generationAvailable:r=!0,generationState:o=null,activeGenerationFiles:i=[]}={}){const s={...e||{},artifact:t},a=by({entry:s,artifact:t,generationState:o,activeGenerationFiles:i});return fh(s,n,{generationAvailable:r||a})?a?!0:tv(o)!0,onState:i=()=>{},onFinalError:s=()=>{},threshold:a=ev,validatePayload:l=null}={}){if(typeof r!="function")throw new TypeError("STEP artifact generation requires a generate function.");const u=Math.max(1,Math.trunc(Number(a)||0));let d=Math.min(tv({failureCount:n}),u);for(;d=u?"error":"loading",failureCount:d,attempt:Math.min(d+1,u),error:x};if(i(y),y.status==="error")return s(x,y,g),{status:"error",state:y,error:g}}}return{status:"error",state:{key:e,file:t,status:"error",failureCount:d,attempt:u,error:""}}}function mq(e,t){return t===B.STEP&&e?.artifact?.ok===!1&&(e.artifact.stale===!0||String(e.artifact.error||"")==="stale_step_artifact")}function fh(e,t,{generationAvailable:n=!0}={}){return!n||t!==B.STEP||e?.artifact?.ok?!1:sq.has(String(e?.artifact?.error||""))}function pq(e,t,n={}){return t===B.STEP&&e?.artifact?.ok===!1&&!fh(e,t,n)}function YO(e,{sourceFormat:t="",entryKey:n="",hasMesh:r=!0,hasDxf:o=!0,hasGcode:i=!0,hasImplicit:s=!0,hasUrdf:a=!0,activeGenerationFiles:l=[],activeStepArtifactGenerationFile:u="",activeStepArtifactGenerationFiles:d=[],stepArtifactGenerationAvailable:m=!0}={}){const p=String(t||"").trim().toLowerCase(),g=new Set([...Array.isArray(l)?l:l?[l]:[]].map(Y=>String(Y||"").trim()).filter(Boolean)),x=new Set([...Array.isArray(d)?d:d?[d]:[],...Array.isArray(u)?u:u?[u]:[]].map(Y=>String(Y||"").trim()).filter(Boolean)),y=p===B.DXF?!o:p===B.GCODE?!i:p===B.IMPLICIT?!s:Hi(p)?!a:!r,S=[...x,...g],b=by({entry:e,activeGenerationFiles:S}),N=fh(e,p,{generationAvailable:m||b}),P=mq(e,p),R=String(e?.artifact?.error||"").trim(),v=!!(n&&g.has(n)),C=!v&&!b&&pq(e,p,{generationAvailable:m}),T=!!(N&&!v&&b);return{artifactBuildable:N,artifactGenerating:T,artifactStale:P,artifactWarning:C,loading:v||T||y&&!C&&!N,pending:y,sourceFormat:p,statusLabel:v?"generating":T?"generating artifact":C?P?"artifact stale":R==="missing_glb"?"artifacts missing":"artifact warning":N?"artifact generates on open":y?"pending":"ready"}}function nv(e){const t=String(e?.artifact?.sourceKind||"").trim().toLowerCase();if(t==="python")return t;const n=String(e?.sourceKind||e?.stepSourceKind||"").trim().toLowerCase();return n==="python"?n:""}function mh(e){return String(e??"").trim()}function Po(e){return mh(e).replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"")}function ZN(e){return mh(e).replace(/\\/g,"/").replace(/\/+$/,"")}function z1(e){return mh(e).replace(/[?#].*$/,"")}function hq(e){const t=mh(e);if(!t)return"";try{return new URL(t,"http://cad.local").pathname}catch{return z1(t)}}function JN(e,t){const n=ZN(e),r=ZN(t);return!n||!r||n===r?"":n.startsWith(`${r}/`)?n.slice(r.length+1):""}function B1(e,t=""){const n=Po(e),r=Po(t);return!n||!r?n:n===r?"":n.startsWith(`${r}/`)?n.slice(r.length+1):n}function QN(e,t=""){const n=Po(e),r=Po(t);if(!n||!r)return n;const o=r.split("/").filter(Boolean);if(o.pop(),!o.length)return n;const s=`/${o.join("/")}/`,a=`/${n}`,l=a.lastIndexOf(s);return l>=0?a.slice(l+1):n}function Xs(e,t={},{anchorFile:n=""}={}){const r=mh(e);if(!r)return"";const o=JN(z1(r),t?.rootPath);if(o)return Po(o);const i=JN(z1(r),t?.directoryRoot);if(i)return QN(B1(i,t?.rootDir),n);const s=Po(hq(r));return QN(B1(s,t?.rootDir),n)}const V1="cad-viewer:active-dir:v1";function qO(){if(typeof window>"u")return null;try{return window.sessionStorage||null}catch{return null}}function ZO(){const e=qO();if(!e)return"";try{return String(e.getItem(V1)||"").trim()}catch{return""}}function gq(e){const t=qO();if(!t)return;const n=String(e||"").trim();try{n?t.setItem(V1,n):t.removeItem(V1)}catch{}}function rv(e){const t=String(e||"").trim();return gq(t),t}const ph="https://github.com/earthtojake/text-to-cad",bq="https://discord.gg/5FGB9DwJYU",bc="npx skills install earthtojake/text-to-cad";function yq(e=""){return String(e??"").trim().replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"")}function JO(e="",t=ph){return yy(e)||yy(t)}function xq(e="",t=bq){return yy(e)||yy(t)}function ov(e="",t=ph){const n=JO(e,t);if(!n)return"";try{const r=new URL(n);if(r.hostname.toLowerCase()!=="github.com")return n.replace(/\/+$/,"");const[,o="",i=""]=r.pathname.split("/");return!o||!i?n.replace(/\/+$/,""):new URL(`/${o}/${i}`,r.origin).href.replace(/\/+$/,"")}catch{return""}}function Sq(e="",t="",n=ph){const r=String(e||"").trim(),o=ov(t,n);return!r||!o?"":`${o}/releases/tag/${encodeURIComponent(r)}`}function Eq(e="",t=ph){const n=ov(e,t);return n?`${n}/releases/latest`:""}function wq(e="",t=ph){const n=ov(e,t);if(!n)return"";try{const r=new URL(n);if(r.hostname.toLowerCase()!=="github.com")return"";const[,o="",i=""]=r.pathname.split("/"),s=decodeURIComponent(o),a=decodeURIComponent(i);return!s||!a?"":`https://api.github.com/repos/${encodeURIComponent(s)}/${encodeURIComponent(a)}/releases/latest`}catch{return""}}function vq(e="",t=""){const n=xy(e),r=xy(t);return!!(n&&r&&QO(r,n)>0)}function Cq(e="",t=""){const n=xy(e),r=xy(t);return!n||!r||QO(r,n)<=0?!1:r.parts[0]>n.parts[0]||r.parts[1]>n.parts[1]}function Mq(e="",t=bc){const n=Aq(e);return/^npx\s+skills\s+install(?:\s+\S+)+$/iu.test(n)?n:String(t||"").trim()}function Iq(e="",t=bc){const n=String(e||""),r=[...Array.from(n.matchAll(/`([^`\r\n]*\bnpx\s+skills\s+install\b[^`\r\n]*)`/giu),o=>o[1]),...Array.from(n.matchAll(/(?:^|\n)\s*([^\r\n]*\bnpx\s+skills\s+install\b[^\r\n]*)/giu),o=>o[1])];for(const o of r){const i=Mq(o,"");if(i)return i}return String(t||"").trim()}function yy(e=""){const t=String(e??"").trim();if(!t)return"";const n=/^[a-z][a-z\d+.-]*:\/\//i.test(t)?t:`https://${t.replace(/^\/+/,"")}`;try{const r=new URL(n);return["http:","https:"].includes(r.protocol)?r.href:""}catch{return""}}function Aq(e=""){return String(e||"").trim().replace(/^`+|`+$/g,"").replace(/^\s*(?:\$|>)\s*/u,"").replace(/\s+/gu," ")}function xy(e=""){const t=String(e??"").trim().replace(/^refs\/tags\//i,"").replace(/^v/i,"");if(!t)return null;const n=t.split("+")[0],[r="",...o]=n.split("-"),i=r.match(/^(\d+)(?:\.(\d+))?(?:\.(\d+))?$/u);return i?{parts:[Number(i[1]),Number(i[2]||0),Number(i[3]||0)],prerelease:o.join("-").split(".").filter(Boolean)}:null}function QO(e,t){for(let n=0;n<3;n+=1){const r=e.parts[n]-t.parts[n];if(r!==0)return r}return Nq(e.prerelease,t.prerelease)}function Nq(e,t){if(!e.length&&!t.length)return 0;if(!e.length)return 1;if(!t.length)return-1;const n=Math.max(e.length,t.length);for(let r=0;r{const a=sv(s);a&&t.add(a)},r=Ep(e);n(r);const o=iv(e),i=Tq(r);return n(Rq(o,i)),t}function Oq(){return yq(_q?.VIEWER_DEFAULT_FILE)||null}function Pb(){if(typeof window>"u")return null;const t=new URLSearchParams(window.location.search).get(Sy);return(typeof t=="string"?Sf(t):"")||null}function kq(){if(typeof window>"u")return null;const t=new URLSearchParams(window.location.search).get(jd);return(typeof t=="string"?String(t).trim():"")||null}function G1(e,t){const n=Sf(t);return n&&e.find(r=>Pq(r).has(n))||null}function Dq({explicitFileParam:e="",matchingEntry:t=null,selectedEntry:n=null,catalogHydrated:r=!1,catalogRefreshing:o=!1}={}){return!Sf(e)||n?!1:t?!0:!r||o}function jq({explicitFileParam:e="",matchingEntry:t=null,selectedEntry:n=null,catalogHydrated:r=!1,catalogRefreshing:o=!1}={}){const i=Sf(e);return!i||n||t||!r||o?"":i}function Lq(e,{defaultFile:t=Oq()}={}){const n=Pb();if(n){const o=G1(e,n);return o?at(o):""}const r=G1(e,Sf(t));return r?at(r):""}function Cm(e,{history:t="replace"}={}){if(typeof window>"u")return;const n=Sf(e),r=new URL(window.location.href);if(r.searchParams.delete("refs"),n){if(r.searchParams.set(Sy,n),r.searchParams.has(jd)){const o=rv(r.searchParams.get(jd));if(o&&ZO()!==o){$1(r,{history:t});return}r.searchParams.delete(jd)}}else r.searchParams.delete(Sy);$1(r,{history:t})}function e_(e,{history:t="replace",preserveFile:n=!1}={}){if(typeof window>"u")return!1;const r=String(e||"").trim(),o=new URL(window.location.href);return o.searchParams.delete("refs"),n||o.searchParams.delete(Sy),r?(o.searchParams.set(jd,r),rv(r)):o.searchParams.delete(jd),$1(o,{history:t})}function ek(e,t){return String(e||"").localeCompare(String(t||""),void 0,{numeric:!0,sensitivity:"base"})}function av(e){const t=at(e);if(!t)return"";const n=t.split("/");return n[n.length-1]||t}function Fq(e){return av(e).replace(/\.step\.json$/i,"").replace(/\.urdf\.json$/i,"").replace(/\.(step|stp|stl|3mf|glb|gcode|dxf|urdf|srdf|sdf|py)$/i,"")}function lv(e){const n=String(e?.rootRelativeFile||at(e)||"").trim().split("/").filter(Boolean);return n.pop(),n.join("/")}function zq(e){const t=av(e),n=/\.([^.]+)$/.exec(t);return String(n?.[1]||"").trim().toLowerCase()}function tk(e){const t=Fq(e);if(!t)return"";const n=String(e?.kind||"").trim().toLowerCase(),o=new Set(["dxf","urdf","srdf","sdf","stl","3mf","glb","gcode","implicit"]).has(n)?n:String(zq(e)||"step").trim().toLowerCase();return o==="dxf"?`${t}.dxf`:o==="urdf"||e?.kind==="urdf"?`${t}.urdf`:o==="srdf"||e?.kind==="srdf"?`${t}.srdf`:o==="sdf"||e?.kind==="sdf"?`${t}.sdf`:o==="stl"||e?.kind==="stl"?`${t}.stl`:o==="3mf"||e?.kind==="3mf"?`${t}.3mf`:o==="glb"||e?.kind==="glb"?`${t}.glb`:o==="gcode"||e?.kind==="gcode"?`${t}.gcode`:o==="implicit"||e?.kind==="implicit"?av(e):`${t}.${o==="stp"?"stp":"step"}`}function dl(e){return tk(e)}function Bq(e,t){const n=dl(e).localeCompare(dl(t),void 0,{numeric:!0,sensitivity:"base"});return n!==0?n:at(e).localeCompare(at(t),void 0,{numeric:!0,sensitivity:"base"})}function t_(e,t){return{id:e,name:t,entries:[],children:new Map}}function nk(e){return{id:e.id,name:e.name,entries:[...e.entries].sort(Bq),directories:[...e.children.values()].map(nk).sort((t,n)=>ek(t.name,n.name))}}function n_(e,{rootName:t="Directory"}={}){const n=t_("",String(t||"Directory"));for(const r of e){const o=lv(r),i=o?o.split("/"):[];let s=n,a="";for(const l of i){a=a?`${a}/${l}`:l;const u=s.children.get(l)||t_(a,l);s.children.set(l,u),s=u}s.entries.push(r)}return nk(n)}function rk(e,t=[]){for(const n of e.directories||[])t.push(n.id),rk(n,t);return t}function Vq(e,t){const n=String(t||"").trim();if(!e)return[];if(!n)return[e];const r=[],o=i=>{if(r.push(i),String(i.id||"")===n)return!0;for(const s of i.directories||[])if(o(s))return!0;return r.pop(),!1};return o(e)?r:[]}function o0(e){return[...(e.directories||[]).map(t=>({type:"directory",key:`directory:${t.id}`,label:t.name,value:t})),...(e.entries||[]).map(t=>({type:"entry",key:`entry:${at(t)}`,label:dl(t),value:t}))].sort((t,n)=>{const r=ek(t.label,n.label);return r!==0?r:t.key.localeCompare(n.key,void 0,{numeric:!0,sensitivity:"base"})})}function $q(e){if(!e)return[];const t=String(e).split("/").filter(Boolean),n=[];let r="";for(const o of t)r=r?`${r}/${o}`:o,n.push(r);return n}function wp(e){return Po(e).split("/").filter(Boolean).pop()||""}function uu(e){const t=String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"");return t.startsWith("/")?t:t.replace(/^\/+/,"")}function Gq(e){const t=Po(e).split("/").filter(Boolean);return t.pop(),t.join("/")}function Uq(...e){return e.map(t=>Po(t)).filter(Boolean).join("/")}function ok(e){return wp(e).replace(/\.(step|stp)$/i,".py")}function Wq(e){const t=Gq(e),n=ok(e);return Uq(t,n)}function ik(e){return/\.(step|stp)$/i.test(Po(e))}function Hq(e){try{return wp(new URL(String(e||"")).pathname)}catch{return""}}function i0(e){const t=String(e||"").trim();if(!t)return"";try{const n=new URL(t);return n.protocol==="http:"||n.protocol==="https:"?n.toString():""}catch{return""}}function Kq(e={}){return String(e?.backend||"").trim().toLowerCase()==="vercel-blob"}function Xq(e){return uu(e?.sourceFile)||uu(e?.source?.file)||uu(e?.source?.path)||Hq(e?.sourceUrl||e?.source?.url)}function Yq(e){return uu(e?.sourceDirectoryFile)||uu(e?.source?.directoryFile)||uu(e?.source?.sourcePath)}function qq(e,t={}){return Xs(e?.assetFile||e?.artifactFile||e?.artifact?.file,t,{anchorFile:e?.file})||Xs(e?.url,t,{anchorFile:e?.file})}function Zq(e){return i0(e?.sourceUrl||e?.source?.url)}function Jq(e){const t=i0(e?.stepUrl||e?.step?.url);return t||(String(e?.sourceKind||e?.stepSourceKind||"").trim().toLowerCase()==="python"?"":Zq(e))}function Qq(e,t){return ik(t)?Jq(e):i0(e?.outputUrl||e?.output?.url||e?.url)}function eZ(e){return String(e||"").includes("\\")?"\\":"/"}function r_(e,t){const n=String(e||"").trim(),r=Po(t);if(!n||!r)return n||r;const o=eZ(n),i=n.replace(/[\\/]+$/,""),s=r.replace(/\//g,o);return`${i}${o}${s}`}function tZ(e,t){const n=Po(e),r=Po(t);return n?r?n===r||n.startsWith(`${r}/`):!0:!1}function nZ(e,t){return tZ(e,t)?B1(e,t):""}function cv(e,{stepSourceStatus:t=null,viewerServerInfo:n={}}={}){const r=at(e);if(!r)return{artifact:null,output:null,source:null};const o=Xs(e?.file||r,n)||Po(e?.file||r),i=wp(o),s=qq(e,n),a=wp(s),l=Kq(n),u=l?Qq(e,o):"",d=l?i0(e?.url):"",m=String(t?.sourceKind||nv(e)).trim().toLowerCase(),p=uu(t?.sourcePath),g=Xq(e),x=Yq(e),y=m==="python"&&ik(o)?Wq(o):"",S=g||p||y,b=p||x,I=!!(n?.rootDir||n?.rootPath||n?.directoryRoot),A=S?I?Xs(S,n,{anchorFile:o})||S:b?"":g||y:"",N=A||S?wp(A||S)||ok(o):"";return{artifact:a?{asset:"artifact",fileRef:r,filename:a,label:a,rootRelativePath:s,...d?{downloadUrl:d}:{}}:null,output:{asset:"output",fileRef:r,filename:i||"download",label:i||"download",rootRelativePath:o,...u?{downloadUrl:u}:{}},source:N?{asset:"source",fileRef:r,filename:N,label:N,rootRelativePath:A,directoryRelativePath:b}:null}}function U1(e,t="output",n=""){const r=`/__cad/download?file=${encodeURIComponent(e)}&asset=${encodeURIComponent(t||"output")}`;if(!n)return r;try{return new URL(r,n).toString()}catch{return r}}function sk(e,t="output",n=""){const r=`/__cad/reveal?file=${encodeURIComponent(e)}&asset=${encodeURIComponent(t||"output")}`;if(!n)return r;try{return new URL(r,n).toString()}catch{return r}}function rZ(e,t={}){const n=Po(t?.rootDir),r=Po(e?.directoryRelativePath),i=nZ(r,n)||Po(e?.rootRelativePath),s=i?Xs(i,t,{anchorFile:e?.fileRef}):"",a=s||r;return{path:s&&t?.rootPath?r_(t.rootPath,s):r&&t?.directoryRoot?r_(t.directoryRoot,r):"",relativePath:a}}function Ko(e){return String(e??"").trim()}function Ey(e){return Ko(e).toLowerCase()}function uv(e){const t=Ko(e);return t?`${t[0].toUpperCase()}${t.slice(1)}`:""}function oZ(e){const t=Ko(e);return t.length>24?`${t.slice(0,12)}...${t.slice(-8)}`:t}function Hr(e,t,n={}){const r=Ko(t);return r?{label:e,value:r,displayValue:n.short?oZ(r):r,href:Ko(n.href),openUrl:Ko(n.openUrl),action:Ko(n.action),asset:n.asset||null,copyValue:n.copy===!0?r:Ko(n.copyValue),mono:n.mono===!0,title:Ko(n.title)||r}:null}function Qd(e){return e.filter(Boolean)}function Mm(e,t){const n=Qd(t);return n.length?{title:e,rows:n}:null}function ak(e){const t=Number(e);if(!Number.isFinite(t)||t<0)return"";const n=Math.round(t);if(n<1024)return`${n} B`;const r=["KB","MB","GB","TB"];let o=n/1024,i=0;for(;o>=1024&&i=10?1:2;return`${o.toFixed(s).replace(/(\.\d*?[1-9])0+$/,"$1").replace(/\.0+$/,"")} ${r[i]} (${n.toLocaleString("en-US")} B)`}function iZ(e){const t=Ey(e?.kind),n=Ey(or(e));return[t?uv(t):"",n&&n!==t?n.toUpperCase():""].filter(Boolean).join(" / ")}function sZ(e){const t=Ey(e?.sourceKind||e?.sourceStatus?.sourceKind||e?.artifact?.sourceKind);return t}function aZ(e){const t=Ey(e);return t==="python"?"Python-generated":t==="step"?"STEP-backed":uv(t)}function lZ(e,t,n={}){const r=Ko(e?.source?.sourcePath||e?.source?.file||e?.sourceDirectoryFile||t?.directoryRelativePath||e?.sourceFile||t?.rootRelativePath);return Xs(r,n,{anchorFile:e?.file})||r}function lk(e){return e?{openUrl:sk(e.fileRef,e.asset),action:"open",asset:e}:{}}function cZ(e){return e?{href:Ko(e.downloadUrl)||U1(e.fileRef,e.asset),action:"download",asset:e}:{}}function o_(e,{includeFileOpenActions:t=!1,includeFileDownloadActions:n=!1}={}){return t?lk(e):n?cZ(e):{}}function uZ(e,{includePythonSource:t=!1,suppressDynamicStatus:n=!1,viewerServerInfo:r={}}={}){const o=sZ(e);if(o==="python"&&!t)return[];const i=e?.source&&typeof e.source=="object"?e.source:{},s=e?.sourceStatus&&typeof e.sourceStatus=="object"?e.sourceStatus:{},a=cv(e,{viewerServerInfo:r}),l=o==="python"?a.source:null,u=lZ(e,l,r);return Qd([Hr("Kind",aZ(o)),o==="python"?Hr("Python source",u||l?.label,{...lk(l),mono:!0,title:u||l?.label||"Python source"}):null,n?null:Hr("Status",s.status),Hr("Source hash",i.sourceHash||s.sourceHash,{mono:!0,short:!0,copy:!0}),n?null:Hr("Current",s.currentHash,{mono:!0,short:!0,copy:!0})])}function dZ(e,{suppressDynamicStatus:t=!1,viewerServerInfo:n={}}={}){const r=e?.artifact&&typeof e.artifact=="object"?e.artifact:{},o=Ko(e?.moduleUrl),i=Xs(e?.moduleFile||o,n,{anchorFile:e?.file})||o;return Qd(t?[Hr("Module",i,{href:o,mono:!0,title:i})]:[Hr("Module",i,{href:o,mono:!0,title:i}),Hr("Artifact",r.error?uv(String(r.error).replace(/_/g," ")):""),Hr("Artifact hash",r.artifactHash,{mono:!0,short:!0,copy:!0}),Hr("Current hash",r.currentHash,{mono:!0,short:!0,copy:!0}),Hr("Message",r.message)])}function fZ(e){const t=e?.headers&&typeof e.headers=="object"?e.headers:{};return Object.entries(t).flatMap(([n,r])=>{const o=Ko(n);if(!o)return[];const i=Array.isArray(r)?r.map(Ko).filter(Boolean).join(", "):r&&typeof r=="object"?JSON.stringify(r):Ko(r);return Hr(o,i)})}function mZ(e,t={}){const n=e?.relations&&typeof e.relations=="object"?e.relations:{};return Object.entries(n).flatMap(([r,o])=>{const i=Ko(r).toUpperCase();return!i||!o||typeof o!="object"?[]:Qd([Hr(`${i} file`,Xs(o.file,t,{anchorFile:e?.file})||o.file,{mono:!0}),Hr(`${i} size`,ak(o.bytes)),Hr(`${i} hash`,o.hash,{mono:!0,short:!0,copy:!0})])})}function pZ(e,t={}){if(!e||typeof e!="object")return[];const n=t.includeFileOpenActions===!0,r=t.includeFileDownloadActions===!0,o=t.suppressDynamicStatus===!0,i=t.viewerServerInfo||{},s=cv(e,{viewerServerInfo:i}),a=Xs(e.file,i)||e.file,l=s.artifact?.rootRelativePath||Xs(e.assetFile||e.url,i,{anchorFile:e.file})||e.url,u=Qd([Hr("Path",a,{...o_(s.output,{includeFileOpenActions:n,includeFileDownloadActions:r}),mono:!0}),Hr("Kind",iZ(e)),Hr("Size",ak(e.bytes)),Hr("Hash",e.hash,{mono:!0,short:!0,copy:!0}),Hr("Asset",l,{...o_(s.artifact,{includeFileOpenActions:n,includeFileDownloadActions:r}),mono:!0,title:l})]);return[Mm("File",u),Mm("Headers",fZ(e)),Mm("Source",uZ(e,{...t,viewerServerInfo:i,suppressDynamicStatus:o})),Mm("Generated",dZ(e,{viewerServerInfo:i,suppressDynamicStatus:o})),Mm("Relations",mZ(e,i))].filter(Boolean)}function hZ({value:e,label:t}){const[n,r]=f.useState(!1),o=n?mu:vu,i=String(e||"").trim();return i?c.jsx("button",{type:"button",className:H("mt-[-0.125rem] inline-flex size-5 shrink-0 items-center justify-center rounded-sm text-muted-foreground transition-colors","hover:bg-sidebar-accent hover:text-sidebar-accent-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/45"),title:`Copy ${t}`,"aria-label":`Copy ${t}`,onClick:async()=>{try{await ps(i),r(!0),window.setTimeout?.(()=>r(!1),1200)}catch{r(!1)}},children:c.jsx(o,{className:"size-3",strokeWidth:2,"aria-hidden":"true"})}):null}function gZ({entry:e,row:t,fileAccessBusyKey:n="",onOpenFileAsset:r}){const o=t.displayValue||t.value,i=String(t.copyValue||"").trim(),s=H("block min-w-0 break-words text-[11px] leading-4",t.mono&&"break-all font-mono text-[10px]"),a=u=>i?c.jsxs("div",{className:"inline-flex max-w-full items-center gap-1.5 align-top",children:[c.jsx("div",{className:"min-w-0 max-w-full",children:u}),c.jsx(hZ,{value:i,label:t.label})]}):u;if(t.action==="open"&&t.asset){const u=`${t.asset.fileRef}:${t.asset.asset}`,d=n===u,m=typeof r=="function";return a(c.jsx("a",{href:t.openUrl||"#",className:H(s,"text-primary underline-offset-4 hover:underline focus-visible:rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/45",(!m||d)&&"pointer-events-none text-muted-foreground"),title:t.title,"aria-disabled":!m||d,"data-open-url":t.openUrl||void 0,onClick:p=>{p.preventDefault(),!(!m||d)&&r(e,t.asset.asset,t.asset)},children:d?"Opening...":o}))}const l=c.jsx("span",{className:s,title:t.title,children:o});return t.href?a(c.jsx("a",{href:t.href,download:t.action==="download"?t.asset?.filename||!0:void 0,className:H(s,"text-primary underline-offset-4 hover:underline focus-visible:rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/45"),title:t.title,children:o})):a(l)}function Ef({entry:e,fileDownloadAvailable:t=!1,viewerServerInfo:n=null,localFileOpenAvailable:r=!1,fileAccessBusyKey:o="",onOpenFileAsset:i,suppressDynamicStatus:s=!1}){const a=pZ(e,{includeFileDownloadActions:t&&!r,includeFileOpenActions:r,includePythonSource:r,viewerServerInfo:n,suppressDynamicStatus:s});return a.length?c.jsx(ci,{value:bt.FILE_METADATA,title:"Metadata","aria-label":"File metadata",children:c.jsx("div",{children:a.map(l=>c.jsx(bo,{title:l.title,contentClassName:"px-3",children:c.jsx("dl",{className:"space-y-1.5",children:l.rows.map(u=>c.jsxs("div",{className:"min-w-0 space-y-0.5 py-0.5",children:[c.jsx("dt",{className:H(Nu,"leading-4"),title:u.label,children:u.label}),c.jsx("dd",{className:"min-w-0 flex-1 text-sidebar-foreground",children:c.jsx(gZ,{entry:e,row:u,fileAccessBusyKey:o,onOpenFileAsset:i})})]},`${l.title}:${u.label}`))})},l.title))})}):null}const bZ=th("inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-md border px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-colors [&>svg]:size-3",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground",secondary:"border-transparent bg-secondary text-secondary-foreground",destructive:"border-transparent bg-destructive text-white dark:bg-destructive/60","destructive-outline":"border-destructive/45 bg-destructive/10 text-destructive dark:border-red-400/40 dark:text-red-300",outline:"text-foreground",warning:"border-amber-500/45 bg-amber-500/10 text-amber-800 dark:text-amber-300","warning-outline":"border-amber-500/45 bg-amber-500/10 text-amber-800 dark:text-amber-300"}},defaultVariants:{variant:"default"}});function Ls({className:e,variant:t,...n}){return c.jsx("span",{"data-slot":"badge",className:H(bZ({variant:t}),e),...n})}const Xn=Object.freeze({ERROR:"error",WARNING:"warning",INFO:"info"}),yZ=Object.freeze({[Xn.ERROR]:3,[Xn.WARNING]:2,[Xn.INFO]:1}),xZ=/(?:^|\n)\s*Regenerate STEP artifacts[^\n]*(?=\n|$)/gi;function Nr(e){return String(e||"").replace(xZ,"").trim()}function Xi(e,t,{mono:n=!1}={}){const r=Nr(t);return r?{label:e,value:r,mono:n}:null}function SZ(e,t={},n=""){const r=Nr(e);return Xs(r,t,{anchorFile:n})||r}function Zc(e,t,n={},r="",o={}){return Xi(e,SZ(t,n,r),o)}function EZ(e){return Nr(e).toLowerCase()==="python"?"python":"step"}function wZ(e,t){return Object.prototype.hasOwnProperty.call(e||{},t)}function s0(e,t=Xn.INFO){const n=Nr(e).toLowerCase();return n===Xn.ERROR?Xn.ERROR:n===Xn.WARNING||n==="warn"?Xn.WARNING:n===Xn.INFO||n==="information"?Xn.INFO:t}function wy(e){return yZ[s0(e,"")]||0}function dv(e){const t=s0(e,"");return t===Xn.ERROR?"Error":t===Xn.WARNING?"Warning":t===Xn.INFO?"Info":""}function fv(e,t=0){if(!e||typeof e!="object")return null;const n=s0(e.level,Xn.INFO),r=Nr(e.title)||dv(n)||"Status",o=Nr(e.message),i=Nr(e.code),s=Nr(e.source),a=Array.isArray(e.details)?e.details.map(l=>!l||typeof l!="object"?null:Xi(l.label,l.value,{mono:l.mono===!0})).filter(Boolean):[];return{id:Nr(e.id)||`${s||"status"}:${i||r}:${t}`,level:n,source:s,code:i,title:r,message:o,details:a}}function yc(e){if(!Array.isArray(e))return[];const t=new Set;return e.map(fv).filter(n=>{if(!n)return!1;const r=[n.level,n.title,n.message,n.details.map(o=>`${o.label}:${o.value}`).join("|")].join(` `);return t.has(r)?!1:(t.add(r),!0)})}function ck(e){return yc(e).filter(t=>t.level===Xn.ERROR||t.level===Xn.WARNING).sort((t,n)=>wy(n.level)-wy(t.level))}function vZ(e){return ck(e).length>0}function uk(e){return yc(e).reduce((t,n)=>wy(n.level)>wy(t)?n.level:t,"")}function mv(e){return qc(e)}function CZ(e,t){const n=Nr(e?.error);return e?.stale===!0||n==="stale_step_artifact"?"STEP artifact stale":n==="missing_glb"?"STEP artifact missing":mv(t)?"STEP artifact metadata warning":"STEP artifact unavailable"}function MZ(e,t){return mv(t)?Xn.WARNING:Xn.ERROR}function dk(e){const t=Nr(e?.error);return e?.stale===!0||t==="stale_step_artifact"?"Generated GLB doesn't match the hash of the STEP file.":t==="missing_glb"?"Generated GLB is missing.":t==="missing_step_topology"?"Generated GLB is missing STEP topology metadata.":t==="missing_selector_topology"?"Generated GLB is missing selector topology metadata.":t==="missing_edge_topology"?"Generated GLB is missing surface edge topology metadata.":t==="missing_surface_edge_attributes"?"Generated GLB is missing surface edge render attributes.":t==="unsupported_step_topology"?"Generated GLB topology metadata is unsupported.":t==="missing_source_path"?"Generated GLB metadata is missing its source path.":t==="missing_step_hash"?"Generated GLB is missing the hash of the STEP file.":"Generated STEP artifact is unavailable."}function IZ(e){return"STEP file missing"}function AZ(e){return Xn.WARNING}function NZ(e,t){return e?.missing?EZ(t?.sourceKind)==="python"?"STEP file was not generated for this Python script; only a GLB artifact is available.":"STEP file is missing from the directory.":Nr(e?.message)||"STEP file is missing from the directory."}function _Z(e){return e?.status==="missing"?"Generator source missing":"Generated source warning"}function TZ(e){return e?.status==="missing"?"This file records a Python generator path, but that source file is not available.":Nr(e?.message)||"Generated source metadata is incomplete."}function RZ(e=null,{viewerServerInfo:t={}}={}){const n=e?.sourceStatus;return!n||n.ok!==!1?[]:yc([{id:"generated-source",level:Xn.WARNING,source:"source-metadata",code:Nr(n.status)||"source_identity",title:_Z(n),message:TZ(n),details:[Zc("File",e?.file,t,e?.file),Xi("Source kind",n.sourceKind||e?.sourceKind),Zc("Python source",n.sourcePath||e?.source?.file,t,e?.file),Xi("Raw message",n.message)].filter(Boolean)}])}function PZ({entry:e=null,stepSourceStatus:t=null,stepArtifactGenerationAvailable:n=!0,stepArtifactGenerationState:r=null,activeGenerationFiles:o=[],viewerServerInfo:i={}}={}){const s=[],a=wZ(t,"artifact")?t?.artifact:e?.artifact;a?.ok===!1&&!uq({entry:e,artifact:a,generationAvailable:n,generationState:r,activeGenerationFiles:o})&&s.push({id:"step-artifact",level:MZ(a,e),source:"catalog",code:Nr(a.error)||"step_artifact_unavailable",title:CZ(a,e),message:dk(a),details:[Xi("Code",a.error),Zc("STEP file",a.stepPath||a.sourcePath||e?.file,i,e?.file),Zc("GLB artifact",a.glbPath,i,e?.file),Zc("CAD path",a.cadPath,i,e?.file),Xi("Source kind",a.sourceKind),Xi("Artifact hash",a.artifactHash,{mono:!0}),Xi("Current hash",a.currentHash,{mono:!0}),Xi("Raw message",a.message)].filter(Boolean)});const l=t?.step;return l?.missing&&s.push({id:"step-source",level:AZ(),source:"step-source-status",code:Nr(l.status)||"missing",title:IZ(),message:NZ(l,t),details:[Zc("STEP file",t?.stepPath||t?.file,i,e?.file),Xi("Source kind",t?.sourceKind),Zc("Python source",t?.sourcePath,i,e?.file)].filter(Boolean)}),yc(s)}function OZ(e){const t=fv(e);if(!t)return"";const n=["CAD Viewer issue",`Level: ${dv(t.level)||t.level}`,`Title: ${t.title}`];if(t.message&&n.push(`Description: ${t.message}`),t.source&&n.push(`Source: ${t.source}`),t.code&&n.push(`Code: ${t.code}`),t.details.length){n.push("","Details:");for(const r of t.details)n.push(`- ${r.label}: ${r.value}`)}return n.join(` `)}function kZ(e=null){const t=Array.isArray(e?.warnings)?e.warnings:[];return yc(t.map((n,r)=>({id:`gcode-warning:${r}`,level:Xn.WARNING,source:"gcode-parser",code:"gcode_warning",title:"G-code warning",message:n})))}function DZ(e=null){const t=e?.staticMetadata&&typeof e.staticMetadata=="object"?e.staticMetadata:{},n=Array.isArray(t.warnings)?t.warnings:[];return yc(n.map((r,o)=>({id:`sdf-warning:${o}`,level:Xn.WARNING,source:"sdf-parser",code:"sdf_warning",title:"SDF warning",message:r})))}function jZ(e=null){if(!e||typeof e!="object")return null;const t=s0(e.severity,Xn.ERROR);return fv({id:`viewer-alert:${Nr(e.summary)||Nr(e.title)||t}`,level:t,source:"viewer",code:"viewer_alert",title:Nr(e.title)||Nr(e.summary)||"Viewer issue",message:Nr(e.message)||Nr(e.summary),details:[Xi("Summary",e.summary),Xi("Resolution",e.resolution),Xi("Command",e.command,{mono:!0})].filter(Boolean)})}function LZ({entry:e=null,fileSheetKind:t="",stepSourceStatus:n=null,stepArtifactGenerationAvailable:r=!0,stepArtifactGenerationState:o=null,activeGenerationFiles:i=[],gcodeData:s=null,urdfData:a=null,viewerAlert:l=null,viewerServerInfo:u=null}={}){if(!e)return[];const d=Nr(t).toLowerCase(),m=[];m.push(...RZ(e,{viewerServerInfo:u})),d==="step"&&m.push(...PZ({entry:e,stepSourceStatus:n,stepArtifactGenerationAvailable:r,stepArtifactGenerationState:o,activeGenerationFiles:i,viewerServerInfo:u})),d==="gcode"&&m.push(...kZ(s)),d==="sdf"&&m.push(...DZ(a?.sdf||a));const p=jZ(l),g=p&&yc(m).some(x=>x.level===p.level&&x.title===p.title&&x.message===p.message);return p&&!g&&m.push(p),yc(m)}const i_=Object.freeze({[Xn.ERROR]:{badgeVariant:"destructive-outline",borderClassName:"border-destructive/70"},[Xn.WARNING]:{badgeVariant:"warning-outline",borderClassName:"border-amber-500/70"},[Xn.INFO]:{badgeVariant:"outline",borderClassName:"border-border"}}),FZ="h-4 min-w-4 self-center rounded-sm px-1 text-[10px] font-medium leading-none",zZ="h-4 self-center rounded-sm px-1.5 py-0 text-[10px] font-medium leading-none";function s_(e){return i_[e]||i_[Xn.INFO]}function wf({items:e=[],value:t="status"}){const[n,r]=f.useState(()=>new Set),[o,i]=f.useState(""),s=ck(e);if(f.useEffect(()=>{if(!o)return;const g=globalThis.setTimeout(()=>i(""),1400);return()=>globalThis.clearTimeout(g)},[o]),!s.length)return null;const a=g=>{r(x=>{const y=new Set(x);return y.has(g)?y.delete(g):y.add(g),y})},l=g=>{r(x=>{if(!x.has(g))return x;const y=new Set(x);return y.delete(g),y})},u=(g,x,y)=>{!y||g.key!=="Enter"&&g.key!==" "||(g.preventDefault(),a(x))},d=async(g,x)=>{g.preventDefault(),g.stopPropagation();try{await ps(OZ(x)),i(x.id)}catch{i("")}},m=uk(s),p=s_(m);return c.jsx(ci,{value:t,title:c.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[c.jsx("span",{children:"Issues"}),c.jsx(Ls,{variant:p.badgeVariant,className:FZ,children:s.length})]}),children:c.jsx("ul",{className:"space-y-3 px-3 py-3 text-xs leading-5",children:s.map(g=>{const x=s_(g.level),y=Array.isArray(g.details)?g.details:[],S=y.length>0,b=n.has(g.id);return c.jsxs("li",{className:H("min-w-0 border-l-2",x.borderClassName),children:[c.jsxs("div",{role:S?"button":void 0,tabIndex:S?0:void 0,className:H("block min-w-0 rounded-md py-1 pl-2.5 pr-1 text-left",S&&"w-full cursor-pointer hover:bg-sidebar-accent/60 hover:text-sidebar-accent-foreground",!S&&"w-full"),onClick:()=>{S&&a(g.id)},onKeyDown:I=>u(I,g.id,S),"aria-expanded":S?b:void 0,children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(Ls,{variant:x.badgeVariant,className:H("shrink-0",zZ),children:dv(g.level)}),c.jsx("div",{className:"min-w-0 flex-1 truncate font-medium leading-4 text-sidebar-foreground",title:g.title,children:g.title}),c.jsx("span",{className:"ml-auto inline-flex h-5 shrink-0 items-center",children:c.jsx(Qe,{type:"button",variant:"ghost",size:"icon-xs",className:"size-5 rounded-sm text-muted-foreground hover:text-sidebar-foreground",onClick:I=>d(I,g),"aria-label":o===g.id?"Copied issue":"Copy issue for agent",title:o===g.id?"Copied":"Copy issue for agent",children:o===g.id?c.jsx(mu,{className:"size-3",strokeWidth:2.25,"aria-hidden":"true"}):c.jsx(vu,{className:"size-3",strokeWidth:2.1,"aria-hidden":"true"})})})]}),g.message?c.jsx("div",{className:"mt-1 line-clamp-2 min-w-0 break-words text-[11px] font-normal leading-4 text-muted-foreground",children:g.message}):null]}),S&&b?c.jsxs("div",{className:"mt-2 space-y-2 pl-2.5",children:[c.jsx("dl",{className:"space-y-1 text-[11px] leading-4",children:y.map((I,A)=>c.jsxs("div",{className:"min-w-0",children:[c.jsx("dt",{className:"text-muted-foreground",children:I.label}),c.jsx("dd",{className:H("min-w-0 break-words text-sidebar-foreground",I.mono&&"break-all font-mono text-[10px] leading-4"),children:I.value})]},`${g.id}:${I.label}:${A}`))}),c.jsx(Qe,{type:"button",variant:"ghost",size:"xs",className:"h-auto rounded-sm px-0 py-0 text-[11px] font-medium text-muted-foreground hover:bg-transparent hover:text-sidebar-foreground",onClick:I=>{I.preventDefault(),I.stopPropagation(),l(g.id)},children:"Collapse"})]}):null]},g.id)})})})}const fk=$Y,a_=VY;function eS(e){const t=Number(e);return Number.isFinite(t)?t.toFixed(4).replace(/\.?0+$/,""):""}function tS(e){const t=Math.round(Number(e)*10)/10;return Number.isFinite(t)?String(t):""}function BZ({index:e,setting:t,onChange:n}){const[r,o]=f.useState(()=>tS(t?.angleDeg));f.useEffect(()=>{o(tS(t?.angleDeg))},[t?.angleDeg]);const i=a=>{const l=Up(a,t?.angleDeg);n(e,{angleDeg:l}),o(tS(l))},s=Gp(t?.direction);return c.jsx(cn,{label:`B${e+1}`,children:c.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_5.75rem] gap-2",children:[c.jsxs("div",{className:"min-w-0",children:[c.jsx("span",{className:"sr-only",children:"Direction"}),c.jsxs(Kw,{type:"single",variant:"outline",size:"sm",value:s,onValueChange:a=>{a&&n(e,{direction:a})},className:"grid h-7 w-full min-w-0 grid-cols-2","aria-label":`Bend ${e+1} direction`,children:[c.jsx(Vp,{value:cu.UP,className:`!h-7 text-[11px] ${D1}`,children:"Up"}),c.jsx(Vp,{value:cu.DOWN,className:`!h-7 text-[11px] ${D1}`,children:"Down"})]})]}),c.jsxs("label",{className:"block",children:[c.jsx("span",{className:"sr-only",children:"Angle"}),c.jsxs("div",{className:"relative",children:[c.jsx(go,{type:"number",min:"0",max:"180",step:"1",inputMode:"decimal",value:r,onChange:a=>{o(a.target.value)},onFocus:a=>{a.currentTarget.select()},onMouseUp:a=>{a.preventDefault()},onBlur:()=>{i(r)},onKeyDown:a=>{a.key==="Enter"&&a.currentTarget.blur()},className:`${fk} w-full pr-9 text-right`,"aria-label":`Bend ${e+1} angle in degrees`}),c.jsx("span",{className:"pointer-events-none absolute inset-y-0 right-2 flex items-center text-xs text-muted-foreground",children:"deg"})]})]})]})})}function VZ({open:e,isDesktop:t,width:n,selectedEntry:r=null,onOpenChange:o,valueMm:i,bendSettings:s,hasDxfData:a,viewerLoading:l,onStartResize:u,onThicknessChange:d,onBendChange:m,fileDownloadAvailable:p=!1,viewerServerInfo:g=null,localFileOpenAvailable:x=!1,fileAccessBusyKey:y="",onOpenFileAsset:S,suppressDynamicMetadataStatus:b=!1,statusItems:I=[],themeSections:A=null,openSectionIds:N=[],onOpenSectionIdsChange:P}){const[R,v]=f.useState(()=>eS(i)),C=Array.isArray(s)?s:[];f.useEffect(()=>{v(eS(i))},[i]);const T=k=>{const z=py(k,i);d(z),v(eS(z))};return c.jsx(xf,{open:e,title:"DXF",isDesktop:t,width:n,onOpenChange:o,onStartResize:u,children:c.jsxs(yf,{type:"multiple",value:N,onValueChange:P,className:"text-sm",children:[c.jsx(wf,{items:I}),c.jsx(ci,{value:"dxf",title:"DXF",children:c.jsxs(r0,{className:"py-0",children:[c.jsx(bo,{title:"Thickness",children:c.jsx(cn,{label:"Material",children:c.jsxs("div",{className:"grid grid-cols-[2rem_minmax(0,1fr)_2rem] items-center gap-1.5",children:[c.jsx(Qe,{type:"button",variant:"ghost",size:"icon-sm",className:a_,onClick:()=>{T(i-.25)},disabled:!a,"aria-label":"Reduce DXF material thickness",title:"Reduce thickness",children:c.jsx(PE,{className:"h-3.5 w-3.5",strokeWidth:2,"aria-hidden":"true"})}),c.jsxs("div",{className:"relative block",children:[c.jsx(go,{type:"number",min:"0.2",max:"25",step:"any",inputMode:"decimal",value:R,disabled:!a,onChange:k=>{v(k.target.value)},onBlur:()=>{T(R)},onKeyDown:k=>{k.key==="Enter"&&k.currentTarget.blur()},className:`${fk} w-full pr-9 text-right`,"aria-label":"DXF material thickness in millimeters"}),c.jsx("span",{className:"pointer-events-none absolute inset-y-0 right-2 flex items-center text-xs text-muted-foreground",children:"mm"})]}),c.jsx(Qe,{type:"button",variant:"ghost",size:"icon-sm",className:a_,onClick:()=>{T(i+.25)},disabled:!a,"aria-label":"Increase DXF material thickness",title:"Increase thickness",children:c.jsx(OE,{className:"h-3.5 w-3.5",strokeWidth:2,"aria-hidden":"true"})})]})})}),c.jsx(bo,{title:"Bends",children:C.length?C.map((k,z)=>c.jsx(BZ,{index:z,setting:k,onChange:m},k.id||`bend-${z+1}`)):c.jsx("p",{className:"px-3 py-1 text-xs text-muted-foreground",children:l?"Loading bends...":"No bends are available."})})]})}),A,c.jsx(Ef,{entry:r,fileDownloadAvailable:p,viewerServerInfo:g,localFileOpenAvailable:x,fileAccessBusyKey:y,onOpenFileAsset:S,suppressDynamicStatus:b})]})})}function _i({className:e,defaultValue:t,value:n,min:r=0,max:o=100,...i}){const s=f.useMemo(()=>Array.isArray(n)?n:Array.isArray(t)?t:[r],[t,r,n]);return c.jsxs(_z,{"data-slot":"slider",defaultValue:t,value:n,min:r,max:o,className:H("relative flex w-full touch-none items-center select-none data-[disabled]:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",e),...i,children:[c.jsx(Tz,{"data-slot":"slider-track",className:H("relative grow overflow-hidden rounded-full bg-muted data-[orientation=horizontal]:h-1 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1"),children:c.jsx(Rz,{"data-slot":"slider-range",className:H("absolute bg-primary data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full")})}),s.map((a,l)=>c.jsx(Pz,{"data-slot":"slider-thumb",className:"relative z-10 block size-3.5 shrink-0 rounded-full border border-background bg-primary shadow-sm ring-1 ring-foreground/15 transition-[color,box-shadow] outline-none hover:ring-2 hover:ring-ring/25 focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50"},l))]})}const $Z=.42,GZ=.08,UZ=.18,WZ=.04,mk=6e4,Ob=1,Jm=7,du=3,HZ=Object.freeze({1:25e3,2:4e4,3:mk,4:9e4,5:14e4,6:22e4,7:32e4}),KZ=1,vy=1e-5,l_=.035,c_=Object.freeze(["#2563eb","#16a34a","#0891b2","#ca8a04","#7c3aed","#0f766e","#4f46e5","#65a30d"]),XZ="#94a3b8",YZ="#64748b",u_=Object.freeze({support:.001,adhesion:.002,infill:.003,calibration:.004,other:.004,surface:.005,wall:.006}),qZ=.008,kb=4,pk=6,nS=Object.freeze([0,0,1]);function To(e,t=0){const n=Number(e);return Number.isFinite(n)?n:t}function W1(e,t,n){return Math.min(Math.max(e,t),n)}function ZZ(e,t=!1){return typeof e=="boolean"?e:t}function JZ(e){return String(e||"").trim().toLowerCase()==="full"?"full":"adaptive"}function hk(e){return W1(Math.round(To(e,du)),Ob,Jm)}function QZ(e){const t=hk(e);return HZ[t]||mk}function wo(e,t){return To(e?.[t])}function d_(){return{min:[1/0,1/0,1/0],max:[-1/0,-1/0,-1/0]}}function f_(e){return!e.min.every(Number.isFinite)||!e.max.every(Number.isFinite)?{min:[0,0,0],max:[1,1,1]}:{min:e.min,max:e.max}}function gk(e){const t=e?.start,n=e?.end;return Math.hypot(wo(n,0)-wo(t,0),wo(n,1)-wo(t,1),wo(n,2)-wo(t,2))}function eJ(e,t){const n=Math.max(0,Math.trunc(To(t,0))-1);if(!Array.isArray(e)||e.length<2)return[0,n];const r=W1(Math.trunc(To(e[0],0)),0,n),o=W1(Math.trunc(To(e[1],n)),0,n);return r<=o?[r,o]:[o,r]}function bk(e={},t=0){const n=e&&typeof e=="object"?e:{},r=JZ(n.detailMode),o=hk(n.detailLevel),i=QZ(o),s=Array.isArray(n.layerRange)?n.layerRange:Number.isFinite(Number(n.maxLayer))?[0,Number(n.maxLayer)]:null;return{showTravel:ZZ(n.showTravel,!1),layerRange:eJ(s,t),detailMode:r,detailLevel:o,maxVisibleSegments:r==="full"?0:Math.max(Math.trunc(To(n.maxVisibleSegments,i)),KZ),extrusionWidthMm:Math.max(To(n.extrusionWidthMm,$Z),.01),travelWidthMm:Math.max(To(n.travelWidthMm,GZ),.01),extrusionHeightMm:Math.max(To(n.extrusionHeightMm,UZ),.01),travelHeightMm:Math.max(To(n.travelHeightMm,WZ),.01)}}function tJ(e){const t=Math.max(0,Math.trunc(To(e,0)));return c_[t%c_.length]}function nJ(e){return e.kind==="travel"?"travel":`layer:${Math.max(0,Math.trunc(To(e.layerIndex,0)))}`}function rJ(e,t){return e==="travel"?"Travel":`Layer ${Math.max(0,Math.trunc(To(t,0)))+1}`}function oJ(e){const t=String(e||"").trim(),n=/^#[0-9a-fA-F]{3}$/.test(t)?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:t;return/^#[0-9a-fA-F]{6}$/.test(n)?[parseInt(n.slice(1,3),16)/255,parseInt(n.slice(3,5),16)/255,parseInt(n.slice(5,7),16)/255]:[1,1,1]}function yk(e,t){const n=Math.max(0,Math.trunc(To(e?.layerIndex,0))),[r,o]=t.layerRange;return no?!1:e?.kind==="travel"?t.showTravel:e?.kind==="extrusion"}function iJ(e,t){const n=Array.isArray(e?.segments)?e.segments:[],r=new Map;let o=0;for(const i of n){if(!yk(i,t)||gk(i)<=vy)continue;const s=Math.max(0,Math.trunc(To(i?.layerIndex,0)));r.set(s,(r.get(s)||0)+1),o+=1}return{visibleSegmentCount:o,segmentsByLayer:r}}function pv(e,t,n,r){return r<=1?!0:e===t||e===n||(e-t)%r===0}function xk(e,t,n,r){let o=0;for(const[i,s]of e.entries())i>=t&&i<=n&&pv(i,t,n,r)&&(o+=s);return o}function sJ(e,t,n){const r=Math.trunc(To(n?.maxVisibleSegments,0));if(n?.detailMode==="full"||r<=0||t<=r)return 1;const[o,i]=n.layerRange,s=Math.max(1,i-o+1);for(let a=2;a<=s;a+=1)if(xk(e,o,i,a)<=r)return a;return s}function aJ(e,t,n,r){let o=0;for(const i of e.keys())i>=t&&i<=n&&pv(i,t,n,r)&&(o+=1);return o}function H1(e,t,n,r){e.min[0]=Math.min(e.min[0],t),e.min[1]=Math.min(e.min[1],n),e.min[2]=Math.min(e.min[2],r),e.max[0]=Math.max(e.max[0],t),e.max[1]=Math.max(e.max[1],n),e.max[2]=Math.max(e.max[2],r)}function lJ(e,t){H1(e,wo(t?.start,0),wo(t?.start,1),wo(t?.start,2)),H1(e,wo(t?.end,0),wo(t?.end,1),wo(t?.end,2))}function cJ(e,t,n){return t==="travel"?YZ:e?.featureCategory==="support"?XZ:tJ(n)}function uJ(e){if(e?.kind==="travel")return l_+qZ;const t=String(e?.featureCategory||"other").trim().toLowerCase();return l_+(u_[t]??u_.other)}function Zg({vertices:e,colors:t,normals:n,bounds:r,offset:o,x:i,y:s,z:a,zOffset:l=0,color:u}){e[o]=i,e[o+1]=s,e[o+2]=a+l,t[o]=u[0],t[o+1]=u[1],t[o+2]=u[2],n[o]=nS[0],n[o+1]=nS[1],n[o+2]=nS[2],H1(r,i,s,a+l)}function dJ({vertices:e,indices:t,colors:n,normals:r,bounds:o,segment:i,segmentIndex:s,width:a,color:l,zOffset:u}){const d=i?.start,m=i?.end,p=wo(d,0),g=wo(d,1),x=wo(d,2),y=wo(m,0),S=wo(m,1),b=wo(m,2),I=y-p,A=S-g,N=b-x;if(!(Math.hypot(I,A,N)>vy))return null;let R=-A,v=I,C=Math.hypot(R,v);C>vy||(R=1,v=0,C=1);const T=a/2,k=R/C*T,z=v/C*T,Y=s*kb,K=Y*3;Zg({vertices:e,colors:n,normals:r,bounds:o,offset:K,x:p+k,y:g+z,z:x,zOffset:u,color:l}),Zg({vertices:e,colors:n,normals:r,bounds:o,offset:K+3,x:p-k,y:g-z,z:x,zOffset:u,color:l}),Zg({vertices:e,colors:n,normals:r,bounds:o,offset:K+6,x:y-k,y:S-z,z:b,zOffset:u,color:l}),Zg({vertices:e,colors:n,normals:r,bounds:o,offset:K+9,x:y+k,y:S+z,z:b,zOffset:u,color:l});const J=s*pk;return t[J]=Y,t[J+1]=Y+1,t[J+2]=Y+2,t[J+3]=Y,t[J+4]=Y+2,t[J+5]=Y+3,!0}function fJ(e,t={}){const n=Array.isArray(e?.layers)?e.layers:[],r=bk(t,n.length),o=Array.isArray(e?.segments)?e.segments:[],{visibleSegmentCount:i,segmentsByLayer:s}=iJ(e,r),a=sJ(s,i,r),[l,u]=r.layerRange,d=xk(s,l,u,a),m=aJ(s,l,u,a),p=new Float32Array(d*kb*3),g=new Uint32Array(d*pk),x=new Float32Array(p.length),y=new Float32Array(p.length),S=[],b=d_(),I=d_();let A=null,N=0;for(const v of o){if(!yk(v,r)||gk(v)<=vy)continue;const C=nJ(v),T=Math.max(0,Math.trunc(To(v?.layerIndex,0)));if(!pv(T,l,u,a))continue;lJ(I,v),(!A||A.key!==C)&&(A={key:C,layerIndex:T,vertexOffset:N*kb,triangleOffset:N*2,segmentCount:0},S.push(A)),dJ({vertices:p,indices:g,colors:x,normals:y,bounds:b,segment:v,segmentIndex:N,width:v.kind==="travel"?r.travelWidthMm:r.extrusionWidthMm,color:oJ(cJ(v,C,T)),zOffset:uJ(v)})&&(A.segmentCount+=1,N+=1)}const P=S.map((v,C)=>{const T=S[C+1]?.vertexOffset??N*kb,k=S[C+1]?.triangleOffset??N*2;return{id:v.key==="travel"?`gcode:travel:${C}`:`gcode:layer:${v.layerIndex}:${C}`,label:rJ(v.key,v.layerIndex),vertexOffset:v.vertexOffset,vertexCount:Math.max(0,T-v.vertexOffset),triangleOffset:v.triangleOffset,triangleCount:Math.max(0,k-v.triangleOffset),bounds:f_(I),segmentCount:v.segmentCount}}).filter(v=>v.vertexCount>0&&v.triangleCount>0),R=f_(I);return{vertices:p,indices:g,normals:y,colors:x,bounds:R,parts:P,has_source_colors:!0,sourceFormat:"gcode",sourceColor:"#2563eb",metadata:{kind:"gcode",previewGeometry:"ribbon",options:r,visibleSegments:i,renderedSegments:N,visibleLayers:Math.max(0,u-l+1),renderedLayers:m,layerStride:a,segmentStride:1,decimationMode:a>1?"layers":"none",decimated:a>1,stats:e?.stats||{},features:Array.isArray(e?.features)?e.features:[],warnings:Array.isArray(e?.warnings)?e.warnings:[]}}}const mJ=Nu,m_="h-4 rounded-sm px-1.5 py-0 text-[10px] font-medium leading-none";function K1(e,t=2){const n=Number(e);return Number.isFinite(n)?n.toFixed(t):0 .toFixed(t)}function ii(e){const t=Number(e);return Number.isFinite(t)?String(Math.round(t)):"0"}function pJ(e){const t=Math.round(Number(e)||0),n=Math.abs(t),r=n%100;if(r>=11&&r<=13)return`${t}th`;switch(n%10){case 1:return`${t}st`;case 2:return`${t}nd`;case 3:return`${t}rd`;default:return`${t}th`}}function rS(e,t=1){return`${K1(e,t)} mm`}function p_(e){const t=ii(e);return`${t} cmd${t==="1"?"":"s"}`}function hJ(e){const t=String(e||"").trim();return t?`${t[0].toUpperCase()}${t.slice(1)}`:"Other"}function gJ(e){switch(Math.round(Number(e)||du)){case 1:return"Light";case 2:return"Lean";case 4:return"Dense";case 5:return"High";case 6:return"Very high";case 7:return"Max adaptive";default:return"Standard"}}function bJ(e){const t=Array.isArray(e?.min)?e.min:[0,0,0],n=Array.isArray(e?.max)?e.max:[0,0,0];return{min:t,max:n}}function oS(e,t,n=1){const{min:r,max:o}=bJ(e);return`${K1(r[t],n)} to ${K1(o[t],n)} mm`}function yJ(e,t){if(e<1)return"0 / 0";const n=t+1;return n>1?`1-${n} / ${e}`:`1 / ${e}`}function xJ(e,t,n){if(n<1)return 0;const i=String(e??"").trim().match(/\b\d+\s*-\s*(\d+)\b/)?.[1]??e;return ui(i,{fallback:t,min:1,max:Math.max(n,0),integer:!0})-1}function Ga({label:e,value:t,mono:n=!1}){const r=String(t??"");return c.jsxs("div",{className:"block min-w-0",children:[c.jsx("span",{className:mJ,children:e}),c.jsx("div",{className:`mt-1 min-h-7 truncate rounded-md border border-border/70 bg-muted/25 px-2 py-1.5 text-[11px] font-medium leading-4 text-foreground ${n?"font-mono":""}`,title:r,children:r})]})}function SJ({open:e,isDesktop:t,width:n,selectedEntry:r=null,onOpenChange:o,onStartResize:i,gcodeData:s=null,previewMetadata:a=null,maxLayer:l=0,showTravel:u=!1,fullDetail:d=!1,previewDetailLevel:m=du,onMaxLayerChange:p,onShowTravelChange:g,onFullDetailChange:x,onPreviewDetailLevelChange:y,fileDownloadAvailable:S=!1,viewerServerInfo:b=null,localFileOpenAvailable:I=!1,fileAccessBusyKey:A="",onOpenFileAsset:N,suppressDynamicMetadataStatus:P=!1,statusItems:R=[],themeSections:v=null,openSectionIds:C=[],onOpenSectionIdsChange:T}){const k=Array.isArray(s?.layers)?s.layers:[],z=s?.stats||{},Y=Array.isArray(s?.features)?s.features:[],J=Y.filter(se=>se?.category==="support").some(se=>Number(se?.extrusionMoves)>0||Number(se?.markerCount)>0),G=Y.reduce((se,Ae)=>se+(Number(Ae?.markerCount)||0),0),Q=Number(a?.renderedSegments),D=Number(a?.visibleSegments),$=Number(a?.layerStride),ie=Number(a?.renderedLayers),W=Number(a?.visibleLayers),Z=!!a?.decimated,Ee=Number.isFinite(Q)&&Number.isFinite(D)?`${ii(Q)} / ${ii(D)}`:"",re=Number.isFinite(ie)&&Number.isFinite(W)?`${ii(ie)} / ${ii(W)}`:"",be=k.length,_e=Math.min(Math.max(Math.round(Number(m)||du),Ob),Jm),Ie=be>0?Math.min(Math.max(Math.trunc(Number(l)||0),0),be-1):0,oe=!!s,me=yJ(be,Ie);return c.jsx(xf,{open:e,title:"G-code",isDesktop:t,width:n,onOpenChange:o,onStartResize:i,children:c.jsxs(yf,{type:"multiple",value:C,onValueChange:T,className:"text-sm",children:[c.jsx(wf,{items:R}),c.jsx(ci,{value:"toolpath",title:"Toolpath",children:c.jsxs("div",{children:[oe?null:c.jsx("p",{className:"px-3 py-2 text-xs text-muted-foreground",children:"Loading G-code..."}),c.jsx(bo,{title:"Summary",contentClassName:"px-3",children:c.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[c.jsxs(Ls,{variant:"secondary",className:"font-normal",children:[ii(be)," layer",be===1?"":"s"]}),c.jsxs(Ls,{variant:"outline",className:"font-normal",children:[ii(z.extrusionMoves)," path",ii(z.extrusionMoves)==="1"?"":"s"]}),c.jsxs(Ls,{variant:J?"secondary":"outline",className:"font-normal",children:["Supports ",J?"yes":"no"]}),Z?c.jsx(Ls,{variant:"outline",className:"font-normal",children:"Layer preview"}):null]})}),c.jsx(bo,{title:"Layers",children:c.jsx(Ni,{label:"Visible layers",value:me,onValueCommit:se=>{p?.(xJ(se,Ie+1,be))},valueInputProps:{disabled:be<=1,ariaLabel:"Visible G-code layers value",inputMode:"numeric"},children:c.jsx(_i,{value:[Ie],min:0,max:Math.max(be-1,0),step:1,disabled:be<=1,onValueChange:se=>{p?.(Number(se?.[0]??0))},className:Us,"aria-label":"Visible G-code layers"})})}),c.jsx(bo,{title:"Preview",children:c.jsx(Ni,{label:"Adaptive detail",value:`${gJ(_e)} (${_e}/${Jm})`,onValueCommit:se=>{y?.(ui(se,{fallback:_e,min:Ob,max:Jm,integer:!0}))},valueInputProps:{disabled:d,ariaLabel:"G-code preview detail value",inputMode:"numeric"},children:c.jsx(_i,{value:[_e],min:Ob,max:Jm,step:1,disabled:d,onValueChange:se=>{y?.(Number(se?.[0]??du))},className:Us,"aria-label":"G-code preview detail"})})}),c.jsxs(bo,{title:"Rendering",children:[c.jsx(Mi,{label:"Travel moves",description:`${ii(z.travelMoves)} move${ii(z.travelMoves)==="1"?"":"s"}`,checked:u,onCheckedChange:se=>g?.(se),ariaLabel:"Show G-code travel moves"}),c.jsx(Mi,{label:"Full detail",description:d?"Exact: render every visible path.":Ee?`${Ee} rendered path${Q===1?"":"s"}${Z&&Number.isFinite($)?` across ${re||"sampled"} layer${ie===1?"":"s"}, every ${pJ($)}`:""}`:"Use adaptive layer sampling.",checked:d,onCheckedChange:se=>x?.(se),ariaLabel:"Render full G-code detail"})]})]})}),c.jsx(ci,{value:"features",title:c.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[c.jsx("span",{children:"Features"}),Y.length?c.jsx(Ls,{variant:"outline",className:m_,children:Y.length}):null,J?c.jsx(Ls,{variant:"outline",className:"font-normal",children:"Supports"}):null]}),children:c.jsx("div",{className:"space-y-2 px-3 py-2.5",children:Y.length?c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex flex-wrap gap-1.5 text-[11px]",children:[c.jsxs(Ls,{variant:J?"secondary":"outline",className:"font-normal",children:["Supports ",J?"included":"not detected"]}),c.jsxs(Ls,{variant:"outline",className:m_,children:[ii(G)," markers"]})]}),c.jsx("ul",{className:"divide-y divide-border/60 overflow-hidden rounded-md border border-border/60 bg-muted/15",children:Y.map(se=>{const Ae=ii(se?.extrusionMoves),we=ii(se?.markerCount),ct=[`${Ae} path${Ae==="1"?"":"s"}`,rS(se?.pathMm,1),se?.layerRangeText||"",we!=="0"?`${we} marker${we==="1"?"":"s"}`:""].filter(Boolean),ut=Array.isArray(se?.rawLabels)&&se.rawLabels.length?se.rawLabels.join(", "):"";return c.jsxs("li",{className:"min-w-0 px-2.5 py-1.5",title:ut,children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"min-w-0 flex-1 truncate text-xs font-medium text-foreground",children:se?.label||"Other"}),c.jsx("span",{className:"shrink-0 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:hJ(se?.category)})]}),c.jsx("p",{className:"truncate text-[11px] leading-5 text-muted-foreground",children:ct.join(" | ")})]},se?.id||se?.label)})})]}):c.jsx("p",{className:"text-xs leading-5 text-muted-foreground",children:"No slicer feature annotations found. The preview can still show layers, extrusion paths, and travel moves."})})}),c.jsx(ci,{value:"stats",title:"Stats",children:c.jsxs("div",{className:"grid grid-cols-2 gap-2 px-3 py-3",children:[c.jsx(Ga,{label:"Extrusion",value:rS(z.extrusionMm,1)}),c.jsx(Ga,{label:"Path length",value:rS(z.pathMm,1)}),c.jsx(Ga,{label:"Retracts",value:ii(z.retractMoves)}),c.jsx(Ga,{label:"Temperature",value:p_(z.temperatureCommands)}),c.jsx(Ga,{label:"Move commands",value:p_(z.movementCommands)}),c.jsx(Ga,{label:"Prime moves",value:ii(z.primeMoves)})]})}),c.jsx(ci,{value:"bounds",title:"Bounds",children:c.jsxs("div",{className:"grid grid-cols-1 gap-2 px-3 py-3",children:[c.jsx(Ga,{label:"X",value:oS(s?.bounds,0,1),mono:!0}),c.jsx(Ga,{label:"Y",value:oS(s?.bounds,1,1),mono:!0}),c.jsx(Ga,{label:"Z",value:oS(s?.bounds,2,2),mono:!0})]})}),v,c.jsx(Ef,{entry:r,fileDownloadAvailable:S,viewerServerInfo:b,localFileOpenAvailable:I,fileAccessBusyKey:A,onOpenFileAsset:N,suppressDynamicStatus:P})]})})}function EJ({...e}){return c.jsx(Dz,{"data-slot":"collapsible",...e})}const wJ=f.forwardRef(function({...t},n){return c.jsx(Oz,{ref:n,"data-slot":"collapsible-trigger",...t})}),vJ=f.forwardRef(function({...t},n){return c.jsx(kz,{ref:n,"data-slot":"collapsible-content",...t})}),Wt=Object.freeze({LOADING:"loading",ASSEMBLY:"assembly",DXF:"dxf",GCODE:"gcode",IMPLICIT:"implicit",ROBOT:"robot",STEP_PART:"step-part",STL_MESH:"stl-mesh",THREE_MF_MESH:"3mf-mesh",GLB_MESH:"glb-mesh"});function hv(e,{sourceFormat:t="",status:n={}}={}){const r=pc(t||e?.kind),o=pc(e?.kind),i=n||{};return i.artifactGenerating||i.loading?Wt.LOADING:o==="assembly"?Wt.ASSEMBLY:r===B.DXF||o===B.DXF?Wt.DXF:r===B.GCODE||o===B.GCODE?Wt.GCODE:r===B.IMPLICIT||o===B.IMPLICIT?Wt.IMPLICIT:Hi(r)||o==="srdf"?Wt.ROBOT:r===B.STL||o===B.STL?Wt.STL_MESH:r===B.THREE_MF||o===B.THREE_MF?Wt.THREE_MF_MESH:r===B.GLB||r==="gltf"||o===B.GLB||o==="gltf"?Wt.GLB_MESH:Wt.STEP_PART}function X1({...e}){return c.jsx(zz,{"data-slot":"context-menu",...e})}const Y1=f.forwardRef(function({...t},n){return c.jsx(jz,{ref:n,"data-slot":"context-menu-trigger",...t})}),q1=f.forwardRef(function({className:t,...n},r){return c.jsx(Lz,{children:c.jsx(Fz,{ref:r,"data-slot":"context-menu-content",className:H("cad-glass-popover z-50 min-w-44 origin-(--radix-context-menu-content-transform-origin) overflow-hidden rounded-md border border-border bg-popover p-1 text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",t),...n})})});function el({className:e,inset:t,variant:n="default",...r}){return c.jsx(Vz,{"data-slot":"context-menu-item","data-inset":t,"data-variant":n,className:H("relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden transition-colors data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive",e),...r})}function Z1({className:e,...t}){return c.jsx(Bz,{"data-slot":"context-menu-separator",className:H("-mx-1 my-1 h-px bg-border",e),...t})}const CJ={},MJ=2e3,IJ=6e4,h_=1e4,AJ=750,J1="dir",g_="file",NJ=new Set(["vercel-blob"]);function gv(){return String(CJ?.VIEWER_ASSET_BACKEND||"").trim().toLowerCase()}function Hp(e=gv()){return NJ.has(String(e||"").trim().toLowerCase())}function _J(e=gv()){return Hp(e)?IJ:MJ}function Sk(e){return!e||typeof e!="object"?{schemaVersion:4,entries:[]}:{schemaVersion:4,entries:Array.isArray(e.entries)?e.entries:[]}}function Ek(e){return!e||typeof e!="object"?{schemaVersion:1,runs:[],files:{}}:{schemaVersion:1,runs:Array.isArray(e.runs)?e.runs:[],files:e.files&&typeof e.files=="object"?e.files:{}}}const Kp=new Set;let Q1="",dr={manifest:Sk(),generationStatus:Ek(),revision:0,catalogHydrated:!1,catalogRefreshing:typeof window<"u",catalogError:"",activeDir:""},Jg=0,Im=null,Am=null,b_=Hp(),y_=!1;Q1=JSON.stringify(dr.manifest);function eE(e,{hydrated:t=!0,refreshing:n=!1,error:r="",activeDir:o=dr.activeDir}={}){const i=Sk(e),s=JSON.stringify(i),a=s!==Q1,l={manifest:a?i:dr.manifest,generationStatus:dr.generationStatus,revision:dr.revision+1,catalogHydrated:t,catalogRefreshing:n,catalogError:r,activeDir:o};if(!(!a&&l.catalogHydrated===dr.catalogHydrated&&l.catalogRefreshing===dr.catalogRefreshing&&l.catalogError===dr.catalogError&&l.activeDir===dr.activeDir)){a&&(Q1=s),dr={...l};for(const u of Kp)u()}}function x_(e){const t=Ek(e),n=JSON.stringify(dr.generationStatus),r=JSON.stringify(t);if(n!==r){dr={...dr,generationStatus:t,revision:dr.revision+1};for(const o of Kp)o()}}function TJ({refreshing:e=dr.catalogRefreshing,error:t=dr.catalogError,activeDir:n=dr.activeDir}={}){if(!(e===dr.catalogRefreshing&&t===dr.catalogError&&n===dr.activeDir)){dr={...dr,revision:dr.revision+1,catalogRefreshing:e,catalogError:t,activeDir:n};for(const r of Kp)r()}}function RJ(e){if(typeof window>"u")return"";try{return String(new URL(window.location.href).searchParams.get(e)||"").trim()}catch{return""}}function Xp({assetBackend:e=gv()}={}){if(typeof window>"u"||Hp(e))return"";let t=null;try{t=new URL(window.location.href)}catch{return""}if(t.searchParams.has(J1)){const n=String(t.searchParams.get(J1)||"").trim();return rv(n)}return ZO()}function a0(e,{activeDir:t=Xp(),includeFile:n=!1,params:r={}}={}){const o=new URL(e,"http://cad.local");if(t&&o.searchParams.set(J1,t),n){const i=RJ(g_);i&&o.searchParams.set(g_,i)}for(const[i,s]of Object.entries(r)){const a=String(s??"").trim();a&&o.searchParams.set(i,a)}return`${o.pathname}${o.search}`}async function bv(e,t){try{const n=await e.json();return String(n?.error||n?.result?.error||n?.result?.validation?.error?.message||t).trim()||t}catch{return t}}async function PJ(e,t,n,r){if(typeof AbortController!="function")return fetch(e,t);const o=new AbortController,i=setTimeout(()=>{o.abort()},n);try{return await fetch(e,{...t,signal:o.signal})}catch(s){throw s?.name==="AbortError"?new Error(r):s}finally{clearTimeout(i)}}async function Yp({markRefreshing:e=!dr.catalogHydrated}={}){if(typeof window>"u")return;if(Im)return Im;const t=++Jg,n=Xp();return e&&TJ({refreshing:!0,error:"",activeDir:n}),Im=(async()=>{try{const r=await PJ(a0("/__cad/catalog",{activeDir:n,includeFile:!0}),{cache:"no-store"},h_,`Timed out loading CAD catalog after ${h_/1e3}s`);if(!r.ok)throw new Error(await bv(r,`Failed to read CAD catalog: ${r.status} ${r.statusText}`));const o=await r.json();t===Jg&&eE(o,{hydrated:!0,refreshing:!1,error:"",activeDir:n})}catch(r){throw t===Jg&&eE(dr.manifest,{hydrated:!0,refreshing:!1,error:r instanceof Error?r.message:String(r),activeDir:n}),r}finally{t===Jg&&(Im=null)}})(),Im}async function vp(){if(typeof window>"u"||b_)return;const e=Xp();return Am||(Am=(async()=>{try{const t=await fetch(a0("/__cad/generation-status",{activeDir:e}),{cache:"no-store"}),n=String(t.headers?.get?.("content-type")||"");if(!t.ok||!n.includes("application/json")){if(t.status===404||t.status===501||!n.includes("application/json")){b_=!0,x_(null);return}throw new Error(`Failed to read CAD generation status: ${t.status} ${t.statusText}`)}x_(await t.json())}catch{}finally{Am=null}})(),Am)}async function OJ(e,{signal:t}={}){if(typeof window>"u")return null;const n=String(e||"").trim();if(!n)throw new Error("Missing STEP file");const r=await fetch(a0("/__cad/step-artifact",{params:{file:n}}),{method:"POST",cache:"no-store",signal:t});if(!r.ok)throw new Error(await bv(r,`Failed to generate STEP artifact: ${r.status} ${r.statusText}`));const o=await r.json();return o?.catalog&&eE(o.catalog),o}async function kJ(e,{signal:t}={}){if(typeof window>"u")return null;const n=String(e||"").trim();if(!n)throw new Error("Missing STEP file");const r=await fetch(a0("/__cad/step-source-status",{params:{file:n}}),{method:"GET",cache:"no-store",signal:t});if(!r.ok)throw new Error(await bv(r,`Failed to check STEP source status: ${r.status} ${r.statusText}`));return r.json()}function S_(){return dr}function DJ(e){return Kp.add(e),()=>{Kp.delete(e)}}if(typeof window<"u"){const e=()=>{Yp({markRefreshing:!1}).catch(t=>{}),vp()};Yp().catch(t=>{}),vp(),y_||(y_=!0,window.setInterval(()=>{document.visibilityState!=="hidden"&&e()},_J()),window.setInterval(()=>{document.visibilityState!=="hidden"&&vp()},AJ),window.addEventListener("focus",e),document.addEventListener("visibilitychange",()=>{document.visibilityState!=="hidden"&&e()}))}const wk=Object.freeze(["stl","glb","3mf"]),vk=96;function jJ(e){return String(e||"").trim().replace(/\\/g,"/").replace(/^\/+/,"")}function LJ(e){const t=String(e||"").trim().toLowerCase().replace(/^\./,"");return wk.includes(t)?t:""}function E_(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}async function FJ({file:e,format:t,parameterValues:n=null,animationState:r=null,resolution:o=vk}={}){const i=jJ(e),s=LJ(t);if(!i)throw new Error("Missing implicit CAD file");if(!s)throw new Error(`Unsupported implicit CAD export format: ${t||"(missing)"}`);const a=await fetch(`/__cad/implicit-export?file=${encodeURIComponent(i)}&format=${encodeURIComponent(s)}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({format:s,resolution:o,...E_(n)?{parameterValues:n}:{},...E_(r)?{animationState:r}:{}})});let l=null;try{l=await a.json()}catch{l=null}if(!a.ok||!l?.ok)throw new Error(String(l?.error||`Implicit CAD export failed with HTTP ${a.status}`));return l.catalog&&Yp({markRefreshing:!1}).catch(()=>{}),l}function Ck({entry:e,onRevealInExplorerView:t}){return typeof t!="function"?null:c.jsx(el,{className:"text-xs",onSelect:()=>{t(e)},children:c.jsx("span",{className:"min-w-0 truncate",children:"Reveal in Explorer View"})})}function zJ({entry:e,asset:t,canRevealFileAssets:n,canCopyFileAssetLinks:r,canCopyFileAssetPaths:o,busyKey:i="",onDownloadFileAsset:s,onRevealFileAsset:a,onRevealInExplorerView:l,onCopyFileAssetReference:u}){if(!t)return null;const d=`${t.fileRef}:${t.asset}`,m=i===d,p=typeof u=="function";return c.jsxs(c.Fragment,{children:[n?c.jsx(el,{className:"text-xs",disabled:m,onSelect:()=>{a(e,t.asset,t)},children:c.jsx("span",{className:"min-w-0 truncate",children:"Reveal in Folder"})}):null,c.jsx(Ck,{entry:e,onRevealInExplorerView:l}),o&&p?c.jsxs(c.Fragment,{children:[c.jsx(el,{className:"text-xs",onSelect:()=>{u(e,t.asset,t,"path")},children:c.jsx("span",{className:"min-w-0 truncate",children:"Copy Path"})}),c.jsx(el,{className:"text-xs",onSelect:()=>{u(e,t.asset,t,"relativePath")},children:c.jsx("span",{className:"min-w-0 truncate",children:"Copy Relative Path"})})]}):null,r&&p?c.jsx(el,{className:"text-xs",onSelect:()=>{u(e,t.asset,t,"link")},children:c.jsx("span",{className:"min-w-0 truncate",children:"Copy Link"})}):null,c.jsx(el,{className:"text-xs",onSelect:()=>{s(e,t.asset,t)},children:c.jsx("span",{className:"min-w-0 truncate",children:"Download"})})]})}function BJ({entry:e,busyKey:t="",onExportImplicitFile:n}){if(String(e?.kind||"").trim().toLowerCase()!=="implicit"||typeof n!="function")return null;const r=String(e?.file||e?.id||"").trim();return c.jsxs(c.Fragment,{children:[c.jsx(Z1,{}),wk.map(o=>{const i=o.toUpperCase(),s=`${r}:export:${o}`;return c.jsx(el,{className:"text-xs",disabled:t===s,onSelect:()=>{n(e,o)},children:c.jsxs("span",{className:"min-w-0 truncate",children:["Export to ",i]})},o)})]})}function tE({entry:e,canRevealFileAssets:t=!1,canCopyFileAssetLinks:n=!1,canCopyFileAssetPaths:r=!1,busyKey:o="",onDownloadFileAsset:i,onExportImplicitFile:s,onRevealFileAsset:a,onRevealInExplorerView:l,onCopyFileAssetReference:u,children:d}){const m=e&&typeof l=="function",p=e&&typeof i=="function",g=e&&typeof s=="function"&&String(e?.kind||"").trim().toLowerCase()==="implicit";if(!m&&!p&&!g)return d;const x=cv(e);return!m&&!x.output&&!g?d:c.jsxs(X1,{modal:!1,children:[c.jsx(Y1,{asChild:!0,children:d}),c.jsxs(q1,{className:"w-64",children:[!x.output||!p?c.jsx(Ck,{entry:e,onRevealInExplorerView:l}):null,x.output&&p?c.jsx(zJ,{entry:e,asset:x.output,canRevealFileAssets:t&&typeof a=="function",canCopyFileAssetLinks:n,canCopyFileAssetPaths:r,busyKey:o,onDownloadFileAsset:i,onRevealFileAsset:a,onRevealInExplorerView:l,onCopyFileAssetReference:u}):null,c.jsx(BJ,{entry:e,busyKey:o,onExportImplicitFile:s})]})]})}const VJ=150,Nm="calc(100vw - 0.75rem)",w_="min(18rem, calc(100vw - 0.75rem))",$J={[Wt.LOADING]:BE,[Wt.ASSEMBLY]:zE,[Wt.DXF]:FE,[Wt.GCODE]:LE,[Wt.IMPLICIT]:Fy,[Wt.ROBOT]:jE,[Wt.STEP_PART]:sf,[Wt.STL_MESH]:DE,[Wt.THREE_MF_MESH]:Ly,[Wt.GLB_MESH]:kE};function GJ(e,t,n){return $J[hv(e,{sourceFormat:t,status:n})]||sf}function Mk({entry:e,depth:t,selectedKey:n,onSelectEntry:r,entrySourceFormat:o,entryHasMesh:i,entryHasDxf:s,entryHasGcode:a,entryHasUrdf:l,activeGenerationFiles:u=[],activeStepArtifactGenerationFile:d="",stepArtifactGenerationAvailable:m=!0,canRevealFileAssets:p=!1,canCopyFileAssetLinks:g=!1,canCopyFileAssetPaths:x=!1,fileAccessBusyKey:y="",onDownloadFileAsset:S,onExportImplicitFile:b,onRevealFileAsset:I,onRevealInExplorerView:A,onCopyFileAssetReference:N,nested:P=!1}){const{isMobile:R,setOpenMobile:v}=nh(),C=at(e),T=C===n,k=dl(e),z=o(e),Y=YO(e,{sourceFormat:z,entryKey:C,hasMesh:i(e),hasDxf:s(e),hasGcode:a(e),hasUrdf:l(e),activeGenerationFiles:u,activeStepArtifactGenerationFile:d,stepArtifactGenerationAvailable:m}),K=GJ(e,z,Y),J=nv(e),G=J==="python"?Fy:J==="step"?C3:null,Q=!!G,D=[k,J==="python"?"Python-backed":"",J==="step"?"STEP-backed":"",Y.statusLabel,e?.kind,String(e?.file||"")].filter(Boolean).join(" | "),$=c.jsxs(jR,{type:"button",isActive:T,size:"sm",title:D,className:H("min-w-0 w-full justify-start"),onClick:()=>{r(C),R&&v(!1)},tooltip:k,children:[c.jsxs("span",{className:"relative flex size-4 shrink-0 items-center justify-center","aria-hidden":"true",children:[c.jsx(K,{className:H("size-4",Y.loading&&"animate-spin")}),Q?c.jsx("span",{className:"absolute -bottom-1 -right-1 flex size-2.5 items-center justify-center rounded-[3px] border border-sidebar bg-sidebar text-sidebar-foreground shadow-sm",children:c.jsx(G,{className:"size-2",strokeWidth:2.5})}):null]}),c.jsx("span",{className:"block min-w-0 flex-1 max-w-full overflow-hidden text-ellipsis whitespace-nowrap",children:k})]});return c.jsx(tE,{entry:e,canRevealFileAssets:p,canCopyFileAssetLinks:g,canCopyFileAssetPaths:x,busyKey:y,onDownloadFileAsset:S,onExportImplicitFile:b,onRevealFileAsset:I,onRevealInExplorerView:A,onCopyFileAssetReference:N,children:$})}function Ik({directory:e,depth:t,queryActive:n,expandedDirectoryIds:r,onToggleDirectory:o,selectedKey:i,onSelectEntry:s,entrySourceFormat:a,entryHasMesh:l,entryHasDxf:u,entryHasGcode:d,entryHasUrdf:m,activeGenerationFiles:p=[],activeStepArtifactGenerationFile:g="",stepArtifactGenerationAvailable:x=!0,canRevealFileAssets:y=!1,canCopyFileAssetLinks:S=!1,canCopyFileAssetPaths:b=!1,fileAccessBusyKey:I="",onDownloadFileAsset:A,onExportImplicitFile:N,onRevealFileAsset:P,onRevealInExplorerView:R,onCopyFileAssetReference:v,nested:C=!1}){const T=n||r.has(e.id),k=C?JM:DR;return c.jsx(EJ,{asChild:!0,open:T,children:c.jsxs(k,{className:"min-w-0 w-full max-w-full",children:[c.jsx(wJ,{asChild:!0,children:c.jsxs(jR,{type:"button",size:"sm",title:e.name,"aria-disabled":n,className:H("group/directory min-w-0 w-full justify-start",n&&"cursor-default"),onClick:z=>{if(n){z.preventDefault();return}o(e.id)},children:[c.jsx(Vd,{className:H("transition-transform",T&&"rotate-90"),"aria-hidden":"true"}),c.jsx("span",{className:"block min-w-0 flex-1 max-w-full overflow-hidden text-ellipsis whitespace-nowrap",children:e.name})]})}),c.jsx(vJ,{className:"min-w-0 w-full max-w-full",children:c.jsx(c5,{className:"min-w-0 w-full max-w-full",children:o0(e).map(z=>z.type==="directory"?c.jsx(Ik,{directory:z.value,depth:t+1,queryActive:n,expandedDirectoryIds:r,onToggleDirectory:o,selectedKey:i,onSelectEntry:s,entrySourceFormat:a,entryHasMesh:l,entryHasDxf:u,entryHasGcode:d,entryHasUrdf:m,activeGenerationFiles:p,activeStepArtifactGenerationFile:g,stepArtifactGenerationAvailable:x,canRevealFileAssets:y,canCopyFileAssetLinks:S,canCopyFileAssetPaths:b,fileAccessBusyKey:I,onDownloadFileAsset:A,onExportImplicitFile:N,onRevealFileAsset:P,onRevealInExplorerView:R,onCopyFileAssetReference:v,nested:!0},z.key):c.jsx(JM,{className:"min-w-0 w-full max-w-full",children:c.jsx(Mk,{entry:z.value,depth:t+1,selectedKey:i,onSelectEntry:s,entrySourceFormat:a,entryHasMesh:l,entryHasDxf:u,entryHasGcode:d,entryHasUrdf:m,activeGenerationFiles:p,activeStepArtifactGenerationFile:g,stepArtifactGenerationAvailable:x,canRevealFileAssets:y,canCopyFileAssetLinks:S,canCopyFileAssetPaths:b,fileAccessBusyKey:I,onDownloadFileAsset:A,onExportImplicitFile:N,onRevealFileAsset:P,onRevealInExplorerView:R,onCopyFileAssetReference:v,nested:!0})},z.key))})})]})})}function UJ({onStartResize:e}){const{isMobile:t,state:n}=nh();return t||n!=="expanded"||typeof e!="function"?null:c.jsx(Qe,{type:"button",variant:"ghost",size:"sm","aria-label":"Resize file viewer sidebar",title:"Resize sidebar",onPointerDown:e,className:"group/sidebar-resize absolute inset-y-0 -right-1.5 z-30 flex h-auto w-3 cursor-col-resize touch-none items-stretch justify-center rounded-none px-0 py-0 hover:bg-transparent",children:c.jsx("span",{className:"my-2 w-px rounded-full bg-transparent transition-colors group-hover/sidebar-resize:bg-sidebar-border group-focus-visible/sidebar-resize:bg-ring"})})}function v_(e){const t=String(e?.rootName||"").trim();if(t)return t;const n=String(e?.rootPath||e?.dir||"").trim().replace(/\\/g,"/").replace(/\/+$/g,"");return n.split("/").filter(Boolean).pop()||n||"Directory"}function C_(e){return String(e?.rootPath||e?.dir||"").trim()}function WJ(e){const t=new Set,n=[];for(const r of Array.isArray(e)?e:[]){const o=String(r?.dir||"").trim(),i=String(r?.rootPath||"").trim(),s=i||o;!o||!s||t.has(s)||(t.add(s),n.push({dir:o,rootPath:i,rootName:String(r?.rootName||"").trim()}))}return n}function HJ({directoryOptions:e=[],activeDirectory:t="",onSelectDirectory:n}){const r=WJ(e);if(r.length<=1)return null;const o=String(t||"").trim(),i=r.find(l=>l.dir===o||l.rootPath===o)||r[0],s=v_(i),a=C_(i);return c.jsxs(hf,{children:[c.jsx(gf,{asChild:!0,children:c.jsxs(Qe,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-full justify-between gap-2 rounded-md p-2 text-xs font-medium text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",title:a||s,children:[c.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[c.jsx("span",{className:"flex size-4 shrink-0 items-center justify-center","aria-hidden":"true",children:c.jsx(LS,{className:"size-4 text-muted-foreground"})}),c.jsx("span",{className:"min-w-0 truncate",children:s})]}),c.jsx(jy,{className:"size-3.5 shrink-0 text-muted-foreground","aria-hidden":"true"})]})}),c.jsx(bf,{align:"start",className:"w-[--radix-dropdown-menu-trigger-width] max-w-[min(28rem,calc(100vw-1rem))]",children:r.map(l=>{const u=v_(l),d=C_(l),m=l.dir===i.dir||l.rootPath===i.rootPath;return c.jsxs(Yo,{className:H("min-w-0 items-start gap-2 text-xs",m&&"bg-accent text-accent-foreground"),onSelect:()=>{typeof n=="function"&&l.dir!==i.dir&&n(l.dir)},title:d||u,children:[c.jsx(LS,{className:"mt-0.5 size-4 shrink-0 text-muted-foreground","aria-hidden":"true"}),c.jsxs("span",{className:"min-w-0 flex-1",children:[c.jsx("span",{className:"block truncate font-medium",children:u}),d?c.jsx("span",{className:"mt-0.5 block truncate text-[11px] text-muted-foreground",children:d}):null]})]},l.rootPath||l.dir)})})]})}function KJ({query:e,onQueryChange:t,filteredEntries:n,catalogEntries:r,filteredEntriesTree:o,selectedKey:i,expandedDirectoryIds:s,onToggleDirectory:a,onSelectEntry:l,entrySourceFormat:u,entryHasMesh:d,entryHasDxf:m,entryHasGcode:p,entryHasUrdf:g,activeGenerationFiles:x=[],activeStepArtifactGenerationFile:y="",stepArtifactGenerationAvailable:S=!0,canRevealFileAssets:b=!1,canCopyFileAssetLinks:I=!1,canCopyFileAssetPaths:A=!1,fileAccessBusyKey:N="",onDownloadFileAsset:P,onExportImplicitFile:R,onRevealFileAsset:v,onRevealInExplorerView:C,onCopyFileAssetReference:T,catalogHydrated:k=!1,catalogRefreshing:z=!1,catalogError:Y="",directoryOptions:K=[],activeDirectory:J="",onSelectDirectory:G,resizable:Q=!0,onStartResize:D}){const $=e.trim().length>0,ie=n.length>0,W=r.length>0,Z=String(Y||"").trim(),Ee=!k||z&&!W;return c.jsxs(c.Fragment,{children:[c.jsxs(r5,{className:"gap-2",children:[c.jsx(HJ,{directoryOptions:K,activeDirectory:J,onSelectDirectory:G}),c.jsx(n5,{type:"search",placeholder:"Search files, ids, or paths...",value:e,onChange:re=>t(re.target.value),"aria-label":"Search CAD files",className:"h-7 text-xs md:text-xs"})]}),c.jsx(o5,{children:c.jsx(ch,{className:"cad-file-viewer-scroll min-h-0 min-w-0 flex-1 overflow-x-hidden",type:"auto",children:c.jsx(i5,{children:c.jsx(s5,{children:ie?c.jsx(a5,{children:o0(o).map(re=>re.type==="directory"?c.jsx(Ik,{directory:re.value,depth:0,queryActive:$,expandedDirectoryIds:s,onToggleDirectory:a,selectedKey:i,onSelectEntry:l,entrySourceFormat:u,entryHasMesh:d,entryHasDxf:m,entryHasGcode:p,entryHasUrdf:g,activeGenerationFiles:x,activeStepArtifactGenerationFile:y,stepArtifactGenerationAvailable:S,canRevealFileAssets:b,canCopyFileAssetLinks:I,canCopyFileAssetPaths:A,fileAccessBusyKey:N,onDownloadFileAsset:P,onExportImplicitFile:R,onRevealFileAsset:v,onRevealInExplorerView:C,onCopyFileAssetReference:T},re.key):c.jsx(DR,{className:"min-w-0 w-full max-w-full",children:c.jsx(Mk,{entry:re.value,depth:0,selectedKey:i,onSelectEntry:l,entrySourceFormat:u,entryHasMesh:d,entryHasDxf:m,entryHasGcode:p,entryHasUrdf:g,activeGenerationFiles:x,activeStepArtifactGenerationFile:y,stepArtifactGenerationAvailable:S,canRevealFileAssets:b,canCopyFileAssetLinks:I,canCopyFileAssetPaths:A,fileAccessBusyKey:N,onDownloadFileAsset:P,onExportImplicitFile:R,onRevealFileAsset:v,onRevealInExplorerView:C,onCopyFileAssetReference:T})},re.key))}):Z&&!W?c.jsxs("p",{className:"px-2 py-3 text-xs text-muted-foreground",children:["CAD catalog unavailable: ",Z]}):Ee?c.jsx("p",{className:"px-2 py-3 text-xs text-muted-foreground",children:"Loading CAD catalog..."}):W?c.jsx("p",{className:"px-2 py-3 text-xs text-muted-foreground",children:"No CAD entries match this filter."}):c.jsx("p",{className:"px-2 py-3 text-xs text-muted-foreground",children:"No CAD entries found."})})})})}),c.jsx(UJ,{onStartResize:Q?D:null})]})}function XJ({previewMode:e,query:t,onQueryChange:n,filteredEntries:r,catalogEntries:o,filteredEntriesTree:i,selectedKey:s,expandedDirectoryIds:a,onToggleDirectory:l,onSelectEntry:u,entrySourceFormat:d,entryHasMesh:m,entryHasDxf:p,entryHasGcode:g,entryHasUrdf:x,activeGenerationFiles:y=[],activeStepArtifactGenerationFile:S="",stepArtifactGenerationAvailable:b=!0,canRevealFileAssets:I=!1,canCopyFileAssetLinks:A=!1,canCopyFileAssetPaths:N=!1,fileAccessBusyKey:P="",onDownloadFileAsset:R,onExportImplicitFile:v,onRevealFileAsset:C,onRevealInExplorerView:T,onCopyFileAssetReference:k,catalogHydrated:z=!1,catalogRefreshing:Y=!1,catalogError:K="",directoryOptions:J=[],activeDirectory:G="",onSelectDirectory:Q,resizable:D=!0,onStartResize:$}){const{isMobile:ie,state:W,openMobile:Z,setOpenMobile:Ee}=nh();if(e)return null;const re=c.jsx(KJ,{query:t,onQueryChange:n,filteredEntries:r,catalogEntries:o,filteredEntriesTree:i,selectedKey:s,expandedDirectoryIds:a,onToggleDirectory:l,onSelectEntry:u,entrySourceFormat:d,entryHasMesh:m,entryHasDxf:p,entryHasGcode:g,entryHasUrdf:x,activeGenerationFiles:y,activeStepArtifactGenerationFile:S,stepArtifactGenerationAvailable:b,canRevealFileAssets:I,canCopyFileAssetLinks:A,canCopyFileAssetPaths:N,fileAccessBusyKey:P,onDownloadFileAsset:R,onExportImplicitFile:v,onRevealFileAsset:C,onRevealInExplorerView:T,onCopyFileAssetReference:k,catalogHydrated:z,catalogRefreshing:Y,catalogError:K,directoryOptions:J,activeDirectory:G,onSelectDirectory:Q,resizable:D,onStartResize:$});if(ie)return c.jsx(_R,{open:Z,onOpenChange:Ee,children:c.jsxs(TR,{side:"left",showCloseButton:!1,className:"cad-glass-surface gap-0 p-0 text-sidebar-foreground",style:{width:w_,maxWidth:Nm},children:[c.jsxs(RR,{className:"sr-only",children:[c.jsx(PR,{children:"CAD Viewer"}),c.jsx(OR,{children:"Browse files in the CAD catalog."})]}),c.jsx("div",{className:"flex h-full min-h-0 w-full flex-col","aria-label":"CAD Viewer",children:re})]})});if(W!=="expanded")return null;const be=`min(var(--sidebar-width), ${Nm})`,_e=ie?{width:w_,maxWidth:Nm}:{width:be,flexBasis:be,minWidth:`min(${VJ}px, ${Nm})`,maxWidth:Nm};return c.jsx("aside",{className:H("cad-glass-surface pointer-events-auto z-30 flex h-full max-w-[calc(100vw_-_0.75rem)] flex-col border-r border-sidebar-border text-sidebar-foreground",ie?"absolute inset-y-0 left-0 shadow-xl":"relative shrink-0"),style:_e,"aria-label":"CAD Viewer",children:re})}function Ak({...e}){return c.jsx(qz,{"data-slot":"alert-dialog",...e})}f.forwardRef(function({...t},n){return c.jsx($z,{ref:n,"data-slot":"alert-dialog-trigger",...t})});function YJ({...e}){return c.jsx(Yz,{"data-slot":"alert-dialog-portal",...e})}const qJ=f.forwardRef(function({className:t,...n},r){return c.jsx(Gz,{ref:r,"data-slot":"alert-dialog-overlay",className:H("fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",t),...n})}),Nk=f.forwardRef(function({className:t,...n},r){return c.jsxs(YJ,{children:[c.jsx(qJ,{}),c.jsx(Uz,{ref:r,"data-slot":"alert-dialog-content",className:H("cad-glass-popover fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-md border p-6 text-foreground shadow-lg duration-200 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",t),...n})]})});function _k({className:e,...t}){return c.jsx("div",{"data-slot":"alert-dialog-header",className:H("flex flex-col gap-2 text-center sm:text-left",e),...t})}function Tk({className:e,...t}){return c.jsx("div",{"data-slot":"alert-dialog-footer",className:H("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t})}const Rk=f.forwardRef(function({className:t,...n},r){return c.jsx(Wz,{ref:r,"data-slot":"alert-dialog-title",className:H("text-lg font-semibold",t),...n})}),Pk=f.forwardRef(function({className:t,...n},r){return c.jsx(Hz,{ref:r,"data-slot":"alert-dialog-description",className:H("text-sm text-muted-foreground",t),...n})}),ZJ=f.forwardRef(function({className:t,...n},r){return c.jsx(Kz,{ref:r,className:H(HE(),t),...n})}),Ok=f.forwardRef(function({className:t,...n},r){return c.jsx(Xz,{ref:r,className:H(HE({variant:"outline"}),t),...n})});function JJ({...e}){return c.jsx(e3,{"data-slot":"popover",...e})}const QJ=f.forwardRef(function({...t},n){return c.jsx(Zz,{ref:n,"data-slot":"popover-trigger",...t})}),eQ=f.forwardRef(function({className:t,align:n="center",sideOffset:r=4,...o},i){return c.jsx(Jz,{children:c.jsx(Qz,{ref:i,"data-slot":"popover-content",align:n,sideOffset:r,className:H("cad-glass-popover z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 text-popover-foreground shadow-md outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...o})})}),kk=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,tQ=["hex","rgb","hsl"];function Ro(e,t,n){const r=Number(e);return Number.isFinite(r)?Math.min(Math.max(r,t),n):t}function nE(e,t="#ffffff"){const n=String(e||"").trim();return kk.test(n)?n.length===4?`#${n[1]}${n[1]}${n[2]}${n[2]}${n[3]}${n[3]}`.toLowerCase():n.toLowerCase():t}function iS(e){return Math.round(Ro(e,0,255)).toString(16).padStart(2,"0")}function Qg({r:e,g:t,b:n}){return`#${iS(e)}${iS(t)}${iS(n)}`.toLowerCase()}function nQ(e){const t=nE(e);return{r:parseInt(t.slice(1,3),16),g:parseInt(t.slice(3,5),16),b:parseInt(t.slice(5,7),16)}}function rQ({r:e,g:t,b:n}){const r=Ro(e,0,255)/255,o=Ro(t,0,255)/255,i=Ro(n,0,255)/255,s=Math.max(r,o,i),a=Math.min(r,o,i),l=s-a;let u=0;return l!==0&&(s===r?u=(o-i)/l%6:s===o?u=(i-r)/l+2:u=(r-o)/l+4,u*=60,u<0&&(u+=360)),{h:u,s:s===0?0:l/s*100,v:s*100}}function M_({h:e,s:t,v:n}){const r=(Number(e)%360+360)%360,o=Ro(t,0,100)/100,i=Ro(n,0,100)/100,s=i*o,a=s*(1-Math.abs(r/60%2-1)),l=i-s;let u=0,d=0,m=0;return r<60?(u=s,d=a):r<120?(u=a,d=s):r<180?(d=s,m=a):r<240?(d=a,m=s):r<300?(u=a,m=s):(u=s,m=a),{r:(u+l)*255,g:(d+l)*255,b:(m+l)*255}}function oQ({r:e,g:t,b:n}){const r=Ro(e,0,255)/255,o=Ro(t,0,255)/255,i=Ro(n,0,255)/255,s=Math.max(r,o,i),a=Math.min(r,o,i),l=s-a;let u=0,d=0;const m=(s+a)/2;return l!==0&&(d=l/(1-Math.abs(2*m-1)),s===r?u=(o-i)/l%6:s===o?u=(i-r)/l+2:u=(r-o)/l+4,u*=60,u<0&&(u+=360)),{h:u,s:d*100,l:m*100}}function iQ({h:e,s:t,l:n}){const r=(Number(e)%360+360)%360,o=Ro(t,0,100)/100,i=Ro(n,0,100)/100,s=(1-Math.abs(2*i-1))*o,a=s*(1-Math.abs(r/60%2-1)),l=i-s/2;let u=0,d=0,m=0;return r<60?(u=s,d=a):r<120?(u=a,d=s):r<180?(d=s,m=a):r<240?(d=a,m=s):r<300?(u=a,m=s):(u=s,m=a),{r:(u+l)*255,g:(d+l)*255,b:(m+l)*255}}function sQ(e){const t=nQ(e),n=oQ(t);return{rgb:t,hsl:{h:Math.round(n.h),s:Math.round(n.s),l:Math.round(n.l)},hsv:rQ(t)}}function cd({label:e,value:t,min:n,max:r,onChange:o}){return c.jsxs("label",{className:"min-w-0 space-y-1",children:[c.jsx("span",{className:"block text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:e}),c.jsx(go,{type:"number",min:n,max:r,value:t,onChange:i=>o(Ro(i.currentTarget.value,n,r)),className:"h-7 px-1.5 text-[11px]"})]})}function yv({value:e="#ffffff",onChange:t,opacity:n=1,onOpacityChange:r,className:o,swatchClassName:i,valueClassName:s,popoverAlign:a="start",showValue:l=!0,showOpacity:u=!1,disabled:d=!1,...m}){const p=nE(e),g=Number.isFinite(Number(n))?Ro(Number(n),0,1):1,[x,y]=f.useState("hex"),[S,b]=f.useState(p),[I,A]=f.useState(!1),N=f.useRef(null),P=f.useRef(null);f.useEffect(()=>{b(p)},[p]),f.useEffect(()=>{A(typeof window<"u"&&typeof window.EyeDropper=="function")},[]);const R=f.useMemo(()=>sQ(p),[p]),v=R.hsv.h,C=`hsl(${v} 100% 50%)`,T=f.useCallback($=>{const ie=nE($,p);b(ie),ie!==p&&t?.(ie)},[p,t]),k=f.useCallback($=>{const ie=N.current?.getBoundingClientRect();if(!ie||ie.width<=0||ie.height<=0)return;const W=Ro(($.clientX-ie.left)/ie.width*100,0,100),Z=Ro((1-($.clientY-ie.top)/ie.height)*100,0,100);T(Qg(M_({h:v,s:W,v:Z})))},[T,v]),z=f.useCallback($=>{const ie=P.current?.getBoundingClientRect();if(!ie||ie.width<=0)return;const W=Ro(($.clientX-ie.left)/ie.width*360,0,360);T(Qg(M_({h:W,s:R.hsv.s,v:R.hsv.v})))},[R.hsv.s,R.hsv.v,T]),Y=$=>{N.current?.setPointerCapture($.pointerId),k($)},K=$=>{P.current?.setPointerCapture($.pointerId),z($)},J=$=>{if(!kk.test(String($||"").trim())){b(p);return}T($)},G=($,ie)=>{T(Qg({...R.rgb,[$]:ie}))},Q=($,ie)=>{T(Qg(iQ({...R.hsl,[$]:ie})))},D=async()=>{if(I)try{const $=await new window.EyeDropper().open();$?.sRGBHex&&T($.sRGBHex)}catch{}};return c.jsxs(JJ,{children:[c.jsx(QJ,{asChild:!0,children:c.jsxs(Qe,{type:"button","data-slot":"color-picker-trigger",variant:"outline",size:"sm",disabled:d,className:H("h-7 w-auto max-w-full justify-start gap-1.5 px-1.5 text-[11px] font-medium",o),...m,children:[c.jsx("span",{className:H("size-4 shrink-0 rounded bg-clip-border shadow-[0_0_0_1px_rgba(15,23,42,0.24)] dark:shadow-[0_0_0_1px_rgba(255,255,255,0.24)]",i),style:{backgroundColor:p,opacity:u?g:void 0},"aria-hidden":"true"}),l?c.jsx("span",{className:H("truncate font-mono uppercase leading-none",s),children:p}):null]})}),c.jsxs(eQ,{align:a,className:"w-64 space-y-3 p-3",children:[c.jsx("div",{ref:N,role:"slider",tabIndex:0,"aria-label":"Saturation and brightness","aria-valuetext":`${Math.round(R.hsv.s)}% saturation, ${Math.round(R.hsv.v)}% brightness`,className:"relative h-32 touch-none overflow-hidden rounded-md border shadow-inner outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50",style:{backgroundColor:C,backgroundImage:"linear-gradient(to top, #000, transparent), linear-gradient(to right, #fff, transparent)"},onPointerDown:Y,onPointerMove:$=>{N.current?.hasPointerCapture($.pointerId)&&k($)},children:c.jsx("span",{className:"absolute size-3 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white shadow-[0_0_0_1px_rgba(0,0,0,0.45)]",style:{left:`${R.hsv.s}%`,top:`${100-R.hsv.v}%`},"aria-hidden":"true"})}),c.jsx("div",{ref:P,role:"slider",tabIndex:0,"aria-label":"Hue","aria-valuemin":0,"aria-valuemax":360,"aria-valuenow":Math.round(v),className:"relative h-3 touch-none rounded-full border outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50",style:{background:"linear-gradient(90deg, #f00, #ff0, #0f0, #0ff, #00f, #f0f, #f00)"},onPointerDown:K,onPointerMove:$=>{P.current?.hasPointerCapture($.pointerId)&&z($)},children:c.jsx("span",{className:"absolute top-1/2 size-4 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white shadow-[0_0_0_1px_rgba(0,0,0,0.45)]",style:{left:`${v/360*100}%`,backgroundColor:C},"aria-hidden":"true"})}),u?c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"flex items-center justify-between gap-2 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:[c.jsx("span",{children:"Opacity"}),c.jsxs("span",{children:[Math.round(g*100),"%"]})]}),c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsx(go,{type:"number",min:0,max:100,step:1,value:Math.round(g*100),onChange:$=>{r?.(Ro($.currentTarget.value,0,100)/100)},className:"h-7 px-1.5 text-[11px]","aria-label":"Color opacity"}),c.jsx("span",{className:"text-[10px] font-medium text-muted-foreground",children:"%"})]})]}):null,c.jsx("div",{className:"flex items-center gap-1 rounded-md bg-muted p-1",children:tQ.map($=>c.jsx(Qe,{type:"button",variant:x===$?"secondary":"ghost",size:"xs",className:"h-6 flex-1 px-2 text-[10px] uppercase",onClick:()=>y($),children:$},$))}),x==="hex"?c.jsxs("div",{className:"flex gap-2",children:[c.jsx(go,{value:S,onChange:$=>b($.currentTarget.value),onBlur:$=>J($.currentTarget.value),onKeyDown:$=>{$.key==="Enter"&&J($.currentTarget.value)},className:"h-7 px-1.5 text-[11px] font-mono uppercase","aria-label":"Hex color"}),I?c.jsx(Qe,{type:"button",variant:"outline",size:"icon-sm",onClick:D,"aria-label":"Pick color from screen",title:"Pick color from screen",children:c.jsx(M3,{className:"h-3.5 w-3.5",strokeWidth:2,"aria-hidden":"true"})}):null]}):null,x==="rgb"?c.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[c.jsx(cd,{label:"R",value:R.rgb.r,min:0,max:255,onChange:$=>G("r",$)}),c.jsx(cd,{label:"G",value:R.rgb.g,min:0,max:255,onChange:$=>G("g",$)}),c.jsx(cd,{label:"B",value:R.rgb.b,min:0,max:255,onChange:$=>G("b",$)})]}):null,x==="hsl"?c.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[c.jsx(cd,{label:"H",value:R.hsl.h,min:0,max:360,onChange:$=>Q("h",$)}),c.jsx(cd,{label:"S",value:R.hsl.s,min:0,max:100,onChange:$=>Q("s",$)}),c.jsx(cd,{label:"L",value:R.hsl.l,min:0,max:100,onChange:$=>Q("l",$)})]}):null]})]})}function aQ({...e}){return c.jsx(QT,{"data-slot":"dialog",...e})}f.forwardRef(function({...t},n){return c.jsx(YT,{ref:n,"data-slot":"dialog-trigger",...t})});function lQ({...e}){return c.jsx(JT,{"data-slot":"dialog-portal",...e})}const cQ=f.forwardRef(function({...t},n){return c.jsx(Dy,{ref:n,"data-slot":"dialog-close",...t})}),uQ=f.forwardRef(function({className:t,...n},r){return c.jsx(qT,{ref:r,"data-slot":"dialog-overlay",className:H("fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",t),...n})}),dQ=f.forwardRef(function({className:t,children:n,showCloseButton:r=!0,...o},i){return c.jsxs(lQ,{children:[c.jsx(uQ,{}),c.jsxs(ZT,{ref:i,"data-slot":"dialog-content",className:H("cad-glass-popover fixed left-[50%] top-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-md border p-6 text-foreground shadow-lg duration-200 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",t),...o,children:[n,r?c.jsxs(Dy,{"data-slot":"dialog-close",className:"absolute right-4 top-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none",children:[c.jsx(eh,{className:"size-4"}),c.jsx("span",{className:"sr-only",children:"Close"})]}):null]})]})});function fQ({className:e,...t}){return c.jsx("div",{"data-slot":"dialog-header",className:H("flex flex-col gap-2 text-center sm:text-left",e),...t})}function mQ({className:e,...t}){return c.jsx("div",{"data-slot":"dialog-footer",className:H("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t})}const pQ=f.forwardRef(function({className:t,...n},r){return c.jsx(eR,{ref:r,"data-slot":"dialog-title",className:H("text-lg font-semibold",t),...n})}),hQ=f.forwardRef(function({className:t,...n},r){return c.jsx(tR,{ref:r,"data-slot":"dialog-description",className:H("text-sm text-muted-foreground",t),...n})});function wa({...e}){return c.jsx(r3,{"data-slot":"select",...e})}function ac({...e}){return c.jsx(o3,{"data-slot":"select-value",...e})}const va=f.forwardRef(function({className:t,size:n="default",showIcon:r=!0,children:o,...i},s){return c.jsxs(t3,{ref:s,"data-slot":"select-trigger","data-size":n,className:H("flex w-full items-center justify-between gap-2 rounded-md border border-input bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 data-[placeholder]:text-muted-foreground data-[size=default]:h-9 data-[size=sm]:h-8 dark:bg-input/30 dark:hover:bg-input/50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...i,children:[o,r?c.jsx(n3,{asChild:!0,children:c.jsx(jy,{className:"size-4 opacity-50"})}):null]})});function Ca({className:e,children:t,position:n="popper",...r}){return c.jsx(i3,{children:c.jsxs(s3,{"data-slot":"select-content",className:H("cad-glass-popover relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-hidden rounded-md border border-border bg-popover text-popover-foreground shadow-md data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,...r,children:[c.jsx(gQ,{}),c.jsx(a3,{className:H("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:t}),c.jsx(bQ,{})]})})}function Ma({className:e,children:t,icon:n=null,...r}){return c.jsxs(l3,{"data-slot":"select-item",className:H("relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-none select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...r,children:[c.jsx("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:c.jsx(c3,{children:c.jsx(mu,{className:"size-4"})})}),n?c.jsx("span",{className:"flex size-3.5 shrink-0 items-center justify-center text-muted-foreground","aria-hidden":"true",children:n}):null,c.jsx(u3,{children:t})]})}function gQ({className:e,...t}){return c.jsx(d3,{"data-slot":"select-scroll-up-button",className:H("flex cursor-default items-center justify-center py-1",e),...t,children:c.jsx(I3,{className:"size-4"})})}function bQ({className:e,...t}){return c.jsx(f3,{"data-slot":"select-scroll-down-button",className:H("flex cursor-default items-center justify-center py-1",e),...t,children:c.jsx(jy,{className:"size-4"})})}function yQ({className:e,...t}){return c.jsx(m3,{"data-slot":"tabs",className:H("flex flex-col gap-2",e),...t})}function xQ({className:e,...t}){return c.jsx(p3,{"data-slot":"tabs-list",className:H("inline-flex h-9 w-fit items-center justify-center rounded-lg bg-muted p-[3px] text-muted-foreground",e),...t})}function SQ({className:e,...t}){return c.jsx(h3,{"data-slot":"tabs-trigger",className:H("inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-xs dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30",e),...t})}function EQ({className:e,...t}){return c.jsx(g3,{"data-slot":"tabs-content",className:H("flex-1 outline-none",e),...t})}const Cy=Object.freeze([Object.freeze({value:Dt.SOLID,label:"Solid",title:"Shaded with CAD edges",Icon:Ly}),Object.freeze({value:Dt.RENDERED,label:"Rendered",title:"Shaded material appearance without edge overlay",Icon:A3}),Object.freeze({value:Dt.TRANSPARENT,label:"X-Ray",title:"Transparent solids with visible CAD edges",Icon:rR}),Object.freeze({value:Dt.HIDDEN_EDGES,label:"Hidden",title:"Shaded with hidden edges visible",Icon:oR}),Object.freeze({value:Dt.HIDDEN_LINES_REMOVED,label:"Lines",title:"Visible lines with hidden lines removed",Icon:N3}),Object.freeze({value:Dt.UNSHADED,label:"Flat",title:"Unshaded flat color",Icon:iR}),Object.freeze({value:Dt.WIREFRAME,label:"Wire",title:"Full wireframe",Icon:_3})]);function Dk(e){return Cy.find(t=>t.value===e)||Cy[0]}function jk({className:e,strokeWidth:t=1.45}){return c.jsxs("svg",{className:e,viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",focusable:"false",children:[c.jsx("path",{d:"M12 3.5 20 8v8l-8 4.5L4 16V8l8-4.5Z",stroke:"currentColor",strokeWidth:t,strokeLinejoin:"round"}),c.jsx("path",{d:"M4 8l8 4.5L20 8M12 12.5v8",stroke:"currentColor",strokeWidth:t,strokeLinecap:"round",strokeLinejoin:"round"})]})}function xv({className:e,strokeWidth:t=1.45}){return c.jsxs("svg",{className:e,viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",focusable:"false",children:[c.jsx("path",{d:"M12 4.6 19.6 6.1l-2 10.1-5.6 4.2-5.6-4.2-2-10.1L12 4.6Z",stroke:"currentColor",strokeWidth:t,strokeLinejoin:"round"}),c.jsx("path",{d:"M4.4 6.1 12 9.2l7.6-3.1M12 9.2v11.2",stroke:"currentColor",strokeWidth:t,strokeLinecap:"round",strokeLinejoin:"round"})]})}const wQ=[{value:"solid",label:"Solid"},{value:"linear",label:"Linear"},{value:"radial",label:"Radial"},{value:"transparent",label:"Transparent"}],vQ=[{value:yo.ORTHOGRAPHIC,label:"Orthographic",title:"Parallel projection for CAD inspection",Icon:jk},{value:yo.PERSPECTIVE,label:"Perspective",title:"Depth projection with vanishing lines",Icon:xv}],CQ=[{value:Ht.SYSTEM,label:"System"},{value:Ht.LIGHT,label:"Light"},{value:Ht.DARK,label:"Dark"}],MQ=[{value:"x",label:"X"},{value:"y",label:"Y"},{value:"z",label:"Z"},{value:"radial",label:"Radial"}],I_=[{value:"directional",label:"Directional"},{value:"spot",label:"Spot"},{value:"point",label:"Point"}],IQ=Nu,ru=uh,Lk=n0,Db=Us,Fk=120,AQ=Object.freeze(["x","y","z"]),NQ=Object.freeze([Object.freeze({id:"feature",label:"Feature",defaultColor:Vs,defaultOpacity:1,defaultThickness:1.15}),Object.freeze({id:"tangent",label:"Tangent",defaultColor:Vs,defaultOpacity:.5,defaultThickness:1.15}),Object.freeze({id:"seam",label:"Seam",defaultColor:Vs,defaultOpacity:.85,defaultThickness:1.15}),Object.freeze({id:"degenerate",label:"Degenerate",defaultColor:Vs,defaultOpacity:1,defaultThickness:0})]);function rE(e,t,n){return Math.min(Math.max(e,t),n)}function no(e,t=2){const n=Number(e);return Number.isFinite(n)?n.toFixed(t):"0"}function sS(e){const t=Number(e);return Number.isFinite(t)?Math.abs(t)>=100?t.toFixed(0):Math.abs(t)>=10?t.toFixed(1):t.toFixed(2):"0"}function lc({label:e,value:t,trailing:n,children:r,className:o,contentClassName:i}){return c.jsx(cn,{label:e,value:t,trailing:n,className:o,contentClassName:i,children:r})}function zk({title:e,value:t,children:n,...r}){return c.jsx(ci,{value:t,title:e,...r,children:n})}function ya({title:e,trailing:t=null,children:n,className:r,hideFirstSeparator:o=!0}){return c.jsx(bo,{title:e,trailing:t,className:r,hideFirstSeparator:o,children:n})}function aS({title:e,children:t,className:n,contentClassName:r}){return c.jsx(WY,{title:e,className:n,contentClassName:r,children:t})}function _Q(e){try{const t=f.Children.only(e);return f.isValidElement(t)&&t.type===ro?t.props:null}catch{return null}}function ho({label:e,value:t,children:n,onValueCommit:r,valueInputProps:o}){const i=_Q(n),s=r||(i?.onChange?a=>{i.onChange(ui(a,{fallback:i.value,min:i.min,max:i.max}))}:null);return c.jsx(Ni,{label:e,value:t,onValueCommit:s,valueInputProps:s?{ariaLabel:`${e} value`,...o}:o,children:n})}function ud({label:e,checked:t,onChange:n,disabled:r=!1,description:o}){return c.jsx(Mi,{label:e,checked:t,onCheckedChange:n,disabled:r,description:o})}function ro({value:e,min:t,max:n,step:r=.01,onChange:o}){const i=Number.isFinite(Number(e))?Number(e):t,[s,a]=f.useState(i),l=f.useRef(null);f.useEffect(()=>{a(i)},[i]),f.useEffect(()=>()=>{l.current&&clearTimeout(l.current)},[]);const u=p=>{const g=Number(p);return Number.isFinite(g)?rE(g,t,n):i},d=p=>{const g=u(p);l.current&&clearTimeout(l.current),Math.abs(g-i)>1e-9&&o(g)},m=p=>{const g=u(p);a(g),l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{d(g)},Fk)};return c.jsx(_i,{value:[s],min:t,max:n,step:r,onValueChange:p=>m(p[0]??s),onValueCommit:p=>d(p[0]??s),className:Db})}function TQ({value:e,min:t=0,max:n=6,digits:r=2,disabled:o=!1,ariaLabel:i,onChange:s}){const a=Number.isFinite(Number(e))?Number(e):t,l=no(a,r),u=d=>{const m=ui(d,{fallback:a,min:t,max:n});Math.abs(m-a)>1e-9&&s?.(m)};return c.jsx(Zw,{value:l,onValueCommit:u,disabled:o,ariaLabel:i,inputMode:"decimal",className:"h-full w-16 shrink-0 rounded-none border-0 bg-transparent px-1.5 py-0 text-right !text-[11px] font-medium tabular-nums shadow-none focus-visible:ring-0 dark:bg-transparent"})}function Bk({label:e,color:t,opacity:n,thickness:r,min:o=0,max:i=6,digits:s=2,disabled:a=!1,onColorChange:l,onOpacityChange:u,onThicknessChange:d}){return c.jsxs("div",{className:H("inline-flex h-7 shrink-0 items-center overflow-hidden rounded-md border border-input bg-transparent shadow-xs dark:bg-input/30",a&&"opacity-50"),children:[c.jsx(Sv,{value:t,opacity:n,showOpacity:!0,showValue:!1,disabled:a,onChange:l,onOpacityChange:u,className:"h-7 w-7 rounded-none border-0 border-r border-input bg-transparent px-1.5 shadow-none",swatchClassName:"size-3.5",title:`${e} edge color`,"aria-label":`${e} edge color`}),c.jsx(TQ,{value:r,min:o,max:i,digits:s,disabled:a,ariaLabel:`${e} edge thickness`,onChange:d}),c.jsx("span",{className:"pr-1.5 text-[10px] font-medium text-muted-foreground",children:"px"})]})}function RQ({label:e,color:t,thickness:n,opacity:r,onColorChange:o,onThicknessChange:i,onOpacityChange:s}){return c.jsx(cn,{label:e,trailing:c.jsx(Bk,{label:e,color:t,opacity:r,thickness:n,onColorChange:o,onOpacityChange:s,onThicknessChange:i}),contentClassName:"hidden"})}function Sv({value:e,onChange:t,className:n,swatchClassName:r,valueClassName:o,showValue:i=!0,disabled:s=!1,...a}){return c.jsx(yv,{value:e,onChange:t,className:H(Lk,"w-fit justify-start gap-1.5 px-1.5",n),swatchClassName:H("size-3.5",r),valueClassName:o,popoverAlign:"end",showValue:i,disabled:s,...a})}function A_({label:e,value:t,onChange:n,className:r,labelClassName:o}){return c.jsx(cn,{label:e,trailing:c.jsx(Sv,{value:t,onChange:n}),className:r,labelClassName:o})}function N_(e,t){return t.reduce((n,r)=>n&&typeof n=="object"?n[r]:void 0,e)}function lS(e,t,n){let r=e;for(let o=0;or(t,a,s)}):c.jsx(A_,{label:e,value:__(n,t,s),onChange:a=>r(t,a)})}function T_(e={}){return(Array.isArray(e.fillColors)&&e.fillColors.length?e.fillColors:[e.defaultColor||"#ffffff"]).slice(0,Tp)}function xc(e){return JSON.stringify(fr(e))}function kQ({colors:e,onChange:t,cycleColors:n=!1}){const r=e.length?e:["#ffffff"],o=i=>{const s=i.filter(Boolean).slice(0,Tp);t(s.length?s:[r[0]||"#ffffff"])};return c.jsxs("div",{className:"flex flex-wrap justify-start gap-1.5","data-cad-fill-color-grid":"true",children:[r.map((i,s)=>c.jsxs("div",{className:H("group relative transition-opacity",!n&&s>0&&"opacity-45 grayscale"),children:[c.jsx(Sv,{value:i,swatchClassName:"size-3.5",onChange:a=>{const l=[...r];l[s]=a,o(l)},"aria-label":`Fill color ${s+1}`,title:`Fill color ${s+1}: ${i}`}),r.length>1?c.jsx(Qe,{type:"button",variant:"outline",size:"icon-xs",className:"absolute -right-1.5 -top-1.5 z-10 size-4 rounded-full border-border !bg-[rgb(245_247_250)] p-0 text-muted-foreground shadow-xs hover:!bg-[rgb(245_247_250)] hover:text-foreground dark:!bg-[rgb(12_15_22)] dark:hover:!bg-[rgb(12_15_22)]",onClick:()=>o(r.filter((a,l)=>l!==s)),"aria-label":`Remove color ${s+1}`,title:`Remove color ${s+1}`,children:c.jsx(eh,{className:"h-2.5 w-2.5",strokeWidth:2.25,"aria-hidden":"true"})}):null]},s)),r.lengtho([...r,r[r.length-1]||"#ffffff"]),"aria-label":"Add fill color",title:"Add fill color",children:c.jsx(OE,{className:"h-3.5 w-3.5",strokeWidth:2,"aria-hidden":"true"})}):null]})}function My({value:e,onChange:t,options:n}){const o=`repeat(${Math.max(1,Math.min(n.length,n.length>4?3:4))}, minmax(0, 1fr))`;return c.jsx(Kw,{type:"single",variant:"outline",size:"sm",value:e,onValueChange:i=>{i&&t(i)},className:"grid min-h-7 w-full min-w-0 auto-rows-[1.75rem]",style:{gridTemplateColumns:o},children:n.map(i=>{const s=i.Icon,a=i.disabled===!0;return c.jsxs(Vp,{value:i.value,disabled:a,className:H("min-w-0 gap-1.5 !h-7 px-1.5 text-[11px]",D1),title:i.title||i.label,"aria-label":i.label,children:[s?c.jsx(s,{className:"size-3",strokeWidth:2,"aria-hidden":"true"}):null,c.jsx("span",{className:"truncate",children:i.label})]},i.value)})})}function oE({preset:e=null}){return e?c.jsx("span",{className:"relative h-4 w-8 shrink-0 overflow-hidden rounded-md border shadow-[inset_0_0_0_1px_rgba(255,255,255,0.12)]",style:{background:e.preview.background},"aria-hidden":"true",children:c.jsx("span",{className:"absolute inset-y-0 right-0 w-3",style:{backgroundColor:e.preview.accentColor,opacity:.9}})}):c.jsx("span",{className:"h-4 w-8 shrink-0 rounded-md border border-dashed bg-muted","aria-hidden":"true"})}function DQ(){const[e,t]=f.useState(()=>typeof window>"u"||typeof window.matchMedia!="function"?Hd:NI({prefersDark:window.matchMedia("(prefers-color-scheme: dark)").matches===!0}));return f.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const n=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>{t(NI({prefersDark:n.matches===!0}))};return r(),n.addEventListener?.("change",r),()=>{n.removeEventListener?.("change",r)}},[]),e}function jQ(e,t){const n=e.findIndex(r=>r.id===t);return n<=0?e:[e[n],...e.slice(0,n),...e.slice(n+1)]}function Ev(e,t,n){const r=e.find(i=>i.id===t)||null;if(r)return r;const o=xc(n);return e.find(i=>xc(i.settings)===o)||null}function $k(e,t){return!e||xc(e.settings)!==xc(t)}function wv(e){return String(e?.id||"").startsWith("custom:")}function LQ(e){const t=ol(e?.presetId||e?.id);return!!(wv(e)&&t&&xc(e.settings)!==xc(N2(t)))}function FQ(e){return wv(e)}function R_(e){return wv(e)}function zQ(e=[]){if(!Array.isArray(e)||!e.length)return!1;if(e.length!==ic.length)return!0;for(let t=0;t{r?.(S)},p=S=>{l(S),m(S)},g=S=>{S.stopPropagation()},x=(S,b)=>{S.preventDefault(),S.stopPropagation(),m(!1),b?.()},y=S=>{!a&&!S.currentTarget.contains(S.relatedTarget)&&m(!1)};return c.jsxs(TO,{open:a,onOpenChange:p,children:[c.jsx(RO,{showChevron:!1,"data-theme-menu-action":"","aria-label":d,title:d,className:H("theme-preset-overflow-trigger flex size-7 shrink-0 items-center justify-center rounded-md p-0","text-muted-foreground transition-colors hover:bg-accent hover:text-accent-foreground","focus:bg-accent focus:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),onPointerEnter:()=>m(!0),onPointerLeave:()=>{a||m(!1)},onFocus:()=>m(!0),onBlur:y,onMouseDown:g,onPointerDown:g,onKeyDown:g,children:c.jsx(R3,{className:"h-4 w-4",strokeWidth:2,"aria-hidden":"true"})}),c.jsxs(PO,{sideOffset:6,className:"w-40",children:[c.jsxs(Yo,{className:"gap-2 text-xs",onSelect:S=>x(S,i),children:[c.jsx(P3,{className:"h-3.5 w-3.5",strokeWidth:2,"aria-hidden":"true"}),c.jsx("span",{children:"Edit"})]}),n?c.jsxs(Yo,{className:"gap-2 text-xs",onSelect:S=>x(S,s),children:[c.jsx(ws,{className:"h-3.5 w-3.5",strokeWidth:2,"aria-hidden":"true"}),c.jsx("span",{children:"Reset to preset"})]}):null,c.jsx(nu,{}),c.jsxs(Yo,{variant:"destructive",disabled:!t,className:"gap-2 text-xs",onSelect:S=>x(S,t?o:null),children:[c.jsx(sR,{className:"h-3.5 w-3.5",strokeWidth:2,"aria-hidden":"true"}),c.jsx("span",{children:"Delete"})]})]})]})}function cS({open:e,onOpenChange:t,title:n,description:r,actionLabel:o,onConfirm:i}){return c.jsx(Ak,{open:e,onOpenChange:t,children:c.jsxs(Nk,{className:"sm:max-w-sm",children:[c.jsxs(_k,{children:[c.jsx(Rk,{children:n}),c.jsx(Pk,{children:r})]}),c.jsxs(Tk,{children:[c.jsx(Ok,{children:"Cancel"}),c.jsx(ZJ,{className:"bg-destructive text-white hover:bg-destructive/90",onClick:i,children:o})]})]})})}function VQ({defaultName:e,onOpenChange:t,onSave:n,open:r}){const o=f.useId(),[i,s]=f.useState(e),a=i.trim();f.useEffect(()=>{r&&s(e)},[e,r]);const l=u=>{if(u.preventDefault(),!a||typeof n!="function")return;n(a)&&t?.(!1)};return c.jsx(aQ,{open:r,onOpenChange:t,children:c.jsx(dQ,{className:"p-5 sm:max-w-sm",children:c.jsxs("form",{className:"grid gap-4",onSubmit:l,children:[c.jsxs(fQ,{className:"gap-1.5",children:[c.jsx(pQ,{className:"text-base",children:"Save Theme"}),c.jsx(hQ,{className:"sr-only",children:"Enter a name for this theme."})]}),c.jsxs("div",{className:"grid gap-1.5",children:[c.jsx("label",{className:IQ,htmlFor:o,children:"Theme name"}),c.jsx(go,{id:o,value:i,autoFocus:!0,onChange:u=>s(u.target.value)})]}),c.jsxs(mQ,{children:[c.jsx(cQ,{asChild:!0,children:c.jsx(Qe,{type:"button",variant:"outline",size:"sm",children:"Cancel"})}),c.jsx(Qe,{type:"submit",size:"sm",disabled:!a,children:"Save theme"})]})]})})})}function $Q({themePresets:e=[],themeSettings:t,themePresetId:n="",updateThemeSettings:r,handleDeleteCustomThemePreset:o,handleEditThemePreset:i,handleResetThemePresetToDefault:s,handleRestoreDefaultThemePresets:a,triggerClassName:l,iconClassName:u}){const[d,m]=f.useState(!1),[p,g]=f.useState(""),[x,y]=f.useState(""),[S,b]=f.useState(!1),[I,A]=f.useState(""),N=DQ(),P=f.useMemo(()=>jQ(e,N),[e,N]),R=f.useMemo(()=>Ev(e,n,t),[e,n,t]),v=R?.id||"",C=R?.label||"Theme",T=e.find(Z=>Z.id===p)||null,k=e.find(Z=>Z.id===x)||null,z=f.useMemo(()=>zQ(e),[e]),Y=Z=>{m(Z),Z||A("")},K=Z=>{A(Ee=>Ee===Z?"":Ee)},J=Z=>{const Ee=e.find(re=>re.id===Z);Ee&&r?.(Ee.settings,{persistGlobal:!0,presetId:Ee.id})},G=Z=>{const Ee=e.find(re=>re.id===Z);R_(Ee)&&typeof o=="function"&&(g(Z),m(!1))},Q=()=>{T&&typeof o=="function"&&o(T.id),g("")},D=Z=>{typeof i=="function"&&i(Z)||J(Z),m(!1)},$=Z=>{y(Z),m(!1)},ie=()=>{k&&typeof s=="function"&&s(k.id),y("")},W=()=>{typeof a=="function"&&a(),b(!1)};return c.jsxs(c.Fragment,{children:[c.jsxs(hf,{open:d,onOpenChange:Y,children:[c.jsx(gf,{asChild:!0,children:c.jsxs(Qe,{type:"button",variant:"ghost",size:"icon-sm","aria-label":`Theme: ${C}`,title:`Theme: ${C}`,className:l,children:[c.jsx(iR,{className:u,strokeWidth:2,"aria-hidden":"true"}),c.jsx("span",{className:"sr-only",children:"Theme"})]})}),c.jsxs(bf,{align:"end",sideOffset:6,className:"w-64",children:[c.jsx(T1,{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"Theme"}),P.map(Z=>{const Ee=Z.id===v,re=LQ(Z),be=R_(Z),_e=I===Z.id;return c.jsxs("div",{"data-active":Ee?"true":void 0,"data-action-hover":_e?"true":void 0,"aria-current":Ee?"true":void 0,className:H("theme-preset-menu-item flex min-w-0 items-center gap-1 rounded-sm text-xs"),children:[c.jsxs(Yo,{className:H("theme-preset-menu-row min-w-0 flex-1 gap-2 px-2 py-1.5 text-xs",Ee&&"font-semibold"),"data-theme-menu-row-surface":"",onSelect:()=>J(Z.id),children:[c.jsx(oE,{preset:Z}),c.jsx("span",{className:"min-w-0 flex-1 truncate",children:Z.label}),Z.id===N?c.jsx("span",{className:"rounded-full border px-1.5 py-0.5 text-[9px] uppercase text-muted-foreground","data-theme-menu-default-badge":"",children:"Default"}):null]}),c.jsx("span",{className:"theme-preset-menu-actions ml-auto flex shrink-0 items-center gap-0.5 rounded-sm px-0.5 py-0.5",children:c.jsx(BQ,{preset:Z,canDeleteTheme:be,canResetToDefault:re,onActionActiveChange:Ie=>{Ie?A(Z.id):K(Z.id)},onEdit:()=>D(Z.id),onReset:()=>$(Z.id),onDelete:()=>G(Z.id)})})]},Z.id)}),z?c.jsxs(c.Fragment,{children:[c.jsx(nu,{}),c.jsxs(Yo,{className:"text-xs",onSelect:Z=>{Z.preventDefault(),b(!0),m(!1)},children:[c.jsx(ws,{className:"h-3.5 w-3.5",strokeWidth:2,"aria-hidden":"true"}),c.jsx("span",{children:"Restore defaults"})]})]}):null]})]}),c.jsx(cS,{open:!!T,onOpenChange:Z=>{Z||g("")},title:"Delete Theme",description:`Delete ${T?.label||"this theme"}? This removes it from your theme list.`,actionLabel:"Delete theme",onConfirm:Q}),c.jsx(cS,{open:!!k,onOpenChange:Z=>{Z||y("")},title:"Reset Theme",description:`Reset ${k?.label||"this theme"} to its built-in preset settings?`,actionLabel:"Reset theme",onConfirm:ie}),c.jsx(cS,{open:S,onOpenChange:b,title:"Restore Defaults",description:"This clears saved theme changes, removes saved themes, and restores deleted presets.",actionLabel:"Restore defaults",onConfirm:W})]})}function GQ({themePresets:e=[],themeSettings:t,themePresetId:n="",updateThemeSettings:r,handleResetThemeSettings:o,handleSaveCustomThemePreset:i,handleUpdateThemePresetSettings:s}){const[a,l]=f.useState(!1),u=f.useMemo(()=>Ev(e,n,t),[e,n,t]),d=u?.id||"",m=FQ(u),p=$k(u,t),g=u?.label?`${u.label} copy`:"Theme copy",x=t.colorMode||Ht.SYSTEM,y=A=>{const N=e.find(P=>P.id===A);N&&r?.(N.settings,{persistGlobal:!0,presetId:N.id})},S=A=>!p||typeof i!="function"?null:i(A),b=()=>{!p||!d||!m||typeof s!="function"||s(d)},I=A=>{r?.(N=>({...fr(N),colorMode:A}))};return c.jsxs(c.Fragment,{children:[c.jsxs(ya,{title:"Theme",children:[c.jsx(lc,{label:"Current",value:p?"Changed":"Saved",children:c.jsxs(wa,{value:d,onValueChange:y,children:[c.jsx(va,{size:"sm",className:H(Lk,"w-full justify-between"),"aria-label":"Theme",children:c.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(oE,{preset:u}),c.jsx("span",{className:"min-w-0 truncate",children:u?.label||"Theme"})]})}),c.jsx(Ca,{children:e.map(A=>c.jsxs(Ma,{value:A.id,className:"text-xs",children:[c.jsx(oE,{preset:A}),c.jsx("span",{className:"min-w-0 truncate",children:A.label})]},A.id))})]})}),c.jsx(lc,{label:"Color mode",children:c.jsx(My,{value:x,options:CQ,onChange:I})}),c.jsx(cn,{children:c.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[c.jsxs(Qe,{type:"button",variant:"outline",size:"sm",className:H(ru,"relative",p?"pr-5":null),disabled:!p||typeof i!="function",onClick:()=>l(!0),children:[c.jsx("span",{children:"Save as"}),p?c.jsx(Gk,{className:"absolute right-1.5 top-1.5 h-1.5 w-1.5"}):null]}),c.jsx(Qe,{type:"button",variant:"outline",size:"sm",className:ru,disabled:!p||!d||!m||typeof s!="function",onClick:b,children:c.jsx("span",{children:"Update"})}),c.jsxs(Qe,{type:"button",variant:"outline",size:"sm",className:ru,disabled:!p||!d||typeof o!="function",onClick:()=>o?.(),children:[c.jsx(ws,{className:"h-3 w-3",strokeWidth:2,"aria-hidden":"true"}),c.jsx("span",{children:"Restore to default"})]})]})})]}),c.jsx(VQ,{defaultName:g,onOpenChange:l,onSave:S,open:a})]})}function UQ({value:e,onChange:t}){const n=Number.isFinite(Number(e?.x))?Number(e.x):0,r=Number.isFinite(Number(e?.z))?Number(e.z):0,[o,i]=f.useState({x:n,z:r}),s=f.useRef(o),a=f.useRef(null),l=o.x,u=o.z;f.useEffect(()=>{const S={x:n,z:r};s.current=S,i(S)},[n,r]),f.useEffect(()=>()=>{a.current&&clearTimeout(a.current)},[]);const d=f.useMemo(()=>{const S=Math.max(Math.abs(l),Math.abs(u),220);return Math.min(5e3,Math.ceil(S*1.2/20)*20)},[l,u]),m=(l+d)/(d*2)*100,p=(d-u)/(d*2)*100,g=(S,b)=>{a.current&&clearTimeout(a.current),S!==n&&t("x",S),b!==r&&t("z",b)},x=(S,b)=>{const I={x:S,z:b};s.current=I,i(I),a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{g(S,b)},Fk)},y=S=>{const b=S.currentTarget.getBoundingClientRect();if(b.width<=0||b.height<=0)return;const I=rE((S.clientX-b.left)/b.width,0,1),A=rE((S.clientY-b.top)/b.height,0,1),N=Math.round((I*2-1)*d),P=Math.round((1-A*2)*d);x(N,P)};return c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"relative h-28 w-full touch-none overflow-hidden rounded-md border bg-background",onPointerDown:S=>{S.currentTarget.setPointerCapture(S.pointerId),y(S)},onPointerMove:S=>{S.currentTarget.hasPointerCapture(S.pointerId)&&y(S)},onPointerUp:S=>{S.currentTarget.hasPointerCapture(S.pointerId)&&S.currentTarget.releasePointerCapture(S.pointerId),g(s.current.x,s.current.z)},children:[c.jsx("div",{className:"absolute inset-0 opacity-45",style:{backgroundImage:"radial-gradient(circle, rgba(154, 169, 188, 0.65) 1.5px, transparent 1.5px)",backgroundSize:"22px 22px"},"aria-hidden":"true"}),c.jsx("div",{className:"absolute inset-x-0 top-1/2 h-px bg-border","aria-hidden":"true"}),c.jsx("div",{className:"absolute inset-y-0 left-1/2 w-px bg-border","aria-hidden":"true"}),c.jsx("div",{className:"absolute size-4 -translate-x-1/2 -translate-y-1/2 rounded-full border border-primary bg-foreground shadow-xs",style:{left:`${m}%`,top:`${p}%`},"aria-hidden":"true"})]}),c.jsxs("div",{className:"flex items-center justify-between text-[10px] text-muted-foreground",children:[c.jsxs("span",{children:["X ",Math.round(l)]}),c.jsxs("span",{children:["Z ",Math.round(u)]}),c.jsxs("span",{children:["range +/-",d]})]})]})}function WQ({displaySettings:e,updateDisplaySettings:t,clipBounds:n=null,showClip:r=!1}){const o=f.useMemo(()=>So(e),[e]),i=f.useMemo(()=>Ws(o.clip),[o.clip]),s=f.useMemo(()=>Wb(o.exploded),[o.exploded]),a=f.useMemo(()=>Ql(o.edges),[o.edges]),l=b=>{t?.(I=>({...So(I),...b}))},u=b=>{t?.(I=>{const A=So(I);return{...A,clip:nV(A.clip,b)}})},d=b=>{t?.(I=>{const A=So(I);return{...A,exploded:Wb({...A.exploded,...b})}})},m=b=>{t?.(I=>{const A=So(I);return{...A,edges:Ql({...A.edges,...b})}})},p=(b,I)=>{t?.(A=>{const N=So(A);return{...N,edges:Ql({...N.edges,classes:{...N.edges?.classes||{},[b]:{...N.edges?.classes?.[b]||{},...I}}})}})},g=()=>{l({edges:Ql()})},y=Dk(o.mode)?.Icon||null,S=(b,I)=>{const A=Number(I),N=Number.isFinite(A)?A:0;u({axis:b,offset:N,offsets:{[b]:N},enabled:N>0})};return c.jsxs(zk,{title:"Display",value:"display",children:[c.jsxs(ya,{title:"Mode",children:[c.jsx(lc,{label:"Projection",children:c.jsx(My,{value:o.projection,onChange:b=>l({projection:b}),options:vQ})}),c.jsx(lc,{label:"Style",children:c.jsxs(wa,{value:o.mode,onValueChange:b=>l({mode:b}),children:[c.jsx(va,{size:"sm",className:"h-7 !text-[11px]","aria-label":"Display mode",children:c.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 overflow-hidden",children:[y?c.jsx(y,{className:"size-3.5 shrink-0 text-muted-foreground",strokeWidth:2,"aria-hidden":"true"}):null,c.jsx(ac,{})]})}),c.jsx(Ca,{children:Cy.map(b=>{const I=b.Icon;return c.jsx(Ma,{value:b.value,className:"text-xs",title:b.title,icon:I?c.jsx(I,{className:"size-3.5",strokeWidth:2}):null,children:b.label},b.value)})})]})})]}),c.jsxs(ya,{title:"Edges",children:[NQ.map(b=>{const I=a.classes?.[b.id]||{},A=I.color||b.defaultColor,N=I.thickness??b.defaultThickness,P=I.opacity??b.defaultOpacity;return c.jsx(RQ,{label:b.label,color:A,thickness:N,opacity:P,onColorChange:R=>p(b.id,{color:R}),onThicknessChange:R=>p(b.id,{thickness:R}),onOpacityChange:R=>p(b.id,{opacity:R})},b.id)}),c.jsx(cn,{label:"Highlight",trailing:c.jsx(Bk,{label:"Highlight",color:a.highlightColor||aw,opacity:a.highlightOpacity??1,thickness:a.highlightThickness??3,min:.5,max:6,digits:1,onColorChange:b=>m({highlightColor:b}),onOpacityChange:b=>m({highlightOpacity:b}),onThicknessChange:b=>m({highlightThickness:b})}),contentClassName:"hidden"}),c.jsx(cn,{children:c.jsxs(Qe,{type:"button",variant:"outline",size:"sm",className:ru,onClick:g,title:"Reset edge display",children:[c.jsx(ws,{className:"h-3 w-3",strokeWidth:2,"aria-hidden":"true"}),c.jsx("span",{children:"Reset"})]})})]}),c.jsxs(ya,{title:"Exploded View",children:[c.jsx(Mi,{label:"Enabled",checked:s.enabled,onCheckedChange:b=>d({enabled:b})}),s.enabled?c.jsxs(c.Fragment,{children:[c.jsx(lc,{label:"Axis",children:c.jsx(My,{value:s.axis,options:MQ,onChange:b=>d({axis:b})})}),c.jsx(Ni,{label:"Spacing",value:`${s.spacing.toFixed(2)}x`,onValueCommit:b=>{d({spacing:ui(b,{fallback:s.spacing,min:.25,max:4})})},children:c.jsx(_i,{className:Db,value:[s.spacing],min:.25,max:4,step:.05,onValueChange:b=>{d({spacing:Array.isArray(b)?b[0]:b})},"aria-label":"Exploded spacing"})}),c.jsx(Ni,{label:"Depth",value:`${s.depth}`,onValueCommit:b=>{d({depth:ui(b,{fallback:s.depth,min:1,max:8,integer:!0})})},children:c.jsx(_i,{className:Db,value:[s.depth],min:1,max:8,step:1,onValueChange:b=>{d({depth:Array.isArray(b)?b[0]:b})},"aria-label":"Exploded depth"})}),c.jsx(Mi,{label:"Merge levels",checked:s.mergeCoplanar,onCheckedChange:b=>d({mergeCoplanar:b})}),c.jsx(Mi,{label:"Ground base",checked:s.keepBaseGrounded,onCheckedChange:b=>d({keepBaseGrounded:b})}),c.jsx(cn,{children:c.jsxs(Qe,{type:"button",variant:"outline",size:"sm",className:ru,onClick:()=>d(ba),title:"Reset exploded view",children:[c.jsx(ws,{className:"h-3 w-3",strokeWidth:2,"aria-hidden":"true"}),c.jsx("span",{children:"Reset"})]})})]}):null]}),r?c.jsxs(ya,{title:"Clip",hideFirstSeparator:!1,children:[AQ.map(b=>{const I=i.offsets?.[b]??_p.offsets[b],A={...i,axis:b,offset:I,offsets:{...i.offsets,[b]:I}},N=qR(n,b),P=Math.max(N.max-N.min,0),R=eV(n,A);return c.jsxs(Ni,{label:b,value:`${sS(R)} mm`,onValueCommit:v=>{const C=ui(v,{fallback:R,min:N.min,max:N.max});S(b,P>0?(C-N.min)/P:I)},valueInputProps:{disabled:!P,ariaLabel:`Clip ${b.toUpperCase()} position`},children:[c.jsx(_i,{className:Db,value:[I],min:0,max:1,step:.001,disabled:!P,onValueChange:v=>{const C=Array.isArray(v)?v[0]:v;S(b,C)},"aria-label":`Clip ${b.toUpperCase()} axis`}),c.jsxs("div",{className:"mt-1 flex justify-between text-[10px] text-[var(--ui-text-muted)]",children:[c.jsx("span",{children:sS(N.min)}),c.jsx("span",{children:sS(N.max)})]})]},b)}),c.jsx(cn,{children:c.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[c.jsxs(Qe,{type:"button",variant:"outline",size:"sm",className:ru,onClick:()=>u({invert:!i.invert}),"aria-pressed":i.invert,title:"Flip clip side",children:[c.jsx(T3,{className:"h-3 w-3",strokeWidth:2,"aria-hidden":"true"}),c.jsx("span",{children:"Flip"})]}),c.jsxs(Qe,{type:"button",variant:"outline",size:"sm",className:ru,onClick:()=>l({clip:Ws(_p)}),title:"Reset clip plane",children:[c.jsx(ws,{className:"h-3 w-3",strokeWidth:2,"aria-hidden":"true"}),c.jsx("span",{children:"Reset"})]})]})})]}):null]})}function HQ({themePresets:e=[],themeSettings:t,themePresetId:n="",resolvedColorSchemeMode:r=Ht.LIGHT,updateThemeSettings:o,handleResetThemeSettings:i,handleSaveCustomThemePreset:s,handleUpdateThemePresetSettings:a}){const[l,u]=f.useState("directional"),d=f.useMemo(()=>Ev(e,n,t),[e,n,t]),m=$k(d,t),p=c.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[c.jsx("span",{children:"Appearance"}),m?c.jsx(Gk,{className:"h-1.5 w-1.5"}):null]}),g=v=>{o(C=>({...C,materials:{...C.materials,...v}}))},x=v=>{o(C=>({...C,background:{...C.background,...v}}))},y=v=>{o(C=>({...C,floor:{...C.floor,...v}}))},S=v=>{o(C=>{const T=C.floor||{};return{...C,floor:{...T,grid:{...T.grid||{},...v}}}})},b=v=>{o(C=>({...C,environment:{...C.environment,...v}}))},I=v=>{o(C=>({...C,lighting:{...C.lighting,...v}}))},N={themeSettings:t,resolvedColorSchemeMode:r,onChange:(v,C,T="")=>{o(k=>{const z=fr(k),Y=PQ(z.modeColors),K={...z,modeColors:Y};if(T===Ht.LIGHT||T===Ht.DARK)return lS(Y[T],v,C),K;const J=Vk(z,r);return lS(K,v,C),lS(Y[J],v,C),K})}},P=(v,C)=>{o(T=>({...T,lighting:{...T.lighting,[v]:{...T.lighting[v],...C}}}))},R=(v,C,T)=>{o(k=>({...k,lighting:{...k.lighting,[v]:{...k.lighting[v],position:{...k.lighting[v].position,[C]:T}}}}))};return c.jsxs(zk,{title:p,value:"appearance","data-cad-theme-appearance-section":"true",children:[c.jsx(GQ,{themePresets:e,themeSettings:t,themePresetId:n,updateThemeSettings:o,handleResetThemeSettings:i,handleSaveCustomThemePreset:s,handleUpdateThemePresetSettings:a}),c.jsxs(ya,{title:"Surface",children:[c.jsx(lc,{label:"Colors",value:`${T_(t.materials).length}/${Tp}`,children:c.jsx(kQ,{colors:T_(t.materials),cycleColors:t.materials.cycleColors===!0,onChange:v=>g({defaultColor:v[0],fillColors:v})})}),c.jsx(ud,{label:"Cycle colors",checked:t.materials.cycleColors===!0,onChange:v=>g({cycleColors:v})}),c.jsx(ud,{label:"Override colors",checked:t.materials.overrideSourceColors===!0,onChange:v=>g({overrideSourceColors:v})}),c.jsx(ho,{label:"Saturation",value:no(t.materials.saturation),children:c.jsx(ro,{value:t.materials.saturation,min:0,max:2.5,step:.01,onChange:v=>g({saturation:v})})}),c.jsx(ho,{label:"Contrast",value:no(t.materials.contrast),children:c.jsx(ro,{value:t.materials.contrast,min:0,max:2.5,step:.01,onChange:v=>g({contrast:v})})}),c.jsx(ho,{label:"Brightness",value:no(t.materials.brightness),children:c.jsx(ro,{value:t.materials.brightness,min:0,max:2,step:.01,onChange:v=>g({brightness:v})})})]}),c.jsxs(ya,{title:"Backdrop",children:[c.jsx(lc,{label:"Style",children:c.jsx(My,{value:t.background.type,onChange:v=>x({type:v}),options:wQ})}),t.background.type==="solid"?c.jsx(Vi,{label:"Color",path:["background","solidColor"],...N}):null,t.background.type==="linear"?c.jsxs(c.Fragment,{children:[c.jsx(Vi,{label:"Start color",path:["background","linearStart"],...N}),c.jsx(Vi,{label:"End color",path:["background","linearEnd"],...N}),c.jsx(ho,{label:"Angle",value:`${no(t.background.linearAngle,0)} deg`,children:c.jsx(ro,{value:t.background.linearAngle,min:-360,max:360,step:1,onChange:v=>x({linearAngle:v})})})]}):null,t.background.type==="radial"?c.jsxs(c.Fragment,{children:[c.jsx(Vi,{label:"Inner color",path:["background","radialInner"],...N}),c.jsx(Vi,{label:"Outer color",path:["background","radialOuter"],...N})]}):null]}),c.jsx(ya,{title:"Floor",trailing:c.jsx(j1,{checked:t.floor?.enabled===!0,onCheckedChange:v=>y({enabled:v}),ariaLabel:"Enable floor"}),children:t.floor?.enabled===!0?c.jsxs(c.Fragment,{children:[c.jsx(Vi,{label:"Color",path:["floor","color"],...N}),c.jsx(ho,{label:"Roughness",value:no(t.floor?.roughness??.72),children:c.jsx(ro,{value:t.floor?.roughness??.72,min:0,max:1,step:.01,onChange:v=>y({roughness:v})})}),c.jsx(ho,{label:"Reflectivity",value:no(t.floor?.reflectivity??.12),children:c.jsx(ro,{value:t.floor?.reflectivity??.12,min:0,max:1,step:.01,onChange:v=>y({reflectivity:v})})}),c.jsx(ho,{label:"Shadow",value:no(t.floor?.shadowOpacity??.45),children:c.jsx(ro,{value:t.floor?.shadowOpacity??.45,min:0,max:1,step:.01,onChange:v=>y({shadowOpacity:v})})}),c.jsx(ho,{label:"Backdrop blend",value:no(t.floor?.horizonBlend??0),children:c.jsx(ro,{value:t.floor?.horizonBlend??0,min:0,max:1,step:.01,onChange:v=>y({horizonBlend:v})})})]}):null}),c.jsx(ya,{title:"Grid",trailing:c.jsx(j1,{checked:t.floor?.grid?.enabled===!0,onCheckedChange:v=>S({enabled:v}),ariaLabel:"Enable grid"}),children:t.floor?.grid?.enabled===!0?c.jsxs(c.Fragment,{children:[c.jsx(Vi,{label:"Floor color",path:["floor","color"],...N}),c.jsx(Vi,{label:"Center line",path:["floor","grid","centerColor"],...N}),c.jsx(Vi,{label:"Cell line",path:["floor","grid","cellColor"],...N}),c.jsx(ho,{label:"Line opacity",value:no(t.floor?.grid?.opacity??.18),children:c.jsx(ro,{value:t.floor?.grid?.opacity??.18,min:0,max:1,step:.01,onChange:v=>S({opacity:v})})}),c.jsx(ho,{label:"Density",value:no(t.floor?.grid?.density??1),children:c.jsx(ro,{value:t.floor?.grid?.density??1,min:.25,max:4,step:.05,onChange:v=>S({density:v})})})]}):null}),c.jsxs(ya,{title:"Lighting",children:[c.jsx(ud,{label:"Environment light",checked:t.environment.enabled,onChange:v=>b({enabled:v})}),c.jsx(ho,{label:"Environment intensity",value:no(t.environment.intensity),children:c.jsx(ro,{value:t.environment.intensity,min:0,max:4,step:.01,onChange:v=>b({intensity:v})})}),c.jsx(ho,{label:"Tone mapping",value:no(t.lighting.toneMappingExposure),children:c.jsx(ro,{value:t.lighting.toneMappingExposure,min:.05,max:6,step:.01,onChange:v=>I({toneMappingExposure:v})})}),c.jsx(aS,{title:"Primary",children:c.jsxs(yQ,{value:l,onValueChange:u,className:"gap-0",children:[c.jsx("div",{className:"px-3 py-1",children:c.jsx(xQ,{className:"grid h-7 w-full grid-cols-3 rounded-md p-0.5",children:I_.map(v=>c.jsx(SQ,{value:v.value,className:"text-[11px]",children:v.label},v.value))})}),I_.map(v=>{const C=t.lighting[v.value],T=v.value!=="directional";return c.jsxs(EQ,{value:v.value,className:H("mt-2",t0),"data-file-sheet-row-stack":"",children:[c.jsx(ud,{label:`${v.label} light`,checked:C.enabled,onChange:k=>P(v.value,{enabled:k})}),c.jsx(Vi,{label:"Color",path:["lighting",v.value,"color"],...N}),c.jsx(ho,{label:"Intensity",value:no(C.intensity),children:c.jsx(ro,{value:C.intensity,min:0,max:20,step:.01,onChange:k=>P(v.value,{intensity:k})})}),v.value==="spot"?c.jsx(ho,{label:"Angle",value:no(C.angle),children:c.jsx(ro,{value:C.angle,min:.01,max:1.57,step:.01,onChange:k=>P(v.value,{angle:k})})}):null,T?c.jsx(ho,{label:"Distance",value:no(C.distance,0),children:c.jsx(ro,{value:C.distance,min:0,max:5e3,step:1,onChange:k=>P(v.value,{distance:k})})}):null,c.jsx(lc,{label:"Position (X/Z)",children:c.jsx(UQ,{value:C.position,onChange:(k,z)=>R(v.value,k,z)})}),c.jsx(ho,{label:"Height (Y)",value:no(C.position.y,0),children:c.jsx(ro,{value:C.position.y,min:-5e3,max:5e3,step:1,onChange:k=>R(v.value,"y",k)})})]},v.value)})]})}),c.jsxs(aS,{title:"Ambient",children:[c.jsx(ud,{label:"Ambient light",checked:t.lighting.ambient.enabled,onChange:v=>P("ambient",{enabled:v})}),c.jsx(Vi,{label:"Ambient color",path:["lighting","ambient","color"],...N}),c.jsx(ho,{label:"Ambient intensity",value:no(t.lighting.ambient.intensity),children:c.jsx(ro,{value:t.lighting.ambient.intensity,min:0,max:20,step:.01,onChange:v=>P("ambient",{intensity:v})})})]}),c.jsxs(aS,{title:"Hemisphere",children:[c.jsx(ud,{label:"Hemisphere light",checked:t.lighting.hemisphere.enabled,onChange:v=>P("hemisphere",{enabled:v})}),c.jsx(Vi,{label:"Sky color",path:["lighting","hemisphere","skyColor"],...N}),c.jsx(Vi,{label:"Ground color",path:["lighting","hemisphere","groundColor"],...N}),c.jsx(ho,{label:"Hemisphere intensity",value:no(t.lighting.hemisphere.intensity),children:c.jsx(ro,{value:t.lighting.hemisphere.intensity,min:0,max:20,step:.01,onChange:v=>P("hemisphere",{intensity:v})})})]})]})]})}function KQ({open:e,title:t="Mesh",isDesktop:n,width:r,selectedEntry:o=null,onOpenChange:i,onStartResize:s,fileDownloadAvailable:a=!1,viewerServerInfo:l=null,localFileOpenAvailable:u=!1,fileAccessBusyKey:d="",onOpenFileAsset:m,suppressDynamicMetadataStatus:p=!1,statusItems:g=[],themeSections:x=null,openSectionIds:y=[],onOpenSectionIdsChange:S}){return c.jsx(xf,{open:e,title:t,isDesktop:n,width:r,onOpenChange:i,onStartResize:s,children:c.jsxs(yf,{type:"multiple",value:y,onValueChange:S,className:"text-sm",children:[c.jsx(wf,{items:g}),x,c.jsx(Ef,{entry:o,fileDownloadAvailable:a,viewerServerInfo:l,localFileOpenAvailable:u,fileAccessBusyKey:d,onOpenFileAsset:m,suppressDynamicStatus:p})]})})}function XQ(e){const t=Number(e);return Number.isFinite(t)?`${t.toFixed(2)}x`:"1.00x"}function _d(e,t,n){e?.onSettingsChange?.(r=>({...Ms(r),[t]:n}))}function eb({label:e,settingKey:t,settings:n,runtime:r}){const o=Xm[t],i=n[t];return c.jsx(Ni,{label:e,value:XQ(i),onValueCommit:s=>{_d(r,t,ui(s,{fallback:i,min:o.min,max:o.max}))},valueInputProps:{ariaLabel:`${e} value`},children:c.jsx(_i,{className:Us,value:[i],min:o.min,max:o.max,step:o.step,onValueChange:s=>_d(r,t,s?.[0]??i),"aria-label":e})})}function YQ({runtime:e=null,value:t="graphics",title:n="Graphics"}){const r=Ms(e?.settings),o=!!e?.model?.colorSource,i=MK(r,Ds);return c.jsx(ci,{value:t,title:n,children:c.jsxs(r0,{children:[eb({label:"Resolution",settingKey:"resolutionScale",settings:r,runtime:e}),eb({label:"Motion resolution",settingKey:"interactionResolutionScale",settings:r,runtime:e}),eb({label:"Ray detail",settingKey:"detail",settings:r,runtime:e}),eb({label:"Normal smoothing",settingKey:"normalSmoothing",settings:r,runtime:e}),c.jsx(Mi,{label:"Model colors",checked:r.modelColors&&o,disabled:!o,onCheckedChange:s=>_d(e,"modelColors",s),ariaLabel:"Model colors"}),c.jsx(Mi,{label:"Soft shadows",checked:r.shadows,onCheckedChange:s=>_d(e,"shadows",s),ariaLabel:"Soft shadows"}),c.jsx(Mi,{label:"Ambient occlusion",checked:r.ambientOcclusion,onCheckedChange:s=>_d(e,"ambientOcclusion",s),ariaLabel:"Ambient occlusion"}),c.jsx(Mi,{label:"Rim light",checked:r.rimLight,onCheckedChange:s=>_d(e,"rimLight",s),ariaLabel:"Rim light"}),c.jsx(cn,{className:"pt-2",children:c.jsxs(Qe,{type:"button",variant:"outline",size:"sm",className:H(uh,"w-full justify-center"),disabled:i,onClick:()=>e?.onSettingsChange?.(Ds),title:"Reset graphics",children:[c.jsx(ws,{className:"h-3.5 w-3.5",strokeWidth:2,"aria-hidden":"true"}),c.jsx("span",{children:"Reset graphics"})]})})]})})}const Uk=.01,qQ=1e-6,ZQ=1e3;function uS(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function P_(e,t=0){const n=Number(e);return Number.isFinite(n)?n:t}function JQ(e){const t=Number(e);return Number.isFinite(t)&&t>0?t:0}function QQ(e){const t=Number(e);return Number.isFinite(t)?Number(t.toPrecision(12)):Uk}function eee(e,t="parameters"){const n=String(e??"").trim();if(!n)throw new Error(`Clipboard does not contain ${t}`);try{return JSON.parse(n)}catch{const r=n.indexOf("{"),o=n.lastIndexOf("}");if(r>=0&&o>r)return JSON.parse(n.slice(r,o+1));throw new Error(`${t} paste must be JSON`)}}function Wk(e){const t=JQ(e?.step),n=P_(e?.min,0),r=P_(e?.max,n),o=Math.abs(r-n),i=o>0?Math.max(10**Math.floor(Math.log10(o/ZQ)),qQ):Uk;return QQ(t>0?Math.min(t,i):i)}function Hk(e,t={}){const n=Array.isArray(e?.parameters)?e.parameters:[];if(!n.length)return"{}";const r=qd(e,t),o=Object.fromEntries(n.map(i=>[i.id,r[i.id]]));return JSON.stringify(o,null,2)}function Kk(e,t,{label:n="parameters",unknownLabel:r="parameter"}={}){const o=uS(e?.parameterMap)?e.parameterMap:{},i=eee(t,n),s=uS(i?.values)?i.values:i;if(!uS(s))throw new Error(`${n} paste must be a JSON object`);const a=[],l={};for(const[d,m]of Object.entries(s)){const p=String(d||"").trim();if(!p)continue;const g=o[p];if(!g){a.push(p);continue}l[p]=bu(g,m)}if(a.length)throw new Error(`Unknown ${r}${a.length===1?"":"s"}: ${a.join(", ")}`);const u=Object.keys(l).length;if(!u)throw new Error(`No known ${r}s found`);return{values:l,count:u}}const dd=uh,tee=n0,Xk=.1,Yk=3;function O_(e){const t=Number(e);return Number.isFinite(t)?Math.abs(t)>=100?t.toFixed(0):Math.abs(t)>=10?t.toFixed(1):t.toFixed(2):"0"}function nee(e){const t=Math.max(Number(e)||0,0);return`${t.toFixed(t>=10?1:2)}s`}function ree(e,t=1){return ui(e,{fallback:t,min:Xk,max:Yk})}function oee({value:e="parameters",title:t="Parameters",runtime:n=null,label:r="parameter",loadingLabel:o="Loading parameters...",noParametersLabel:i="No parameters.",hideWhenEmpty:s=!1,showEnableToggle:a=!1,enableLabel:l="Enable",animationAriaLabel:u="Animation",copyTitle:d="Copy parameter JSON",pasteTitle:m="Paste parameter JSON",resetTitle:p="Reset parameters"}){const g=n?.definition||null,x=Array.isArray(g?.parameters)?g.parameters:[],y=Array.isArray(g?.animations)?g.animations:[],S=String(n?.status||"").trim(),b=String(n?.error||"").trim(),I=n?.parameterValues||{},A=n?.animationState||{},N=Math.max(Number(A.duration)||1,.001),P=n?.enabled!==!1,R=x.length>0||y.length>0;return s&&g&&!R&&S!=="loading"&&!b||!(g||S==="loading"||b)?null:c.jsx(ci,{value:e,title:t,children:c.jsxs(r0,{children:[g&&a?c.jsx(Mi,{label:l,checked:P,onCheckedChange:C=>n?.onEnabledChange?.(C),ariaLabel:l}):null,S==="loading"?c.jsx("p",{className:"px-3 py-2 text-xs text-[var(--ui-text-muted)]",children:o}):null,b?c.jsx("p",{className:"whitespace-pre-line px-3 py-2 text-xs text-destructive",children:b}):null,g&&y.length?c.jsxs(c.Fragment,{children:[y.length>1?c.jsx(cn,{label:"Animation",children:c.jsxs(wa,{value:String(A.activeId||y[0]?.id||""),onValueChange:C=>n?.onAnimationSelect?.(C),disabled:!P,children:[c.jsx(va,{size:"sm",className:"h-7 !text-[11px]","aria-label":u,children:c.jsx(ac,{})}),c.jsx(Ca,{children:y.map(C=>c.jsx(Ma,{value:C.id,children:C.label},C.id))})]})}):null,c.jsx(cn,{children:c.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[c.jsxs(Qe,{type:"button",variant:"outline",size:"sm",className:H(dd,"justify-center"),onClick:()=>n?.onAnimationPlayToggle?.(),disabled:!P,"aria-label":`${A.playing?"Pause":"Play"} ${r} animation`,title:`${A.playing?"Pause":"Play"} ${r} animation`,children:[A.playing?c.jsx(VE,{className:"h-3.5 w-3.5",strokeWidth:2,"aria-hidden":"true"}):c.jsx($E,{className:"h-3.5 w-3.5",strokeWidth:2,"aria-hidden":"true"}),c.jsx("span",{children:A.playing?"Pause":"Play"})]}),c.jsxs(Qe,{type:"button",variant:"outline",size:"sm",className:H(dd,"justify-center"),onClick:()=>n?.onAnimationReset?.(),disabled:!P,"aria-label":`Restart ${r} animation`,title:"Restart",children:[c.jsx(ws,{className:"h-3.5 w-3.5",strokeWidth:2,"aria-hidden":"true"}),c.jsx("span",{children:"Reset"})]})]})}),c.jsx(Ni,{label:"Time",value:nee(A.elapsedSec),onValueCommit:C=>{n?.onAnimationScrub?.(ui(C,{fallback:A.elapsedSec,min:0,max:N}))},valueInputProps:{disabled:!P,ariaLabel:`${r} animation time value`},children:c.jsx(_i,{className:Us,value:[Number(A.elapsedSec)||0],min:0,max:N,step:.01,onValueChange:C=>n?.onAnimationScrub?.(C?.[0]??0),disabled:!P,"aria-label":`${r} animation time`})}),c.jsx(Ni,{label:"Speed",value:`${O_(A.speed||1)}x`,onValueCommit:C=>{n?.onAnimationSpeedChange?.(ree(C,A.speed||1))},valueInputProps:{disabled:!P,ariaLabel:`${r} animation speed value`},children:c.jsx(_i,{className:Us,value:[Number(A.speed)||1],min:Xk,max:Yk,step:.1,onValueChange:C=>n?.onAnimationSpeedChange?.(C?.[0]??1),disabled:!P,"aria-label":`${r} animation speed`})})]}):null,g&&!x.length?c.jsx("p",{className:"px-3 py-2 text-xs text-[var(--ui-text-muted)]",children:i}):null,x.map(C=>{const T=I?.[C.id]??C.defaultValue,k=Wk(C);return C.type==="boolean"?c.jsx(Mi,{label:C.label,checked:T===!0,onCheckedChange:z=>n?.onParameterChange?.(C.id,z),disabled:!P,ariaLabel:C.label},C.id):C.type==="enum"?c.jsx(cn,{label:C.label,children:c.jsxs(wa,{value:String(T??""),onValueChange:z=>n?.onParameterChange?.(C.id,z),disabled:!P,children:[c.jsx(va,{size:"sm",className:"h-7 !text-[11px]","aria-label":C.label,children:c.jsx(ac,{})}),c.jsx(Ca,{children:C.options.map(z=>c.jsx(Ma,{value:z.value,children:z.label},z.value))})]})},C.id):C.type==="color"?c.jsx(cn,{label:C.label,trailing:c.jsx(yv,{value:String(T||"#ffffff"),onChange:z=>n?.onParameterChange?.(C.id,z),disabled:!P,className:H(tee,"w-fit justify-start gap-1.5 px-1.5"),swatchClassName:"size-3.5",popoverAlign:"end","aria-label":C.label})},C.id):C.type==="button"?c.jsx(cn,{children:c.jsx(Qe,{type:"button",variant:"outline",size:"sm",className:H(dd,"w-full justify-center"),onClick:()=>n?.onParameterChange?.(C.id,Number(T||0)+1),disabled:!P,children:C.label})},C.id):C.type==="string"?c.jsx(cn,{label:C.label,trailing:c.jsx(Zw,{value:String(T??""),onValueCommit:z=>n?.onParameterChange?.(C.id,z),disabled:!P,inputMode:"text",ariaLabel:`${C.label} value`,className:"w-40 max-w-[min(12rem,55vw)] text-left font-medium tabular-nums"})},C.id):c.jsx(Ni,{label:C.label,value:`${O_(T)}${C.unit?` ${C.unit}`:""}`,onValueCommit:z=>{n?.onParameterChange?.(C.id,ui(z,{fallback:T,min:C.min,max:C.max}))},valueInputProps:{disabled:!P,ariaLabel:`${C.label} slider value`},children:c.jsx(_i,{className:Us,value:[Number(T)||0],min:C.min,max:C.max,step:k,onValueChange:z=>n?.onParameterChange?.(C.id,z?.[0]??T),disabled:!P,"aria-label":C.label})},C.id)}),g&&x.length?c.jsxs(c.Fragment,{children:[c.jsx(cn,{className:"pt-2",children:c.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[c.jsxs(Qe,{type:"button",variant:"outline",size:"sm",className:H(dd,"justify-center"),onClick:()=>{n?.onCopyParams?.()},title:d,children:[c.jsx(vu,{className:"h-3.5 w-3.5",strokeWidth:2,"aria-hidden":"true"}),c.jsx("span",{children:"Copy parameters"})]}),c.jsxs(Qe,{type:"button",variant:"outline",size:"sm",className:H(dd,"justify-center"),onClick:()=>{n?.onPasteParams?.()},title:m,children:[c.jsx(cR,{className:"h-3.5 w-3.5",strokeWidth:2,"aria-hidden":"true"}),c.jsx("span",{children:"Paste parameters"})]})]})}),n?.onResetParameters?c.jsx(cn,{children:c.jsxs(Qe,{type:"button",variant:"outline",size:"sm",className:H(dd,"w-full justify-center"),onClick:()=>n.onResetParameters(),title:p,children:[c.jsx(ws,{className:"h-3.5 w-3.5",strokeWidth:2,"aria-hidden":"true"}),c.jsx("span",{children:"Reset parameters"})]})}):null]}):null]})})}function iee({open:e,title:t="Implicit CAD",isDesktop:n,width:r,selectedEntry:o=null,onOpenChange:i,onStartResize:s,parameterRuntime:a=null,graphicsRuntime:l=null,fileDownloadAvailable:u=!1,viewerServerInfo:d=null,localFileOpenAvailable:m=!1,fileAccessBusyKey:p="",onOpenFileAsset:g,suppressDynamicMetadataStatus:x=!1,statusItems:y=[],themeSections:S=null,openSectionIds:b=[],onOpenSectionIdsChange:I}){return c.jsx(xf,{open:e,title:t,isDesktop:n,width:r,onOpenChange:i,onStartResize:s,children:c.jsxs(yf,{type:"multiple",value:b,onValueChange:I,className:"text-sm",children:[c.jsx(wf,{items:y}),c.jsx(oee,{runtime:a,label:"implicit parameter",loadingLabel:"Loading implicit parameters...",noParametersLabel:"No implicit parameters.",hideWhenEmpty:!0,animationAriaLabel:"Implicit animation",copyTitle:"Copy implicit parameter JSON",pasteTitle:"Paste implicit parameter JSON"}),c.jsx(YQ,{runtime:l}),S,c.jsx(Ef,{entry:o,fileDownloadAvailable:u,viewerServerInfo:d,localFileOpenAvailable:m,fileAccessBusyKey:p,onOpenFileAsset:g,suppressDynamicStatus:x})]})})}function see(e){return Wk(e)}function aee(e,t={}){return Hk(e,t)}function lee(e,t){return Kk(e,t,{label:"STEP parameter",unknownLabel:"STEP parameter"})}const _m=uh,cee=n0,uee="grid h-5 w-5 shrink-0 place-items-center rounded-sm px-0 text-current/60 hover:bg-sidebar-accent/45 hover:text-sidebar-accent-foreground focus-visible:bg-sidebar-accent/45",dee="h-5 w-5 rounded-sm px-0 text-current/60 shadow-none hover:bg-sidebar-accent/45 hover:text-sidebar-accent-foreground focus-visible:bg-sidebar-accent/45 focus-visible:text-sidebar-accent-foreground",fee="h-7 min-w-0 text-xs font-normal",k_="px-1.5 pb-1 pt-2 text-[10px] font-medium text-sidebar-foreground/45",qk="size-3.5 shrink-0 text-current/60",mee="grid h-5 w-5 shrink-0 place-items-center text-current/60",iE=22,pee=14,Zk=128,D_="tree",hee=120,tb=10,gee="h-5 w-full justify-start rounded-sm px-1.5 text-[10px] font-medium text-sidebar-foreground/60 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:bg-sidebar-accent focus-visible:text-sidebar-accent-foreground",Jk=.1,Qk=3;function j_(e){const t=Number(e);return Number.isFinite(t)?Math.abs(t)>=100?t.toFixed(0):Math.abs(t)>=10?t.toFixed(1):t.toFixed(2):"0"}function bee(e){const t=Math.max(Number(e)||0,0);return`${t.toFixed(t>=10?1:2)}s`}function yee(e,t=1){return ui(e,{fallback:t,min:Jk,max:Qk})}function xee(e,t){const n=Array.isArray(e)?e.map(o=>String(o||"").trim()).filter(Boolean):[];if(!n.length)return!1;const r=new Set(Array.isArray(t)?t:[]);return n.every(o=>r.has(o))}function See(e,t){const n=new Set,r=[];for(const o of Array.isArray(e)?e:[]){const i=Math.max(Number(o?.depth)||0,0);r.length=i;const a=i>0&&r[i-1]===!0||xee(o?.leafPartIds,t);r[i]=a,a&&n.add(String(o?.id||"").trim())}return n}function Eee(e){return String(e?.id||e?.occurrenceId||"").trim()}function wee(e,t){const n=new Set((Array.isArray(t)?t:[]).map(i=>String(i||"").trim()).filter(Boolean));if(!n.size)return null;const r=new Set,o=[];for(const i of Array.isArray(e)?e:[]){const s=String(i?.id||"").trim(),a=Math.max(Number(i?.depth)||0,0);o.length=a;const u=a>0&&o[a-1]===!0||n.has(s);o[a]=u,u&&s&&r.add(s)}return r}function L_(e,{block:t="nearest"}={}){if(!e)return;const n=e.closest("[data-slot='scroll-area-viewport']");if(!n){e.scrollIntoView?.({block:t,behavior:"instant"});return}const r=e.getBoundingClientRect(),o=n.getBoundingClientRect();if(t==="center"){const s=r.top+r.height/2,a=o.top+o.height/2;n.scrollTop+=s-a;return}const i=o.top+hee;if(r.topo.bottom&&(n.scrollTop+=r.bottom-o.bottom)}function sE(e){const t=String(e?.topologyType||"").trim();if(t)return t;const n=String(e?.nodeType||e?.node?.nodeType||"").trim();return n.startsWith("topology-")?n.slice(9):""}function vee(e){return String(e?.detail||e?.node?.detail||e?.summary||e?.node?.summary||"").trim()}function Cee(e,t){const n=vee(e).toLowerCase(),r=String(e?.label||e?.node?.displayName||"").trim().toLowerCase(),o=`${n} ${r}`;if(t==="face")return/\bplane\b/.test(o)?"plane":/\bcylinder\b/.test(o)?"cylinder":/\bcone\b/.test(o)?"cone":/\bsphere\b/.test(o)?"sphere":/\btorus\b/.test(o)?"torus":/\bbspline\b|\bspline\b|\bbezier\b/.test(o)?"spline":"face";if(t==="edge")return/\bcircle\b/.test(o)?"circle":/\bellipse\b/.test(o)?"ellipse":/\bline\b/.test(o)?"line":/\bbspline\b|\bspline\b|\bbezier\b/.test(o)?"spline":"edge";if(t==="shape"){if(/\bsolid\b/.test(o))return"solid";if(/\bshell\b/.test(o))return"shell"}return t}function eD(e){const t=String(e||"").trim();return t?`${t.slice(0,1).toUpperCase()}${t.slice(1)}`:""}function Mee(e,t,n=""){const r=String(e?.label||e?.node?.displayName||"").trim(),o=String(t||"").trim(),i=String(n||"").trim();if(o){const l=eD(o),u=r.toLowerCase();return[l&&!u.startsWith(o.toLowerCase())?l:"",r,i].filter(Boolean).join(" ")}return[String(e?.nodeType||e?.node?.nodeType||"").trim()==="assembly"?"Assembly":"Component",r,i].filter(Boolean).join(" ")}function rc(e,t){const n=String(t||"").trim();return n?`${e}: ${n}`:""}function tD(e){const t=String(e||"").trim().replace(/^#/,"");return t?`#${t}`:""}function Iee(e,{topologyType:t="",topologyReferenceId:n="",detail:r="",disabledReason:o=""}={}){const i=String(e?.label||e?.node?.displayName||"").trim(),s=String(e?.nodeType||e?.node?.nodeType||"").trim(),a=t?eD(t):s==="assembly"?"Assembly":"Component",l=t?String(e?.node?.displaySelector||e?.displaySelector||n||"").trim():String(e?.node?.occurrenceId||e?.node?.id||e?.id||"").trim();return[rc(a||"Item",i),rc("Ref",tD(l)),rc("Info",r),rc("Status",o)].filter(Boolean).join(` `)}function Aee(e,t=""){return[rc("Mate",e?.label),rc("Ref",tD(e?.id)),rc("Info",e?.detail),rc("Status",t)].filter(Boolean).join(` `)}function Nee({depth:e}){const t=Math.min(Math.max(Math.trunc(Number(e)||0),0),Math.floor(Zk/iE));return t<1?null:c.jsx("span",{className:"pointer-events-none absolute inset-y-0 left-0","aria-hidden":"true",children:Array.from({length:t}).map((n,r)=>c.jsx("span",{className:"absolute inset-y-0 border-l border-sidebar-border/65",style:{left:`${r*iE+pee}px`}},r))})}function Ua({children:e}){return c.jsx("svg",{className:qk,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.45",strokeLinecap:"round",strokeLinejoin:"round",shapeRendering:"geometricPrecision","aria-hidden":"true",children:e})}function _ee({row:e,type:t}){const n=String(t||"").trim(),r=Cee(e,n),o=`relative ${qk}`;return n==="occurrence"?null:n==="shape"?r==="shell"?c.jsxs(Ua,{children:[c.jsx("path",{d:"M4.5 4.5h7v7h-7z"}),c.jsx("path",{d:"M6.25 6.25h3.5v3.5h-3.5z"})]}):c.jsx("span",{className:o,"aria-hidden":"true",children:c.jsx("span",{className:"absolute left-[3px] top-[3px] size-2.5 rotate-45 rounded-[1px] border border-current"})}):n==="face"?r==="cylinder"?c.jsxs(Ua,{children:[c.jsx("ellipse",{cx:"8",cy:"4",rx:"4",ry:"2"}),c.jsx("path",{d:"M4 4v8"}),c.jsx("path",{d:"M12 4v8"}),c.jsx("ellipse",{cx:"8",cy:"12",rx:"4",ry:"2"})]}):r==="cone"?c.jsxs(Ua,{children:[c.jsx("path",{d:"M8 3 4 12"}),c.jsx("path",{d:"M8 3l4 9"}),c.jsx("path",{d:"M4 12c1.25 1.25 6.75 1.25 8 0"})]}):r==="sphere"?c.jsxs(Ua,{children:[c.jsx("circle",{cx:"8",cy:"8",r:"5"}),c.jsx("path",{d:"M8 3c1.3 1.35 2 3.05 2 5s-.7 3.65-2 5"}),c.jsx("path",{d:"M3 8h10"})]}):r==="torus"?c.jsxs(Ua,{children:[c.jsx("ellipse",{cx:"8",cy:"8",rx:"5.2",ry:"3.4"}),c.jsx("ellipse",{cx:"8",cy:"8",rx:"2.2",ry:"1.25"})]}):r==="spline"?c.jsxs(Ua,{children:[c.jsx("path",{d:"M3 11.5c2.1-6.6 7.6 1 10-5.8"}),c.jsx("path",{d:"M3.5 12.7h8.8",opacity:"0.45"})]}):c.jsx("span",{className:o,"aria-hidden":"true",children:c.jsx("span",{className:"absolute inset-[3px] rounded-[1px] border border-current bg-current/15"})}):n==="edge"?r==="circle"?c.jsxs(Ua,{children:[c.jsx("circle",{cx:"8",cy:"8",r:"4.6"}),c.jsx("circle",{cx:"8",cy:"8",r:"1.2",fill:"currentColor",stroke:"none",opacity:"0.25"})]}):r==="ellipse"?c.jsx(Ua,{children:c.jsx("ellipse",{cx:"8",cy:"8",rx:"5.4",ry:"3.2"})}):r==="spline"?c.jsxs(Ua,{children:[c.jsx("path",{d:"M2.8 10.6c2.1-5.8 5.2 2.8 10.4-4.8"}),c.jsx("circle",{cx:"2.8",cy:"10.6",r:"0.9",fill:"currentColor",stroke:"none"}),c.jsx("circle",{cx:"13.2",cy:"5.8",r:"0.9",fill:"currentColor",stroke:"none"})]}):c.jsxs("span",{className:o,"aria-hidden":"true",children:[c.jsx("span",{className:"absolute left-[2px] top-[7px] h-px w-3 rotate-[-28deg] rounded-full bg-current"}),c.jsx("span",{className:"absolute left-[1px] top-[8px] size-1 rounded-full bg-current"}),c.jsx("span",{className:"absolute right-[1px] top-[3px] size-1 rounded-full bg-current"})]}):null}function Tee({row:e}){const t=sE(e);return t?c.jsx(_ee,{row:e,type:t}):null}function Ree(e){return Array.isArray(e)?e.filter(t=>t&&typeof t=="object").map((t,n)=>{const r=`m${n+1}`,o=String(t.id||r).trim()||r,i=String(t.sourceLabel||t.name||"").trim(),s=String(t.label||"").trim(),a=i||(s&&s!==o?s:"")||o,l=String(t.type||t.relation||"mate").trim()||"mate",u=String(t.fixed||"").trim(),d=String(t.moving||"").trim(),m=u&&d?`${u} -> ${d}`:u||d,p=[o,l,m].filter(Boolean).join(" ");return{id:o,label:a,detail:p}}):[]}function Pee({animationState:e,duration:t,enabled:n,onScrub:r}){const o=FX(),i=e?.playing?o:Number(e?.elapsedSec)||0,s=Math.min(Math.max(i,0),t);return c.jsx(Ni,{label:"Time",value:bee(s),onValueCommit:a=>{r?.(ui(a,{fallback:s,min:0,max:t}))},valueInputProps:{disabled:!n,ariaLabel:"STEP animation time value"},children:c.jsx(_i,{className:Us,value:[s],min:0,max:t,step:.01,onValueChange:a=>r?.(a?.[0]??0),disabled:!n,"aria-label":"STEP animation time"})})}function Oee({open:e,isDesktop:t,width:n,onOpenChange:r,onStartResize:o,selectedEntry:i,viewerLoading:s,isAssemblyView:a=!1,stepTreeRoot:l,assemblyMates:u=[],expandedTreeNodeIds:d,stepTreeRootShowMore:m=!1,onStepTreeRootShowMoreChange:p,loadableTreeNodeIds:g=[],selectedPartIds:x,selectedReferenceIds:y=[],selectedMateIds:S=[],selectableNodeIds:b=null,activeTreeNodeId:I="",activeTreeNodeScrollKey:A="",hoveredPartId:N,hoveredReferenceId:P="",hoveredMateId:R="",hiddenPartIds:v,focusedNodeIds:C=[],onSelectTreeNode:T,onSelectReferenceNode:k,onSelectMateNode:z,onCopyTreeNodeReference:Y,onCopyMateNodeReference:K,onFocusTreeNode:J,onUnfocusTreeNode:G,onExitAllIsolate:Q,onHideOtherTreeNode:D,onToggleTreeNode:$,onClearSelection:ie,onHoverTreeNode:W,onHoverReferenceNode:Z,onHoverMateNode:Ee,treeSelectionDisabled:re=!1,treeSelectionDisabledReason:be="",onTogglePartVisibility:_e,hideAllParts:Ie,showAllHiddenParts:oe,stepModule:me=null,fileDownloadAvailable:se=!1,viewerServerInfo:Ae=null,localFileOpenAvailable:we=!1,fileAccessBusyKey:ct="",onOpenFileAsset:ut,suppressDynamicMetadataStatus:Tt=!1,statusItems:Ve=[],themeSections:St=null,openSectionIds:wt=[],onOpenSectionIdsChange:Vn}){const De=f.useRef(new Map),xe=f.useRef(""),yt=Array.isArray(x)?x:[],Te=f.useMemo(()=>new Set((Array.isArray(y)?y:[]).map(X=>String(X||"").trim()).filter(Boolean)),[y]),rt=String(Array.isArray(y)&&y[y.length-1]||"").trim(),Re=f.useMemo(()=>new Set((Array.isArray(S)?S:[]).map(X=>String(X||"").trim()).filter(Boolean)),[S]),Fe=Array.isArray(v)?v:[],on=f.useMemo(()=>new Set((Array.isArray(C)?C:[]).map(X=>String(X||"").trim()).filter(Boolean)),[C]),ht=String(P||"").trim(),jt=String(R||"").trim(),qt=f.useMemo(()=>Array.isArray(b)?new Set(b.map(X=>String(X||"").trim()).filter(Boolean)):null,[b]),sn=l,Mn=hr(sn),fn=Mn.length>0&&(a||Eee(sn)===hs),Bt=f.useMemo(()=>Ree(u),[u]),qe=Mn.length+Bt.length>tb,Vt=qe?Math.min(Mn.length,tb):Mn.length,We=qe?Math.max(tb-Vt,0):Bt.length,ze=f.useMemo(()=>Bb(sn,d,{omitRoot:fn,showAllRootChildren:!0}),[fn,d,sn]),Ze=f.useMemo(()=>rt&&ze.find(X=>String(X?.topologyReferenceId||"").trim()===rt)||null,[rt,ze]),vt=f.useMemo(()=>qe?[...yt,I,Ze?.id].map(At=>String(At||"").trim()).filter(Boolean).some(At=>L5(sn,At)>=Vt):!1,[Ze,I,Vt,qe,yt,sn]),Tn=f.useMemo(()=>!qe||Re.size<1||We>=Bt.length?!1:Bt.some((X,At)=>At>=We&&Re.has(String(X?.id||"").trim())),[Bt,We,qe,Re]),pe=qe&&(vt||Tn),Xe=qe&&(m||pe),He=f.useMemo(()=>Bb(sn,d,{omitRoot:fn,rootChildLimit:tb,showAllRootChildren:!qe||Xe}),[fn,d,qe,Xe,sn]),Rn=qe?Math.max(Mn.length-Vt,0):0,xn=f.useMemo(()=>He.map(X=>String(X?.id||"")).join(` `),[He]),ue=f.useMemo(()=>See(He,Fe),[Fe,He]),Rt=f.useMemo(()=>wee(He,C),[C,He]),Zt=a||fn?He.length>0:He.some(X=>X?.hasChildren),qn=qe&&!Xe?Bt.slice(0,We):Bt,Ct=Bt.length>0,wr=qn.length>0,vr=qe&&!Xe?Math.max(Bt.length-qn.length,0):0,Qt=Rn+vr,In=qe&&(!pe||m),gr=Xe?"Show less":`Show ${Qt} more`,lo=Xe?"Show less":"Show more",Mt=In?c.jsx("div",{className:"py-0.5",role:"presentation",children:c.jsx(Qe,{type:"button",variant:"ghost",size:"xs",className:gee,title:lo,onClick:X=>{X.stopPropagation(),p?.(!Xe)},children:gr})}):null,gt=f.useMemo(()=>rt&&He.find(X=>String(X?.topologyReferenceId||"").trim()===rt)||null,[rt,He]),Sn=String(I||yt[yt.length-1]||"").trim(),On=String(gt?.id||Sn||"").trim(),Kr=f.useMemo(()=>On&&He.find(X=>String(X?.id||"").trim()===On||String(X?.node?.selectionPartId||"").trim()===On)||null,[On,He]),Xr=Kr?.node?.visualOnly===!0?!1:!!sE(Kr),Co=on.size>0,br=a===!0,j=Array.isArray(wt)&&wt.includes(D_),de=re?String(be||"Tree selection is disabled in the current parameter state.").trim():"",L=f.useMemo(()=>new Set((Array.isArray(d)?d:[]).map(X=>String(X||"").trim()).filter(Boolean)),[d]),te=f.useMemo(()=>new Set((Array.isArray(g)?g:[]).map(X=>String(X||"").trim()).filter(Boolean)),[g]),fe=X=>{const At=String(X?.id||"").trim();return!!(X?.hasChildren||At&&te.has(At))},ae=f.useMemo(()=>{const X=[],At=new Set;for(const ne of He){const ye=String(ne?.id||"").trim();!ye||At.has(ye)||fe(ne)&&(At.add(ye),X.push(ye))}return X},[te,He]),he=f.useMemo(()=>ae.filter(X=>!L.has(X)),[ae,L]),ot=f.useMemo(()=>ae.filter(X=>L.has(X)),[ae,L]),It=f.useMemo(()=>{const X=new Map;for(const At of He){const ne=String(At?.id||"").trim();ne&&X.set(ne,At);const ye=String(At?.node?.selectionPartId||"").trim();ye&&!X.has(ye)&&X.set(ye,At)}return X},[He]),Pt=(X,At=1)=>{if(!He.length)return;const ne=At<0?-1:1;let ye=Math.min(Math.max(Number(X)||0,0),He.length-1);for(;ye>=0&&ye{const X=String(A||"").trim();if(!X||X===xe.current||!On||!j)return;const At=()=>{const ye=De.current.get(On);ye&&(xe.current=X,L_(ye,{block:Xr?"center":"nearest"}))};if(typeof window>"u"){At();return}const ne=window.requestAnimationFrame(At);return()=>{window.cancelAnimationFrame(ne)}},[On,Xr,A,j,xn]),i?c.jsx(xf,{open:e,title:"STEP",isDesktop:t,width:n,onOpenChange:r,onStartResize:o,children:c.jsxs(yf,{type:"multiple",value:wt,onValueChange:Vn,children:[c.jsx(wf,{items:Ve}),c.jsx(ci,{value:D_,title:"Tree",triggerProps:{title:de||void 0},children:c.jsx("div",{className:"max-w-full overflow-hidden px-1.5 pb-2",children:c.jsxs("div",{className:"select-none space-y-px",role:"tree","aria-multiselectable":"true","aria-disabled":re,title:de||void 0,onClick:X=>{re||X.target===X.currentTarget&&ie?.()},children:[Ct?c.jsx("div",{className:k_,role:"presentation",children:"Instances"}):null,s&&!He.length?c.jsx("p",{className:"px-1.5 py-2 text-xs text-[var(--ui-text-muted)]",children:"Loading STEP tree..."}):null,Zt?He.map((X,At)=>{const ye=X?.node?.visualOnly===!0?"":sE(X),it=!!ye,ft=String(X.id||"").trim(),xt=String(X.node?.selectionPartId||X.id||"").trim(),_r=String(X.topologyReferenceId||"").trim(),Ti=it?String(X.node?.partId||"").trim():"",Ra=!!ye&&_r&&typeof k=="function",Pa=String(X.detail||"").trim(),Cr=ye?"":Pa,Xt=Mee(X,ye,Pa),os=fe(X),kn=!!X.expanded,Tr=it?Te.has(_r):yt.includes(xt),Ri=it&&Ti&&(Rt?.has(Ti)||on.has(Ti)||qt?.has(Ti)),_u=!Rt||Rt.has(ft)||Ri,Zn=!it&&on.has(ft),qr=(ye==="shape"||ye==="occurrence")&&on.has(String(X.node?.partId||"").trim()),mi=it?Ra&&_u&&!qr:!Zn&&(!qt||qt.has(xt)||Tr),Jn=ue.has(String(X.id||"").trim()),ar=Co&&!_u,Mr=re||Jn||!mi,pi=Tr&&!Jn&&!Zn&&!qr,co=!Jn&&!Mr&&(it?_r&&ht===_r:N===xt),Qs=de||(mi?"":qr?"Select a face or edge of this isolated component":it?"":Co?"Exit isolate to select this node":"Select a parent assembly to inspect this node"),ko=Mr&&!(!it&&br&&!re&&(Zn?typeof G=="function":typeof _e=="function")),is=Iee(X,{topologyType:ye,topologyReferenceId:_r,detail:Pa,disabledReason:Qs}),Mo=Math.min(Math.max(X.depth,0)*iE,Zk),uo=$e=>{const ki=$e.shiftKey;it?k?.(_r,{multiSelect:ki}):T?.(xt,{multiSelect:ki})},wc=()=>{if(!Mr){if(it){_r&&Z?.(_r);return}W?.(xt)}},hl=()=>{if(it){_r&&Z?.("");return}Mr||W?.("")},Pi=$e=>{if(Mr){$e.preventDefault();return}uo($e)},Do=$e=>{if(!($e.target!==$e.currentTarget||Mr)){if($e.key==="ArrowDown"){$e.preventDefault(),Pt(At+1,1);return}if($e.key==="ArrowUp"){$e.preventDefault(),Pt(At-1,-1);return}if($e.key==="Home"){$e.preventDefault(),Pt(0,1);return}if($e.key==="End"){$e.preventDefault(),Pt(He.length-1,-1);return}if($e.key==="Enter"||$e.key===" "){$e.preventDefault(),uo($e);return}if(os&&$e.key==="ArrowRight"&&!kn){$e.preventDefault(),$?.(X.id);return}os&&$e.key==="ArrowLeft"&&kn&&($e.preventDefault(),$?.(X.id))}},Ns=Zn?typeof G=="function":typeof J=="function",_s=re||!mi&&!Tr||Jn&&!Tr,Qo=it||re||!Ns||!Zn&&!mi&&!Tr,Dn=!it&&Co&&on.size>1&&typeof Q=="function",$r=it||re||Jn||typeof D!="function",ea=it||re||(Jn?typeof oe!="function":typeof Ie!="function"),tn=it||Zn||!br||typeof _e!="function",Zr=it?[]:yt.map($e=>String($e||"").trim()).filter(Boolean),Rr=it?[]:Array.from(new Set([...Zr,xt].filter(Boolean))),Qn=Rr.map($e=>It.get($e)||null).filter(Boolean),ei=Qn.filter($e=>fe($e)&&!L.has(String($e.id||"").trim())).map($e=>String($e.id||"").trim()).filter(Boolean),Oi=Qn.filter($e=>fe($e)&&L.has(String($e.id||"").trim())).map($e=>String($e.id||"").trim()).filter(Boolean),Pr=Rr.length||1,ti=ei.length<1||typeof $!="function",jo=Oi.length<1||typeof $!="function",Tu=he.length<1||typeof $!="function",Nf=ot.length<1||typeof $!="function",Ru=it?_r:xt;return c.jsxs("div",{className:"relative min-w-0 max-w-full",children:[c.jsx(Nee,{depth:X.depth}),c.jsx("div",{className:"relative flex h-7 min-w-0 max-w-full items-center",style:Mo>0?{marginLeft:`${Mo}px`}:void 0,children:c.jsxs(X1,{modal:!1,children:[c.jsx(Y1,{asChild:!0,children:c.jsxs("div",{ref:$e=>{if($e){De.current.set(X.id,$e),xt&&xt!==X.id&&De.current.set(xt,$e);return}De.current.delete(X.id),xt&&xt!==X.id&&De.current.delete(xt)},role:"treeitem","aria-expanded":os?kn:void 0,"aria-selected":Tr,"aria-label":Xt,"data-step-tree-node-id":X.id||void 0,"data-step-tree-node-type":X.nodeType||void 0,"data-step-tree-topology-reference-id":_r||void 0,"data-selection-disabled":Mr?"true":void 0,"aria-disabled":ko,tabIndex:Mr?-1:0,className:H("group/tree-row flex h-7 min-w-0 w-full max-w-full items-center gap-1 rounded-md px-1 outline-none transition-colors",Mr?"cursor-default text-sidebar-foreground/55":"cursor-pointer text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:bg-sidebar-accent focus-visible:text-sidebar-accent-foreground",pi?"bg-sidebar-accent font-medium text-sidebar-accent-foreground":co&&"bg-sidebar-accent text-sidebar-accent-foreground",(Jn||ar)&&"opacity-45"),title:is,onClick:Pi,onKeyDown:Do,onMouseEnter:wc,onMouseLeave:hl,children:[c.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5 overflow-hidden",children:[os?c.jsx(Qe,{type:"button",variant:"ghost",size:"icon-sm",className:uee,onClick:$e=>{$e.stopPropagation(),$?.(X.id)},"aria-label":kn?`Collapse ${X.label}`:`Expand ${X.label}`,title:kn?"Collapse":"Expand",children:c.jsx(Vd,{className:H("size-3.5 transition-transform",kn&&"rotate-90"),strokeWidth:2,"aria-hidden":"true"})}):null,c.jsxs("div",{className:H(fee,"flex min-w-0 flex-1 shrink touch-manipulation items-center justify-start gap-1.5 overflow-hidden px-0 text-left",Mr&&"text-sidebar-foreground/55"),children:[c.jsx(Tee,{row:X}),c.jsx("span",{className:"min-w-0 flex-1 overflow-hidden",children:c.jsxs("span",{className:"flex min-w-0 items-baseline gap-1.5 overflow-hidden text-xs font-medium leading-4",children:[c.jsx("span",{className:"min-w-0 truncate",children:X.label}),Cr?c.jsx("span",{className:"min-w-0 truncate text-[10px] font-normal text-current/50",children:Cr}):null]})})]})]}),!it&&br?c.jsx(Qe,{type:"button",variant:"ghost",size:"icon-sm",className:H(dee,"ml-1 shrink-0",!Jn&&!pi&&!co&&!Zn&&"opacity-0 group-hover/tree-row:opacity-100 focus-visible:opacity-100",Jn&&"text-current/75",re&&"cursor-default text-current/35 hover:!bg-transparent hover:!text-current/35"),disabled:re||(Zn?typeof G!="function":typeof _e!="function"),"aria-label":Zn?`Exit isolate for ${X.label}`:Jn?`Show ${X.label}`:`Hide ${X.label}`,title:Zn?"Exit isolate":Jn?"Show":"Hide",onClick:$e=>{if($e.stopPropagation(),Zn){G?.(X.id);return}_e?.(X.id)},children:Zn?c.jsx(eh,{className:"size-3",strokeWidth:2,"aria-hidden":"true"}):Jn?c.jsx(rR,{className:"size-3",strokeWidth:1.8,"aria-hidden":"true"}):c.jsx(oR,{className:"size-3",strokeWidth:1.8,"aria-hidden":"true"})}):null]})}),c.jsx(q1,{className:"w-44",children:c.jsx(R1,{Item:el,Separator:Z1,selected:Tr,isolated:Zn,hidden:Jn,actionCount:Pr,copyReferenceDisabled:!Ru||typeof Y!="function",selectDisabled:_s,showIsolate:!it,isolateDisabled:Qo,showExitAllIsolate:Dn,exitAllIsolateDisabled:re||!Dn,showHideOther:!it,hideOtherDisabled:$r,hideAllDisabled:ea,hideAllLabel:"Show all",showVisibility:!it&&!Zn,visibilityDisabled:tn,showHideAll:!1,showExpandCollapse:os||Qn.some($e=>fe($e))||ae.length>0,expandSelectedDisabled:ti,collapseSelectedDisabled:jo,expandAllDisabled:Tu,collapseAllDisabled:Nf,onCopyReference:()=>{Y?.(Ru,{topology:it})},onSelect:$e=>{if(!it&&Tr&&Zr.length>1){ie?.();return}uo($e)},onIsolate:()=>{if(Zn){G?.(X.id);return}J?.(Rr)},onExitAllIsolate:()=>{Q?.()},onHideOther:()=>{D?.(Rr)},onHideAll:()=>{if(Jn){oe?.();return}Ie?.()},onToggleVisibility:()=>{for(const $e of Rr)_e?.($e)},onExpandSelected:()=>{for(const $e of ei)$?.($e)},onCollapseSelected:()=>{for(const $e of Oi)$?.($e)},onExpandAll:()=>{for(const $e of he)$?.($e)},onCollapseAll:()=>{for(const $e of ot)$?.($e)}})})]})})]},X.id)}):null,wr?null:Mt,!Zt&&!s?c.jsx("p",{className:"px-1.5 py-2 text-xs text-[var(--ui-text-muted)]",children:"No assembly tree"}):null,wr?c.jsxs(c.Fragment,{children:[c.jsx("div",{className:k_,role:"presentation",children:"Mates"}),qn.map(X=>{const At=Re.has(X.id),ne=jt===X.id,ye=re||typeof z!="function",it=Aee(X,de),ft=xt=>{z?.(X.id,{multiSelect:xt?.shiftKey===!0})};return c.jsxs(X1,{modal:!1,children:[c.jsx(Y1,{asChild:!0,children:c.jsxs("div",{role:"treeitem","aria-label":[X.label,X.detail].filter(Boolean).join(" "),"aria-selected":At,"aria-disabled":ye,tabIndex:ye?-1:0,className:H("flex h-7 min-w-0 max-w-full items-center gap-1.5 rounded-md px-1 text-xs outline-none transition-colors",ye?"cursor-default text-sidebar-foreground/55":"cursor-pointer text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:bg-sidebar-accent focus-visible:text-sidebar-accent-foreground",At?"bg-sidebar-accent font-medium text-sidebar-accent-foreground":ne&&"bg-sidebar-accent text-sidebar-accent-foreground"),title:it,onClick:xt=>{if(ye){xt.preventDefault();return}ft(xt)},onKeyDown:xt=>{xt.target!==xt.currentTarget||ye||(xt.key==="Enter"||xt.key===" ")&&(xt.preventDefault(),ft(xt))},onMouseEnter:()=>{ye||Ee?.(X.id)},onMouseLeave:()=>{ye||Ee?.("")},children:[c.jsx("span",{className:mee,"aria-hidden":"true",children:c.jsx(O3,{className:"size-3.5",strokeWidth:1.8})}),c.jsx("span",{className:"min-w-0 flex-1 truncate font-medium leading-4",children:X.label})]})}),c.jsx(q1,{className:"w-44",children:c.jsx(R1,{Item:el,Separator:Z1,selected:At,copyReferenceDisabled:!X.id||typeof K!="function",selectDisabled:ye,showIsolate:!1,showHideOther:!1,showVisibility:!1,showHideAll:!1,showExpandCollapse:!1,onCopyReference:()=>{K?.(X.id)},onSelect:ft})})]},X.id)}),Mt]}):null]})})}),Ke||Et==="loading"||Pe?c.jsx(ci,{value:"parameters",title:"Parameters",children:c.jsxs(r0,{children:[Ke?c.jsx(Mi,{label:"Enable",checked:Kt,onCheckedChange:X=>me?.onEnabledChange?.(X),ariaLabel:"Enable STEP module"}):null,Et==="loading"?c.jsx("p",{className:"px-3 py-2 text-xs text-[var(--ui-text-muted)]",children:"Loading STEP module..."}):null,Pe?c.jsx("p",{className:"whitespace-pre-line px-3 py-2 text-xs text-destructive",children:Pe}):null,Ke&&Ne.length?c.jsxs(c.Fragment,{children:[Ne.length>1?c.jsx(cn,{label:"Animation",children:c.jsxs(wa,{value:String(Se.activeId||Ne[0]?.id||""),onValueChange:X=>me?.onAnimationSelect?.(X),disabled:!Kt,children:[c.jsx(va,{size:"sm",className:"h-7 !text-[11px]","aria-label":"STEP animation",children:c.jsx(ac,{})}),c.jsx(Ca,{children:Ne.map(X=>c.jsx(Ma,{value:X.id,children:X.label},X.id))})]})}):null,c.jsx(cn,{children:c.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[c.jsxs(Qe,{type:"button",variant:"outline",size:"sm",className:H(_m,"justify-center"),onClick:()=>me?.onAnimationPlayToggle?.(),disabled:!Kt,children:[Se.playing?c.jsx(VE,{className:"h-3.5 w-3.5",strokeWidth:2,"aria-hidden":"true"}):c.jsx($E,{className:"h-3.5 w-3.5",strokeWidth:2,"aria-hidden":"true"}),c.jsx("span",{children:Se.playing?"Pause":"Play"})]}),c.jsxs(Qe,{type:"button",variant:"outline",size:"sm",className:H(_m,"justify-center"),onClick:()=>me?.onAnimationReset?.(),disabled:!Kt,"aria-label":"Restart STEP animation",title:"Restart",children:[c.jsx(ws,{className:"h-3.5 w-3.5",strokeWidth:2,"aria-hidden":"true"}),c.jsx("span",{children:"Reset"})]})]})}),c.jsx(Pee,{animationState:Se,duration:Yr,enabled:Kt,onScrub:me?.onAnimationScrub}),c.jsx(Ni,{label:"Speed",value:`${j_(Se.speed||1)}x`,onValueCommit:X=>{me?.onAnimationSpeedChange?.(yee(X,Se.speed||1))},valueInputProps:{disabled:!Kt,ariaLabel:"STEP animation speed value"},children:c.jsx(_i,{className:Us,value:[Number(Se.speed)||1],min:Jk,max:Qk,step:.1,onValueChange:X=>me?.onAnimationSpeedChange?.(X?.[0]??1),disabled:!Kt,"aria-label":"STEP animation speed"})})]}):null,Ke&&!en.length?c.jsx("p",{className:"px-3 py-2 text-xs text-[var(--ui-text-muted)]",children:"No module parameters."}):null,en.map(X=>{const At=En?.[X.id]??X.defaultValue,ne=see(X);return X.type==="boolean"?c.jsx(Mi,{label:X.label,checked:At===!0,onCheckedChange:ye=>me?.onParameterChange?.(X.id,ye),disabled:!Kt,ariaLabel:X.label},X.id):X.type==="enum"?c.jsx(cn,{label:X.label,children:c.jsxs(wa,{value:String(At??""),onValueChange:ye=>me?.onParameterChange?.(X.id,ye),disabled:!Kt,children:[c.jsx(va,{size:"sm",className:"h-7 !text-[11px]","aria-label":X.label,children:c.jsx(ac,{})}),c.jsx(Ca,{children:X.options.map(ye=>c.jsx(Ma,{value:ye.value,children:ye.label},ye.value))})]})},X.id):X.type==="color"?c.jsx(cn,{label:X.label,trailing:c.jsx(yv,{value:String(At||"#ffffff"),onChange:ye=>me?.onParameterChange?.(X.id,ye),disabled:!Kt,className:H(cee,"w-fit justify-start gap-1.5 px-1.5"),swatchClassName:"size-3.5",popoverAlign:"end","aria-label":X.label})},X.id):X.type==="button"?c.jsx(cn,{children:c.jsx(Qe,{type:"button",variant:"outline",size:"sm",className:H(_m,"w-full justify-center"),onClick:()=>me?.onParameterChange?.(X.id,Number(At||0)+1),disabled:!Kt,children:X.label})},X.id):c.jsx(Ni,{label:X.label,value:`${j_(At)}${X.unit?` ${X.unit}`:""}`,onValueCommit:ye=>{me?.onParameterChange?.(X.id,ui(ye,{fallback:At,min:X.min,max:X.max}))},valueInputProps:{disabled:!Kt,ariaLabel:`${X.label} slider value`},children:c.jsx(_i,{className:Us,value:[Number(At)||0],min:X.min,max:X.max,step:ne,onValueChange:ye=>me?.onParameterChange?.(X.id,ye?.[0]??At),disabled:!Kt,"aria-label":X.label})},X.id)}),Ke&&en.length?c.jsx(cn,{className:"pt-2",children:c.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[c.jsxs(Qe,{type:"button",variant:"outline",size:"sm",className:H(_m,"justify-center"),onClick:()=>{me?.onCopyParams?.()},title:"Copy STEP parameter JSON",children:[c.jsx(vu,{className:"h-3.5 w-3.5",strokeWidth:2,"aria-hidden":"true"}),c.jsx("span",{children:"Copy parameters"})]}),c.jsxs(Qe,{type:"button",variant:"outline",size:"sm",className:H(_m,"justify-center"),onClick:()=>{me?.onPasteParams?.()},title:"Paste STEP parameter JSON",children:[c.jsx(cR,{className:"h-3.5 w-3.5",strokeWidth:2,"aria-hidden":"true"}),c.jsx("span",{children:"Paste parameters"})]})]})}):null]})}):null,St,c.jsx(Ef,{entry:i,fileDownloadAvailable:se,viewerServerInfo:Ae,localFileOpenAvailable:we,fileAccessBusyKey:ct,onOpenFileAsset:ut,suppressDynamicStatus:Tt})]})}):null}function kee({...e}){return c.jsx(b3,{"data-slot":"toast-provider",...e})}function Dee({className:e,...t}){return c.jsx(y3,{"data-slot":"toast",className:H("cad-glass-popover pointer-events-auto rounded-md border border-border px-4 py-2.5 text-xs font-medium text-popover-foreground shadow-lg shadow-black/10 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-right-2 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:slide-in-from-top-2",e),...t})}function jee({...e}){return c.jsx(x3,{"data-slot":"toast-title",...e})}function Lee({className:e,...t}){return c.jsx(S3,{"data-slot":"toast-viewport",className:H("fixed right-4 top-4 z-50 flex max-h-screen w-[min(calc(100vw-2rem),22rem)] flex-col gap-2 outline-none",e),...t})}function Fee({copyStatus:e,screenshotStatus:t,persistenceStatus:n,motionErrorStatus:r,previewMode:o,onClear:i}){const s=r||e||t||n,a=!!r;return!s||o?null:c.jsxs(kee,{duration:2200,swipeDirection:"right",children:[c.jsx(Dee,{open:!0,className:a?"border-destructive/40 text-destructive":void 0,onOpenChange:l=>{l||i?.()},children:c.jsx(jee,{children:s})}),c.jsx(Lee,{})]})}const Ho=Nu,ks=n0,fd=uh,zee=.001,Bee=3500;function F_(e,t){return Math.abs(Number(e)-Number(t))<=zee}function Iy(e){const t=String(e?.type||"").trim().toLowerCase();return t==="continuous"||t==="revolute"}function Vee(e){return Iy(e)?"deg":"m"}function dS(e,t){const n=Iy(t)?10:1e4,r=Math.round(Number(e)*n)/n,o=Number.isFinite(r)?r:0;return Iy(t)?`${o}°`:`${o} m`}function fS(e,t="0"){const n=Number(e);if(!Number.isFinite(n))return t;const r=Math.round(n*1e3)/1e3;return String(Object.is(r,-0)?0:r)}function mS(e){const t=Number(e);if(!Number.isFinite(t))return"";const n=Math.round(t*1e4)/1e4;return String(Object.is(n,-0)?0:n)}function $ee(e,t){return!Array.isArray(e)||!Array.isArray(t)||e.length<3||t.length<3?!1:[0,1,2].every(n=>Math.abs(Number(e[n])-Number(t[n]))<=5e-4)}function nb(e,t,n,r){const o=Number.isFinite(Number(e))?Number(e):r;return Math.min(Math.max(o,t),Math.max(t,n))}const Gee=f.memo(function({joint:t,valueDeg:n,onValueChange:r}){const o=String(t?.name||"").trim(),i=Number.isFinite(Number(t?.minValueDeg))?Number(t.minValueDeg):-180,s=Number.isFinite(Number(t?.maxValueDeg))?Number(t.maxValueDeg):180,a=nb(n,i,s,0),l=Vee(t),u=Iy(t)?1:.001,d=f.useRef(0),m=f.useRef(a),p=f.useRef(a),g=f.useRef(!1),x=f.useRef(0),[y,S]=f.useState(a),b=()=>{x.current&&typeof window<"u"&&window.clearTimeout(x.current),x.current=0},I=(R=p.current)=>{b(),g.current=!1;const v=nb(R,i,s,p.current);m.current=v,S(v)},A=R=>{m.current=R,g.current=!0,b(),typeof window<"u"&&(x.current=window.setTimeout(()=>{I()},Bee))};f.useEffect(()=>{if(p.current=a,g.current){F_(a,m.current)&&I(a);return}m.current=a,S(a)},[a]),f.useEffect(()=>()=>{d.current&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(d.current),b()},[]);const N=(R,v={})=>{if(m.current=R,typeof requestAnimationFrame!="function"){r(t,R,v);return}d.current||(d.current=requestAnimationFrame(()=>{d.current=0,r(t,m.current,v)}))},P=(R,v={})=>{const C=nb(R,i,s,y);m.current=C,d.current&&typeof cancelAnimationFrame=="function"&&(cancelAnimationFrame(d.current),d.current=0),S(C),A(C),r(t,C,v)};return c.jsx(Ni,{label:o||"Joint",value:dS(y,t),onValueCommit:R=>{P(ui(R,{fallback:y,min:i,max:s}))},valueInputProps:{ariaLabel:`${o||"Joint"} value in ${l}`},children:c.jsx(_i,{className:H(Us,"min-w-0"),min:i,max:s,step:u,value:[y],onValueChange:R=>{const v=nb(R?.[0],i,s,y);F_(v,m.current)||(S(v),A(v),N(v,{scrub:!0}))},onValueCommit:R=>{P(R?.[0],{scrub:!0})},"aria-label":o||"Joint value",title:`${dS(i,t)} to ${dS(s,t)}`})})}),Uee=f.memo(function({axis:t,value:n,disabled:r,onValueChange:o}){const i=Number.isFinite(Number(n))?Number(n):0,[s,a]=f.useState(()=>mS(i));f.useEffect(()=>{a(mS(i))},[i]);const l=u=>{const d=Number(u),m=Number.isFinite(d)?d:i;a(mS(m)),o?.(m)};return c.jsxs("label",{className:"block min-w-0",children:[c.jsx("span",{className:Ho,children:t}),c.jsx(go,{type:"number",step:"0.001",inputMode:"decimal",disabled:r,value:s,onChange:u=>{a(u.target.value)},onFocus:u=>{u.currentTarget.select()},onMouseUp:u=>{u.preventDefault()},onBlur:()=>{l(s)},onKeyDown:u=>{u.key==="Enter"&&u.currentTarget.blur()},className:`${ks} mt-1 text-right`,"aria-label":`Target ${t} coordinate`})]})});function Wo({label:e,value:t}){const n=String(t??"");return c.jsxs("div",{className:"block min-w-0",children:[c.jsx("span",{className:Ho,children:e}),c.jsx("div",{className:"mt-1 min-h-7 truncate rounded-md border border-border/70 bg-muted/25 px-2 py-1.5 text-[11px] font-medium leading-4 text-foreground",title:n,children:n})]})}function Wee(e,t){return!e||typeof e!="object"?"":t.map(n=>String(e?.[n]||"").trim()).filter(Boolean).join(" / ")}function Tm({title:e,items:t,fields:n}){const r=Array.isArray(t)?t.map(o=>Wee(o,n)).filter(Boolean):[];return r.length?c.jsxs("div",{className:"space-y-1.5 rounded-md border border-border/80 bg-background/40 p-3",children:[c.jsx("span",{className:Ho,children:e}),c.jsxs("div",{className:"space-y-1",children:[r.slice(0,5).map((o,i)=>c.jsx("div",{className:"truncate text-[11px] font-medium leading-4 text-foreground",title:o,children:o},`${e}:${i}`)),r.length>5?c.jsxs("div",{className:"text-xs text-muted-foreground",children:[r.length-5," more"]}):null]})]}):null}function Hee({open:e,title:t="URDF",sourceFormat:n="urdf",showJoints:r=!0,showMotion:o=!0,isDesktop:i,width:s,selectedEntry:a=null,onOpenChange:l,onStartResize:u,joints:d,groupStates:m,activeGroupStateId:p,jointValues:g,onJointValueChange:x,onGroupStateSelect:y,onCopyJointAngles:S,onResetPose:b,motion:I=null,sdf:A=null,fileDownloadAvailable:N=!1,viewerServerInfo:P=null,localFileOpenAvailable:R=!1,fileAccessBusyKey:v="",onOpenFileAsset:C,suppressDynamicMetadataStatus:T=!1,statusItems:k=[],themeSections:z=null,openSectionIds:Y=[],onOpenSectionIdsChange:K}){const J=String(n||"").trim().toLowerCase()==="sdf",G=Array.isArray(d)?d:[],Q=Array.isArray(m)?m:[],D=A?.info&&typeof A.info=="object"?A.info:{},$=D.staticMetadata&&typeof D.staticMetadata=="object"?D.staticMetadata:{},ie=Array.isArray($.includes)?$.includes:[],W=Array.isArray($.plugins)?$.plugins:[],Z=Array.isArray($.sensors)?$.sensors:[],Ee=Array.isArray($.lights)?$.lights:[],re=Array.isArray($.physics)?$.physics:[],be=Number.isFinite(Number($.nestedModelCount))?Number($.nestedModelCount):0,_e=!!(ie.length||W.length||Z.length||Ee.length||re.length),Ie=Array.isArray(I?.endEffectors)?I.endEffectors:[],oe=Array.isArray(I?.planningGroups)?I.planningGroups:[],me=Array.isArray(I?.targetFrames)?I.targetFrames:[],se=o&&I?.serverLive===!0&&Ie.length>0,Ae=String(I?.activeEndEffectorName||Ie[0]?.name||"").trim(),we=String(I?.activePlanningGroupName||oe[0]?.name||"").trim(),ct=String(I?.activeTargetFrameName||me[0]||"").trim(),ut=Array.isArray(I?.targetPosition)?I.targetPosition:[0,0,0],Tt=Array.isArray(I?.currentPosition)?I.currentPosition:null,Ve=I?.moveit2&&typeof I.moveit2=="object"?I.moveit2:{},St=!!I?.solving,wt=I?.actionsEnabled!==!1,Vn=I?.serverLive?"connected":"offline",De=!!I?.selectPoseActive,xe=Tt?$ee(ut,Tt):!0,yt=Q.some(Re=>String(Re?.id||"").trim()===p)?p:"__custom__",Te=Q.find(Re=>String(Re?.id||"").trim()===yt),rt=yt==="__custom__"?"custom":String(Te?.label||Te?.name||yt);return c.jsx(xf,{open:e,title:t,isDesktop:i,width:s,onOpenChange:l,onStartResize:u,children:c.jsxs(yf,{type:"multiple",value:Y,onValueChange:K,children:[c.jsx(wf,{items:k}),J?c.jsx(ci,{value:"sdf",title:"SDF",children:c.jsxs("div",{children:[c.jsx(bo,{title:"Document",contentClassName:"px-3",children:c.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[c.jsx(Wo,{label:"Version",value:String(D.version||"unknown")}),c.jsx(Wo,{label:"Document",value:String(D.documentKind||"model")}),D.worldName?c.jsx(Wo,{label:"World",value:String(D.worldName)}):null,c.jsx(Wo,{label:"Frame mode",value:D.nativeFrameSemantics?"native":"compat"}),c.jsx(Wo,{label:"Root link",value:String(D.rootLink||"")}),c.jsx(Wo,{label:"Model",value:String(D.modelName||t||"model")})]})}),c.jsx(bo,{title:"Counts",contentClassName:"px-3",children:c.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[c.jsx(Wo,{label:"Links",value:String(D.linkCount??G.length)}),c.jsx(Wo,{label:"Joints",value:String(D.jointCount??d?.length??0)}),c.jsx(Wo,{label:"Frames",value:String(D.frameCount??0)}),c.jsx(Wo,{label:"Includes",value:String(ie.length)}),c.jsx(Wo,{label:"Plugins",value:String(W.length)}),c.jsx(Wo,{label:"Sensors",value:String(Z.length)}),c.jsx(Wo,{label:"Lights",value:String(Ee.length)}),c.jsx(Wo,{label:"Physics",value:String(re.length)}),c.jsx(Wo,{label:"Nested models",value:fS(be)}),c.jsx(Wo,{label:"Unsupported geom.",value:`${fS(D.unsupportedVisualCount)} / ${fS(D.unsupportedCollisionCount)}`})]})}),_e?c.jsxs(bo,{title:"Metadata",contentClassName:"px-3",children:[c.jsx(Tm,{title:"Includes",items:ie,fields:["name","uri"]}),c.jsx(Tm,{title:"Plugins",items:W,fields:["name","filename"]}),c.jsx(Tm,{title:"Sensors",items:Z,fields:["name","type"]}),c.jsx(Tm,{title:"Lights",items:Ee,fields:["name","type"]}),c.jsx(Tm,{title:"Physics",items:re,fields:["name","type","default"]})]}):null]})}):null,se?c.jsx(ci,{value:"motion",title:"MoveIt2",children:c.jsxs("div",{children:[c.jsx(bo,{title:"Status",children:c.jsx(cn,{children:c.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[c.jsxs("label",{className:"block min-w-0",children:[c.jsx("span",{className:Ho,children:"SRDF"}),c.jsx(go,{value:I?.srdf?.srdf||I?.srdf?.srdfHash||"linked",readOnly:!0,disabled:!0,className:`${ks} mt-1`,"aria-label":"SRDF status"})]}),c.jsxs("label",{className:"block min-w-0",children:[c.jsx("span",{className:Ho,children:"MoveIt2 server"}),c.jsx(go,{value:Vn,readOnly:!0,disabled:!0,className:`${ks} mt-1`,"aria-label":"MoveIt2 server status"})]})]})})}),c.jsxs(bo,{title:"Target",children:[c.jsx(cn,{children:c.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[c.jsxs("label",{className:"block min-w-0",children:[c.jsx("span",{className:Ho,children:"Planning group"}),c.jsxs(wa,{value:we,disabled:St||oe.length<=1,onValueChange:Re=>{I?.onMoveIt2SettingChange?.("activePlanningGroupName",Re)},children:[c.jsx(va,{size:"sm",className:"mt-1 h-7 !text-[11px]",children:c.jsx(ac,{placeholder:"Select group"})}),c.jsx(Ca,{children:oe.map(Re=>{const Fe=String(Re?.name||"").trim();return Fe?c.jsx(Ma,{value:Fe,children:Fe},Fe):null})})]})]}),c.jsxs("label",{className:"block min-w-0",children:[c.jsx("span",{className:Ho,children:"End effector"}),c.jsxs(wa,{value:Ae,disabled:St||Ie.length<=1,onValueChange:Re=>{I?.onEndEffectorChange?.(Re)},children:[c.jsx(va,{size:"sm",className:"mt-1 h-7 !text-[11px]",children:c.jsx(ac,{placeholder:"Select end effector"})}),c.jsx(Ca,{children:Ie.map(Re=>{const Fe=String(Re?.name||"").trim();return Fe?c.jsx(Ma,{value:Fe,children:Fe},Fe):null})})]})]}),c.jsxs("label",{className:"block min-w-0",children:[c.jsx("span",{className:Ho,children:"Target frame"}),c.jsxs(wa,{value:ct,disabled:St||me.length<=1,onValueChange:Re=>{I?.onMoveIt2SettingChange?.("targetFrame",Re)},children:[c.jsx(va,{size:"sm",className:"mt-1 h-7 !text-[11px]",children:c.jsx(ac,{placeholder:"Select frame"})}),c.jsx(Ca,{children:me.map(Re=>{const Fe=String(Re||"").trim();return Fe?c.jsx(Ma,{value:Fe,children:Fe},Fe):null})})]})]})]})}),c.jsx(cn,{children:c.jsx("div",{className:"grid grid-cols-3 gap-2",children:["X","Y","Z"].map((Re,Fe)=>c.jsx(Uee,{axis:Re,value:ut[Fe],disabled:St,onValueChange:on=>{I?.onTargetPositionChange?.(Fe,on)}},Re))})})]}),c.jsx(bo,{title:"Solver",children:c.jsx(cn,{children:c.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[c.jsxs("label",{className:"block min-w-0",children:[c.jsx("span",{className:Ho,children:"IK timeout"}),c.jsx(go,{type:"number",step:"0.01",min:"0.001",value:Ve.ikTimeout??.05,disabled:St,onChange:Re=>I?.onMoveIt2SettingChange?.("ikTimeout",Re.target.value),className:`${ks} mt-1 text-right`})]}),c.jsxs("label",{className:"block min-w-0",children:[c.jsx("span",{className:Ho,children:"IK attempts"}),c.jsx(go,{type:"number",step:"1",min:"1",value:Ve.ikAttempts??1,disabled:St,onChange:Re=>I?.onMoveIt2SettingChange?.("ikAttempts",Re.target.value),className:`${ks} mt-1 text-right`})]}),c.jsxs("label",{className:"block min-w-0",children:[c.jsx("span",{className:Ho,children:"Tolerance"}),c.jsx(go,{type:"number",step:"0.001",min:"0.0001",value:Ve.ikTolerance??.002,disabled:St,onChange:Re=>I?.onMoveIt2SettingChange?.("ikTolerance",Re.target.value),className:`${ks} mt-1 text-right`})]})]})})}),c.jsxs(bo,{title:"Planning",children:[c.jsx(cn,{children:c.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[c.jsxs("label",{className:"block min-w-0",children:[c.jsx("span",{className:Ho,children:"Planning pipeline"}),c.jsx(go,{value:Ve.planningPipeline??"ompl",disabled:St,onChange:Re=>I?.onMoveIt2SettingChange?.("planningPipeline",Re.target.value),className:`${ks} mt-1`})]}),c.jsxs("label",{className:"block min-w-0",children:[c.jsx("span",{className:Ho,children:"Planner ID"}),c.jsx(go,{value:Ve.plannerId??"RRTConnectkConfigDefault",disabled:St,onChange:Re=>I?.onMoveIt2SettingChange?.("plannerId",Re.target.value),className:`${ks} mt-1`})]})]})}),c.jsx(cn,{children:c.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[c.jsxs("label",{className:"block min-w-0",children:[c.jsx("span",{className:Ho,children:"Plan time"}),c.jsx(go,{type:"number",step:"0.1",min:"0.1",value:Ve.planningTime??1,disabled:St,onChange:Re=>I?.onMoveIt2SettingChange?.("planningTime",Re.target.value),className:`${ks} mt-1 text-right`})]}),c.jsxs("label",{className:"block min-w-0",children:[c.jsx("span",{className:Ho,children:"Velocity"}),c.jsx(go,{type:"number",step:"0.05",min:"0.01",max:"1",value:Ve.maxVelocityScalingFactor??1,disabled:St,onChange:Re=>I?.onMoveIt2SettingChange?.("maxVelocityScalingFactor",Re.target.value),className:`${ks} mt-1 text-right`})]}),c.jsxs("label",{className:"block min-w-0",children:[c.jsx("span",{className:Ho,children:"Acceleration"}),c.jsx(go,{type:"number",step:"0.05",min:"0.01",max:"1",value:Ve.maxAccelerationScalingFactor??1,disabled:St,onChange:Re=>I?.onMoveIt2SettingChange?.("maxAccelerationScalingFactor",Re.target.value),className:`${ks} mt-1 text-right`})]})]})})]}),c.jsx(bo,{title:"Actions",children:c.jsx(cn,{children:c.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[c.jsx(Qe,{type:"button",variant:De?"secondary":"outline",size:"sm",className:fd,disabled:St||!wt,onClick:()=>{if(De){I?.onCancelSelectPose?.();return}I?.onSelectPose?.()},"aria-pressed":De,children:c.jsx("span",{children:"Select Pose"})}),xe?null:c.jsx(Qe,{type:"button",variant:"outline",size:"sm",className:fd,disabled:St,onClick:()=>{I?.onUseCurrentPosition?.()},children:c.jsx("span",{children:"Reset"})}),c.jsx(Qe,{type:"button",variant:"default",size:"sm",className:fd,disabled:St||!wt||xe,onClick:()=>{I?.onSolve?.()},children:c.jsx("span",{children:St?"Solving...":"Solve pose"})}),c.jsx(Qe,{type:"button",variant:"default",size:"sm",className:fd,disabled:St||!wt||xe,onClick:()=>{I?.onPlan?.()},children:c.jsx("span",{children:St?"Planning...":"Plan to pose"})})]})})})]})}):null,r?c.jsx(ci,{value:"joints",title:"Joints",children:G.length?c.jsxs(c.Fragment,{children:[c.jsxs(bo,{title:"Controls",children:[Q.length?c.jsx(cn,{label:"Group state",children:c.jsxs(wa,{value:yt,onValueChange:Re=>{if(Re==="__custom__")return;const Fe=Q.find(on=>String(on?.id||"").trim()===Re);Fe&&y?.(Fe)},children:[c.jsx(va,{size:"sm",className:"h-7 !text-[11px]",children:c.jsx("span",{className:"truncate",children:rt})}),c.jsx(Ca,{children:Q.map(Re=>{const Fe=String(Re?.id||"").trim(),on=String(Re?.label||Re?.name||"").trim()||"State";return c.jsx(Ma,{value:Fe,children:on},Fe)})})]})}):null,c.jsx(cn,{children:c.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[c.jsxs(Qe,{type:"button",variant:"outline",size:"sm",className:fd,onClick:b,children:[c.jsx(ws,{className:"h-3.5 w-3.5",strokeWidth:2,"aria-hidden":"true"}),c.jsx("span",{children:"Reset pose"})]}),c.jsxs(Qe,{type:"button",variant:"outline",size:"sm",className:fd,onClick:()=>{S?.()},children:[c.jsx(vu,{className:"h-3.5 w-3.5",strokeWidth:2,"aria-hidden":"true"}),c.jsx("span",{children:J?"Copy values":"Copy angles"})]})]})})]}),c.jsx(bo,{title:"Values",children:G.map(Re=>c.jsx(Gee,{joint:Re,valueDeg:g?.[Re.name]??Re?.defaultValueDeg??0,onValueChange:x},Re.name))})]}):c.jsx("p",{className:"px-3 py-2 text-xs text-muted-foreground",children:"No movable joints are available."})}):null,z,c.jsx(Ef,{entry:a,fileDownloadAvailable:N,viewerServerInfo:P,localFileOpenAvailable:R,fileAccessBusyKey:v,onOpenFileAsset:C,suppressDynamicStatus:T})]})})}function Kee({command:e}){const t=String(e||"").trim(),[n,r]=f.useState(!1),[o,i]=f.useState("");if(f.useEffect(()=>{r(!1),i("")},[t]),f.useEffect(()=>{if(!n)return;const a=globalThis.setTimeout(()=>r(!1),1600);return()=>globalThis.clearTimeout(a)},[n]),!t)return null;async function s(){try{await ps(t),r(!0),i("")}catch(a){r(!1),i(a instanceof Error?a.message:"Copy failed")}}return c.jsxs("div",{className:"mt-3 min-w-0 max-w-full",children:[c.jsxs("div",{className:"flex w-full min-w-0 max-w-full items-center gap-2 rounded-md bg-muted px-2.5 py-2",children:[c.jsx("code",{className:"block min-w-0 flex-1 truncate text-xs leading-5 text-foreground",title:t,children:t}),c.jsx(Qe,{type:"button",variant:"ghost",size:"icon-xs",className:"shrink-0 text-muted-foreground hover:text-foreground",onClick:s,"aria-label":n?"Copied rebuild command":"Copy rebuild command",title:n?"Copied":"Copy rebuild command",children:n?c.jsx(mu,{className:"size-3.5","aria-hidden":"true"}):c.jsx(vu,{className:"size-3.5","aria-hidden":"true"})})]}),o?c.jsx("p",{className:"mt-1 text-xs text-destructive",children:o}):null]})}function Xee({viewerAlertOpen:e,viewerAlert:t,previewMode:n,setViewerAlertOpen:r}){if(!t||n)return null;const o=t.severity==="warning",i=!!t.compact;return c.jsx(Ak,{open:e,onOpenChange:r,children:c.jsxs(Nk,{className:i?"max-w-sm":"max-w-md",children:[c.jsxs(_k,{children:[c.jsx(Ls,{variant:o?"warning":"destructive",className:"mb-1",children:o?"Warning":"Error"}),c.jsx(Rk,{children:t.title}),c.jsxs(Pk,{className:i?"leading-5 whitespace-pre-line":"space-y-3 leading-6",children:[c.jsx("span",{className:"block",children:t.message}),!i&&t.resolution?c.jsx("span",{className:"block text-muted-foreground/80",children:t.resolution}):null]})]}),c.jsx(Kee,{command:t.command}),c.jsx(Tk,{children:c.jsx(Ok,{"aria-label":"Close alert dialog",children:"Close"})})]})})}const nD=Object.freeze(["Accomplishing","Actioning","Actualizing","Architecting","Baking","Beaming","Beboppin'","Befuddling","Billowing","Blanching","Bloviating","Boogieing","Boondoggling","Booping","Bootstrapping","Brewing","Bunning","Burrowing","Calculating","Canoodling","Caramelizing","Cascading","Catapulting","Cerebrating","Channeling","Channelling","Choreographing","Churning","Coalescing","Cogitating","Combobulating","Composing","Computing","Concocting","Considering","Contemplating","Cooking","Crafting","Creating","Crunching","Crystallizing","Cultivating","Deciphering","Deliberating","Determining","Dilly-dallying","Discombobulating","Doing","Doodling","Drizzling","Ebbing","Effecting","Elucidating","Embellishing","Enchanting","Envisioning","Evaporating","Fermenting","Fiddle-faddling","Finagling","Flambéing","Flibbertigibbeting","Flowing","Flummoxing","Fluttering","Forging","Forming","Frolicking","Frosting","Gallivanting","Galloping","Garnishing","Generating","Gesticulating","Germinating","Gitifying","Grooving","Gusting","Harmonizing","Hashing","Hatching","Herding","Honking","Hullaballooing","Hyperspacing","Ideating","Imagining","Improvising","Incubating","Inferring","Infusing","Ionizing","Jitterbugging","Julienning","Kneading","Leavening","Levitating","Lollygagging","Manifesting","Marinating","Meandering","Metamorphosing","Misting","Moonwalking","Moseying","Mulling","Mustering","Musing","Nebulizing","Nesting","Newspapering","Noodling","Nucleating","Orbiting","Orchestrating","Osmosing","Perambulating","Percolating","Perusing","Philosophising","Photosynthesizing","Pollinating","Pondering","Pontificating","Pouncing","Precipitating","Prestidigitating","Processing","Proofing","Propagating","Puttering","Puzzling","Quantumizing","Razzle-dazzling","Razzmatazzing","Recombobulating","Reticulating","Roosting","Ruminating","Sautéing","Scampering","Schlepping","Scurrying","Seasoning","Shenaniganing","Shimmying","Simmering","Skedaddling","Sketching","Slithering","Smooshing","Sock-hopping","Spelunking","Spinning","Sprouting","Stewing","Sublimating","Swirling","Swooping","Symbioting","Synthesizing","Tempering","Thinking","Thundering","Tinkering","Tomfoolering","Topsy-turvying","Transfiguring","Transmuting","Twisting","Undulating","Unfurling","Unravelling","Vibing","Waddling","Wandering","Warping","Whatchamacalliting","Whirlpooling","Whirring","Whisking","Wibbling","Working","Wrangling","Zesting","Zigzagging"]);function z_(){const e=[...nD];for(let t=e.length-1;t>0;t-=1){const n=Math.floor(Math.random()*(t+1));[e[t],e[n]]=[e[n],e[t]]}return e}function Yee({viewerLoading:e,previewMode:t}){const[n,r]=f.useState(()=>z_()),[o,i]=f.useState(0),[s,a]=f.useState(0),[l,u]=f.useState(0),d=["|","/","-","\\"],m=["",".","..","..."];if(f.useEffect(()=>{if(!e||t)return;const y=z_();r(y),i(0),a(0),u(0);const S=window.setInterval(()=>{i(A=>(A+1)%y.length)},900),b=window.setInterval(()=>{a(A=>(A+1)%d.length)},90),I=window.setInterval(()=>{u(A=>(A+1)%m.length)},360);return()=>{window.clearInterval(S),window.clearInterval(b),window.clearInterval(I)}},[t,e]),!e||t)return null;const p=n[o]||nD[0],g=d[s],x=m[l];return c.jsxs("div",{className:"pointer-events-none absolute inset-0 z-20 overflow-hidden",children:[c.jsx("div",{className:"cad-loading-overlay absolute inset-0"}),c.jsx("div",{className:"absolute inset-0 flex items-center justify-center px-4",children:c.jsxs("div",{role:"status","aria-live":"polite",className:"cad-loading-ascii relative z-10 max-w-[min(90vw,38rem)] text-center font-mono text-sm text-popover-foreground",children:[c.jsx("span",{className:"sr-only",children:p}),c.jsxs("span",{className:"inline-flex w-[24ch] items-start justify-start text-left sm:w-[26ch]",children:[c.jsx("span",{className:"inline-block w-[2ch]",children:g}),c.jsx("span",{className:"inline-block w-[1ch]",children:" "}),c.jsx("span",{children:p}),c.jsx("span",{className:"inline-block w-[3ch]",children:x})]})]})})]})}const qee="w-[min(15rem,calc(100vw-2rem))]";function Zee({className:e,children:t}){return c.jsx("div",{className:H("cad-glass-surface pointer-events-auto flex min-h-0 flex-col overflow-hidden rounded-md border border-sidebar-border text-sidebar-foreground shadow-sm",e),children:t})}function ga({label:e,active:t=!1,tooltipSide:n="bottom",className:r,children:o,...i}){return c.jsxs(KE,{children:[c.jsx(XE,{asChild:!0,children:c.jsx(Qe,{type:"button",variant:t?"secondary":"ghost",size:"icon-xs",className:H("size-6 rounded-sm text-sidebar-foreground/70 shadow-none transition hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 focus-visible:ring-ring/45 data-[variant=secondary]:bg-sidebar-accent data-[variant=secondary]:text-sidebar-accent-foreground data-[variant=secondary]:hover:bg-sidebar-accent",r),"aria-label":e,...i,children:o})}),c.jsx(YE,{side:n,sideOffset:6,children:e})]})}function Jee({className:e,layout:t="wrap",drawingToolOptions:n,drawingTool:r,handleSelectDrawingTool:o,handleUndoDrawing:i,handleRedoDrawing:s,handleClearDrawings:a,canUndoDrawing:l,canRedoDrawing:u,drawingStrokes:d}){const m=i,p=s,g=a,x=l,y=u,S=d.length,b=t==="scroll",I=c.jsxs("div",{className:H("flex gap-1",b?"w-max min-w-full flex-nowrap":"flex-wrap"),children:[n.map(({id:A,label:N,Icon:P})=>{const R=r===A;return c.jsx(ga,{label:N,active:R,"aria-pressed":R,onClick:()=>o(A),children:c.jsx(P,{className:"size-3.5",strokeWidth:2,"aria-hidden":"true"})},A)}),c.jsx(ga,{label:"Undo",onClick:m,disabled:!x,children:c.jsx(k3,{className:"size-3.5",strokeWidth:2,"aria-hidden":"true"})}),c.jsx(ga,{label:"Redo",onClick:p,disabled:!y,children:c.jsx(D3,{className:"size-3.5",strokeWidth:2,"aria-hidden":"true"})}),c.jsx(ga,{label:"Clear all",onClick:g,disabled:!S,children:c.jsx(sR,{className:"size-3.5",strokeWidth:2,"aria-hidden":"true"})})]});return c.jsx(Zee,{className:H("p-1.5",e),children:c.jsx(By,{delayDuration:250,children:b?c.jsx(ch,{className:"min-w-0 max-w-full",type:"auto",scrollbars:"horizontal",children:I}):I})})}const aE=Object.freeze([Object.freeze({value:yo.ORTHOGRAPHIC,label:"Orthographic projection",title:"Switch to orthographic projection",Icon:jk}),Object.freeze({value:yo.PERSPECTIVE,label:"Perspective projection",title:"Switch to perspective projection",Icon:xv})]);function Qee(e){const t=ul(e);return aE.find(n=>n.value===t)||aE[0]}function B_(e){return String(e?.label||"").replace(/\s+projection$/i,"")||"Perspective"}function ete({displayMode:e,onDisplayModeChange:t,projection:n,onProjectionChange:r,open:o=!1,onOpenChange:i,triggerClassName:s,iconClassName:a="size-3",contentAlign:l="start",contentSide:u="bottom",contentSideOffset:d=6}){const m=typeof t=="function",p=typeof r=="function",g=Dk(e),x=Qee(n),y=x.Icon||xv,S=`Display and projection: ${g?.label||"Solid"}, ${B_(x)}`;return c.jsxs(hf,{open:o,onOpenChange:i,children:[c.jsx(gf,{asChild:!0,children:c.jsxs("button",{type:"button","aria-label":S,className:s,onPointerDown:b=>{b.stopPropagation()},children:[c.jsx(y,{className:a,strokeWidth:2,"aria-hidden":"true"}),c.jsx("span",{className:"sr-only",children:S})]})}),c.jsxs(bf,{align:l,side:u,sideOffset:d,className:"w-44",children:[p?c.jsxs(c.Fragment,{children:[c.jsx(T1,{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"Projection"}),aE.map(b=>{const I=b.Icon,A=x.value===b.value;return c.jsxs(Yo,{className:"text-xs",onSelect:()=>{r?.(b.value)},children:[c.jsx(I,{className:"size-3 text-muted-foreground",strokeWidth:2,"aria-hidden":"true"}),B_(b),A?c.jsx(mu,{className:"ml-auto size-3.5 text-popover-foreground",strokeWidth:2,"aria-hidden":"true"}):c.jsx("span",{className:"ml-auto size-3.5","aria-hidden":"true"})]},b.value)})]}):null,m&&p?c.jsx(nu,{}):null,m?c.jsxs(c.Fragment,{children:[c.jsx(T1,{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"Display"}),Cy.map(b=>{const I=g.value===b.value;return c.jsxs(Yo,{className:"text-xs",onSelect:()=>{t?.(b.value)},children:[b.label,I?c.jsx(mu,{className:"ml-auto size-3.5 text-popover-foreground",strokeWidth:2,"aria-hidden":"true"}):c.jsx("span",{className:"ml-auto size-3.5","aria-hidden":"true"})]},b.value)})]}):null]})]})}const tte="cad-glass-surface border border-sidebar-border text-sidebar-foreground shadow-sm",nte="grid size-6 shrink-0 place-items-center rounded-sm text-sidebar-foreground/70 shadow-none transition hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/45 disabled:pointer-events-none disabled:opacity-50 data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground";function rte({renderFormat:e,floatingCadToolbarPosition:t,selectionToolActive:n,referenceSelectionPending:r=!1,referenceSelectionUnavailable:o=!1,referenceSelectionDeferred:i=!1,urdfPosePickerAvailable:s=!1,urdfPosePickerActive:a=!1,handleToggleUrdfPosePicker:l,stepAnimationAvailable:u=!1,stepAnimationPlaying:d=!1,stepAnimationDisabled:m=!1,handleStepAnimationPlayToggle:p,drawToolActive:g,handleSelectTabToolMode:x,displayMode:y,onDisplayModeChange:S,projection:b,onProjectionChange:I,viewerLoading:A,selectedMeshData:N,selectedDxfData:P,selectedImplicitModel:R,drawingToolOptions:v,drawingTool:C,handleSelectDrawingTool:T,handleUndoDrawing:k,handleRedoDrawing:z,handleClearDrawings:Y,canUndoDrawing:K,canRedoDrawing:J,drawingStrokes:G,handleEnterPreviewMode:Q,handleScreenshotCopy:D}){const[$,ie]=f.useState(!1),W=e===B.DXF,Z=e===B.IMPLICIT,Ee=e===B.URDF,re=Hi(e),be=df(e),_e=Z?!!R:W?!!P:!!N,Ie=A||!_e,oe=A||!N||r||o||i,me=A||!N||!s,se=r?"Preparing selection":"Select",Ae=e===B.STEP&&u,we=A||!N||m,ct=d?"Pause":"Play",ut=e===B.STEP&&typeof S=="function"&&typeof I=="function";return c.jsxs("div",{className:"absolute z-20 flex flex-col items-end gap-1",style:t,children:[c.jsx(By,{delayDuration:250,children:c.jsxs("div",{className:`pointer-events-auto inline-flex h-8 w-fit items-center gap-0.5 self-end rounded-md p-1 ${tte}`,children:[!W&&!Z&&!re&&!be?c.jsxs(c.Fragment,{children:[c.jsx(ga,{label:se,active:i?!1:n,onClick:()=>x("references"),disabled:oe,"aria-pressed":i?!1:n,children:c.jsx(j3,{className:"size-3",strokeWidth:2,"aria-hidden":"true"})}),c.jsx(ga,{label:"Draw",active:g,onClick:()=>x("draw"),disabled:A||!N,"aria-pressed":g,children:c.jsx(uR,{className:"size-3",strokeWidth:2,"aria-hidden":"true"})}),ut?c.jsx(ete,{displayMode:y,onDisplayModeChange:S,projection:b,onProjectionChange:I,open:$,onOpenChange:ie,triggerClassName:nte,contentAlign:"end",contentSide:"bottom",contentSideOffset:6}):null,Ae?c.jsx(ga,{label:ct,active:d,onClick:p,disabled:we,"aria-pressed":d,children:d?c.jsx(VE,{className:"size-3",strokeWidth:2,"aria-hidden":"true"}):c.jsx($E,{className:"size-3",strokeWidth:2,"aria-hidden":"true"})}):null]}):null,!W&&Ee?c.jsx(ga,{label:"Select Pose",active:a,onClick:l,disabled:me,"aria-pressed":a,children:c.jsx(L3,{className:"size-3",strokeWidth:2,"aria-hidden":"true"})}):null,W?null:c.jsx(ga,{label:"Orbit",onClick:Q,disabled:A||!_e,children:c.jsx(F3,{className:"size-3",strokeWidth:2,"aria-hidden":"true"})}),c.jsx(ga,{label:"Copy screenshot",onClick:()=>{D()},disabled:Ie,children:c.jsx(z3,{className:"size-3",strokeWidth:2,"aria-hidden":"true"})})]})}),!W&&!be&&g?c.jsx(Jee,{className:qee,drawingToolOptions:v,drawingTool:C,handleSelectDrawingTool:T,handleUndoDrawing:k,handleRedoDrawing:z,handleClearDrawings:Y,canUndoDrawing:K,canRedoDrawing:J,drawingStrokes:G}):null]})}function ote({previewMode:e,selectedEntry:t,...n}){return e||!t?null:c.jsx(rte,{...n})}function ite({...e}){return c.jsx("nav",{"aria-label":"breadcrumb","data-slot":"breadcrumb",...e})}function V_({className:e,...t}){return c.jsx("ol",{"data-slot":"breadcrumb-list",className:H("flex flex-wrap items-center gap-1.5 text-sm break-words text-muted-foreground sm:gap-2.5",e),...t})}function $_({className:e,...t}){return c.jsx("li",{"data-slot":"breadcrumb-item",className:H("inline-flex items-center gap-1.5",e),...t})}function ste({children:e,className:t,...n}){return c.jsx("li",{"data-slot":"breadcrumb-separator",role:"presentation","aria-hidden":"true",className:H("[&>svg]:size-3.5",t),...n,children:e??c.jsx(Vd,{})})}const vv="system",yu="light",qo="dark",Ay=vv,xu="cad-viewer:theme",Cp="cad-viewer:color-scheme",ate=Object.freeze({"studio-light":yu,ivory:yu,graphite:qo,blueprint:qo,solarized:qo,terminal:qo,"candy-core":qo}),lte=Object.freeze([{id:vv,label:"System"},{id:yu,label:"Light"},{id:qo,label:"Dark"}]),cte=Object.freeze(Object.fromEntries(lte.map(e=>[e.id,e])));function hh(e){const t=String(e||"").trim().toLowerCase(),n=ate[t]||t;return cte[n]?n:Ay}function rD(e,{prefersDark:t=!1}={}){const n=hh(e);return n===vv?t?qo:yu:n}function oD(){if(typeof window>"u")return null;try{return window.localStorage||null}catch{return null}}function G_(e=oD()){if(!e)return Ay;try{return hh(e.getItem(Cp))}catch{return Ay}}function ute(e,t={}){const n=t.storage||oD();if(!n)return!0;const r=hh(e);try{return r===Ay?n.removeItem(Cp):n.setItem(Cp,r),!0}catch(o){return typeof t.onWriteError=="function"&&t.onWriteError({key:Cp,error:o}),!1}}function dte(e,t=document.documentElement,{prefersDark:n=!1}={}){if(!t)return;const r=hh(e),o=rD(r,{prefersDark:n});t.dataset.themePreference=r,t.dataset.theme=o,t.classList.toggle("dark",o===qo),t.style.colorScheme=o}function fte(e){return!Array.isArray(e)||e.length<=4?(Array.isArray(e)?e:[]).map(t=>({type:"node",node:t})):[{type:"node",node:e[0]},{type:"ellipsis",label:"...",nodes:e.slice(1,-2)},...e.slice(-2).map(t=>({type:"node",node:t}))]}function mte(e){return e?.type==="directory"?e?.directory||e?.menuDirectory||null:e?.menuDirectory||null}function iD(e){return String(e?.id||e?.name||"Directory")}function pte(e,t){return!Array.isArray(e)||t<0||t>=e.length?null:t>0?e[t-1]:e[t]||null}function hte({directoryTree:e,selectedEntry:t,selectedFileLabel:n,selectedFileTitle:r}){if(!e)return t?[{type:"entry",label:n,title:r,entry:t,menuDirectory:null}]:[{type:"placeholder",label:n,title:r,menuDirectory:null}];if(!t)return[{type:"placeholder",label:n,title:r,menuDirectory:e}];const o=lv(t),i=Vq(e,o),s=i.map((l,u)=>{const d=String(l?.id||"").trim();return d?{type:"directory",id:d,label:String(l?.name||"Folder"),title:iD(l),directory:l,menuDirectory:pte(i,u)}:null}).filter(Boolean),a=i[i.length-1]||e;return[...s,{type:"entry",label:n,title:r,entry:t,menuDirectory:a}]}const gte="0.3.9",bte={version:gte},U_={};function W_(e){return e==="dxf"?"DXF sheet":e==="urdf"?"URDF sheet":e==="srdf"?"SRDF sheet":e==="sdf"?"SDF sheet":e==="step"?"STEP sheet":e==="implicit"?"Implicit CAD sheet":"file sheet"}function yte(e,t){const n=typeof t=="function"?t(e):e?.kind||"";return String(n||"").trim().toLowerCase()}function xte(e,{entrySourceFormat:t,entryHasMesh:n,entryHasDxf:r,entryHasGcode:o,entryHasUrdf:i,activeGenerationFiles:s=[],activeStepArtifactGenerationFile:a="",stepArtifactGenerationAvailable:l=!0}){const u=yte(e,t),d=typeof r=="function"?r(e):!0,m=typeof o=="function"?o(e):!0,p=typeof i=="function"?i(e):!0,g=typeof n=="function"?n(e):!0;return YO(e,{sourceFormat:u,entryKey:at(e),hasMesh:g,hasDxf:d,hasGcode:m,hasUrdf:p,activeGenerationFiles:s,activeStepArtifactGenerationFile:a,stepArtifactGenerationAvailable:l})}const Ste={[Wt.LOADING]:BE,[Wt.ASSEMBLY]:zE,[Wt.DXF]:FE,[Wt.GCODE]:LE,[Wt.IMPLICIT]:Fy,[Wt.ROBOT]:jE,[Wt.STEP_PART]:sf,[Wt.STL_MESH]:DE,[Wt.THREE_MF_MESH]:Ly,[Wt.GLB_MESH]:kE};function Ete(e,t,n){return Ste[hv(e,{sourceFormat:t,status:n})]||sf}function sD({entry:e,selectedKey:t,onSelectEntry:n,sidebarLabelForEntry:r,entrySourceFormat:o,entryHasMesh:i,entryHasDxf:s,entryHasGcode:a,entryHasUrdf:l,activeGenerationFiles:u=[],activeStepArtifactGenerationFile:d="",stepArtifactGenerationAvailable:m=!0}){const p=at(e),g=p===t,x=typeof r=="function"?r(e):p,y=xte(e,{entrySourceFormat:o,entryHasMesh:i,entryHasDxf:s,entryHasGcode:a,entryHasUrdf:l,activeGenerationFiles:u,activeStepArtifactGenerationFile:d,stepArtifactGenerationAvailable:m}),{sourceFormat:S}=y,b=Ete(e,S,y),I=[x,y.statusLabel,e?.kind,String(e?.file||p)].filter(Boolean).join(" | ");return c.jsxs(Yo,{"data-active":g,className:H("min-w-0 max-w-80 text-xs focus:bg-sidebar-accent focus:text-sidebar-accent-foreground","data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground"),title:I,disabled:!p||typeof n!="function","aria-current":g?"page":void 0,onSelect:()=>{p&&typeof n=="function"&&n(p)},children:[c.jsx(b,{className:H("size-3.5 shrink-0",y.loading&&"animate-spin"),"aria-hidden":"true"}),c.jsx("span",{className:"block min-w-0 flex-1 truncate",children:x})]})}function aD({directory:e,selectedKey:t,onSelectEntry:n,sidebarLabelForEntry:r,entrySourceFormat:o,entryHasMesh:i,entryHasDxf:s,entryHasGcode:a,entryHasUrdf:l,activeGenerationFiles:u=[],activeStepArtifactGenerationFile:d="",stepArtifactGenerationAvailable:m=!0,canRevealFileAssets:p=!1,canCopyFileAssetLinks:g=!1,canCopyFileAssetPaths:x=!1,fileAccessBusyKey:y="",onDownloadFileAsset:S,onExportImplicitFile:b,onRevealFileAsset:I,onCopyFileAssetReference:A}){const N=o0(e);return N.length?N.map(P=>P.type==="directory"?c.jsx(lD,{directory:P.value,selectedKey:t,onSelectEntry:n,sidebarLabelForEntry:r,entrySourceFormat:o,entryHasMesh:i,entryHasDxf:s,entryHasGcode:a,entryHasUrdf:l,activeGenerationFiles:u,activeStepArtifactGenerationFile:d,stepArtifactGenerationAvailable:m,canRevealFileAssets:p,canCopyFileAssetLinks:g,canCopyFileAssetPaths:x,fileAccessBusyKey:y,onDownloadFileAsset:S,onExportImplicitFile:b,onRevealFileAsset:I,onCopyFileAssetReference:A},P.key):c.jsx(sD,{entry:P.value,selectedKey:t,onSelectEntry:n,sidebarLabelForEntry:r,entrySourceFormat:o,entryHasMesh:i,entryHasDxf:s,entryHasGcode:a,entryHasUrdf:l,activeGenerationFiles:u,activeStepArtifactGenerationFile:d,stepArtifactGenerationAvailable:m,canRevealFileAssets:p,canCopyFileAssetLinks:g,canCopyFileAssetPaths:x,fileAccessBusyKey:y,onDownloadFileAsset:S,onExportImplicitFile:b,onRevealFileAsset:I,onCopyFileAssetReference:A},P.key)):c.jsxs(Yo,{disabled:!0,className:"max-w-80 text-xs",children:[c.jsx(dR,{className:"size-3.5 shrink-0","aria-hidden":"true"}),c.jsx("span",{className:"block min-w-0 truncate",children:String(e?.name||"Empty")})]})}function Cv({children:e}){return c.jsx(ch,{className:"max-h-96 w-full",type:"auto",viewportClassName:"max-h-96",children:e})}function lD({directory:e,label:t="",title:n="",selectedKey:r,onSelectEntry:o,sidebarLabelForEntry:i,entrySourceFormat:s,entryHasMesh:a,entryHasDxf:l,entryHasGcode:u,entryHasUrdf:d,activeGenerationFiles:m=[],activeStepArtifactGenerationFile:p="",stepArtifactGenerationAvailable:g=!0,canRevealFileAssets:x=!1,canCopyFileAssetLinks:y=!1,canCopyFileAssetPaths:S=!1,fileAccessBusyKey:b="",onDownloadFileAsset:I,onExportImplicitFile:A,onRevealFileAsset:N,onCopyFileAssetReference:P}){const R=String(t||e?.name||"Folder"),v=String(n||iD(e));return c.jsxs(TO,{children:[c.jsxs(RO,{className:"min-w-0 max-w-80 text-xs",title:v,children:[c.jsx(dR,{className:"size-3.5 shrink-0","aria-hidden":"true"}),c.jsx("span",{className:"block min-w-0 flex-1 truncate",children:R})]}),c.jsx(PO,{className:"w-max max-w-80",children:c.jsx(Cv,{children:c.jsx(aD,{directory:e,selectedKey:r,onSelectEntry:o,sidebarLabelForEntry:i,entrySourceFormat:s,entryHasMesh:a,entryHasDxf:l,entryHasGcode:u,entryHasUrdf:d,activeGenerationFiles:m,activeStepArtifactGenerationFile:p,stepArtifactGenerationAvailable:g,canRevealFileAssets:x,canCopyFileAssetLinks:y,canCopyFileAssetPaths:S,fileAccessBusyKey:b,onDownloadFileAsset:I,onExportImplicitFile:A,onRevealFileAsset:N,onCopyFileAssetReference:P})})})]})}function H_({node:e,current:t,selectedKey:n,onSelectEntry:r,sidebarLabelForEntry:o,entrySourceFormat:i,entryHasMesh:s,entryHasDxf:a,entryHasGcode:l,entryHasUrdf:u,activeGenerationFiles:d=[],activeStepArtifactGenerationFile:m="",stepArtifactGenerationAvailable:p=!0,selectedStepSourceStatus:g=null,canRevealFileAssets:x=!1,canCopyFileAssetLinks:y=!1,canCopyFileAssetPaths:S=!1,fileAccessBusyKey:b="",onDownloadFileAsset:I,onExportImplicitFile:A,onRevealFileAsset:N,onRevealInExplorerView:P,onCopyFileAssetReference:R,filenameLoadActivity:v}){const C=String(e?.label||""),T=String(e?.title||C),k=(e?.type==="directory"||e?.type==="placeholder"||e?.type==="entry")&&e?.menuDirectory||null;if(!(!!k&&o0(k).length>0)){const G=c.jsxs("span",{className:H("inline-flex min-w-0 items-center gap-2 text-xs font-medium",t?"max-w-[min(36rem,55vw)] text-foreground":"max-w-32"),title:T,children:[c.jsx("span",{className:"block min-w-0 truncate",children:C}),t&&e?.type==="entry"?c.jsx(K_,{activity:v}):null]});return e?.type!=="entry"||!e?.entry?G:c.jsx(tE,{entry:e.entry,stepSourceStatus:g,canRevealFileAssets:x,canCopyFileAssetLinks:y,canCopyFileAssetPaths:S,busyKey:b,onDownloadFileAsset:I,onExportImplicitFile:A,onRevealFileAsset:N,onRevealInExplorerView:P,onCopyFileAssetReference:R,children:G})}const Y=c.jsxs("button",{type:"button",className:H("inline-flex min-w-0 items-center gap-2 rounded-sm text-xs font-medium transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",t?"max-w-[min(36rem,55vw)] text-foreground":"max-w-32 text-muted-foreground"),"aria-label":`Browse ${C}`,"aria-current":t?"page":void 0,title:T,onPointerDown:G=>{G.button===1&&G.preventDefault()},children:[c.jsx("span",{className:"block min-w-0 truncate",children:C}),t&&e?.type==="entry"?c.jsx(K_,{activity:v}):null]}),K=c.jsx(gf,{asChild:!0,children:Y}),J=e?.type==="entry"&&e?.entry?c.jsx(tE,{entry:e.entry,stepSourceStatus:g,canRevealFileAssets:x,canCopyFileAssetLinks:y,canCopyFileAssetPaths:S,busyKey:b,onDownloadFileAsset:I,onExportImplicitFile:A,onRevealFileAsset:N,onRevealInExplorerView:P,onCopyFileAssetReference:R,children:K}):K;return c.jsxs(hf,{children:[J,c.jsx(bf,{align:"start",sideOffset:6,className:"w-max max-w-80",children:c.jsx(Cv,{children:c.jsx(aD,{directory:k,selectedKey:n,onSelectEntry:r,sidebarLabelForEntry:o,entrySourceFormat:i,entryHasMesh:s,entryHasDxf:a,entryHasGcode:l,entryHasUrdf:u,activeGenerationFiles:d,activeStepArtifactGenerationFile:m,stepArtifactGenerationAvailable:p,canRevealFileAssets:x,canCopyFileAssetLinks:y,canCopyFileAssetPaths:S,fileAccessBusyKey:b,onDownloadFileAsset:I,onExportImplicitFile:A,onRevealFileAsset:N,onCopyFileAssetReference:R})})})]})}function wte({nodes:e,selectedKey:t,onSelectEntry:n,sidebarLabelForEntry:r,entrySourceFormat:o,entryHasMesh:i,entryHasDxf:s,entryHasGcode:a,entryHasUrdf:l,activeGenerationFiles:u=[],activeStepArtifactGenerationFile:d="",stepArtifactGenerationAvailable:m=!0,canRevealFileAssets:p=!1,canCopyFileAssetLinks:g=!1,canCopyFileAssetPaths:x=!1,fileAccessBusyKey:y="",onDownloadFileAsset:S,onExportImplicitFile:b,onRevealFileAsset:I,onCopyFileAssetReference:A,title:N}){const P=Array.isArray(e)?e.filter(Boolean):[],R=P.map(v=>v.label).join(" / ")||N;return c.jsxs(hf,{children:[c.jsx(gf,{asChild:!0,children:c.jsx("button",{type:"button",className:"inline-flex h-6 min-w-7 items-center justify-center rounded-md px-1.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":"Show collapsed path folders",title:R,children:c.jsx("span",{"aria-hidden":"true",children:"..."})})}),c.jsx(bf,{align:"start",sideOffset:6,className:"w-max max-w-80",children:c.jsx(Cv,{children:P.map((v,C)=>{const T=mte(v);return v.type==="directory"&&T?c.jsx(lD,{directory:T,label:v.label,title:v.title,selectedKey:t,onSelectEntry:n,sidebarLabelForEntry:r,entrySourceFormat:o,entryHasMesh:i,entryHasDxf:s,entryHasGcode:a,entryHasUrdf:l,activeGenerationFiles:u,activeStepArtifactGenerationFile:d,stepArtifactGenerationAvailable:m,canRevealFileAssets:p,canCopyFileAssetLinks:g,canCopyFileAssetPaths:x,fileAccessBusyKey:y,onDownloadFileAsset:S,onExportImplicitFile:b,onRevealFileAsset:I,onCopyFileAssetReference:A},`${v.type}:${v.id}:${C}`):v.type==="entry"&&v.entry?c.jsx(sD,{entry:v.entry,selectedKey:t,onSelectEntry:n,sidebarLabelForEntry:r,entrySourceFormat:o,entryHasMesh:i,entryHasDxf:s,entryHasGcode:a,entryHasUrdf:l,activeGenerationFiles:u,activeStepArtifactGenerationFile:d,stepArtifactGenerationAvailable:m,canRevealFileAssets:p,canCopyFileAssetLinks:g,canCopyFileAssetPaths:x,fileAccessBusyKey:y,onDownloadFileAsset:S,onExportImplicitFile:b,onRevealFileAsset:I,onCopyFileAssetReference:A},`${v.type}:${at(v.entry)}:${C}`):c.jsx(Yo,{disabled:!0,className:"max-w-80 text-xs",children:c.jsx("span",{className:"block min-w-0 truncate",children:v.label})},`${v.type}:${v.label}:${C}`)})})})]})}function K_({activity:e}){const t=String(e?.label||"").trim();if(!e?.loading||!t)return null;const n=String(e?.title||t).trim();return c.jsxs("span",{role:"status","aria-live":"polite",title:n,className:"inline-flex min-w-0 max-w-36 shrink items-center gap-1 rounded-md border border-border/70 bg-sidebar-accent px-1.5 py-0.5 text-[10px] font-medium leading-none text-sidebar-accent-foreground",children:[c.jsx(BE,{className:"size-3 shrink-0 animate-spin","aria-hidden":"true"}),c.jsx("span",{className:"min-w-0 truncate",children:t})]})}function vte(e){return c.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",...e,children:c.jsx("path",{d:"M12 .5C5.65.5.5 5.65.5 12c0 5.09 3.29 9.4 7.86 10.92.58.1.79-.25.79-.56v-2.02c-3.2.7-3.87-1.37-3.87-1.37-.53-1.34-1.29-1.7-1.29-1.7-1.06-.73.08-.71.08-.71 1.17.08 1.79 1.2 1.79 1.2 1.04 1.78 2.73 1.27 3.4.97.1-.75.41-1.27.74-1.56-2.55-.29-5.24-1.28-5.24-5.68 0-1.25.45-2.28 1.2-3.08-.12-.29-.52-1.46.11-3.04 0 0 .98-.31 3.2 1.18A11.13 11.13 0 0 1 12 6.16c.99 0 1.98.13 2.91.39 2.22-1.49 3.2-1.18 3.2-1.18.63 1.58.23 2.75.11 3.04.75.8 1.2 1.83 1.2 3.08 0 4.41-2.69 5.39-5.25 5.67.42.36.79 1.08.79 2.17v3.03c0 .31.21.67.8.56A11.52 11.52 0 0 0 23.5 12C23.5 5.65 18.35.5 12 .5Z"})})}function Cte(e){return c.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",...e,children:c.jsx("path",{d:"M20.32 4.37a19.8 19.8 0 0 0-4.89-1.51.07.07 0 0 0-.07.03c-.21.38-.44.86-.61 1.25a18.27 18.27 0 0 0-5.49 0 12.64 12.64 0 0 0-.62-1.25.08.08 0 0 0-.07-.03 19.74 19.74 0 0 0-4.89 1.51.07.07 0 0 0-.03.03C.53 9.05-.32 13.58.1 18.06a.08.08 0 0 0 .03.06 19.9 19.9 0 0 0 5.99 3.03.08.08 0 0 0 .08-.03c.46-.63.87-1.3 1.23-1.99a.08.08 0 0 0-.04-.11 13.1 13.1 0 0 1-1.87-.89.08.08 0 0 1-.01-.13c.13-.09.25-.19.37-.29a.07.07 0 0 1 .08-.01c3.93 1.79 8.18 1.79 12.06 0a.07.07 0 0 1 .08.01c.12.1.25.2.37.29a.08.08 0 0 1-.01.13 12.3 12.3 0 0 1-1.87.89.08.08 0 0 0-.04.11c.36.7.77 1.36 1.23 1.99a.08.08 0 0 0 .08.03 19.84 19.84 0 0 0 6-3.03.08.08 0 0 0 .03-.05c.5-5.18-.84-9.67-3.55-13.66a.06.06 0 0 0-.02-.04ZM8.02 15.33c-1.18 0-2.16-1.09-2.16-2.42s.96-2.42 2.16-2.42c1.21 0 2.18 1.1 2.16 2.42 0 1.33-.96 2.42-2.16 2.42Zm7.98 0c-1.18 0-2.16-1.09-2.16-2.42s.96-2.42 2.16-2.42c1.21 0 2.18 1.1 2.16 2.42 0 1.33-.95 2.42-2.16 2.42Z"})})}const Rm="size-7",Pm="size-4",Mte="cad-viewer:latest-release:v1:",Ite=360*60*1e3,Ate=250,Nte=700,Xl=Object.freeze({updateAvailable:!1,latestVersion:"",releaseUrl:"",installCommand:bc,latestReleaseNewer:!1});function _te(e){return e===qo?yu:qo}function cD(e){return`${Mte}${e}`}function Tte(e,t=Date.now()){if(!e||typeof window>"u"||!window.localStorage)return null;try{const n=window.localStorage.getItem(cD(e)),r=n?JSON.parse(n):null,o=Number(r?.expiresAt||0),i=String(r?.latestVersion||"").trim(),s=String(r?.releaseUrl||"").trim(),a=String(r?.installCommand||"").trim();return!i||o<=t?null:{latestVersion:i,releaseUrl:s,installCommand:a}}catch{return null}}function Rte(e,t,n=Date.now()){if(!e||typeof window>"u"||!window.localStorage)return;const r=String(t?.latestVersion||"").trim();if(r)try{window.localStorage.setItem(cD(e),JSON.stringify({latestVersion:r,releaseUrl:String(t?.releaseUrl||"").trim(),installCommand:String(t?.installCommand||"").trim(),expiresAt:n+Ite}))}catch{}}function Pte(e,t=""){const n=String(e?.tag_name||"").trim();return n?{latestVersion:n,releaseUrl:String(e?.html_url||t||"").trim(),installCommand:Iq(e?.body,bc)}:null}function pS(e,t){const n=String(t?.latestVersion||"").trim(),r=String(t?.releaseUrl||"").trim(),o=String(t?.installCommand||bc).trim();if(!n)return Xl;const i=vq(e,n);return{updateAvailable:Cq(e,n),latestVersion:n,releaseUrl:r,installCommand:o,latestReleaseNewer:i}}function Ote({currentVersion:e,latestReleaseApiUrl:t,latestReleaseUrl:n,mockLatestVersion:r="",mockLatestReleaseUrl:o=""}){const[i,s]=f.useState(Xl);return f.useEffect(()=>{const a=String(e||"").trim(),l=String(t||"").trim(),u=String(r||"").trim();if(!a){s(Xl);return}if(u){s(pS(a,{latestVersion:u,releaseUrl:String(o||n||"").trim(),installCommand:bc}));return}if(!l||typeof fetch!="function"){s(Xl);return}const d=Tte(l);if(d){s(pS(a,d));return}s(Xl);const m=new AbortController;return fetch(l,{signal:m.signal,headers:{Accept:"application/vnd.github+json"}}).then(p=>{if(!p.ok)throw new Error(`GitHub latest release check failed with ${p.status}`);return p.json()}).then(p=>{if(m.signal.aborted)return;const g=Pte(p,n);if(!g){d||s(Xl);return}Rte(l,g),s(pS(a,g))}).catch(p=>{p?.name!=="AbortError"&&(d||s(Xl))}),()=>{m.abort()}},[e,t,n,o,r]),i}function hS({label:e,version:t,action:n=null}){const r=String(t||"").trim();return r?c.jsxs("div",{className:"flex min-w-0 flex-col items-start gap-1.5 px-0.5 text-left",children:[c.jsx("span",{className:"text-[11px] font-medium leading-none text-muted-foreground",children:e}),c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx("span",{className:"min-w-0 text-left font-mono text-[12px] leading-5 text-foreground tabular-nums",children:r}),n]})]}):null}function kte({version:e,releaseUrl:t,releaseCheck:n=Xl}){const r=String(e||"").trim(),[o,i]=f.useState(""),s=f.useRef(!1);if(!r)return null;const a=!!n?.updateAvailable,l=a?String(n?.releaseUrl||t||"").trim():String(t||"").trim(),u=String(n?.latestVersion||"").trim(),d=!!n?.latestReleaseNewer,m=u&&d,p=m?String(n?.releaseUrl||"").trim():"",g=String(n?.installCommand||bc).trim()||bc,x=!!u&&!d,y=a?"Update CAD Viewer":l?`Open release ${r}`:`Version ${r}`,S=async I=>{if(I.preventDefault(),I.stopPropagation(),!s.current){s.current=!0,globalThis.setTimeout(()=>{s.current=!1},250);try{await ps(g),i("copied"),globalThis.setTimeout(()=>{i("")},1600)}catch{i("failed")}}},b=c.jsx(Qe,{asChild:!!l,variant:a?"default":"ghost",size:"xs",className:H("inline-flex rounded-sm px-2 text-xs font-medium leading-none",a?"h-6 px-2 text-[11px]":"h-7 text-muted-foreground tabular-nums hover:text-sidebar-foreground"),"aria-label":y,children:l?c.jsx("a",{href:l,target:"_blank",rel:"noreferrer",children:c.jsx("span",{className:"inline-flex items-center gap-1",children:a?c.jsx("span",{children:"Update"}):c.jsx("span",{children:r})})}):c.jsx("span",{className:"inline-flex items-center gap-1",children:a?c.jsx("span",{children:"Update"}):c.jsx("span",{children:r})})});return c.jsxs(KE,{delayDuration:a?Ate:Nte,children:[c.jsx(XE,{asChild:!0,children:b}),c.jsx(YE,{side:"bottom",sideOffset:6,className:"cad-glass-popover w-fit max-w-[calc(100vw-1rem)] border border-border bg-popover p-2 text-left text-popover-foreground shadow-lg shadow-black/10",arrowClassName:"bg-popover fill-popover",children:c.jsxs("div",{className:"inline-flex max-w-full flex-col gap-3",children:[m?c.jsxs("div",{className:"grid w-full min-w-0 grid-cols-2 gap-3",children:[c.jsx(hS,{label:"Current Version",version:r}),c.jsx(hS,{label:"Latest Version",version:u,action:p?c.jsx(Qe,{asChild:!0,variant:"default",size:"xs",className:"h-4 !min-h-0 rounded-sm !px-1.5 !py-0 text-[10px] font-medium leading-none","aria-label":`Update CAD Viewer to ${u}`,children:c.jsx("a",{href:p,target:"_blank",rel:"noreferrer",children:"Update"})}):null})]}):c.jsx(hS,{label:"Current Version",version:r}),c.jsxs("div",{className:"flex min-w-0 flex-col gap-1.5",children:[c.jsx("div",{className:"px-0.5 text-[11px] font-medium leading-none text-muted-foreground",children:"Update Command"}),c.jsxs("div",{className:"flex h-8 min-w-0 items-center gap-2 rounded-sm border border-border/60 bg-muted/35 p-1 pl-2",children:[c.jsx("code",{className:"min-w-0 flex-1 whitespace-nowrap font-mono text-[11px] leading-5 text-foreground",children:g}),c.jsx(Qe,{type:"button",variant:"ghost",size:"icon",className:"inline-flex size-6 shrink-0 items-center justify-center rounded-sm border border-border text-foreground transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50","aria-label":o==="copied"?"Install command copied":"Copy install command",onPointerDown:S,onClick:S,children:o==="copied"?c.jsx(mu,{className:"size-3","aria-hidden":"true"}):c.jsx(vu,{className:"size-3","aria-hidden":"true"})})]})]}),o==="failed"?c.jsx("div",{className:"text-[11px] text-muted-foreground",children:"Copy failed"}):null,x?c.jsxs("div",{className:"flex items-center gap-1.5 px-0.5 text-[11px] font-medium text-muted-foreground",children:[c.jsx(V3,{className:"size-3 text-primary","aria-hidden":"true"}),c.jsx("span",{children:"You are up to date"})]}):null]})})]})}function Dte({previewMode:e,sidebarLabelForEntry:t,directoryTree:n=null,selectedKey:r="",selectedEntry:o,onSelectEntry:i,entrySourceFormat:s,entryHasMesh:a,entryHasDxf:l,entryHasGcode:u,entryHasUrdf:d,activeGenerationFiles:m=[],activeStepArtifactGenerationFile:p="",stepArtifactGenerationAvailable:g=!0,themePresets:x=[],themeSettings:y,themePresetId:S="",resolvedColorSchemeMode:b=yu,onColorSchemePreferenceChange:I,updateThemeSettings:A,handleResetThemeSettings:N,handleSaveCustomThemePreset:P,handleUpdateThemePresetSettings:R,handleDeleteCustomThemePreset:v,handleEditThemePreset:C,handleResetThemePresetToDefault:T,handleRestoreDefaultThemePresets:k,filenameLoadActivity:z=null,selectedStepSourceStatus:Y=null,canRevealFileAssets:K=!1,canCopyFileAssetLinks:J=!1,canCopyFileAssetPaths:G=!1,fileAccessBusyKey:Q="",onDownloadFileAsset:D,onExportImplicitFile:$,onRevealFileAsset:ie,onRevealInExplorerView:W,onCopyFileAssetReference:Z,fileSheetKind:Ee="",fileSheetOpen:re=!1,onToggleFileSheet:be,navigationAvailable:_e=!0}){const Ie=String(bte.version).trim(),oe=xq(U_?.VIEWER_DISCORD_URL),me=JO(U_?.VIEWER_GITHUB_URL),se=Sq(Ie,me),Ae=Eq(me),we=e?"":wq(me),Tt=Ote({currentVersion:Ie,latestReleaseApiUrl:we,latestReleaseUrl:Ae,mockLatestVersion:"",mockLatestReleaseUrl:""});if(e)return null;const Ve=o&&typeof t=="function"?t(o):"Select a file",St=o?String(o.file||o.id||Ve):Ve,wt=_e||!!o,Vn=hte({directoryTree:_e?n:null,selectedEntry:o,selectedFileLabel:Ve,selectedFileTitle:St}),De=fte(Vn),xe=Vn[Vn.length-1]||null,yt="bg-accent text-accent-foreground",Te=!!Ee&&typeof be=="function",rt=re?`Collapse ${W_(Ee)}`:`Expand ${W_(Ee)}`,Re=BG(y),Fe=b===qo?qo:yu,on=_te(Fe),qt=`Browser color mode: ${Fe===qo?"dark":"light"}. Switch to ${on===qo?"dark":"light"} mode.`,sn=Fe===qo?aR:lR,Mn=()=>{typeof I=="function"&&I(on)};return c.jsxs("header",{className:"cad-glass-surface pointer-events-auto flex h-11 shrink-0 items-center gap-2 border-b border-sidebar-border px-2 text-sidebar-foreground",children:[_e?c.jsx(e5,{title:"Toggle CAD Viewer","aria-label":"Toggle CAD Viewer",className:"shrink-0"}):null,wt?c.jsx(ite,{className:"min-w-0 flex-1 overflow-hidden",children:c.jsxs(ch,{className:"h-8 min-w-0 whitespace-nowrap",type:"auto",viewportClassName:"overflow-y-hidden",scrollbars:"horizontal",children:[xe?c.jsx(V_,{className:"flex h-8 min-w-full flex-nowrap gap-1.5 pr-2 text-xs sm:hidden",children:c.jsx($_,{className:"min-w-0",children:c.jsx(H_,{node:xe,current:!0,selectedKey:r,onSelectEntry:i,sidebarLabelForEntry:t,entrySourceFormat:s,entryHasMesh:a,entryHasDxf:l,entryHasGcode:u,entryHasUrdf:d,activeGenerationFiles:m,activeStepArtifactGenerationFile:p,stepArtifactGenerationAvailable:g,selectedStepSourceStatus:Y,canRevealFileAssets:K,canCopyFileAssetLinks:J,canCopyFileAssetPaths:G,fileAccessBusyKey:Q,onDownloadFileAsset:D,onExportImplicitFile:$,onRevealFileAsset:ie,onRevealInExplorerView:W,onCopyFileAssetReference:Z,filenameLoadActivity:z})})}):null,c.jsx(V_,{className:"hidden h-8 min-w-full w-max flex-nowrap gap-1.5 pr-2 text-xs sm:flex sm:gap-1.5",children:De.map((fn,Bt)=>c.jsxs(f.Fragment,{children:[c.jsx($_,{className:"min-w-0",children:fn.type==="ellipsis"?c.jsx(wte,{nodes:fn.nodes,selectedKey:r,onSelectEntry:i,sidebarLabelForEntry:t,entrySourceFormat:s,entryHasMesh:a,entryHasDxf:l,entryHasGcode:u,entryHasUrdf:d,activeGenerationFiles:m,activeStepArtifactGenerationFile:p,stepArtifactGenerationAvailable:g,canRevealFileAssets:K,canCopyFileAssetLinks:J,canCopyFileAssetPaths:G,fileAccessBusyKey:Q,onDownloadFileAsset:D,onExportImplicitFile:$,onRevealFileAsset:ie,onCopyFileAssetReference:Z,title:St}):c.jsx(H_,{node:fn.node,current:Bt===De.length-1,selectedKey:r,onSelectEntry:i,sidebarLabelForEntry:t,entrySourceFormat:s,entryHasMesh:a,entryHasDxf:l,entryHasGcode:u,entryHasUrdf:d,activeGenerationFiles:m,activeStepArtifactGenerationFile:p,stepArtifactGenerationAvailable:g,selectedStepSourceStatus:Y,canRevealFileAssets:K,canCopyFileAssetLinks:J,canCopyFileAssetPaths:G,fileAccessBusyKey:Q,onDownloadFileAsset:D,onExportImplicitFile:$,onRevealFileAsset:ie,onRevealInExplorerView:W,onCopyFileAssetReference:Z,filenameLoadActivity:z})}),Bti?.kind==="assembly",i=>or(i)===B.STEP&&i?.kind!=="assembly",i=>or(i)===B.DXF,i=>or(i)===B.GCODE,i=>or(i)===B.IMPLICIT,i=>Hi(or(i))||i?.kind==="srdf",i=>df(or(i))];for(const i of o){const s=t.find(a=>i(a));Y_(n,r,s)}for(const i of t){if(n.length>=X_)break;Y_(n,r,i)}return n.slice(0,X_)}function Wte({entries:e,onSelectEntry:t,catalogHydrated:n=!1,catalogRefreshing:r=!1,catalogError:o="",directorySelectionActive:i=!1,directoryOptions:s=[],onSelectDirectory:a}){const l=Ute(e),u=$te(s),d=l.length>0,m=u.length>0,p=String(o||"").trim(),g=!n||r&&!d,x=i?"Select a directory":"Select a file";return c.jsx("div",{className:"pointer-events-none absolute inset-0 z-20 flex min-w-0 items-center justify-center px-4 py-6",children:c.jsxs("section",{className:"cad-glass-popover pointer-events-auto w-full max-w-2xl overflow-hidden rounded-md border border-sidebar-border text-popover-foreground shadow-xl shadow-black/10","aria-label":"CAD Viewer home",children:[c.jsx("div",{className:"border-b border-sidebar-border px-5 py-4 sm:px-6",children:c.jsx("h1",{className:"text-lg font-medium leading-6 text-foreground sm:text-xl",children:x})}),c.jsx("div",{className:"divide-y divide-sidebar-border/70",children:i?m?u.map(y=>{const S=Bte(y),b=Vte(y);return c.jsxs(Qe,{type:"button",variant:"ghost",className:"group h-auto w-full justify-start rounded-none px-5 py-3 text-left hover:bg-sidebar-accent/80 focus-visible:ring-inset has-[>svg]:px-5 sm:px-6 sm:has-[>svg]:px-6",onClick:()=>{typeof a=="function"&&a(y.dir)},title:b||S,children:[c.jsx(LS,{className:"size-4 shrink-0 text-muted-foreground group-hover:text-foreground","aria-hidden":"true"}),c.jsxs("span",{className:"min-w-0 flex-1",children:[c.jsx("span",{className:"block min-w-0 truncate text-sm font-medium text-foreground",children:S}),b?c.jsx("span",{className:"mt-0.5 block min-w-0 truncate text-[11px] font-normal text-muted-foreground",children:b}):null]}),c.jsx("span",{className:H("shrink-0 rounded-md border border-sidebar-border px-1.5 py-0.5 text-[10px] font-semibold uppercase leading-none text-muted-foreground","max-sm:hidden"),children:"Directory"}),c.jsx(Vd,{className:"size-4 shrink-0 text-muted-foreground transition-transform group-hover:translate-x-0.5 group-hover:text-foreground","aria-hidden":"true"})]},y.rootPath||y.dir)}):c.jsx("p",{className:"px-5 py-5 text-sm text-muted-foreground sm:px-6",children:"No active directories found."}):d?l.map(y=>{const S=at(y),b=or(y),I=Lte(y,b),A=dl(y)||S,N=zte(y),P=Fte(y,b);return c.jsxs(Qe,{type:"button",variant:"ghost",className:"group h-auto w-full justify-start rounded-none px-5 py-3 text-left hover:bg-sidebar-accent/80 focus-visible:ring-inset has-[>svg]:px-5 sm:px-6 sm:has-[>svg]:px-6",onClick:()=>{S&&typeof t=="function"&&t(S)},title:N||A,children:[c.jsx(I,{className:"size-4 shrink-0 text-muted-foreground group-hover:text-foreground","aria-hidden":"true"}),c.jsxs("span",{className:"min-w-0 flex-1",children:[c.jsx("span",{className:"block min-w-0 truncate text-sm font-medium text-foreground",children:A}),N?c.jsx("span",{className:"mt-0.5 block min-w-0 truncate text-[11px] font-normal text-muted-foreground",children:N}):null]}),c.jsx("span",{className:H("shrink-0 rounded-md border border-sidebar-border px-1.5 py-0.5 text-[10px] font-semibold uppercase leading-none text-muted-foreground","max-sm:hidden"),children:P}),c.jsx(Vd,{className:"size-4 shrink-0 text-muted-foreground transition-transform group-hover:translate-x-0.5 group-hover:text-foreground","aria-hidden":"true"})]},S)}):p?c.jsxs("p",{className:"break-words px-5 py-5 text-sm text-muted-foreground sm:px-6",role:"status",children:["CAD catalog unavailable: ",p]}):g?c.jsx("p",{className:"px-5 py-5 text-sm text-muted-foreground sm:px-6",role:"status",children:"Loading CAD catalog..."}):c.jsx("p",{className:"px-5 py-5 text-sm text-muted-foreground sm:px-6",children:"No CAD entries found."})})]})})}const Hte=1,Kte=new Set(["LINE","ARC","CIRCLE","LWPOLYLINE"]),ll=1e-9;function vo(e,t=0){const n=Number(e);return Number.isFinite(n)?n:t}function Wc(e){return String(e||"").trim().toLowerCase().includes("bend")?"bend":"cut"}function l0(e){return String(e||"").trim()||"0"}function ou(e){const t=e%360;return t<0?t+360:t}function Xte(e,t,n){const r=Math.abs(n);return r>=360-ll?!0:n>=0?(ou(e)-ou(t)+360)%360<=r+ll:(ou(t)-ou(e)+360)%360<=r+ll}function Mp(e,t,n){const r=n*Math.PI/180;return[e[0]+t*Math.cos(r),e[1]+t*Math.sin(r)]}function Yte(e){const t=e.startAngleDeg+e.sweepAngleDeg,n=[Mp(e.center,e.radius,e.startAngleDeg),Mp(e.center,e.radius,t)];for(const r of[0,90,180,270])Xte(r,e.startAngleDeg,e.sweepAngleDeg)&&n.push(Mp(e.center,e.radius,r));return n}function gS(e,t){return e?{minX:Math.min(e.minX,t.minX),minY:Math.min(e.minY,t.minY),maxX:Math.max(e.maxX,t.maxX),maxY:Math.max(e.maxY,t.maxY)}:t}function qte(e){return{minX:Math.min(e.start[0],e.end[0]),minY:Math.min(e.start[1],e.end[1]),maxX:Math.max(e.start[0],e.end[0]),maxY:Math.max(e.start[1],e.end[1])}}function Zte(e){return{minX:e.center[0]-e.radius,minY:e.center[1]-e.radius,maxX:e.center[0]+e.radius,maxY:e.center[1]+e.radius}}function Jte(e){const t=Yte(e),n=t.map(o=>o[0]),r=t.map(o=>o[1]);return{minX:Math.min(...n),minY:Math.min(...r),maxX:Math.max(...n),maxY:Math.max(...r)}}function Om(e,{minX:t,maxY:n}){return[e[0]-t,n-e[1]]}function Pn(e){const t=Math.round(vo(e)*1e6)/1e6;return Math.abs(t)s.code===8)?.value),n=vo(e.find(s=>s.code===10)?.value),r=vo(e.find(s=>s.code===20)?.value),o=vo(e.find(s=>s.code===11)?.value),i=vo(e.find(s=>s.code===21)?.value);return{layer:t,start:[n,r],end:[o,i]}}function nne(e){const t=l0(e.find(s=>s.code===8)?.value),n=vo(e.find(s=>s.code===40)?.value,-1);if(n<=0)throw new Error("Invalid DXF arc radius");const r=ou(vo(e.find(s=>s.code===50)?.value));let i=(ou(vo(e.find(s=>s.code===51)?.value))-r+360)%360;return i<=ll&&(i=360),{layer:t,center:[vo(e.find(s=>s.code===10)?.value),vo(e.find(s=>s.code===20)?.value)],radius:n,startAngleDeg:r,sweepAngleDeg:i,endAngleDeg:r+i}}function rne(e){const t=l0(e.find(r=>r.code===8)?.value),n=vo(e.find(r=>r.code===40)?.value,-1);if(n<=0)throw new Error("Invalid DXF circle radius");return{layer:t,center:[vo(e.find(r=>r.code===10)?.value),vo(e.find(r=>r.code===20)?.value)],radius:n}}function one(e,t,n,r){const o=n[0]-t[0],i=n[1]-t[1],s=Math.hypot(o,i);if(s<=ll||Math.abs(r)<=ll)return null;const a=4*Math.atan(r),l=s*(1+r*r)/(4*Math.abs(r)),u=[(t[0]+n[0])/2,(t[1]+n[1])/2],d=[-i/s,o/s],m=s*(1-r*r)/(4*r),p=[u[0]+d[0]*m,u[1]+d[1]*m];return{layer:e,center:p,radius:l,startAngleDeg:ou(Math.atan2(t[1]-p[1],t[0]-p[0])*180/Math.PI),sweepAngleDeg:a*180/Math.PI}}function ine(e){const t=l0(e.find(l=>l.code===8)?.value),n=Math.trunc(vo(e.find(l=>l.code===70)?.value,0)),r=[];let o=null;for(const l of e){if(l.code===10){o&&Number.isFinite(o.point[0])&&Number.isFinite(o.point[1])&&r.push(o),o={point:[vo(l.value),Number.NaN],bulge:0};continue}if(l.code===20&&o){o.point[1]=vo(l.value);continue}l.code===42&&o&&(o.bulge=vo(l.value))}if(o&&Number.isFinite(o.point[0])&&Number.isFinite(o.point[1])&&r.push(o),r.length<2)throw new Error("Invalid DXF LWPOLYLINE; expected at least 2 vertices");const i=[],s=[],a=(l,u)=>{const d=l.point,m=u.point;if(!(d[0]===m[0]&&d[1]===m[1])){if(Math.abs(l.bulge)>ll){const p=one(t,d,m,l.bulge);p&&s.push(p);return}i.push({layer:t,start:d,end:m})}};for(let l=0;l180+ll?1:0,b=g.sweepAngleDeg>=0?0:1;d.push(q_(g.layer,Wc(g.layer),`M ${Pn(x[0])} ${Pn(x[1])} A ${Pn(g.radius)} ${Pn(g.radius)} 0 ${S} ${b} ${Pn(y[0])} ${Pn(y[1])}`)),bS(p,g.layer).pathCount+=1}for(const g of s.circles){const x=Om(g.center,{minX:a.minX,maxY:a.maxY});m.push({layer:g.layer,kind:Wc(g.layer),cx:Pn(x[0]),cy:Pn(x[1]),r:Pn(g.radius)}),bS(p,g.layer).circleCount+=1}return{schemaVersion:Hte,fileRef:t,sourceUrl:n,sourceUnits:i.sourceUnits,defaultThicknessMm:Pn(i.defaultThicknessMm),bounds:{minX:0,minY:0,maxX:Pn(l),maxY:Pn(u),width:Pn(l),height:Pn(u)},counts:{paths:d.length,circles:m.length,entities:d.length+m.length},layers:[...p.keys()].sort().map(g=>p.get(g)),geometry:{lines:s.lines.map(g=>({layer:g.layer,kind:Wc(g.layer),start:[Pn(g.start[0]),Pn(g.start[1])],end:[Pn(g.end[0]),Pn(g.end[1])]})),arcs:s.arcs.map(g=>({layer:g.layer,kind:Wc(g.layer),center:[Pn(g.center[0]),Pn(g.center[1])],radius:Pn(g.radius),startAngleDeg:Pn(g.startAngleDeg),sweepAngleDeg:Pn(g.sweepAngleDeg)})),circles:s.circles.map(g=>({layer:g.layer,kind:Wc(g.layer),center:[Pn(g.center[0]),Pn(g.center[1])],radius:Pn(g.radius)}))},paths:d,circles:m}}const cne=1,uD=1e-7,yS=1e-7,une=.8,dne=6,fne=160,cc=Object.freeze({id:"unclassified",label:"Unclassified",category:"other",rawLabel:""}),Z_=Object.freeze({support:0,wall:1,surface:2,infill:3,adhesion:4,calibration:5,other:6}),mne=Object.freeze([{id:"support-interface",label:"Support interface",category:"support",patterns:[/\bsupport\b.*\b(interface|roof|floor)\b/,/\binterface\b.*\bsupport\b/]},{id:"support",label:"Support",category:"support",patterns:[/\bsupport(?:s| material)?\b/]},{id:"overhang-wall",label:"Overhang wall",category:"wall",patterns:[/\boverhang\b.*\b(wall|perimeter)\b/]},{id:"outer-wall",label:"Outer wall",category:"wall",patterns:[/\bouter\b.*\b(wall|perimeter|shell)\b/,/\bexternal\b.*\b(perimeter|wall|shell)\b/,/\bwall outer\b/]},{id:"inner-wall",label:"Inner wall",category:"wall",patterns:[/\binner\b.*\b(wall|perimeter|shell)\b/,/\binternal\b.*\bperimeter\b/,/\bwall inner\b/]},{id:"wall",label:"Wall",category:"wall",patterns:[/\b(wall|perimeter|shell)\b/]},{id:"bridge",label:"Bridge",category:"surface",patterns:[/\bbridge\b/]},{id:"top-surface",label:"Top surface",category:"surface",patterns:[/\btop\b.*\b(surface|skin|shell|solid infill|infill)\b/]},{id:"bottom-surface",label:"Bottom surface",category:"surface",patterns:[/\bbottom\b.*\b(surface|skin|shell|solid infill|infill)\b/]},{id:"surface",label:"Surface",category:"surface",patterns:[/\b(skin|surface)\b/]},{id:"gap-fill",label:"Gap fill",category:"infill",patterns:[/\bgap\b.*\bfill\b/]},{id:"internal-solid-infill",label:"Internal solid infill",category:"infill",patterns:[/\binternal\b.*\bsolid\b.*\binfill\b/,/\bsolid\b.*\binfill\b/]},{id:"sparse-infill",label:"Sparse infill",category:"infill",patterns:[/\bsparse\b.*\binfill\b/,/\binternal\b.*\binfill\b/,/\bfill\b/]},{id:"infill",label:"Infill",category:"infill",patterns:[/\binfill\b/]},{id:"skirt",label:"Skirt",category:"adhesion",patterns:[/\bskirt\b/]},{id:"brim",label:"Brim",category:"adhesion",patterns:[/\bbrim\b/]},{id:"raft",label:"Raft",category:"adhesion",patterns:[/\braft\b/]},{id:"prime-tower",label:"Prime tower",category:"calibration",patterns:[/\b(prime|wipe)\b.*\btower\b/]},{id:"ironing",label:"Ironing",category:"surface",patterns:[/\bironing\b/]},{id:"flush",label:"Flush",category:"calibration",patterns:[/\bflush\b/]},{id:"wipe",label:"Wipe",category:"calibration",patterns:[/\bwipe\b/]},{id:"custom",label:"Custom",category:"other",patterns:[/\bcustom\b/]}]),pne=new Set(["G0","G1","G2","G3","G20","G21","G28","G90","G91","G92","M82","M83","M84","M104","M106","M107","M109","M140","M190"]);function Yi(e,t=0){const n=Number(e);return Number.isFinite(n)?n:t}function Ny(e){return[Yi(e?.[0]),Yi(e?.[1]),Yi(e?.[2])]}function dD(e){return String(e||"").split(";",1)[0].trim()}function hne(e){const t=dD(e).toUpperCase();if(!t)return"";const n=t.split(/\s+/,1)[0];return/^[GMT]\d+(?:\.\d+)?$/.test(n)?n.split(".",1)[0]:n}function gne(e){const t=dD(e).toUpperCase(),n={};for(const r of t.matchAll(/([A-Z])([-+]?(?:\d+(?:\.\d*)?|\.\d+))/g))n[r[1]]=Number(r[2]);return n}function bne(e){const t=String(e||""),n=t.indexOf(";");return n>=0?t.slice(n+1).trim():""}function Mv(e){return String(e||"").replace(/^["']+|["']+$/g,"").replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}function yne(e){return Mv(e).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)}function xne(e){const t=Mv(e);return t?t.toLowerCase().split(" ").map(n=>n?`${n[0].toUpperCase()}${n.slice(1)}`:"").join(" "):"Other"}function Sne(e){const t=Mv(e),n=t.toLowerCase();for(const o of mne)if(o.patterns.some(i=>i.test(n)))return{id:o.id,label:o.label,category:o.category,rawLabel:t};const r=yne(t);return{id:r?`other:${r}`:cc.id,label:r?xne(t):cc.label,category:"other",rawLabel:t}}function Ene(e){const t=bne(e);if(!t)return null;const n=t.match(/^(?:FEATURE|TYPE|PRINT_FEATURE|TOOLPATH(?:_TYPE)?|PATH_TYPE)\s*[:=]\s*(.+)$/i);return n?.[1]?Sne(n[1]):null}function wne(e,t){const n=Yi(t?.[0])-Yi(e?.[0]),r=Yi(t?.[1])-Yi(e?.[1]),o=Yi(t?.[2])-Yi(e?.[2]);return Math.hypot(n,r,o)}function fl(e){return Math.round(Yi(e)*1e6)/1e6}function J_(e,t){const n=Ny(t);for(let r=0;r<3;r+=1)e.min[r]=Math.min(e.min[r],n[r]),e.max[r]=Math.max(e.max[r],n[r])}function Q_(e){return fl(e).toFixed(6)}function vne(e,t){if(!e.length)return 0;const n=fl(t);let r=0,o=1/0;for(let i=0;iyS&&(n.primeMoves+=1);return}const p=a>yS?"extrusion":"travel";p==="extrusion"?(n.extrusionMoves+=1,n.extrusionMm+=a):n.travelMoves+=1,n.movementCommands+=1,n.pathMm+=m,J_(t,i),J_(t,s),e.push({lineNumber:r,command:o,kind:p,start:Ny(i),end:Ny(s),z:fl(s[2]),extrusionDelta:a,feedRate:Number.isFinite(l)?l:null,lengthMm:m,arc:!!u,featureId:d?.id||cc.id,featureLabel:d?.label||cc.label,featureCategory:d?.category||cc.category,featureRaw:d?.rawLabel||""})}function Ine({start:e,end:t,tokens:n,clockwise:r}){if(!Object.hasOwn(n,"I")||!Object.hasOwn(n,"J"))return null;const o=e[0]+n.I,i=e[1]+n.J,s=Math.hypot(e[0]-o,e[1]-i);if(!(s>uD))return null;const a=Math.atan2(e[1]-i,e[0]-o);let u=Math.atan2(t[1]-i,t[0]-o)-a;r&&u>=0?u-=Math.PI*2:!r&&u<=0&&(u+=Math.PI*2);const d=Math.ceil(Math.abs(u*s)/une),m=Math.max(dne,Math.min(fne,d)),p=[Ny(e)];for(let g=1;g<=m;g+=1){const x=g/m,y=a+u*x;p.push([o+s*Math.cos(y),i+s*Math.sin(y),e[2]+(t[2]-e[2])*x])}return p}function Ane(e){return!e.min.every(Number.isFinite)||!e.max.every(Number.isFinite)?{min:[0,0,0],max:[1,1,1]}:{min:e.min.map(t=>fl(t)),max:e.max.map(t=>fl(t))}}function Nne(e){const t=new Map;for(const r of e){if(r.kind!=="extrusion")continue;const o=Q_(r.z);t.has(o)||t.set(o,fl(r.z))}if(!t.size)for(const r of e){const o=Q_(r.z);t.has(o)||t.set(o,fl(r.z))}const n=[...t.values()].sort((r,o)=>r-o).map((r,o)=>({index:o,z:r,segmentCount:0,extrusionMoves:0,travelMoves:0}));for(const r of e){const o=vne(n,r.z);r.layerIndex=o,n[o]&&(n[o].segmentCount+=1,r.kind==="extrusion"?n[o].extrusionMoves+=1:n[o].travelMoves+=1)}return n}function eT(e,t){const n=t?.id?t:cc;e.has(n.id)||e.set(n.id,{id:n.id,label:n.label||cc.label,category:n.category||cc.category,rawLabels:new Set,markerCount:0,firstLine:null,lastLine:null,firstLayerIndex:null,lastLayerIndex:null,segmentCount:0,extrusionMoves:0,travelMoves:0,extrusionMm:0,pathMm:0});const r=e.get(n.id);return n.rawLabel&&r.rawLabels.add(n.rawLabel),r}function _ne(e){return!Number.isInteger(e.firstLayerIndex)||!Number.isInteger(e.lastLayerIndex)?"":e.firstLayerIndex===e.lastLayerIndex?`Layer ${e.firstLayerIndex+1}`:`Layers ${e.firstLayerIndex+1}-${e.lastLayerIndex+1}`}function Tne(e,t){const n=new Map;for(const r of t){const o=eT(n,r.feature);o.markerCount+=1,o.firstLine=o.firstLine==null?r.lineNumber:Math.min(o.firstLine,r.lineNumber),o.lastLine=o.lastLine==null?r.lineNumber:Math.max(o.lastLine,r.lineNumber)}for(const r of e){const o=eT(n,{id:r.featureId,label:r.featureLabel,category:r.featureCategory,rawLabel:r.featureRaw});o.segmentCount+=1,o.pathMm+=Yi(r.lengthMm),Number.isInteger(r.layerIndex)&&(o.firstLayerIndex=o.firstLayerIndex==null?r.layerIndex:Math.min(o.firstLayerIndex,r.layerIndex),o.lastLayerIndex=o.lastLayerIndex==null?r.layerIndex:Math.max(o.lastLayerIndex,r.layerIndex)),r.kind==="extrusion"?(o.extrusionMoves+=1,o.extrusionMm+=Yi(r.extrusionDelta)):r.kind==="travel"&&(o.travelMoves+=1)}return[...n.values()].map(r=>({...r,rawLabels:[...r.rawLabels].sort((o,i)=>o.localeCompare(i)),layerRangeText:_ne(r),pathMm:fl(r.pathMm),extrusionMm:fl(r.extrusionMm)})).sort((r,o)=>{const i=(Z_[r.category]??99)-(Z_[o.category]??99);if(i!==0)return i;const s=o.extrusionMoves-r.extrusionMoves;return s!==0?s:r.label.localeCompare(o.label)})}function Rne(e,t){const n=[...e],r=[...t.entries()].sort((o,i)=>o[0].localeCompare(i[0])).slice(0,12).map(([o,i])=>`${o} line ${i}`);return r.length&&n.push(`Unsupported or ignored commands were left out of the preview: ${r.join(", ")}.`),n}function Pne(e,{sourceUrl:t="",fileRef:n=""}={}){const r=String(e||"").split(/\r?\n/),o=[],i=new Map,s=[],a={min:[1/0,1/0,1/0],max:[-1/0,-1/0,-1/0]},l={lines:r.length,nonCommentLines:0,movementCommands:0,extrusionMoves:0,travelMoves:0,retractMoves:0,primeMoves:0,temperatureCommands:0,extrusionMm:0,pathMm:0},u={x:0,y:0,z:0,e:0};let d=!0,m=!0,p="mm",g=!1,x=!1,y=null;const S=[];for(let A=0;AMath.abs(Number(e[r]??(r===3?1:0))-n)<=jne)}function Fne(e){const t=e?.extras?.cadSourceColor;return t===!0||t===!1?t:null}function zne(e){const t=e?.userData?.cadSourceColor;return t===!0||t===!1?t:null}function Bne(e,t){return Lne(gD(e),Dne)&&t?.color?.getHexString?.()==="dddddd"}function Vne(e,t,{rawMaterial:n=null,stepTopology:r=!1}={}){if(!t||!e?.color)return null;const o=zne(e)??Fne(n);return o===!1||r&&o!==!0&&Bne(n,e)?null:{rgb:[e.color.r,e.color.g,e.color.b],hex:`#${e.color.getHexString()}`,opacity:$ne(e,n)}}function $ne(e,t=null){const n=Number(e?.opacity);if(Number.isFinite(n))return Math.min(Math.max(n,0),1);const r=gD(t)?.[3],o=Number(r);return Number.isFinite(o)?Math.min(Math.max(o,0),1):1}function Gne(e,t){if(Array.isArray(e)){const n=Number.isInteger(t?.materialIndex)?t.materialIndex:0;return e[n]||e[0]||null}return e||null}function Une(e){return Number.isInteger(e?.materialIndex)?e.materialIndex:0}function Wne(e,t){return!Array.isArray(e)||e.length<=0?null:e[Une(t)]||e[0]||null}function Hne(e){const t=e?.elements;return!Array.isArray(t)&&!(t instanceof Float32Array)?!1:[1,0,0,0,0,0,-1,0,0,1,0,0,0,0,0,1].every((r,o)=>Math.abs(Number(t[o])-r)<1e-6)}function Kne(e,t){t?.updateWorldMatrix?.(!0,!0);const n=Array.isArray(t?.children)?t.children:[];return n.length!==1||!Hne(n[0]?.matrixWorld)?null:new e.Matrix4().copy(n[0].matrixWorld).invert()}function bD(e){let t=e||null;for(;t;){const r=String(t.userData?.cadOccurrenceId||"").trim();if(r)return r;t=t.parent||null}const n=String(e?.name||"").trim();return/^o\d+(?:\.\d+)*$/.test(n)?n:""}function Xne(e){let t=!1;return e?.traverse?.(n=>{t||(t=!!String(n?.userData?.cadOccurrenceId||"").trim())}),t}function Yne(e,t){const n=e.x*SS,r=e.y*SS,o=e.z*SS;return t?{x:n,y:-o,z:r}:{x:n,y:r,z:o}}function yD(e,t){return e?e.getX(t):t}function nT(e,t){for(const n of t){const r=e?.getAttribute?.(n);if(r)return r}return null}function xD(e,t,n){for(let r=0;r<3;r+=1){const o=yD(t,n+r);if(o<0||o>=e.count)return!1}return!0}function qne(e,t,n,r){let o=0;for(let i=0;i0,r=Array.isArray(t?.parser?.json?.materials)?t.parser.json.materials:[],o=Kne(e,t?.scene),i=!!t?.parser?.json?.extensions?.STEP_topology,s=!i&&!Xne(t?.scene)&&!o,a=[],l=new Set;let u=0,d=0,m=!1;const p=new Map;t?.scene?.traverse?.(R=>{if(!R?.isMesh||!R.geometry)return;const v=bD(R)||String(R?.name||`glb:${a.length}`).trim(),C=p.get(v)||0,T=Array.isArray(R.geometry.groups)&&R.geometry.groups.length?R.geometry.groups:[null];T.forEach((k,z)=>{const Y=Zne(e,R,k,Gne(R.material,k),n,o,s,C+z,a.length,{rawMaterial:Wne(r,k),stepTopology:i});Y&&(a.push(Y),u+=Y.vertexCount,d+=Y.triangleCount*3,m||=!!(Y.surfaceEdgeBarycentric&&Y.surfaceEdgeClass),Y.color&&l.add(Y.color.toLowerCase()))}),p.set(v,C+T.length)});const g=new Float32Array(u*3),x=new Uint32Array(d),y=new Float32Array(u*3),S=m?new Float32Array(u*3):null,b=m?new Uint8Array(u*3):null,I=[],A={vertices:g,indices:x,normals:y,surfaceEdgeBarycentric:S,surfaceEdgeClass:b,bounds:pD()},N={vertexOffset:0,indexOffset:0};for(const R of a)I.push(Jne(e,R,A,N));const P=new Float32Array(0);return{vertices:g,indices:x,normals:y,surfaceEdgeBarycentric:S||new Float32Array(0),surfaceEdgeClass:b||new Uint8Array(0),colors:P,edge_indices:new Uint32Array(0),bounds:hD(A.bounds),parts:I,has_source_colors:l.size>0,sourceColor:l.size===1?[...l][0]:""}}function ere(e,t){const n=new e;return new Promise((r,o)=>{n.parse(t,"",r,o)})}async function tre(e){const[t,{GLTFLoader:n}]=await Promise.all([_o(()=>import("./vendor-three-SYzIooV9.js").then(o=>o.T),[]),_o(()=>import("./vendor-three-SYzIooV9.js").then(o=>o.G),[])]),r=await ere(n,e);return Qne(t,r)}function nre(e){e.computeBoundingBox();const t=e.boundingBox?.min,n=e.boundingBox?.max;return!t||!n?{min:[0,0,0],max:[0,0,0]}:{min:[t.x,t.y,t.z],max:[n.x,n.y,n.z]}}const rre=Math.PI/4;function ore(e,t){const n=e.clone();n.deleteAttribute?.("normal");const r=typeof t=="function"?t(n,rre):n;return r!==n&&n.dispose?.(),r.getAttribute("normal")||r.computeVertexNormals?.(),r}function ire(e,t){const n=e.getIndex?.();if(n?.count>0)return new Uint32Array(n.array);const r=new Uint32Array(t);for(let o=0;oimport("./vendor-three-SYzIooV9.js").then(i=>i.h),[]),_o(()=>import("./vendor-three-SYzIooV9.js").then(i=>i.B),[])]),o=new t().parse(e);try{return sre(o,{toCreasedNormals:n})}finally{o.dispose?.()}}const lre=new Set(["default"]),cre=new Set(["#fafafb","#b6c4ce"]),rT=Object.freeze({rgb:[.4677837961,.5520114015,.6172065624],hex:"#b6c4ce"});function u0(e){if(!e?.length)return{min:[0,0,0],max:[0,0,0]};const t=[1/0,1/0,1/0],n=[-1/0,-1/0,-1/0];for(let r=0;r+2n.localName===t)}function Td(e,t){return Ld(e,t)[0]||null}function ure(e,t){if(!e?.attributes)return"";const n=e.getAttribute?.(t);if(n)return n;for(const r of Array.from(e.attributes))if(r.localName===t||String(r.name||"").split(":").pop()===t)return r.value||"";return""}function ES(e,t=0){const n=Number(e);return Number.isFinite(n)?n:t}function wS(e){const t=Number(e);return Number.isInteger(t)&&t>=0?t:-1}function SD(e,t){if(typeof DOMParser!="function")throw new Error("3MF XML parsing is unavailable in this environment");const n=new DOMParser().parseFromString(e,"application/xml");if(n.querySelector?.("parsererror"))throw new Error(`Invalid 3MF XML: ${t}`);return n}function oT(e,t){const n=String(t||"").trim().split(/\s+/).map(o=>Number(o));if(n.length!==12||n.some(o=>!Number.isFinite(o)))return null;const r=new e.Matrix4;return r.set(n[0],n[3],n[6],n[9],n[1],n[4],n[7],n[10],n[2],n[5],n[8],n[11],0,0,0,1),r}function dre(e){const t=[],n=Td(e,"vertices");for(const i of Ld(n,"vertex"))t.push([ES(i.getAttribute("x")),ES(i.getAttribute("y")),ES(i.getAttribute("z"))]);const r=[],o=Td(e,"triangles");for(const i of Ld(o,"triangle")){const s=[wS(i.getAttribute("v1")),wS(i.getAttribute("v2")),wS(i.getAttribute("v3"))];s.every(a=>a>=0)&&r.push(s)}return{vertices:t,triangles:r}}function fre(e,t,n){const r=SD(t,n),o=r.documentElement?.localName==="model"?r.documentElement:r.querySelector?.("model");if(!o)throw new Error(`3MF model part is missing a model node: ${n}`);const i=Td(o,"resources"),s=new Map;for(const u of Ld(i,"object")){const d=String(u.getAttribute("id")||"").trim();if(!d)continue;const m=String(u.getAttribute("name")||u.getAttribute("partnumber")||"").trim(),p=Td(u,"mesh"),g=Td(u,"components"),x=[];for(const y of Ld(g,"component")){const S=String(y.getAttribute("objectid")||"").trim();S&&x.push({objectId:S,path:Iv(ure(y,"path"),n),transform:oT(e,y.getAttribute("transform"))})}s.set(d,{id:d,name:m,mesh:p?dre(p):null,components:x})}const a=[],l=Td(o,"build");for(const u of Ld(l,"item")){const d=String(u.getAttribute("objectid")||"").trim();d&&a.push({objectId:d,transform:oT(e,u.getAttribute("transform"))})}return{path:n,objects:s,build:a}}function mre(e,t){const n=SD(e,t);return Array.from(n.querySelectorAll?.("Relationship")||[]).map(r=>({target:Iv(r.getAttribute("Target")),type:String(r.getAttribute("Type")||"").trim()})).filter(r=>r.target)}function pre(e){if(!e?.color)return null;const t=`#${e.color.getHexString()}`.toLowerCase(),n=String(e.name||"").trim().toLowerCase();return lre.has(n)&&cre.has(t)?{rgb:rT.rgb,hex:rT.hex,generatedDefault:!0}:{rgb:[e.color.r,e.color.g,e.color.b],hex:t,generatedDefault:!1}}function hre(e,t){if(Array.isArray(e)){const n=Number.isInteger(t?.materialIndex)?t.materialIndex:0;return e[n]||e[0]||null}return e||null}function gre(e,t,n,r,o){const i=n?.geometry,s=i?.getAttribute?.("position");if(!s||s.itemSize!==3||s.count<=0)return;i.getAttribute("normal")||i.computeVertexNormals?.(),n.updateWorldMatrix?.(!0,!1);const a=n.matrixWorld||null,l=a?new e.Matrix3().getNormalMatrix(a):null,u=i.getAttribute("normal"),d=i.getIndex?.(),m=Math.max(0,Math.floor(Number(r?.start||0))),p=d?.count||s.count,g=Math.floor(Number(r?.count||p-m)),x=Math.max(0,Math.min(g,p-m)),y=x-x%3;if(y<=0)return;const S=pre(o),b=new e.Vector3,I=new e.Vector3,A=Math.floor(t.vertices.length/3),N=Math.floor(t.indices.length/3),P=[];for(let k=0;k=s.count)continue;const K=Math.floor(P.length/3);b.set(s.getX(Y),s.getY(Y),s.getZ(Y)),a&&b.applyMatrix4(a),t.vertices.push(b.x,b.y,b.z),P.push(b.x,b.y,b.z),u?.itemSize===3&&Y{if(s?.isMesh&&s.geometry){const a=Array.isArray(s.geometry.groups)&&s.geometry.groups.length?s.geometry.groups:[null];for(const l of a)gre(e,n,s,l,hre(s.material,l))}});const r=new Float32Array(n.vertices),o=n.colors.length===n.vertices.length?new Float32Array(n.colors):new Float32Array(0),i=o.length===r.length&&o.length>0&&n.colorSet.size>0;return{vertices:r,indices:new Uint32Array(n.indices),normals:new Float32Array(n.normals),colors:i?o:new Float32Array(0),edge_indices:new Uint32Array(0),bounds:u0(r),parts:n.parts,has_source_colors:i,sourceColor:n.colorSet.size===1?[...n.colorSet][0]:""}}function yre(e,t,n,r,o){if(!n?.vertices?.length||!n?.triangles?.length)return;const i=Math.floor(t.vertices.length/3),s=Math.floor(t.indices.length/3),a=new e.Vector3,l=[new e.Vector3,new e.Vector3,new e.Vector3],u=new e.Vector3,d=new e.Vector3,m=new e.Vector3,p=[];for(const b of n.triangles){const I=b.map(A=>n.vertices[A]);if(!I.some(A=>!A)){for(let A=0;A<3;A+=1){const N=I[A];l[A].set(N[0],N[1],N[2]).applyMatrix4(r)}u.subVectors(l[1],l[0]),d.subVectors(l[2],l[0]),m.crossVectors(u,d).normalize(),(!Number.isFinite(m.x)||!Number.isFinite(m.y)||!Number.isFinite(m.z))&&m.set(0,0,0);for(const A of l){a.copy(A);const N=Math.floor(p.length/3);t.vertices.push(a.x,a.y,a.z),p.push(a.x,a.y,a.z),t.normals.push(m.x,m.y,m.z),t.indices.push(i+N)}}}const g=Math.floor(p.length/3),x=Math.floor(g/3);if(g<=0||x<=0)return;const y=`3mf:${t.parts.length}`,S=String(o||y).trim()||y;t.parts.push({id:y,occurrenceId:y,name:S,label:S,nodeType:"part",color:"",bounds:u0(p),vertexOffset:i,vertexCount:g,triangleOffset:s,triangleCount:x,edgeIndexOffset:0,edgeIndexCount:0})}function xre(e,t){for(const[n,r]of e)if(r.objects.has(t))return{modelPath:n,objectData:r.objects.get(t)};return null}function ED(e,t,n,r,o,i,s=[]){const a=`${r}#${o}`;if(s.includes(a))throw new Error(`3MF component cycle detected at ${a}`);let u=n.get(r)?.objects?.get(o)||null,d=r;if(!u){const m=xre(n,o);u=m?.objectData||null,d=m?.modelPath||r}if(!u)throw new Error(`3MF object ${o} is missing from ${r}`);if(u.mesh){yre(e,t,u.mesh,i,u.name||`${d}#${u.id}`);return}for(const m of u.components||[]){const p=m.path||d,g=i.clone();m.transform&&g.multiply(m.transform),ED(e,t,n,p,m.objectId,g,[...s,a])}}function Sre(e){const t=new Float32Array(e.vertices);return{vertices:t,indices:new Uint32Array(e.indices),normals:new Float32Array(e.normals),colors:new Float32Array(0),edge_indices:new Uint32Array(0),bounds:u0(t),parts:e.parts,has_source_colors:!1,sourceColor:""}}async function Ere(e,t){const n=await _o(()=>import("./vendor-three-SYzIooV9.js").then(S=>S.i),[]),r=new TextDecoder,o=n.unzipSync(new Uint8Array(t)),i=S=>{const b=Iv(S),I=o[b];return I?r.decode(I):""},s=Object.keys(o).filter(S=>/^3D\/.*\.model$/i.test(S)).sort((S,b)=>{const I=/\/3dmodel\.model$/i.test(S)?1:0,A=/\/3dmodel\.model$/i.test(b)?1:0;return I-A||S.localeCompare(b)});if(!s.length)throw new Error("3MF package does not contain any 3D model parts");const a=new Map;for(const S of s){const b=i(S);b&&a.set(S,fre(e,b,S))}const l=i("_rels/.rels"),u=l?mre(l,"_rels/.rels").find(S=>/\.model$/i.test(S.target))?.target:"",d=a.has(u)?u:s.find(S=>a.get(S)?.build?.length)||s[0],m=a.get(d);if(!m)throw new Error("3MF package does not contain a readable build model");const p=new e.Matrix4,g={vertices:[],indices:[],normals:[],parts:[]},x=m.build.length?m.build:Array.from(m.objects.keys()).map(S=>({objectId:S,transform:null}));for(const S of x){const b=S.transform?S.transform.clone():p.clone();ED(e,g,a,d,S.objectId,b)}const y=Sre(g);if(!y.indices.length)throw new Error("3MF package did not produce any triangles");return y}async function wre(e){const[t,{ThreeMFLoader:n}]=await Promise.all([_o(()=>import("./vendor-three-SYzIooV9.js").then(o=>o.T),[]),_o(()=>import("./vendor-three-SYzIooV9.js").then(o=>o._),[])]),r=new n;try{return bre(t,r.parse(e))}catch(o){try{return await Ere(t,e)}catch{throw o}}}let Wa=null,iT=1;const ef=new Map;function sT(){if(typeof DOMException=="function")return new DOMException("The operation was aborted.","AbortError");const e=new Error("The operation was aborted.");return e.name="AbortError",e}function vre(){return typeof Worker=="function"&&typeof URL=="function"}function Cre(e){for(const t of ef.values())t.cleanup(),t.reject(e);ef.clear()}function Mre(){if(!vre())return null;if(Wa)return Wa;try{Wa=new Worker(new URL("/assets/glbMeshWorker-MCreI3ZZ.js",import.meta.url),{type:"module"})}catch{return Wa=null,null}return Wa.addEventListener("message",e=>{const t=e.data||{},n=ef.get(t.id);if(!n)return;if(ef.delete(t.id),n.cleanup(),t.ok){n.resolve(t.meshData);return}const r=new Error(t.error?.message||"Failed to load GLB mesh in worker.");r.name=t.error?.name||"Error",n.reject(r)}),Wa.addEventListener("error",e=>{const t=new Error(e?.message||"GLB mesh worker failed.");Cre(t),Wa?.terminate?.(),Wa=null}),Wa}function Ire(e,{signal:t}={}){const n=Mre();if(!n)return null;if(t?.aborted)return Promise.reject(sT());const r=iT;return iT+=1,new Promise((o,i)=>{const s=()=>{t?.removeEventListener?.("abort",a)},a=()=>{ef.delete(r),s(),n.postMessage({type:"cancel",id:r}),i(sT())};ef.set(r,{resolve:o,reject:i,cleanup:s}),t?.addEventListener?.("abort",a,{once:!0}),n.postMessage({type:"loadGlb",id:r,url:e})})}let Ha=null,aT=1;const tf=new Map;function lT(){if(typeof DOMException=="function")return new DOMException("The operation was aborted.","AbortError");const e=new Error("The operation was aborted.");return e.name="AbortError",e}function Are(){return typeof Worker=="function"&&typeof URL=="function"}function Nre(e){for(const t of tf.values())t.cleanup(),t.reject(e);tf.clear()}function _re(){if(!Are())return null;if(Ha)return Ha;try{Ha=new Worker(new URL("/assets/stlMeshWorker-0yVf-FuZ.js",import.meta.url),{type:"module"})}catch{return Ha=null,null}return Ha.addEventListener("message",e=>{const t=e.data||{},n=tf.get(t.id);if(!n)return;if(tf.delete(t.id),n.cleanup(),t.ok){n.resolve(t.meshData);return}const r=new Error(t.error?.message||"Failed to load STL mesh in worker.");r.name=t.error?.name||"Error",n.reject(r)}),Ha.addEventListener("error",e=>{const t=new Error(e?.message||"STL mesh worker failed.");Nre(t),Ha?.terminate?.(),Ha=null}),Ha}function Tre(e,{signal:t}={}){const n=_re();if(!n)return null;if(t?.aborted)return Promise.reject(lT());const r=aT;return aT+=1,new Promise((o,i)=>{const s=()=>{t?.removeEventListener?.("abort",a)},a=()=>{tf.delete(r),s(),n.postMessage({type:"cancel",id:r}),i(lT())};tf.set(r,{resolve:o,reject:i,cleanup:s}),t?.addEventListener?.("abort",a,{once:!0}),n.postMessage({type:"loadStl",id:r,url:e})})}function vf(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function wD(e,t){return new Error(`Failed to fetch ${e}: ${t.status} ${t.statusText}`)}const cT=new Map,uT=new Map,ob=new Map,lE=new Map,cE=new Map,uE=new Map,dE=new Map,fE=new Map,mE=new Map,pE=new Map,hE=new Map,gE=new Map,bE=new Map,yE=new Map,Rre="version https://git-lfs.github.com/spec/v1",Pre=512;async function Ore(e,{signal:t}={}){const n=await fetch(e,{signal:t});if(!n.ok)throw wD(e,n);return n.text()}async function kre(e,{signal:t}={}){const n=await fetch(e,{signal:t});if(!n.ok)throw wD(e,n);return n.arrayBuffer()}async function Is(e,t,n,{cachePending:r=!0}={}){if(!t)throw new Error("Missing asset cache key");if(e.has(t)){const i=e.get(t);if(r||typeof i?.then!="function")return i}if(!r){const i=await n();return e.set(t,i),i}let o;return o=n().catch(i=>{throw e.get(t)===o&&e.delete(t),i}),e.set(t,o),o}function As(e,t){const n=e.get(t);return n&&typeof n.then!="function"?n:null}function ns(e,t,n){return e.set(t,n),n}function Za(e){return e instanceof DOMException&&e.name==="AbortError"}function Dre(e){const t=Number(e?.byteLength||0);if(!Number.isFinite(t)||t<=0)return null;const n=new TextDecoder("utf-8").decode(new Uint8Array(e,0,Math.min(t,Pre)));if(!n.startsWith(Rre))return null;const r=n.match(/^oid sha256:([0-9a-f]{64})\r?$/m)?.[1]||"",o=n.match(/^size ([0-9]+)\r?$/m)?.[1]||"",i=o?Number(o):null;return{oid:r,size:Number.isSafeInteger(i)?i:null}}function jre(e){const t=String(e||"").trim();if(!t)return"(unknown)";try{const n=typeof window<"u"&&window.location?.href?window.location.href:"http://localhost/",r=new URL(t,n);return decodeURIComponent(r.pathname||t)}catch{return t.split(/[?#]/)[0]||t}}function Cf(e,t,n="Render asset"){const r=Dre(e);if(!r)return;const o=r.size!==null?` Expected LFS object size: ${r.size} bytes.`:"",i=r.oid?` sha256:${r.oid}.`:"";throw new Error(`${n} is a Git LFS pointer, not downloaded mesh data: ${jre(t)}.${i}${o} Fetch the LFS object for this file and reload the viewer.`)}function xE(){if(typeof DOMException=="function")return new DOMException("The operation was aborted.","AbortError");const e=new Error("The operation was aborted.");return e.name="AbortError",e}function Lre(e,t){return t?t.aborted?Promise.reject(xE()):new Promise((n,r)=>{const o=()=>{t.removeEventListener?.("abort",i)},i=()=>{o(),r(xE())};t.addEventListener?.("abort",i,{once:!0}),e.then(s=>{o(),n(s)},s=>{o(),r(s)})}):e}async function bh(e,{signal:t}={}){const n=await Is(cT,e,()=>Ore(e,{signal:t}),{cachePending:!t});return ns(cT,e,n)}async function Mf(e,{signal:t}={}){if(!e)throw new Error("Missing asset cache key");if(t?.aborted)throw xE();const n=As(uT,e);if(n)return n;let r=ob.get(e);return r||(r=kre(e).then(o=>ns(uT,e,o)).finally(()=>{ob.get(e)===r&&ob.delete(e)}),ob.set(e,r)),Lre(r,t)}async function vD(e,{signal:t,preferWorker:n=!1}={}){const r=await Is(lE,e,async()=>{if(n){const i=Ire(e,{signal:t});if(i)try{return await i}catch(s){if(t?.aborted||Za(s))throw s}}const o=await Mf(e,{signal:t});return Cf(o,e,"GLB render asset"),tre(o)},{cachePending:!t});return ns(lE,e,r)}function CD(e){return As(lE,e)}async function Fre(e,{signal:t}={}){const n=await Is(cE,e,async()=>{const r=Tre(e,{signal:t});if(r)try{return await r}catch(i){if(t?.aborted||Za(i))throw i}const o=await Mf(e,{signal:t});return Cf(o,e,"STL render asset"),are(o)},{cachePending:!t});return ns(cE,e,n)}function zre(e){return As(cE,e)}async function Bre(e,{signal:t}={}){const n=await Is(uE,e,async()=>{const r=await Mf(e,{signal:t});return Cf(r,e,"3MF render asset"),wre(r)},{cachePending:!t});return ns(uE,e,n)}function Vre(e){return As(uE,e)}function Av(e){const t=new DataView(e);if(t.byteLength<20||t.getUint32(0,!0)!==1179937895||t.getUint32(4,!0)!==2)throw new Error("Invalid GLB topology container");const n=Math.min(t.getUint32(8,!0),t.byteLength);let r=12,o=null,i=null;for(;r+8<=n;){const s=t.getUint32(r,!0),a=t.getUint32(r+4,!0);if(r+=8,r+s>n)throw new Error("Invalid GLB chunk length");a===1313821514?o=JSON.parse(new TextDecoder("utf-8").decode(e.slice(r,r+s)).trim()):a===5130562&&(i={buffer:e,byteOffset:r,byteLength:s}),r+=s}if(!o||!i)throw new Error("GLB topology requires JSON and BIN chunks");return{json:o,bin:i}}function MD(e,t,n){const r=Number(n),o=Array.isArray(e?.bufferViews)?e.bufferViews[r]:null;if(!Number.isInteger(r)||!o||Number(o.buffer||0)!==0)return null;const i=t.byteOffset+Number(o.byteOffset||0),s=Number(o.byteLength||0);return!Number.isFinite(i)||!Number.isFinite(s)||s<0||it.byteOffset+t.byteLength?null:{byteOffset:i,byteLength:s}}function $re(e,t){if(!vf(t))return null;const n=MD(e.json,e.bin,t.bufferView);if(!n)return null;const r=Number(t.count||0),o=Number(t.byteOffset||0);if(!Number.isFinite(r)||r<0||!Number.isFinite(o)||o<0)return null;const i=n.byteOffset+o;return t.dtype==="float32"?new Float32Array(e.bin.buffer,i,r):t.dtype==="uint32"?new Uint32Array(e.bin.buffer,i,r):null}function ID(e,t){const n=e?.buffers?.views;if(!vf(n))return{};const r={};for(const[o,i]of Object.entries(n)){const s=$re(t,i);s&&(r[o]=s)}return r}function Gre(e){const t=Array.isArray(e?.json?.meshes)?e.json.meshes:[];let n=0;for(const r of t)for(const o of Array.isArray(r?.primitives)?r.primitives:[]){n+=1;const i=o?.attributes||{};if(i[fD]===void 0||i[mD]===void 0)return!1}return n>0}function Nv(e){const t=e.json?.extensions?.[xs];if(!vf(t))throw new Error(`GLB is missing ${xs}`);if(!c0(t.schemaVersion))throw new Error(`Unsupported ${xs} schemaVersion ${t.schemaVersion||"unknown"}; expected ${gh}`);if(t.edgeView===void 0||t.edgeView===null)throw new Error(`${xs} edgeView is not available`);if(!Gre(e))throw new Error(`${xs} requires ${fD} and ${mD} on every STEP mesh primitive`);return t}function _v(e,t,n="utf-8"){const r=MD(e.json,e.bin,t);if(!r)return null;const o=new Uint8Array(e.bin.buffer,r.byteOffset,r.byteLength);return JSON.parse(new TextDecoder(String(n||"utf-8")).decode(o))}function Ure(e){const t=Av(e),n=Nv(t),r=_v(t,n.indexView,n.encoding);if(!vf(r))throw new Error(`${xs} indexView is invalid`);if(!c0(r.schemaVersion))throw new Error(`Unsupported ${xs} index schemaVersion ${r.schemaVersion||"unknown"}; expected ${gh}`);return r}function Wre(e){const t=Av(e),n=Nv(t),r=_v(t,n.selectorView,n.encoding);if(!vf(r))throw new Error(`${xs} selectorView is not available`);if(!c0(r.schemaVersion))throw new Error(`Unsupported ${xs} selector schemaVersion ${r.schemaVersion||"unknown"}; expected ${gh}`);if(r?.buffers?.littleEndian===!1)throw new Error("Big-endian selector buffers are not supported");return{manifest:r,buffers:ID(r,t)}}function Hre(e){const t=Av(e),n=Nv(t),r=_v(t,n.edgeView,n.encoding);if(!vf(r))throw new Error(`${xs} edgeView is not available`);if(!c0(r.schemaVersion))throw new Error(`Unsupported ${xs} edgeView schemaVersion ${r.schemaVersion||"unknown"}; expected ${gh}`);if(String(r.profile||"")!=="surface-edges")throw new Error(`${xs} edgeView has unsupported profile ${r.profile||"unknown"}`);if(r?.buffers?.littleEndian===!1)throw new Error("Big-endian edgeView buffers are not supported");return{manifest:r,buffers:ID(r,t)}}async function Kre(e,{signal:t}={}){const n=await Is(mE,e,async()=>{const r=await Mf(e,{signal:t});return Cf(r,e,"GLB topology asset"),Ure(r)},{cachePending:!t});return ns(mE,e,n)}function Xre(e){return As(mE,e)}async function Yre(e,{signal:t}={}){const n=e,r=await Is(dE,n,async()=>{const o=await Mf(e,{signal:t});return Cf(o,e,"GLB selector topology asset"),Wre(o)},{cachePending:!t});return ns(dE,n,r)}function qre(e){return As(dE,e)}async function Zre(e,{signal:t}={}){const n=e,r=await Is(fE,n,async()=>{const o=await Mf(e,{signal:t});return Cf(o,e,"GLB display edge topology asset"),Hre(o)},{cachePending:!t});return ns(fE,n,r)}function Jre(e){return As(fE,e)}async function Qre(e,{signal:t}={}){const n=await Is(pE,e,async()=>{const r=await bh(e,{signal:t});return lne(r,{fileRef:"",sourceUrl:e})},{cachePending:!t});return ns(pE,e,n)}function eoe(e){return As(pE,e)}async function toe(e,{signal:t}={}){const n=await Is(hE,e,async()=>{const r=await bh(e,{signal:t});return Pne(r,{fileRef:"",sourceUrl:e})},{cachePending:!t});return ns(hE,e,n)}function noe(e){return As(hE,e)}function AD(e){return String(e||"")}async function ND(e,{signal:t}={}){const n=AD(e),r=await Is(gE,n,async()=>{const[o,{parseUrdf:i}]=await Promise.all([bh(e,{signal:t}),_o(()=>import("./parseUrdf-C7WqROHT.js"),__vite__mapDeps([0,1,2,3,4]))]);return i(o,{sourceUrl:e})},{cachePending:!t});return ns(gE,n,r)}function roe(e){return As(gE,AD(e))}function _D(e,t=""){return[e,t].filter(Boolean).join("::")}async function ooe(e,{signal:t,urdfUrl:n=""}={}){const r=_D(e,n),o=await Is(bE,r,async()=>{const[i,s,{parseSrdf:a,motionFromSrdf:l}]=await Promise.all([bh(e,{signal:t}),ND(n,{signal:t}),_o(()=>import("./parseSrdf-5nF_MoHR.js"),[])]),u=a(i,{sourceUrl:e,urdfData:s});return{srdfData:u,urdfData:{...s,motion:l(u),srdf:u}}},{cachePending:!t});return ns(bE,r,o)}function ioe(e,{urdfUrl:t=""}={}){return As(bE,_D(e,t))}function TD(e){return String(e||"")}async function soe(e,{signal:t}={}){const n=TD(e),r=await Is(yE,n,async()=>{const[o,{parseSdf:i}]=await Promise.all([bh(e,{signal:t}),_o(()=>import("./parseSdf-D2U6Dgo_.js"),__vite__mapDeps([5,1,2,3,4]))]);return i(o,{sourceUrl:e})},{cachePending:!t});return ns(yE,n,r)}function aoe(e){return As(yE,TD(e))}const Hc=new Map;function RD(e){return String(e||"").trim()}function loe(e){const t=String(e||"").trim();if(!t)throw new Error("Missing implicit CAD module URL");return t}async function coe(e,{signal:t}={}){const n=RD(e);if(!n)throw new Error("Missing implicit CAD module URL");if(t?.aborted)throw new DOMException("The operation was aborted.","AbortError");if(!Hc.has(n)){let o;o=import(loe(n)).then(i=>{const s=pf(i,{sourceUrl:n});return Hc.get(n)===o&&Hc.set(n,s),s}).catch(i=>{throw Hc.delete(n),i}),Hc.set(n,o)}const r=Hc.get(n);return!r||typeof r.then!="function"||!t?r:new Promise((o,i)=>{const s=()=>{t.removeEventListener?.("abort",s),i(new DOMException("The operation was aborted.","AbortError"))};if(t.aborted){s();return}t.addEventListener?.("abort",s,{once:!0}),r.then(a=>{t.removeEventListener?.("abort",s),o(a)},a=>{t.removeEventListener?.("abort",s),i(a)})})}function uoe(e){const t=Hc.get(RD(e));return t&&typeof t.then!="function"?t:null}const _y=Object.freeze([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),doe=/^#(?:[0-9a-fA-F]{3}){1,2}$/,ib=32,sb=24,vS=12;function CS(e){return e<=.04045?e/12.92:((e+.055)/1.055)**2.4}function SE(e){const t=String(e||"").trim();if(!doe.test(t))return null;const n=t.length===4?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:t;return[CS(Number.parseInt(n.slice(1,3),16)/255),CS(Number.parseInt(n.slice(3,5),16)/255),CS(Number.parseInt(n.slice(5,7),16)/255)]}function es(e,t=_y){return!Array.isArray(e)||e.length!==16?[...t]:e.map((n,r)=>Number.isFinite(Number(n))?Number(n):t[r])}function d0(e,t=[0,0,1]){return!Array.isArray(e)||e.length<3?[...t]:[Number.isFinite(Number(e[0]))?Number(e[0]):t[0],Number.isFinite(Number(e[1]))?Number(e[1]):t[1],Number.isFinite(Number(e[2]))?Number(e[2]):t[2]]}function PD(e){const[t,n,r]=d0(e,[0,0,1]),o=Math.hypot(t,n,r);return o<=1e-9?[0,0,1]:[t/o,n/o,r/o]}function Fd(e,t){const n=es(e),r=es(t),o=new Array(16).fill(0);for(let i=0;i<4;i+=1)for(let s=0;s<4;s+=1){let a=0;for(let l=0;l<4;l+=1)a+=n[i*4+l]*r[l*4+s];o[i*4+s]=a}return o}function foe(e,t,n){return[1,0,0,Number.isFinite(Number(e))?Number(e):0,0,1,0,Number.isFinite(Number(t))?Number(t):0,0,0,1,Number.isFinite(Number(n))?Number(n):0,0,0,0,1]}function moe(e,t,n){const r=Number.isFinite(Number(e))?Number(e):0,o=Number.isFinite(Number(t))?Number(t):0,i=Number.isFinite(Number(n))?Number(n):0,s=Math.sin(r),a=Math.cos(r),l=Math.sin(o),u=Math.cos(o),d=Math.sin(i),m=Math.cos(i);return[m*u,m*l*s-d*a,m*l*a+d*s,0,d*u,d*l*s+m*a,d*l*a-m*s,0,-l,u*s,u*a,0,0,0,0,1]}function Hae(e){const t=Array.isArray(e)?e:[];return Fd(foe(t[0],t[1],t[2]),moe(t[3],t[4],t[5]))}function poe(e,t){const[n,r,o]=PD(e),i=Math.cos(t),s=Math.sin(t),a=1-i;return[i+n*n*a,n*r*a-o*s,n*o*a+r*s,0,r*n*a+o*s,i+r*r*a,r*o*a-n*s,0,o*n*a-r*s,o*r*a+n*s,i+o*o*a,0,0,0,0,1]}function Ty(e,t){const n=es(e),[r,o,i]=d0(t,[0,0,0]);return[n[0]*r+n[1]*o+n[2]*i+n[3],n[4]*r+n[5]*o+n[6]*i+n[7],n[8]*r+n[9]*o+n[10]*i+n[11]]}function OD(e){const t=es(e);return[t[0],t[4],t[8],-(t[0]*t[3]+t[4]*t[7]+t[8]*t[11]),t[1],t[5],t[9],-(t[1]*t[3]+t[5]*t[7]+t[9]*t[11]),t[2],t[6],t[10],-(t[2]*t[3]+t[6]*t[7]+t[10]*t[11]),0,0,0,1]}function hoe(e,t){const n=Array.isArray(e?.min)?e.min:[0,0,0],r=Array.isArray(e?.max)?e.max:[0,0,0],i=[[n[0],n[1],n[2]],[n[0],n[1],r[2]],[n[0],r[1],n[2]],[n[0],r[1],r[2]],[r[0],n[1],n[2]],[r[0],n[1],r[2]],[r[0],r[1],n[2]],[r[0],r[1],r[2]]].map(u=>Ty(t,u)),s=i.map(u=>u[0]),a=i.map(u=>u[1]),l=i.map(u=>u[2]);return{min:[Math.min(...s),Math.min(...a),Math.min(...l)],max:[Math.max(...s),Math.max(...a),Math.max(...l)]}}function qp(e){const t=(Array.isArray(e)?e:[]).filter(Boolean);if(!t.length)return{min:[0,0,0],max:[0,0,0]};const n=t.flatMap(i=>[i.min[0],i.max[0]]),r=t.flatMap(i=>[i.min[1],i.max[1]]),o=t.flatMap(i=>[i.min[2],i.max[2]]);return{min:[Math.min(...n),Math.min(...r),Math.min(...o)],max:[Math.max(...n),Math.max(...r),Math.max(...o)]}}function goe(e){const t=Array.isArray(e?.joints)?e.joints:[];return Object.fromEntries(t.filter(n=>String(n?.type||"")!=="fixed"&&!n?.mimic).map(n=>[String(n?.name||""),Number(n?.defaultValueDeg)||0]).filter(([n])=>n))}function uc(e,t){const n=Number(e?.defaultValueDeg)||0,r=String(e?.type||"");if(r==="fixed")return n;const o=Number.isFinite(Number(t))?Number(t):n;if(r==="continuous")return o;const i=Number.isFinite(Number(e?.minValueDeg))?Number(e.minValueDeg):o,s=Number.isFinite(Number(e?.maxValueDeg))?Number(e.maxValueDeg):o;return Math.min(Math.max(o,i),Math.max(i,s))}function kD(e){const t=String(e?.type||"fixed");return t==="continuous"||t==="revolute"}function boe(e,t){const n=uc(e,t);return kD(e)?n*Math.PI/180:n}function yoe(e,t){const n=Number.isFinite(Number(t))?Number(t):0;return kD(e)?n*180/Math.PI:n}function xoe(e,t){const[n,r,o]=PD(e),i=Number.isFinite(Number(t))?Number(t):0;return[1,0,0,n*i,0,1,0,r*i,0,0,1,o*i,0,0,0,1]}function Soe(e,t){const n=String(e?.type||"fixed"),r=es(e?.originTransform),o=es(e?.preMotionTransform,r),i=es(e?.postMotionTransform);if(n==="fixed")return Fd(o,i);const s=d0(e?.axis??e?.axisInJointFrame??e?.axisInParentFrame,[0,0,1]);let a;if(n==="prismatic")a=xoe(s,uc(e,t));else{const l=uc(e,t)*Math.PI/180;a=poe(s,l)}return Fd(Fd(o,a),i)}function DD(e,t,n,r=new Set){const o=String(e?.name||"");if(!e?.mimic)return uc(e,n?.[o]);if(r.has(o))return uc(e,e?.defaultValueDeg);r.add(o);const i=e.mimic,s=t.get(String(i.joint||"")),a=s?DD(s,t,n,r):Number(n?.[i.joint])||0;r.delete(o);const l=s?boe(s,a):a,u=Number.isFinite(Number(i.multiplier))?Number(i.multiplier):1,d=Number.isFinite(Number(i.offset))?Number(i.offset):0;return uc(e,yoe(e,u*l+d))}function Tv(e,t={}){const n=String(e?.rootLink||""),r=es(e?.rootWorldTransform),o=Array.isArray(e?.joints)?e.joints:[],i=new Map(o.map(u=>[String(u?.name||""),u]).filter(([u])=>u)),s=new Map;if(!n)return s;const a=new Map;for(const u of o){const d=String(u?.parentLink||"");if(!d)continue;const m=a.get(d)||[];m.push(u),a.set(d,m)}const l=(u,d)=>{s.set(u,d);const m=a.get(u)||[];for(const p of m){const g=String(p?.childLink||"");if(!g)continue;const x=DD(p,i,t),y=Fd(d,Soe(p,x));l(g,y)}};return l(n,r),s}function EE(e,t,n,r){const o=String(n||"").trim(),i=String(r||"").trim();if(!o||!i)return null;const s=Tv(e,t),a=s.get(o),l=s.get(i);return!a||!l?null:Ty(OD(l),Ty(a,[0,0,0]))}function Eoe(e,t,n,r){const o=String(r||"").trim();if(!o)return null;const s=Tv(e,t).get(o);return s?Ty(OD(s),n):null}function woe(e,t,n){const r=t||n;return r?e instanceof Map?e.get(r)||null:e&&typeof e=="object"&&e[r]||null:null}function Rv(e,t){return{min:e,max:t}}function Pv(e,t,n,r){return{vertices:new Float32Array(e),normals:new Float32Array(t),indices:new Uint32Array(n),colors:new Float32Array(0),edge_indices:new Uint32Array(0),bounds:r,has_source_colors:!1}}function voe(e){const[t,n,r]=d0(e,[1,1,1]),o=t/2,i=n/2,s=r/2,a=[],l=[],u=[],d=[[[1,0,0],[[o,-i,-s],[o,i,-s],[o,i,s],[o,-i,s]]],[[-1,0,0],[[-o,i,-s],[-o,-i,-s],[-o,-i,s],[-o,i,s]]],[[0,1,0],[[-o,i,-s],[o,i,-s],[o,i,s],[-o,i,s]]],[[0,-1,0],[[o,-i,-s],[-o,-i,-s],[-o,-i,s],[o,-i,s]]],[[0,0,1],[[-o,-i,s],[o,-i,s],[o,i,s],[-o,i,s]]],[[0,0,-1],[[-o,i,-s],[o,i,-s],[o,-i,-s],[-o,-i,-s]]]];for(const[m,p]of d){const g=a.length/3;for(const x of p)a.push(...x),l.push(...m);u.push(g,g+1,g+2,g,g+2,g+3)}return Pv(a,l,u,Rv([-o,-i,-s],[o,i,s]))}function Coe(e,t){const n=Number.isFinite(Number(e))?Number(e):.5,r=(Number.isFinite(Number(t))?Number(t):1)/2,o=[],i=[],s=[];for(let a=0;aI.bounds)),parts:S,has_source_colors:b,lightweightGeometry:!0,geometrySource:{type:"urdf-source-parts",urdfData:e,meshesByUrl:t}}}let i=0,s=0,a=!1;for(const S of r){const b=S.partMesh;i+=Math.floor((b.vertices?.length||0)/3),s+=b.indices?.length||0;const I=String(S.visual?.color||"").trim();a||=dT(I,b)}const l=a,u=new Float32Array(i*3),d=new Float32Array(i*3),m=new Uint32Array(s),p=l?new Float32Array(i*3).fill(1):new Float32Array(0),g=[];let x=0,y=0;for(let S=0;SS.bounds)),parts:g,has_source_colors:l}}function wE(e){return!!e?.has_source_colors&&e.colors?.length>0&&e.colors.length===e.vertices?.length}function dT(e,t){return!!SE(e)||!e&&wE(t)}function _oe(e,t,n={},r=null){const o=Tv(e,n);if(r instanceof Map)for(const[l,u]of r.entries())o.set(String(l||""),es(u));else if(r&&typeof r=="object")for(const[l,u]of Object.entries(r))o.set(String(l||""),es(u));const i=Array.isArray(t?.parts)?t.parts:[],s=t?.geometrySource&&typeof t.geometrySource=="object"?t.geometrySource:t,a=i.map(l=>{const u=o.get(String(l?.linkName||""))||[..._y],d=es(l?.localTransform),m=Fd(u,d),p=l?.sourceBounds||l?.bounds;return{...l,transform:m,bounds:hoe(p,m)}});return{meshData:{...t,geometrySource:s,bounds:qp(a.map(l=>l.bounds)),parts:a},linkWorldTransforms:o}}function Toe(e,t,n={},r=null){const o=_oe(e,t,n,r);return!t||typeof t!="object"?o:(t.geometrySource=o.meshData.geometrySource||t.geometrySource||t,t.bounds=o.meshData.bounds,t.parts=o.meshData.parts,{...o,meshData:t})}const fT=Object.freeze([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Roe(e){return!Array.isArray(e)||e.length!==16?[...fT]:e.map((t,n)=>Number.isFinite(Number(t))?Number(t):fT[n])}function Poe(e){const t=e?.assembly?.mesh;return t&&typeof t=="object"?t:null}function mT(e){return String(Poe(e)?.addressing||"").trim()==="gltf-node-extras"}function jD(e){const t=e?.assembly?.root;return t&&typeof t=="object"?t:null}function MS(e){if(!Array.isArray(e)||e.length<3)return null;const t=e.slice(0,3).map(n=>Number(n));return t.every(n=>Number.isFinite(n))?t:null}function pT(e){if(!e||typeof e!="object")return null;const t={part:String(e.part||"").trim(),frame:String(e.frame||"").trim()},n=MS(e.position),r=MS(e.orientation);n&&(t.position=n),r&&(t.orientation=r);const o=e.axes&&typeof e.axes=="object"?e.axes:null;if(o){const i={};for(const s of["x","y","z"]){const a=MS(o[s]);a&&(i[s]=a)}Object.keys(i).length&&(t.axes=i)}return t.position||t.orientation||t.part||t.frame?t:null}function Ooe(e){const t=e?.assemblyMates;return Array.isArray(t)?t.filter(n=>n&&typeof n=="object").map((n,r)=>{const o=String(n.id||`m${r+1}`).trim()||`m${r+1}`;return{id:o,label:String(n.label||o).trim()||o,sourceLabel:String(n.sourceLabel||n.name||"").trim(),type:String(n.type||n.relation||"mate").trim(),relation:String(n.relation||n.type||"mate").trim(),fixed:String(n.fixed||"").trim(),moving:String(n.moving||"").trim(),parameters:n.parameters&&typeof n.parameters=="object"?n.parameters:{},fixedEndpoint:pT(n.fixedEndpoint),movingEndpoint:pT(n.movingEndpoint)}}):[]}function Ov(e){const t=[],n=e?[e]:[];for(;n.length;){const r=n.pop(),o=Array.isArray(r?.children)?r.children:[];if(o.length){for(let i=o.length-1;i>=0;i-=1)n.push(o[i]);continue}String(r?.nodeType||"").trim()==="part"&&t.push(r)}return t}function hT(e){const t=[],n=e?[e]:[];for(;n.length;){const r=n.pop();t.push(r);const o=Array.isArray(r?.children)?r.children:[];for(let i=o.length-1;i>=0;i-=1)n.push(o[i])}return t}function oc(e,t){const n=String(t||"").trim();if(!e||!n||n==="root")return e||null;const r=[e];for(;r.length;){const o=r.pop();if(String(o?.id||"").trim()===n)return o;const i=Array.isArray(o?.children)?o.children:[];for(let s=i.length-1;s>=0;s-=1)r.push(i[s])}return null}function koe(e){return String(e?.id||"").trim()||"root"}function Zp(e){return Ov(e).map(t=>String(t?.id||"").trim()).filter(Boolean)}function Doe(e){const t=new Map;for(const n of Array.isArray(e)?e:[]){const r=String(n?.id||"").trim();if(!r)continue;const o=Array.isArray(n?.leafPartIds)&&n.leafPartIds.length?n.leafPartIds:Zp(n);for(const i of o){const s=String(i||"").trim();s&&t.set(s,r)}}return t}function joe(e,{pickPartIdMap:t,validLeafPartIds:n=[]}={}){const r=String(e||"").trim();if(!r)return"";const o=n instanceof Set?n:new Set((Array.isArray(n)?n:[]).map(s=>String(s||"").trim()).filter(Boolean)),i=t instanceof Map?String(t.get(r)||"").trim():"";return i||(o.size&&o.has(r)?r:i||r)}function Loe(e,{assemblyPartMap:t,fallbackPartId:n="",validLeafPartIds:r=[]}={}){const o=String(e||"").trim(),i=r instanceof Set?r:new Set((Array.isArray(r)?r:[]).map(u=>String(u||"").trim()).filter(Boolean)),s=u=>!i.size||i.has(u),a=u=>{const d=new Set,m=[];for(const p of Array.isArray(u)?u:[]){const g=String(p||"").trim();!g||d.has(g)||!s(g)||(d.add(g),m.push(g))}return m};if(o){const u=t instanceof Map&&t.get(o)||null,d=a(u?Zp(u):[o]);if(d.length)return d}const l=String(n||"").trim();return a([l])}function ab(e){return String(e?.occurrenceId||e?.id||"").trim()}function Gc(e,t){return Math.max(0,Math.floor(Number(e?.[t])||0))}function Foe(e,t){return[String(e?.occurrenceId||"").trim(),String(e?.id||"").trim()].filter(Boolean).some(r=>t.has(r))}function zoe(e,t){return[String(e?.occurrenceId||"").trim(),String(e?.id||"").trim()].filter(Boolean).some(r=>t.some(o=>r.startsWith(o)))}function Boe(e,t){const n=Array.isArray(e?.parts)?e.parts:[],r=new Set([t?.occurrenceId,t?.id].map(s=>String(s||"").trim()).filter(Boolean)),o=n.filter(s=>Foe(s,r));if(o.length)return o;const i=[...r].map(s=>`${s}.`);return i.length?n.filter(s=>zoe(s,i)):[]}function Voe(e,t){const n=jD(e);if(!n)throw new Error("Assembly topology is missing assembly.root");const r=Ov(n),o=[],i=[];for(const T of r){const k=String(T?.id||T?.occurrenceId||"").trim(),z=String(T?.occurrenceId||T?.id||"").trim(),Y=Boe(t,T);if(!Y.length){const K=z||k;K&&i.push(K);continue}o.push({manifestPart:T,sourceParts:Y})}if(!o.length)throw new Error("Assembly topology did not match any renderable GLB nodes");let s=0,a=0;for(const{sourceParts:T}of o)for(const k of T)s+=Gc(k,"vertexCount"),a+=Gc(k,"triangleCount")*3;const l=t?.vertices||new Float32Array(0),u=t?.normals||new Float32Array(0),d=t?.colors||new Float32Array(0),m=t?.surfaceEdgeBarycentric||new Float32Array(0),p=t?.surfaceEdgeClass||new Uint8Array(0),g=t?.indices||new Uint32Array(0),x=d.length===l.length&&d.length>0,y=m.length===l.length&&p.length===l.length&&l.length>0,S=new Float32Array(s*3),b=new Float32Array(s*3),I=x?new Float32Array(s*3):new Float32Array(0),A=y?new Float32Array(s*3):new Float32Array(0),N=y?new Uint8Array(s*3):new Uint8Array(0),P=new Uint32Array(a),R=[];let v=0,C=0;for(const{manifestPart:T,sourceParts:k}of o){const z=String(T?.id||T?.occurrenceId||"").trim(),Y=String(T?.occurrenceId||T?.id||"").trim(),K=k[0],J=v,G=Math.floor(C/3),Q=[];for(const W of k){const Z=Gc(W,"vertexOffset"),Ee=Gc(W,"vertexCount"),re=Gc(W,"triangleOffset"),be=Gc(W,"triangleCount"),_e=Math.floor(C/3)-G;Q.push({occurrenceId:ab(W),primitiveIndex:Gc(W,"primitiveIndex"),triangleOffset:_e,triangleCount:be});const Ie=Z*3,oe=Ie+Ee*3;S.set(l.subarray(Ie,oe),v*3),u.length>=oe&&b.set(u.subarray(Ie,oe),v*3),x&&d.length>=oe&&I.set(d.subarray(Ie,oe),v*3),y&&m.length>=oe&&A.set(m.subarray(Ie,oe),v*3),y&&p.length>=oe&&N.set(p.subarray(Ie,oe),v*3);const me=re*3,se=me+be*3;for(let Ae=me;AeW.bounds));R.push({...K,...T,id:z||Y||ab(K),occurrenceId:Y||z||ab(K),name:$,label:$,nodeType:"part",sourceKind:String(T?.sourceKind||"").trim(),sourcePath:D,partSourcePath:D,sourceBounds:ie,bounds:T?.bbox||ie,transform:Roe(T?.worldTransform||T?.transform),hasSourceColors:$oe(T)&&(x||k.some(W=>!!W.hasSourceColors||!!W.color)),vertexOffset:J,vertexCount:v-J,triangleOffset:G,triangleCount:Math.floor(C/3)-G,sourcePartRanges:Q,edgeIndexOffset:0,edgeIndexCount:0})}return{...t,vertices:S,indices:P,normals:b,colors:I,surfaceEdgeBarycentric:A,surfaceEdgeClass:N,edge_indices:new Uint32Array(0),parts:R,bounds:qp(R.map(T=>T.bounds))||t?.bounds,assemblyRoot:n,assemblyMates:Ooe(e),meshlessLeafPartIds:i,partTransformsBaked:!0,has_source_colors:x}}function $oe(e){return e?.useSourceColors!==!1}async function Goe(e,t,n){const r=Array.isArray(e)?e:[],o=Math.min(r.length,Math.max(1,Math.floor(Number(t)||1))),i=new Array(r.length);let s=0;async function a(){for(;sa())),i}function gT(e){return e===B.STL||e===B.THREE_MF||e===B.GLB?e:""}function Uoe(e){const t=gT(gA(e,{baseUrl:typeof window<"u"?window.location.href:""}));if(t)return t;try{const n=new URL(e,typeof window<"u"?window.location.href:"http://localhost/");for(const r of["file","path"]){const o=n.searchParams.get(r),i=gT(gA(o||"",{baseUrl:n.href}));if(i)return i}}catch{}return""}function Woe(e){return e===B.STL||e===B.THREE_MF||e===B.GLB?e:B.GLB}function LD(e,{fallback:t=B.GLB}={}){return Uoe(e)||Woe(t)}function FD(e,t={}){const n=LD(e,t);return n===B.STL?zre(e):n===B.THREE_MF?Vre(e):CD(e)}async function zD(e,t={}){const n=LD(e,t);return n===B.STL?Fre(e,t):n===B.THREE_MF?Bre(e,t):vD(e,t)}const BD=32*1024*1024,Hoe=1e6,Koe=160*1024*1024;function Xoe(e){return ArrayBuffer.isView(e)&&Number(e.byteLength)||0}function VD(e){return or(e)===B.STEP?WO(e,"glb"):0}function Yoe(e){return VD(e)>0}function $D(e){return VD(e)>=BD}function qoe(e){return or(e)===B.GLB&&nq(e)>=BD}function GD(e){return $D(e)||qoe(e)}function Zoe(e){const t=Math.floor((Number(e?.indices?.length)||0)/3),n=Array.isArray(e?.parts)?e.parts.reduce((r,o)=>{const i=Number(o?.triangleCount);return r+(Number.isFinite(i)&&i>0?i:0)},0):0;return{triangleCount:Math.max(t,n),typedArrayBytes:[e?.vertices,e?.indices,e?.normals,e?.colors,e?.edge_indices,e?.surfaceEdgeBarycentric,e?.surfaceEdgeClass,e?.guide_line_segments].reduce((r,o)=>r+Xoe(o),0)}}function Joe(e){const t=Zoe(e);return t.triangleCount>=Hoe||t.typedArrayBytes>=Koe}const bT=3;function IS(e){if(!Array.isArray(e)||e.length<3)return null;const t=e.slice(0,3).map(n=>Number(n));return t.every(n=>Number.isFinite(n))?t:null}function yT(e){if(!e||typeof e!="object")return null;const t={part:String(e.part||"").trim(),frame:String(e.frame||"").trim()},n=IS(e.position),r=IS(e.orientation);n&&(t.position=n),r&&(t.orientation=r);const o=e.axes&&typeof e.axes=="object"?e.axes:null;if(o){const i={};for(const s of["x","y","z"]){const a=IS(o[s]);a&&(i[s]=a)}Object.keys(i).length&&(t.axes=i)}return t.position||t.orientation||t.part||t.frame?t:null}function UD(e){const t=e?.assemblyMates;return Array.isArray(t)?t.filter(n=>n&&typeof n=="object").map((n,r)=>{const o=String(n.id||`m${r+1}`).trim()||`m${r+1}`;return{id:o,label:String(n.label||o).trim()||o,sourceLabel:String(n.sourceLabel||n.name||"").trim(),type:String(n.type||n.relation||"mate").trim(),relation:String(n.relation||n.type||"mate").trim(),fixed:String(n.fixed||"").trim(),moving:String(n.moving||"").trim(),parameters:n.parameters&&typeof n.parameters=="object"?n.parameters:{},fixedEndpoint:yT(n.fixedEndpoint),movingEndpoint:yT(n.movingEndpoint)}}):[]}function Si(e){e.current?.abort(),e.current=null}function xT(){return typeof window>"u"||typeof window.setTimeout!="function"?Promise.resolve():new Promise(e=>{window.setTimeout(e,0)})}function Qoe(){if(typeof DOMException=="function")return new DOMException("The operation was aborted.","AbortError");const e=new Error("The operation was aborted.");return e.name="AbortError",e}function eie(){const e=typeof navigator<"u"?Number(navigator.hardwareConcurrency):0;return!Number.isFinite(e)||e<=0?bT:Math.max(2,Math.min(bT,Math.floor(e/2)))}function ST(e){return[...new Set((Array.isArray(e?.links)?e.links:[]).flatMap(t=>Array.isArray(t?.visuals)?t.visuals:[]).map(t=>String(t?.meshUrl||"").trim()).filter(Boolean))]}async function tie(e,{signal:t,onProgress:n}={}){const r=e.length;let o=0;return n?.(o,r),Goe(e,eie(),async i=>{if(t?.aborted)throw Qoe();await xT();const s=await zD(i,{signal:t,fallback:B.STL});return o+=1,n?.(o,r),await xT(),s})}function nie(e){return FD(Qw(e),{fallback:Iu(e)})}function rie(e,t){return zD(Qw(e),{...t,fallback:Iu(e),preferWorker:GD(e)})}function oie(e,t=null){return{...e,parts:null,assemblyRoot:jD(t),assemblyMates:UD(t)}}function iie({entryHasMesh:e,entryHasReferences:t,entryHasDisplayEdges:n=()=>!1,entryHasDxf:r,entryHasGcode:o,buildNormalizedReferenceState:i}){const[s,a]=f.useState(null),[l,u]=f.useState(!1),[d,m]=f.useState(""),[p,g]=f.useState(""),[x,y]=f.useState(ke.READY),[S,b]=f.useState(""),[I,A]=f.useState(null),[N,P]=f.useState(ke.PENDING),[R,v]=f.useState(""),[C,T]=f.useState(""),[k,z]=f.useState(null),[Y,K]=f.useState(ke.PENDING),[J,G]=f.useState(""),[Q,D]=f.useState(""),[$,ie]=f.useState(null),[W,Z]=f.useState(ke.PENDING),[Ee,re]=f.useState(""),[be,_e]=f.useState(""),[Ie,oe]=f.useState(null),[me,se]=f.useState(ke.PENDING),[Ae,we]=f.useState(""),[ct,ut]=f.useState(""),[Tt,Ve]=f.useState(null),[St,wt]=f.useState(Wn.IDLE),[Vn,De]=f.useState(""),[xe,yt]=f.useState(""),[Te,rt]=f.useState(null),[Re,Fe]=f.useState(Wn.IDLE),[on,ht]=f.useState(""),[jt,qt]=f.useState(""),sn=f.useRef(0),Mn=f.useRef(0),fn=f.useRef(0),Bt=f.useRef(0),dt=f.useRef(0),qe=f.useRef(0),Vt=f.useRef(0),We=f.useRef(null),ze=f.useRef(null),Ze=f.useRef(null),vt=f.useRef(null),Tn=f.useRef(null),pe=f.useRef(null),Xe=f.useRef(null),He=f.useCallback(L=>HO(L),[]),Rn=f.useCallback((L,te,fe)=>{const ae=Voe(te,fe);return{file:L.file,kind:L.kind,meshHash:He(L),meshData:{...ae,assemblyMates:UD(te)},assemblyStructureReady:!0,assemblyInteractionReady:!0,assemblyBackgroundError:""}},[He]),xn=f.useCallback((L,te,fe=null)=>{const ae=oie(te,fe);return{file:L.file,kind:L.kind,meshHash:He(L),meshData:ae,assemblyStructureReady:!!ae.assemblyRoot,assemblyInteractionReady:!1,assemblyBackgroundError:""}},[He]),ue=f.useCallback(L=>{if(!e(L))return null;if(L?.kind==="assembly"){const fe=vn(L,"glb"),ae=gy(L),he=CD(fe);if(!he)return null;const ot=Xre(ae);return ot?mT(ot)?Rn(L,ot,he):null:xn(L,he)}const te=nie(L);return te?{file:L.file,kind:L.kind,meshHash:F1(L),meshData:te}:null},[xn,Rn,e]),Rt=f.useCallback(L=>{if(!t(L))return null;const te=qre(KN(L));return te?i(L,te):null},[i,t]),Zt=f.useCallback((L,te)=>({file:L.file,fileRef:String(L?.file||"").trim(),kind:L.kind,displayEdgeHash:zt(L,"displayEdgeTopology"),displayEdgeRuntime:ZU(te)}),[]),qn=f.useCallback(L=>{if(!n(L))return null;const te=Jre(XN(L));return te?Zt(L,te):null},[Zt,n]),fi=f.useCallback(L=>{if(!r(L))return null;const te=eoe(vn(L,"dxf"));return te?{file:L.file,kind:L.kind,dxfHash:zt(L,"dxf"),dxfData:te}:null},[r]),Ct=f.useCallback(L=>{if(!o(L))return null;const te=noe(vn(L,"gcode"));return te?{file:L.file,kind:L.kind,gcodeHash:zt(L,"gcode"),gcodeData:te}:null},[o]),wr=f.useCallback(L=>{if(String(L?.kind||"").trim().toLowerCase()!==B.IMPLICIT)return null;const te=uoe(vn(L,"implicit"));return te?{file:L.file,kind:L.kind,implicitHash:zt(L,"implicit"),model:te}:null},[]),vr=f.useCallback(L=>{const te=String(L?.kind||"").trim().toLowerCase();if(!["urdf","srdf","sdf"].includes(te)||!vn(L,te==="sdf"?"sdf":"urdf"))return null;const ae=te==="srdf"?ioe(vn(L,"srdf"),{urdfUrl:vn(L,"urdf")}):null,he=te==="srdf"?ae?.urdfData:te==="sdf"?aoe(vn(L,"sdf")):roe(vn(L,"urdf"));if(!he)return null;const ot=ST(he),It=ot.map(Ke=>FD(Ke,{fallback:B.STL})).filter(Boolean);if(It.length!==ot.length)return null;const Pt=new Map(ot.map((Ke,en)=>[Ke,It[en]]));return{file:L.file,kind:L.kind,urdfHash:Wp(L),urdfData:he,meshesByUrl:Pt}},[]),Qt=f.useCallback(()=>{sn.current+=1,Si(We),u(!1),m(""),g("")},[]),In=f.useCallback(()=>{Mn.current+=1,Si(ze),T("")},[]),gr=f.useCallback(()=>{fn.current+=1,Si(Ze),D("")},[]),lo=f.useCallback(()=>{Bt.current+=1,Si(vt),_e("")},[]),Mt=f.useCallback(()=>{dt.current+=1,Si(Tn),ut("")},[]),gt=f.useCallback(()=>{qe.current+=1,Si(pe),yt("")},[]),Sn=f.useCallback(()=>{Vt.current+=1,Si(Xe),qt("")},[]),On=f.useCallback(async L=>{Qt();const te=sn.current;if(!e(L)){a(null),y(ke.PENDING),b("");return}const fe=ue(L);if(fe&&(a(fe),y(ke.READY),b(""),L?.kind!=="assembly"||fe.assemblyInteractionReady||fe.assemblyBackgroundError))return;const ae=new AbortController;We.current=ae,u(!0),m(String(L?.file||"").trim()),g(L?.kind==="assembly"?"loading assembly mesh":"loading mesh");const he=L?.kind==="assembly"&&!!fe;let ot=he;he||(y(ke.LOADING),b(""));try{if(L?.kind==="assembly"){const en=vn(L,"glb"),Ne=gy(L);if(!en)throw new Error(`STEP assembly is missing GLB asset: ${L.file||"(unknown)"}`);const Et=fe?.meshData||await vD(en,{signal:ae.signal,preferWorker:GD(L)});if(te!==sn.current)return;fe||(a(xn(L,Et)),y(ke.READY),b(""),ot=!0),g("loading topology");const Pe=await Kre(Ne,{signal:ae.signal});if(te!==sn.current)return;if(fe?.assemblyStructureReady||a(xn(L,Et,Pe)),mT(Pe)){g("building assembly"),a(Rn(L,Pe,Et)),y(ke.READY),b("");return}throw new Error("STEP assembly topology is not self-contained.")}if(!Qw(L)){const en=Iu(L).toUpperCase();throw new Error(`${en} entry is missing ${en} asset: ${L.file||"(unknown)"}`)}const Pt=await rie(L,{signal:ae.signal}),Ke=F1(L);if(te!==sn.current)return;g("building"),a({file:L.file,kind:L.kind,meshHash:Ke,meshData:Pt}),y(ke.READY)}catch(It){if(te!==sn.current||Za(It)||ae.signal.aborted)return;if(L?.kind==="assembly"&&ot){a(Pt=>!Pt||Pt.file!==L.file||Pt.meshHash!==He(L)?Pt:{...Pt,assemblyBackgroundError:It instanceof Error?It.message:String(It)});return}y(ke.ERROR),b(It instanceof Error?It.message:String(It))}finally{te===sn.current&&(u(!1),m(""),g("")),We.current===ae&&(We.current=null)}},[xn,Rn,Qt,e,He,ue]),Kr=f.useCallback(async L=>{gt();const te=qe.current;if(!t(L)){Ve(null),wt(Wn.DISABLED),De("");return}const fe=Rt(L);if(fe){Ve(fe),wt(fe.disabledReason?Wn.DISABLED:Wn.READY),De(fe.disabledReason||"");return}const ae=new AbortController;pe.current=ae,wt(Wn.LOADING),De(""),yt("loading topology");try{const he=await Yre(KN(L),{signal:ae.signal});if(te!==qe.current)return;const ot=i(L,he);Ve(ot),wt(ot.disabledReason?Wn.DISABLED:Wn.READY),De(ot.disabledReason||"")}catch(he){if(te!==qe.current||Za(he)||ae.signal.aborted)return;wt(Wn.ERROR),De(he instanceof Error?he.message:String(he))}finally{pe.current===ae&&(pe.current=null),te===qe.current&&yt("")}},[i,gt,t,Rt]),Xr=f.useCallback(async L=>{Sn();const te=Vt.current;if(!n(L)){rt(null),Fe(Wn.DISABLED),ht("");return}const fe=qn(L);if(fe){rt(fe),Fe(Wn.READY),ht("");return}const ae=new AbortController;Xe.current=ae,Fe(Wn.LOADING),ht(""),qt("loading edges");try{const he=await Zre(XN(L),{signal:ae.signal});if(te!==Vt.current)return;rt(Zt(L,he)),Fe(Wn.READY),ht("")}catch(he){if(te!==Vt.current||Za(he)||ae.signal.aborted)return;rt(null),Fe(Wn.ERROR),ht(he instanceof Error?he.message:String(he))}finally{Xe.current===ae&&(Xe.current=null),te===Vt.current&&qt("")}},[Zt,Sn,n,qn]),Co=f.useCallback(async L=>{In();const te=Mn.current;if(!r(L)){A(null),P(ke.PENDING),v("");return}const fe=fi(L);if(fe){A(fe),P(ke.READY),v("");return}const ae=new AbortController;ze.current=ae,P(ke.LOADING),v(""),T("loading DXF");try{const he=await Qre(vn(L,"dxf"),{signal:ae.signal});if(te!==Mn.current)return;T("building preview"),A({file:L.file,kind:L.kind,dxfHash:zt(L,"dxf"),dxfData:he}),P(ke.READY)}catch(he){if(te!==Mn.current||Za(he)||ae.signal.aborted)return;P(ke.ERROR),v(he instanceof Error?he.message:String(he))}finally{ze.current===ae&&(ze.current=null),te===Mn.current&&T("")}},[In,r,fi]),br=f.useCallback(async L=>{gr();const te=fn.current;if(!o(L)){z(null),K(ke.PENDING),G("");return}const fe=Ct(L);if(fe){z(fe),K(ke.READY),G("");return}const ae=new AbortController;Ze.current=ae,K(ke.LOADING),G(""),D("loading G-code");try{const he=await toe(vn(L,"gcode"),{signal:ae.signal});if(te!==fn.current)return;D("building preview"),z({file:L.file,kind:L.kind,gcodeHash:zt(L,"gcode"),gcodeData:he}),K(ke.READY)}catch(he){if(te!==fn.current||Za(he)||ae.signal.aborted)return;K(ke.ERROR),G(he instanceof Error?he.message:String(he))}finally{Ze.current===ae&&(Ze.current=null),te===fn.current&&D("")}},[gr,o,Ct]),j=f.useCallback(async L=>{lo();const te=Bt.current;if(String(L?.kind||"").trim().toLowerCase()!==B.IMPLICIT){ie(null),Z(ke.PENDING),re("");return}const fe=wr(L);if(fe){ie(fe),Z(ke.READY),re("");return}const ae=new AbortController;vt.current=ae,Z(ke.LOADING),re(""),_e("loading implicit CAD");try{const he=await coe(vn(L,"implicit"),{signal:ae.signal});if(te!==Bt.current)return;ie({file:L.file,kind:L.kind,implicitHash:zt(L,"implicit"),model:he}),Z(ke.READY)}catch(he){if(te!==Bt.current||Za(he)||ae.signal.aborted)return;Z(ke.ERROR),re(he instanceof Error?he.message:String(he))}finally{vt.current===ae&&(vt.current=null),te===Bt.current&&_e("")}},[lo,wr]),de=f.useCallback(async L=>{Mt();const te=dt.current,fe=String(L?.kind||"").trim().toLowerCase();if(!["urdf","srdf","sdf"].includes(fe)){oe(null),se(ke.PENDING),we("");return}if(!vn(L,fe==="sdf"?"sdf":"urdf")){oe(null),se(ke.PENDING),we("");return}const he=vr(L);if(he){oe(he),se(ke.READY),we("");return}const ot=new AbortController;Tn.current=ot,se(ke.LOADING),we(""),ut(fe==="sdf"?"loading SDF":fe==="srdf"?"loading SRDF":"loading URDF");try{const Pt=(fe==="srdf"?await ooe(vn(L,"srdf"),{signal:ot.signal,urdfUrl:vn(L,"urdf")}):fe==="sdf"?{urdfData:await soe(vn(L,"sdf"),{signal:ot.signal})}:{urdfData:await ND(vn(L,"urdf"),{signal:ot.signal})}).urdfData,Ke=ST(Pt);ut(Ke.length?"loading meshes":"building robot");const en=await tie(Ke,{signal:ot.signal,onProgress:(Et,Pe)=>{te===dt.current&&Pe>0&&ut(`loading meshes ${Et}/${Pe}`)}});if(te!==dt.current)return;ut("building robot");const Ne=new Map(Ke.map((Et,Pe)=>[Et,en[Pe]]));oe({file:L.file,kind:L.kind,urdfHash:Wp(L),urdfData:Pt,meshesByUrl:Ne}),se(ke.READY)}catch(It){if(te!==dt.current||Za(It)||ot.signal.aborted)return;se(ke.ERROR),we(It instanceof Error?It.message:String(It))}finally{Tn.current===ot&&(Tn.current=null),te===dt.current&&ut("")}},[Mt,vr]);return f.useEffect(()=>()=>{Si(We),Si(ze),Si(Ze),Si(vt),Si(Tn),Si(pe),Si(Xe)},[]),{meshState:s,setMeshState:a,meshLoadInProgress:l,meshLoadTargetFile:d,meshLoadStage:p,status:x,setStatus:y,error:S,setError:b,dxfState:I,setDxfState:A,dxfStatus:N,setDxfStatus:P,dxfError:R,setDxfError:v,dxfLoadStage:C,gcodeState:k,setGcodeState:z,gcodeStatus:Y,setGcodeStatus:K,gcodeError:J,setGcodeError:G,gcodeLoadStage:Q,implicitState:$,setImplicitState:ie,implicitStatus:W,setImplicitStatus:Z,implicitError:Ee,setImplicitError:re,implicitLoadStage:be,urdfState:Ie,setUrdfState:oe,urdfStatus:me,setUrdfStatus:se,urdfError:Ae,setUrdfError:we,urdfLoadStage:ct,referenceState:Tt,setReferenceState:Ve,referenceStatus:St,setReferenceStatus:wt,referenceError:Vn,setReferenceError:De,referenceLoadStage:xe,displayEdgeState:Te,setDisplayEdgeState:rt,displayEdgeStatus:Re,setDisplayEdgeStatus:Fe,displayEdgeError:on,setDisplayEdgeError:ht,displayEdgeLoadStage:jt,getCachedMeshState:ue,getCachedReferenceState:Rt,getCachedDisplayEdgeState:qn,getCachedDxfState:fi,getCachedGcodeState:Ct,getCachedImplicitState:wr,getCachedUrdfState:vr,cancelMeshLoad:Qt,cancelDxfLoad:In,cancelGcodeLoad:gr,cancelImplicitLoad:lo,cancelUrdfLoad:Mt,cancelReferenceLoad:gt,cancelDisplayEdgeLoad:Sn,loadMeshForEntry:On,loadDxfForEntry:Co,loadGcodeForEntry:br,loadImplicitForEntry:j,loadUrdfForEntry:de,loadReferencesForEntry:Kr,loadDisplayEdgesForEntry:Xr}}const sie="[data-slot='sidebar-wrapper']";function aie(){return document.querySelector(sie)}function AS(e){aie()?.style.setProperty("--sidebar-width",`${e}px`)}function ET(e=1600){const t=Number(window.innerWidth);return Number.isFinite(t)&&t>0?t:e}function wT(e,t=0){const n=Number(e);return Number.isFinite(n)?Math.max(t,n):t}function lb(e,t,n){const r=Number(e),o=Number(t),i=Number(n),s=Number.isFinite(o)&&o>0?o:0,a=Number.isFinite(i)&&i>0?Math.max(s,i):s,l=Number.isFinite(r)?r:s;return Math.min(Math.max(l,s),a)}function md({viewportWidth:e,sidebarOpen:t=!1,sheetOpen:n=!1,sidebarWidth:r=0,sheetWidth:o=0,sidebarMinWidth:i=0,sheetMinWidth:s=0,sidebarMaxWidth:a=0,sheetMaxWidth:l=0}={}){if(!t&&!n)return{sidebarWidth:0,sheetWidth:0};const u=Number(a),d=Number(l);if(t&&!n)return{sidebarWidth:lb(r,i,u),sheetWidth:0};if(!t&&n)return{sidebarWidth:0,sheetWidth:lb(o,s,d)};const m=Math.max(0,Number(i)||0),p=Math.max(0,Number(s)||0);let g=lb(r,m,u),x=lb(o,p,d);return{sidebarWidth:g,sheetWidth:x}}function lie({isDesktop:e,setLayoutMode:t,setSidebarOpen:n,setTabToolsOpen:r,setLayoutViewportWidth:o,clampSidebarWidth:i,clampTabToolsWidth:s,setSidebarWidth:a,setTabToolsWidth:l,panelResizeStateRef:u,tabToolsResizeStateRef:d,defaultSidebarWidth:m,sidebarMinWidth:p,tabToolsMinWidth:g,endPanelResize:x,endTabToolsResize:y}){f.useEffect(()=>{const S=()=>{const b=ET();t(zy(b))};return S(),window.addEventListener("resize",S),()=>{window.removeEventListener("resize",S)}},[t]),f.useEffect(()=>{if(!e)return;const S=()=>{o(b=>ET(b)),a(b=>wT(b,p)),l(b=>wT(b,g))};return S(),window.addEventListener("resize",S),()=>{window.removeEventListener("resize",S)}},[e,o,a,l,p,g]),f.useEffect(()=>{const S=I=>{const A=u.current;if(!A)return;const N=A.startWidth+(I.clientX-A.startX);if(N{const I=u.current;if(!I)return;const A=Math.max(p,i(I.latestWidth??I.startWidth));AS(A),a(A),x()};return window.addEventListener("pointermove",S),window.addEventListener("pointerup",b),window.addEventListener("pointercancel",b),()=>{window.removeEventListener("pointermove",S),window.removeEventListener("pointerup",b),window.removeEventListener("pointercancel",b),d.current||(document.body.style.cursor="",document.body.style.userSelect="")}},[i,x,u,m,n,a,p,d]),f.useEffect(()=>{const S=I=>{const A=d.current;if(!A)return;const N=A.startWidth-(I.clientX-A.startX);if(N{d.current&&y()};return window.addEventListener("pointermove",S),window.addEventListener("pointerup",b),window.addEventListener("pointercancel",b),()=>{window.removeEventListener("pointermove",S),window.removeEventListener("pointerup",b),window.removeEventListener("pointercancel",b),u.current||(document.body.style.cursor="",document.body.style.userSelect="")}},[s,y,u,r,l,g,d])}function cie({isAssemblyView:e,supportsPartSelection:t,assemblyPartsLoaded:n,selectedEntryHasReferences:r,setSelectedReferenceIds:o,selectedReferenceIdsRef:i,setHoveredListReferenceId:s,setHoveredModelReferenceId:a,assemblyParts:l,validAssemblyPartIds:u,validHiddenPartIds:d,selectedPartIdsRef:m,setSelectedPartIds:p,parseAssemblyPartReferenceSelectionId:g,setHiddenPartIds:x,setHoveredListPartId:y,setHoveredModelPartId:S}){f.useEffect(()=>{e||r||(i.current=[],o([]),s(""),a(""))},[e,r,i,s,a,o]),f.useEffect(()=>{if(!n)return;if(!t){m.current=[],p([]),x([]),y(""),S("");return}const b=new Set((Array.isArray(u)?u:l.map(A=>A.id)).map(A=>String(A||"").trim()).filter(Boolean)),I=new Set((Array.isArray(d)?d:[...b]).map(A=>String(A||"").trim()).filter(Boolean));m.current=m.current.filter(A=>b.has(A)),p(A=>A.filter(N=>b.has(N))),i.current=i.current.filter(A=>{const N=g(A);return!N||b.has(N.partId)}),o(A=>A.filter(N=>{const P=g(N);return!P||b.has(P.partId)})),x(A=>A.filter(N=>I.has(N))),y(A=>A&&!b.has(A)?"":A),S(A=>A&&!b.has(A)?"":A),s(A=>{const N=g(A);return N&&!b.has(N.partId)?"":A}),a(A=>{const N=g(A);return N&&!b.has(N.partId)?"":A})},[l,n,t,u,d,g,i,m,x,y,s,S,a,p,o])}function uie({selectedKey:e="",selectedKeyExists:t=!1,urlSelectionRequested:n=!1,nextSelectedKey:r=""}={}){return!(!n||!r||r===e)}function die({key:e="",createTabRecord:t,initialSelectedTabSnapshot:n=null,fileSessionState:r=null}={}){const o=r?.slices?.tab||null;return t(e,o||n||{})}function fie({manifestEntries:e,cadFileParamForEntry:t=()=>"",cadDirectorySessionBootstrappedRef:n,setOpenTabs:r,applyTabRecord:o,selectedEntryKeyFromUrl:i,createTabRecord:s,initialSelectedTabSnapshot:a=null,upsertTabRecord:l,selectedEntry:u,defaultDocumentTitle:d,selectedKey:m,entryMap:p,buildActiveTabSnapshot:g,catalogEntries:x,manifestRevision:y=0,readCadParam:S=()=>null,activateEntryTab:b,resetActiveDirectory:I,writeCadParam:A,readEntrySessionState:N=()=>null,applyEntrySessionState:P=()=>{}}){const R=f.useRef(y),v=f.useRef(!1);f.useLayoutEffect(()=>{if(n.current)return;n.current=!0;const C=i(e);if(v.current=!!S()&&!C,C){const T=N(C),k=die({key:C,createTabRecord:s,initialSelectedTabSnapshot:a,fileSessionState:T});r(z=>l(z,C,k)),o(k),P(C,T)}},[P,o,s,e,S,N,i,r,l,a,n]),f.useEffect(()=>{const C=tk(u);document.title=C?`${d} | ${C}`:d},[d,u]),f.useLayoutEffect(()=>{const C=!!S(),T=i(x),k=!!(m&&p.has(m));if(uie({selectedKey:m,selectedKeyExists:k,urlSelectionRequested:C,nextSelectedKey:T})){v.current=!1,b(T);return}if(k){r(z=>l(z,m,g()));return}if(!T){if(m){if(y===R.current&&!p.size)return;I()}return}T!==m&&b(T)},[b,g,x,p,y,S,I,i,m,r,l]),f.useEffect(()=>{const C=()=>{const T=i(x);if(T){b(T);return}I()};return window.addEventListener("popstate",C),()=>{window.removeEventListener("popstate",C)}},[b,x,I,i]),f.useEffect(()=>{if(u){A(t(u));return}if(!m){if(!!S()&&(i(x)||S()||v.current&&(y===R.current||!p.size)))return;A("")}},[x,t,y,S,u,i,m,A]),f.useEffect(()=>{m&&r(C=>l(C,m,g()))},[g,m,r,l])}function WD(){return new Map}function mie(e){const t=WD();for(const n of Array.isArray(e)?e:[])t.set(n.id,n);return t}function vT(e){const t=WD();for(const n of Array.isArray(e)?e:[])t.set(n.id,n);return t}function pie({selectedReferencesMatch:e,referenceState:t,isAssemblyView:n,supportsPartSelection:r,assemblyParts:o,assemblyPartMap:i,inspectedAssemblyNodeId:s,inspectedAssemblyPartTopologyReferences:a,selectedReferenceIds:l,selectedPartIds:u,hoveredListReferenceId:d,hoveredModelReferenceId:m,hoveredListPartId:p,hoveredModelPartId:g}){const x=e?Array.isArray(t?.references)?t.references:[]:[],y=f.useMemo(()=>r&&Array.isArray(o)?o:[],[o,r]),S=f.useMemo(()=>i instanceof Map?i:mie(y),[i,y]),b="".trim(),I=f.useMemo(()=>b?[b]:[],[b]),A=f.useMemo(()=>b&&S.get(b)||null,[b,S]),N=f.useMemo(()=>vT(x),[x]),P=n&&!!b&&String(A?.nodeType||"").trim()==="part"&&!(Array.isArray(A?.children)&&A.children.length>0),R=f.useMemo(()=>Array.isArray(a)?a:[],[a]),v=f.useMemo(()=>vT(P?R:x),[x,R,P]),C=String(A?.name||A?.displayName||"the selected part").trim(),T=f.useMemo(()=>l.map(J=>v.get(J)).filter(Boolean),[v,l]),k=f.useMemo(()=>u.map(J=>S.get(J)).filter(Boolean),[S,u]),z=d||m,Y=z&&v.get(z)||null;return{currentReferences:x,assemblyParts:y,assemblyPartMap:S,inspectedAssemblyPartIds:I,inspectedAssemblyPartId:b,inspectedAssemblyPart:A,allReferences:x,mixedReferenceList:x,referenceMap:N,isInspectingAssemblyPart:P,activeReferenceMap:v,inspectedAssemblyPartReferences:R,inspectedAssemblyPartSourceLabel:C,selectedReferences:T,selectedParts:k,hoveredReferenceId:z,hoveredReference:Y,hoveredPartId:p||g||"",visibleReferences:P?R:x,filteredReferences:P?R:x,filteredAssemblyParts:y}}function hie({copyStatus:e,screenshotStatus:t,setCopyStatus:n,setScreenshotStatus:r,previewMode:o,viewerAlertOpen:i,themeSheetOpen:s,tabToolsOpen:a,isDesktop:l,sidebarOpen:u,previewUiStateRef:d,tabToolMode:m,drawingUndoStackRef:p,drawingRedoStackRef:g,handleUndoDrawing:x,handleRedoDrawing:y,setPreviewMode:S,setViewerAlertOpen:b,setThemeMenuOpen:I,setTabToolsOpen:A,setSidebarOpen:N,setTabToolMode:P}){f.useEffect(()=>{if(!(e||t))return;const R=window.setTimeout(()=>{n(""),r("")},2200);return()=>window.clearTimeout(R)},[e,t,n,r]),f.useEffect(()=>{if(!(o||i||s||a||!l&&u))return;const R=v=>{if(!v.defaultPrevented&&!_w(v.target)&&!v.altKey&&(v.metaKey||v.ctrlKey)){const C=String(v.key||"").toLowerCase(),T=C==="y"||C==="z"&&v.shiftKey;if(C==="z"&&!v.shiftKey&&p.current.length){v.preventDefault(),x();return}if(T&&g.current.length){v.preventDefault(),y();return}}if(v.key==="Escape"){if(o){const C=d.current;d.current=null,S(!1),C&&(b(C.viewerAlertOpen),I(C.themeMenuOpen),N(C.sidebarOpen),A(C.tabToolsOpen),P(C.tabToolMode));return}b(!1),I(!1),A(!1),l||N(!1)}};return window.addEventListener("keydown",R),()=>{window.removeEventListener("keydown",R)}},[g,p,y,x,l,s,o,d,I,S,N,P,A,b,u,a,i])}const Qm=Object.freeze({dxf:"",step:"python -m cadpy.step_artifact --repo-root . --step",urdf:"",sdf:""});function ep(e,t){const n=String(e||"").trim();return n?`${n} ${t}`:""}function gie(e,t=null){const n=or(t);return n===B.STEP&&nv(t)==="python"?"":n===B.DXF?ep(Qm.dxf,e):n===B.URDF||n===B.SRDF?String(t?.kind||"").trim().toLowerCase()==="srdf"?"":ep(Qm.urdf,e):n===B.SDF?ep(Qm.sdf,e):n===B.STL||n===B.THREE_MF||n===B.GLB||n===B.GCODE?"":ep(Qm.step,e)}function NS(e,t,n){const r=at(e);if(!r)return null;const o=or(e),i=gie(r,e),s=o===B.STL||o===B.THREE_MF||o===B.GLB||o===B.GCODE,a=o===B.THREE_MF?"3MF":o===B.GLB?"GLB":o===B.GCODE?"G-code":"STL",l=s?`Confirm the ${a} exists in the repo and reload the page.`:"Try reloading the page. If the problem persists, rebuild the render assets for this entry.",u=s?`Confirm the ${a} exists in the repo and reload the page.`:"Rebuild the CAD assets for this entry, then reload the page.",d=o===B.STEP&&e?.artifact?.ok===!1?e?.artifact:null;if(d&&!t){const m=String(d.error||"").trim(),x=d.stale===!0||m==="stale_step_artifact"?"STEP artifact stale":m==="missing_glb"?"STEP artifact missing":"STEP artifact unavailable",y=mv(e);if(!y||!n)return{severity:y?"warning":"error",...y?{blocking:!1}:{},compact:!0,summary:x,title:x,message:dk(d),command:i}}return n?{severity:"error",summary:"Mesh load failed",title:"Failed to load render mesh",message:n,resolution:l,command:i}:t?null:{severity:"error",summary:"Mesh unavailable",title:"No mesh data is available",message:"The selected entry is listed in the CAD catalog but no renderable mesh data could be loaded for it.",resolution:u,command:i}}function bie(e,t,n,r){if(!e)return null;const o=ep(Qm.dxf,e),i=String(r||"").trim();return n?{severity:"error",summary:"DXF load failed",title:"Failed to load DXF flat pattern",message:n,resolution:"Try reloading the page. If the problem persists, rebuild the CAD assets for this entry.",command:o}:/DXF 3D bend preview currently requires vertical bend lines/i.test(i)?null:i?{severity:"warning",summary:"DXF 3D preview unavailable",title:"Failed to build the DXF 3D preview",message:i,resolution:"The flat pattern can still be shown, but the 3D extrusion preview could not be built from the current DXF geometry.",command:o}:t?null:{severity:"error",summary:"DXF unavailable",title:"No DXF flat pattern is available",message:"The selected entry does not have a ready DXF companion asset for the flat-pattern viewer.",resolution:"Rebuild the CAD assets for this entry, then reload the page.",command:o}}function yie(e,t,n){return e?n?{severity:"error",summary:"Implicit CAD load failed",title:"Failed to load implicit CAD module",message:n,resolution:"Check the exported GLSL distance function and reload the page."}:t?null:{severity:"error",summary:"Implicit CAD unavailable",title:"No implicit CAD model is available",message:"The selected entry is listed in the CAD catalog but the implicit CAD module did not load.",resolution:"Confirm the .implicit.js or .implicit.mjs file exists and exports an implicit.js/0.1.0 model."}:null}function HD(e){const t=at(e),n=rq(e);return t&&n?`${t}:${n}`:""}function xie(e){return Array.isArray(e)?e.filter(t=>t&&typeof t=="object").map(t=>({...t,id:String(t.id||"").trim(),label:String(t.label||t.id||"Reference").trim()||"Reference",summary:String(t.summary||t.shortSummary||"").trim(),shortSummary:String(t.shortSummary||t.summary||"").trim(),copyText:String(t.copyText||"").trim(),partId:String(t.partId||"").trim(),entityType:String(t.entityType||"").trim(),selectorType:String(t.selectorType||"").trim(),normalizedSelector:String(t.normalizedSelector||"").trim(),displaySelector:String(t.displaySelector||"").trim()})).filter(t=>t.id):[]}function Sie(e,t=null,{copyCadPath:n,partId:r="",transform:o=null,remapOccurrenceId:i="",remapOccurrencePrefix:s=null}={}){const a=qU(t,{copyCadPath:n||iv(e),partId:r,transform:o,remapOccurrenceId:i,remapOccurrencePrefix:s}),l=xie(a.references);return{fileRef:at(e),kind:e.kind,referenceHash:HD(e),stepRelPath:at(e),stepHash:String(a.stepHash||e?.hash||""),counts:{faces:Number(a.faces?.length||0),edges:Number(a.edges?.length||0)},parts:[],selectorRuntime:a,references:l,disabledReason:""}}function CT(e){const t=String(e||"").trim(),n="assembly-part:";if(t.startsWith(n)){const r=t.slice(n.length).trim();return r?{partId:r}:null}if(t.startsWith("topology|")){const r=t.split("|"),o=String(r[1]||"").trim();return o?{partId:o}:null}return null}function MT(e,t=""){return`selector-ref::${String(t||"").trim()||"root"}`}function IT(e,t,n,r){if(!n)return null;let o=e.get(n);return o||(o={cadPath:r,selectors:[],seenSelectors:new Set},e.set(n,o),t.push({kind:"group",key:n}),o)}function Eie(e,t,n,r=""){const o=String(n||"").trim(),i=String(r||"").trim()||o;return!o||!i||e.has(i)?!1:(e.set(i,o),t.push({kind:"plain",key:i}),!0)}function wie(e,t,n,r,o=""){const i=String(r||"").trim();if(!i)return 0;const s=rh(i);if(!s)return Eie(t,n,i,o),0;const{cadPath:a,selectors:l}=s;if(!l.length){const m=IT(e,n,MT(a,"root"),a);return!m||m.seenSelectors.has("")?0:(m.seenSelectors.add(""),1)}const u=IT(e,n,MT(a,"selectors"),a);if(!u)return 0;let d=0;for(const m of l)u.seenSelectors.has(m)||(u.seenSelectors.add(m),u.selectors.push(m),d+=1);return d}function Gs(e,{allowPlain:t=!1}={}){const n=String(e||"").trim();return n?n.startsWith("#")?n.split(/\s+/)[0]||"":t?n:"":""}function vie(e){const t=new Map,n=new Map,r=[];for(const i of e)wie(t,n,r,String(i?.copyText||"").trim(),String(i?.id||"").trim());return{text:r.map(i=>{if(i.kind==="plain")return n.get(i.key)||"";const s=t.get(i.key);return s?dc({cadPath:s.cadPath,selectors:i.key.endsWith("::selectors")?BS(s.selectors):[]}):""}).map(i=>Gs(i,{allowPlain:!0})).filter(Boolean).join(` `)}}function Cie(e,t){const n=[e?.displaySelector,e?.occurrenceId,e?.sourceOccurrenceId,e?.sourceRootTargetOccurrenceId,e?.id].map(r=>{const o=String(r||"").trim();return/^(?:o\d+(?:\.\d+)*(?:\.[sfev]\d+)?|[sfev]\d+|m\d+)$/i.test(o)?o:""}).find(Boolean)||"";return n?dc({selector:n}):""}function _S(e){return e?{id:"step-entry:whole",copyText:dc()}:null}function Mie(e){return String(e?.id||"").trim()}function KD(e,t){const n=Mie(e);return n?dc({selector:n}):""}function km({references:e=[],parts:t=[],mates:n=[],entry:r=null}={}){const o=Array.isArray(e)?[...e]:[],i=[];for(const l of t){const u=Cie(l);if(!u){i.push(String(l?.name||l?.id||"part"));continue}const d=String(l?.id||l?.occurrenceId||"").trim();o.push({id:`assembly-part:${d}`,copyText:u})}for(const l of Array.isArray(n)?n:[]){const u=KD(l);u&&o.push({id:`assembly-mate:${String(l?.id||"").trim()}`,copyText:u})}const{text:s}=vie(o);return{lines:String(s||"").split(` `).map(l=>Gs(l,{allowPlain:!0})).filter(Boolean),copiedCount:o.length,missingPartNames:i}}function Iie(e,{limit:t=1}={}){const n=Array.isArray(e)?e:[],r=Math.max(1,Number(t)||1),o=n.map(s=>Gs(s,{allowPlain:!0})).filter(Boolean);return o.length?`Copy ${o.slice(0,r).join(", ")}`:"Copy refs"}function pd(e,t){if(e===t)return!0;if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;for(let n=0;ni!==r):[...o,r]:o.length===1&&o[0]===r?[]:[r]}const XD=11,YD="custom:",Aie="appearance",kv=1,vE=`cad-viewer:directory-session:v${kv}`,CE=280,ME=365,Nie=280;T2(Rp.settings);function qD(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Jp(e,t=""){return String(e??t)}function tp(e){return Array.isArray(e)?e.map(t=>String(t??"").trim()).filter(Boolean):[]}function ZD(e){return[...new Set(tp(e))]}function JD(e){return Array.isArray(e)?ZD(e):null}function _ie(e,t){const n=Number(e);return Number.isFinite(n)?n:t}function zd(e){const t=Number(e);return!Number.isFinite(t)||t<=0?null:Math.round(t)}function QD(e,t=!1){return typeof e=="boolean"?e:t}function Tie(e){return typeof e=="boolean"?e:null}function Rie(e,t=ME){const n=zd(e),r=zd(t)||zd(ME);return!n||n===r?null:n}function Pie(e,t=CE){const n=zd(e),r=zd(t)||zd(CE);return!n||n===r?null:n}function Dv(e){return nB(e)?Nie:ME}function hd(e){return Array.isArray(e)?[...e]:[]}function gd(e,t){if(e===t)return!0;if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;for(let n=0;n0?n:1}}function ej(e){const t=Jp(e||Jt.FREEHAND);switch(t){case Jt.LINE:case Jt.ARROW:case Jt.DOUBLE_ARROW:case Jt.RECTANGLE:case Jt.CIRCLE:case Jt.FILL:case Jt.ERASE:case Jt.FREEHAND:return t;default:return Jt.FREEHAND}}function Oie(e){return Jp(e||oo.REFERENCES)===oo.DRAW?oo.DRAW:oo.REFERENCES}function cb(e,t,n){if(e===t)return!0;if(!Array.isArray(e)||!Array.isArray(t)||e.lengthzH(e)},{key:"dxfThicknessMm",defaultValue:0,normalize:e=>{const t=_ie(e,0);return t>0?t:0}},{key:"referenceQuery",defaultValue:"",normalize:Jp},{key:"selectedReferenceIds",defaultValue:[],normalize:tp,clone:hd,equals:gd},{key:"selectedPartIds",defaultValue:[],normalize:tp,clone:hd,equals:gd},{key:"inspectedAssemblyNodeId",defaultValue:"",normalize:e=>Jp(e).trim()},{key:"expandedAssemblyPartIds",defaultValue:[],normalize:tp,clone:hd,equals:gd},{key:"expandedStepTreeNodeIds",defaultValue:[],normalize:ZD,clone:hd,equals:gd},{key:"stepTreeRootShowMore",defaultValue:!1,normalize:QD},{key:"fileSheetOpenSectionIds",defaultValue:null,normalize:JD,clone:e=>Array.isArray(e)?hd(e):null,equals:(e,t)=>Array.isArray(e)||Array.isArray(t)?gd(e||[],t||[]):e===t},{key:"hiddenPartIds",defaultValue:[],normalize:tp,clone:hd,equals:gd},{key:"camera",defaultValue:null,normalize:TT,clone:TT,equals:HR},{key:"drawingTool",defaultValue:Jt.FREEHAND,normalize:ej},{key:"tabToolMode",defaultValue:oo.REFERENCES,normalize:Oie},{key:"drawingStrokes",defaultValue:[],normalize:pa,clone:pa,equals:jv},{key:"drawingUndoStack",defaultValue:[],normalize:ub,clone:ub,equals:PT},{key:"drawingRedoStack",defaultValue:[],normalize:ub,clone:ub,equals:PT}];function IE(e,t={}){const n={};for(const r of e){let o=qD(t||{},r.key)?t[r.key]:void 0;typeof o>"u"&&(o=r.defaultValue),n[r.key]=r.normalize?r.normalize(o,r.defaultValue):o}return n}function Lie(e,t={}){const n=IE(e,t),r={};for(const o of e){const i=n[o.key];r[o.key]=o.clone?o.clone(i):i}return r}function Fie(e,t={},n={}){for(const r of e){const o=IE([r],t)[r.key],i=IE([r],n)[r.key];if(!(r.equals||Object.is)(o,i))return!1}return!0}function zie(e){return String(e||"").trim()}function nj(e,t){try{const n=e.getItem(t);return n?JSON.parse(n):null}catch{return null}}function rj(e,t,n={}){typeof n.onWriteError=="function"&&n.onWriteError({key:e,error:t})}function Lv(e,t,n,r={}){try{return e.setItem(t,JSON.stringify(n)),!0}catch(o){return rj(t,o,r),!1}}function f0(e,t,n={}){try{return e.removeItem(t),!0}catch(r){return rj(t,r,n),!1}}function oj(){return typeof window<"u"?window.sessionStorage:null}function jb(e={},t={}){return{fileViewerOpen:QD(e?.fileViewerOpen,!1),fileViewerExpandedDirectoryIds:JD(e?.fileViewerExpandedDirectoryIds),fileViewerWidthPx:Pie(e?.fileViewerWidthPx,t.defaultFileViewerWidthPx),fileSheetOpen:Tie(e?.fileSheetOpen),fileSheetWidthPx:Rie(e?.fileSheetWidthPx,t.defaultFileSheetWidthPx),theme:dj(e?.theme)}}function Bie(e={},t={}){const n=jb(e,t),r={version:kv};return(n.fileViewerOpen||qD(e||{},"fileViewerOpen"))&&(r.fileViewerOpen=n.fileViewerOpen),Array.isArray(n.fileViewerExpandedDirectoryIds)&&(r.fileViewerExpandedDirectoryIds=n.fileViewerExpandedDirectoryIds),n.fileViewerWidthPx&&(r.fileViewerWidthPx=n.fileViewerWidthPx),typeof n.fileSheetOpen=="boolean"&&(r.fileSheetOpen=n.fileSheetOpen),n.fileSheetWidthPx&&(r.fileSheetWidthPx=n.fileSheetWidthPx),n.theme&&(r.theme=n.theme),Object.keys(r).length>1?r:null}function ij(e={}){const t=e.storage||oj();if(!t)return jb({},e);const n=nj(t,vE);return!n||n.version!==kv?jb({},e):jb(n,e)}function Vie(e={},t={}){const n=t.storage||oj();if(!n)return!0;const r=Bie(e,t);return r?Lv(n,vE,r,t):f0(n,vE,t)}function Sc(e){return String(e||"").trim()}function Ta(e,t=[]){const n=Sc(e);return n&&t.some(r=>r.id===n)?n:""}function $ie(e){return String(e||"").trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"theme"}function Fv(e){return String(e||"").trim().replace(/\s+/g," ")}function sj(e){return`${YD}${$ie(e)}`}function Gie(e,t=[]){const n=sj(e),r=new Set(t.map(o=>o.id));if(!r.has(n))return n;for(let o=2;o<1e3;o+=1){const i=`${n}-${o}`;if(!r.has(i))return i}return`${n}-${Date.now().toString(36)}`}function Uie(e){const t=e?.background||{},n=String(t.type||"").trim().toLowerCase();if(n==="radial")return`radial-gradient(circle at 32% 24%, ${t.radialInner||t.solidColor||"#111827"} 0%, ${t.radialOuter||t.solidColor||"#030712"} 100%)`;if(n==="linear")return`linear-gradient(135deg, ${t.linearStart||t.solidColor||"#111827"} 0%, ${t.solidColor||t.linearStart||"#111827"} 52%, ${t.linearEnd||t.solidColor||"#030712"} 100%)`;const r=t.solidColor||e?.floor?.color||"#111827";return`linear-gradient(135deg, ${r} 0%, ${r} 100%)`}function m0(e){const t=e?.materials?.fillColors?.[0]||e?.materials?.defaultColor||Rp.settings.materials.defaultColor;return{background:Uie(e),modelColor:t,accentColor:e?.floor?.color||t||Rp.settings.floor.color}}function aj(e){const t=fr(e?.settings);return{id:Sc(e?.id),label:Fv(e?.label)||Sc(e?.id),description:String(e?.description||"Built-in theme"),presetId:ol(e?.id),preview:e?.preview||m0(t),settings:t}}function zv(){return ic.map(aj).filter(e=>e.id&&e.label)}function Wie(e){return Sc(e).startsWith(YD)}function Bv(e,t=[]){const n=Sc(e);return Wie(n)&&t.some(r=>r.id===n)?n:""}function lj(e){const t=Sc(e?.id),n=ol(t);if(t&&n)return null;const r=Sc(e?.presetId||e?.sourcePresetId),o=ol(r);if(r&&!o)return null;const i=o?gw(o):null,s=t||sj(e?.label||e?.name),a=Fv(e?.label||e?.name||i?.label||s),l=e?.theme&&typeof e.theme=="object"?e.theme:e?.settings,u=fr(l&&typeof l=="object"?l:i?.settings);if(!s||!a||!u||ol(s))return null;const d=o||"";return{id:s,label:a,description:String(e?.description||"Saved theme"),presetId:d,preview:m0(u),settings:u}}function yh(e){const t=Array.isArray(e)?e:e?.themes;if(!Array.isArray(t))return[];const n=new Set,r=[];for(const o of t){const i=lj(o);!i||n.has(i.id)||(n.add(i.id),r.push(i))}return r}function rs(e,t={}){return[...t.fallbackToDefault!==!1?zv():[],...yh(e)]}function Hie(e){return{id:e.id,label:e.label,description:e.description,presetId:e.presetId||"",theme:e.settings}}function OT(e){return JSON.stringify(fr(e))}function fu(e=zv()){return Ta(Hd,e)||e[0]?.id||Hd}function cj({activeThemeId:e="",themeId:t="",customPresets:n=[],themes:r=null}={}){const o=rs(r||n),i=yh(o),s=Ta(e||t,o),a=fu(o);return!i.length&&(!s||s===a)?null:{version:XD,activeThemeId:s===a?"":s,themes:i.map(Hie)}}function If(){const e=zv();if(typeof window>"u")return{customPresets:e,themeId:fu(e)};const t=nj(window.localStorage,xu);if(!t||t.version!==XD)return{customPresets:e,themeId:fu(e)};const n=rs(t);return{customPresets:n,themeId:Ta(t.activeThemeId,n)||fu(n)}}function xh(e={},t={}){if(typeof window>"u")return!0;const n=cj(e);return n?Lv(window.localStorage,xu,n,t):f0(window.localStorage,xu,t)}function so(){return If().customPresets}function Kie(e,t={}){const n=If(),r=rs(e);return xh({themeId:n.themeId,customPresets:r},t)}function Xie(e,t,n,r={}){const o=Fv(e);if(!o)return null;const i=fr(t),s=Vv(r.sourceThemeId||r.presetId,n);return lj({id:Gie(o,n),label:o,presetId:ol(r.sourcePresetId||s?.presetId||s?.id),settings:i})}function Yie(e,t,n={}){const r=rs(n.customPresets||so()),o=Xie(e,t,r,n);if(!o)return null;const i=[...r,o];return xh({activeThemeId:o.id,customPresets:i},n)?{preset:o,customPresets:i}:null}function qie(e,t={}){const n=If(),r=yh(n.customPresets),o=Bv(e,r);if(!o)return!1;const i=r.filter(a=>a.id!==o);if(i.length===r.length)return!0;const s=n.themeId===o?"":n.themeId;return xh({themeId:s,customPresets:i},t)}function Zie(e,t,n={}){const r=If(),o=yh(r.customPresets),i=Bv(e,o);if(!i)return!1;const s=fr(t),a=o.map(l=>l.id===i?{...l,preview:m0(s),settings:s}:l);return xh({themeId:i,customPresets:a},n)}function Jie(e,t={}){const n=If(),r=yh(n.customPresets),o=Bv(e,r),i=r.find(d=>d.id===o),s=ol(i?.presetId||i?.id);if(!i||!s)return!1;const a=aj(gw(s)),l={...i,presetId:s,preview:m0(a.settings),settings:a.settings},u=r.map(d=>d.id===o?l:d);return xh({themeId:n.themeId,customPresets:u},t)}function Qie(e={}){return typeof window>"u"?!0:f0(window.localStorage,xu,e)}function uj(e=so()){return rs(e)}function Vv(e,t=so()){const n=rs(t),r=Ta(e,n);return uj(t).find(o=>o.id===r)||null}function ese(e,t=so()){const n=Vv(e,t);return fr(n?.settings||N2(e))}function Ry(e,t=so()){const n=fr(e),r=JSON.stringify(n);for(const o of rs(t))if(JSON.stringify(fr(o.settings))===r)return o.id;return null}function AE(e="",t=null,n=so()){const r=rs(n),o=Ta(e||fu(r),r)||r[0]?.id||Hd;return{presetId:o,settings:fr(t||ese(o,n))}}function $v(e=so()){if(typeof window>"u")return null;const t=String(window.location?.search||"").trim();if(!t)return null;let n;try{n=new URLSearchParams(t)}catch{return null}const r=String(n.get(Aie)||"").trim();if(!r)return null;const o=rs(e),i=Ta(r,o);return i?AE(i,null,o):null}function Py(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function dj(e){if(!Py(e)||!Py(e.settings))return null;const t=fr(e.settings);return t?{presetId:Sc(e.presetId),settings:t}:null}function tse(e={},t=so()){if(!Py(e)||!Py(e.settings))return null;const n=rs(t),r=fr(e.settings),o=Ta(e.presetId,n)||Ry(r,n)||fu(n),i=Vv(o,n);return i&&OT(r)===OT(i.settings)?null:{presetId:o,settings:r}}function nse(e){return dj(e)!==null}function rse(e=so()){const t=$v(e);if(t)return t;const n=Kc(e),r=ij({}).theme;if(!nse(r))return n;const o=rs(e);return{presetId:Ta(r.presetId,o)||n.presetId,settings:fr(r.settings)}}function ose(e,t={}){const n=rs(t.themes||t.customPresets||so()),r=Ta(t.presetId||Ry(e,n),n)||fu(n);return cj({themeId:r,customPresets:n})}function Kc(e=so()){const t=$v(e);if(t)return t;if(typeof window>"u")return AE("",null,e);const n=If(),r=e?rs(e):n.customPresets,o=Ta(n.themeId,r);return AE(o,null,r)}function ise(e,t={}){if(typeof window>"u")return!0;const n=ose(e,t);return n?Lv(window.localStorage,xu,n,t):f0(window.localStorage,xu,t)}function Oy(e){return Lie(tj,e||{})}function fj(e,t){return Fie(tj,e||{},t||{})}function Dm(e,t={}){const n=Oy(t);return!n.inspectedAssemblyNodeId&&Array.isArray(t?.expandedAssemblyPartIds)&&(n.inspectedAssemblyNodeId=String(t.expandedAssemblyPartIds[t.expandedAssemblyPartIds.length-1]||"").trim()),{key:zie(e),...n}}const Su=1,mj="cad-viewer:file-session",sse="cad-viewer:file-session:index",ase="__root__";function pj(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function sr(e,t=""){return String(e??t).trim()}function cl(e,t=0){const n=Number(e);return Number.isFinite(n)?n:t}function lse(e,t=0){const n=cl(e,t);return n>0?n:t}function hj(e,t=!1){return typeof e=="boolean"?e:t}function Oo(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function jm(e,t){return JSON.stringify(e)===JSON.stringify(t)}function ky(e){if(e==null)return null;if(typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)?e:0;if(Array.isArray(e))return e.map(ky);if(!Oo(e))return null;const t={};for(const[n,r]of Object.entries(e))t[String(n)]=ky(r);return t}function gj(e,t){try{const n=e.getItem(t);return n?JSON.parse(n):null}catch{return null}}function bj(e,t,n={}){typeof n.onWriteError=="function"&&n.onWriteError({key:e,error:t})}function yj(e,t,n,r={}){try{return e.setItem(t,JSON.stringify(n)),!0}catch(o){return bj(t,o,r),!1}}function Gv(e,t,n={}){try{return e.removeItem(t),!0}catch(r){return bj(t,r,n),!1}}function Uv(){return typeof window<"u"?window.sessionStorage:null}function Wv(e){return sr(e)||ase}function NE(e){return encodeURIComponent(sr(e))}function Hv(e,t){return[mj,`v${Su}`,NE(Wv(e)),NE(t)].join(":")}function xj(e){return[sse,`v${Su}`,NE(Wv(e))].join(":")}function Sj(e,t){const n=gj(e,xj(t));return!n||n.version!==Su||!Array.isArray(n.files)?[]:[...new Set(n.files.map(r=>sr(r)).filter(Boolean))]}function Ej(e,t,n,r={}){const o=[...new Set((Array.isArray(n)?n:[]).map(s=>sr(s)).filter(Boolean))].sort(),i=xj(t);return o.length?yj(e,i,{version:Su,files:o},r):Gv(e,i,r)}function cse(e,t,n,r={}){const o=sr(n);if(!o)return!0;const i=Sj(e,t);return i.includes(o)?!0:Ej(e,t,[...i,o],r)}function wj(e){return Wp(e)}function use(e){return zt(e,"dxf")}function dse(e){return[zt(e,"stepModule"),sr(e?.hash)].filter(Boolean).join(":")}function fse(e){return[zt(e,"implicit"),sr(e?.hash)].filter(Boolean).join(":")}function mse(e){return[sr(e?.kind).toLowerCase(),sr(e?.hash),zt(e,"selectorTopology"),zt(e,"topology"),zt(e,"glb")].filter(Boolean).join(":")||sr(e?.file)}function pse(e){return[sr(e?.kind).toLowerCase(),sr(e?.hash),zt(e,"selectorTopology"),zt(e,"topology"),zt(e,"glb"),zt(e,"stl"),zt(e,"3mf"),zt(e,"dxf"),wj(e)].filter(Boolean).join(":")||sr(e?.file)}function vj(e){return{tab:pse(e),dxf:use(e),stepModule:dse(e),implicit:fse(e),urdf:wj(e),largeFile:mse(e)}}function hse(e){return Oo(e)?So(e):null}function gse(e){return Array.isArray(e)?e.map(t=>{if(!Oo(t))return null;const n=sr(t.direction).toLowerCase()==="down"?"down":"up";return{id:sr(t.id),direction:n,angleDeg:Math.min(Math.max(cl(t.angleDeg,0),0),180)}}).filter(Boolean):[]}function bse(e){return Oo(e)?{thicknessMm:lse(e.thicknessMm,0),bendSettings:gse(e.bendSettings)}:null}function Cj(e){return Oo(e)?{activeId:sr(e.activeId),playing:!1,elapsedSec:Math.max(cl(e.elapsedSec,0),0),speed:Math.min(Math.max(cl(e.speed,1),.1),5)}:{activeId:"",playing:!1,elapsedSec:0,speed:1}}function yse(e){return Oo(e)?{enabled:hj(e.enabled,!0),parameterValues:Oo(e.parameterValues)?ky(e.parameterValues):{},animationState:Cj(e.animationState)}:null}function xse(e){return Oo(e)?{parameterValues:Oo(e.parameterValues)?ky(e.parameterValues):{},animationState:Cj(e.animationState)}:null}function Sse(e){return Oo(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[sr(t),cl(n,0)]).filter(([t])=>t)):{}}function Ese(e){if(!Oo(e))return{};const t={};for(const[n,r]of Object.entries(e)){const o=sr(n);!o||!Array.isArray(r)||(t[o]=[cl(r[0],0),cl(r[1],0),cl(r[2],0)])}return t}function wse(e){if(!Oo(e))return{};const t={};for(const r of["activePlanningGroupName","activeEndEffectorName","targetFrame","planningPipeline","plannerId"]){const o=sr(e[r]);o&&(t[r]=o)}for(const r of["ikTimeout","ikAttempts","ikTolerance","planningTime","maxVelocityScalingFactor","maxAccelerationScalingFactor"])pj(e,r)&&(t[r]=cl(e[r],0));const n=Ese(e.targetsByEndEffector);return Object.keys(n).length&&(t.targetsByEndEffector=n),t}function vse(e){return Oo(e)?{jointValues:Sse(e.jointValues),motionState:wse(e.motionState)}:null}function Cse(e){return Oo(e)?{selectableTopologyEnabled:hj(e.selectableTopologyEnabled,!1)}:null}const Mj=Object.freeze({display:{normalize:hse,equals:XV,signatureKey:"tab"},tab:{normalize:Oy,equals:fj,signatureKey:"tab"},dxf:{normalize:bse,equals:jm,signatureKey:"dxf"},stepModule:{normalize:yse,equals:jm,signatureKey:"stepModule"},implicit:{normalize:xse,equals:jm,signatureKey:"implicit"},urdf:{normalize:vse,equals:jm,signatureKey:"urdf"},largeFile:{normalize:Cse,equals:jm,signatureKey:"largeFile"}});function Mse(e,t,n,r={}){const o=Mj[e]?.signatureKey;if(!o||r.skipSignatureCheck===!0)return!0;const i=sr(t?.[o]),s=sr(n?.[o]);return!!(i&&s&&i===s)}function Ise(e,t={}){if(!Oo(e))return{};const n=t.currentSignatures||{},r=t.signatures||{},o={};for(const[i,s]of Object.entries(Mj)){if(!pj(e,i)||!Mse(i,r,n,t))continue;const a=s.normalize(e[i]);a!==null&&(o[i]=a)}return o}function Ase({fileKey:e="",entry:t=null,slices:n={}}={}){const r=sr(e||t?.file);return Kv({version:Su,fileKey:r,signatures:vj(t),slices:n},{fileKey:r,entry:t,skipSignatureCheck:!0})}function Kv(e,t={}){if(!Oo(e)||e.version!==Su)return null;const n=sr(e.fileKey||t.fileKey);if(!n||t.fileKey&&n!==sr(t.fileKey))return null;const r=Oo(e.signatures)?e.signatures:{},o=t.entry?vj(t.entry):t.currentSignatures||r,i=Ise(e.slices,{currentSignatures:o,signatures:r,skipSignatureCheck:t.skipSignatureCheck});return{version:Su,fileKey:n,signatures:{...r},slices:i}}function RS(e,t,n=null,r={}){const o=r.storage||Uv(),i=sr(t||n?.file);return!o||!i?null:Kv(gj(o,Hv(e,i)),{fileKey:i,entry:n})}function Nse(e,t,n,r={}){const o=r.storage||Uv(),i=sr(t||n?.fileKey);if(!o||!i)return!0;const s=Kv(n,{fileKey:i,skipSignatureCheck:!0}),a=Hv(e,i);if(!s||!Object.keys(s.slices).length)return Gv(o,a,r);const l=yj(o,a,s,r),u=cse(o,e,i,r);return l&&u}function _se(e,t,n={}){const r=n.storage||Uv();if(!r)return!0;const o=new Set((Array.isArray(t)?t:[]).map(l=>sr(l)).filter(Boolean)),i=Sj(r,e);let s=!0;const a=[];for(const l of i){if(o.has(l)){a.push(l);continue}s=Gv(r,Hv(e,l),n)&&s}return Ej(r,e,a,n)&&s}const Rd=Object.freeze({COLOR_SCHEME:"colorScheme",THEME:"theme",IGNORE:"ignore"});function Tse(e){const t=String(e||"");return!t||t.startsWith(mj)?Rd.IGNORE:t===Cp?Rd.COLOR_SCHEME:t===xu?Rd.THEME:Rd.IGNORE}function Dr(e,t=0){const n=Number(e);return Number.isFinite(n)?n:t}function Ao(e,t,n){return Math.min(Math.max(Dr(e,t),t),n)}function bd(e,t){const n=Object.keys(e||{}),r=Object.keys(t||{});return n.length!==r.length?!1:n.every(o=>Object.hasOwn(t||{},o)&&e?.[o]===t?.[o])}function np(e,t){const n=Array.isArray(e?.animations)?e.animations:[];if(!n.length)return null;const r=String(t||"").trim();return n.find(o=>o.id===r)||n[0]||null}function Lm(e){return{activeId:np(e,"")?.id||"",playing:!1,elapsedSec:0,speed:1}}function Ka(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function Lb(e,t){const n=Array.isArray(e?.animations)?e.animations:[];if(!n.length)return null;const r=String(t||"").trim();return n.find(o=>o.id===r)||n[0]||null}function PS(e){return{activeId:Lb(e,"")?.id||"",playing:!1,elapsedSec:0,speed:1}}const Rse=840,Pd=240,p0=.001;function Eu(e,t=0){const n=Number(e);return Number.isFinite(n)?n:t}function Ij(e){return Math.min(Math.max(Eu(e,1),0),1)}function nf(e){return!e||typeof e!="object"?[]:Object.entries(e).map(([t,n])=>[String(t||"").trim(),Eu(n,0)]).filter(([t])=>t).sort(([t],[n])=>t.localeCompare(n))}function Pse(e,t){return!t||!e?!1:e instanceof Set||e instanceof Map?e.has(t):!!e?.[t]}function Ose(e){const t=Eu(e,0),n=((t+180)%360+360)%360-180;return n===-180&&t>0?180:n}function Aj(e,t,n,r){const o=Eu(t,0),i=Eu(n,o);return Pse(r,e)?Ose(i-o):i-o}function kse(e){const t=Ij(e);return t*t*t*(t*(6*t-15)+10)}function Ip(e,t,n=p0){const r=nf(e),o=nf(t);if(r.length!==o.length)return!1;for(let i=0;in)return!1}return!0}function Dse(e,t,n,r=p0,o=null){const i=nf(t),s=new Map(nf(e)),a=kse(n),l={};let u=!0;for(const[d,m]of i){const p=s.has(d)?s.get(d):m,g=Aj(d,p,m,o),x=p+g*a;Math.abs(g*(1-a))<=r||a>=1?l[d]=m:(l[d]=x,u=!1)}return{values:l,done:u}}function jse(e,t,n,r=Pd,o=p0,i=null){const s=nf(t),a=new Map(nf(e)),l=Math.max(Eu(n,0),0),u=Math.max(Eu(r,Pd),1),d=Ij(1-Math.exp(-l/u)),m={};let p=!0;for(const[g,x]of s){const y=a.has(g)?a.get(g):x,S=Aj(g,y,x,i),b=y+S*d;Math.abs(S*(1-d))<=o||d>=1?m[g]=x:(m[g]=b,p=!1)}return{values:m,done:p}}const Lse=1e-6;function _E(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Xv(e,t=0){const n=Number(e);return Number.isFinite(n)?n:t}function Nj(e){const t=String(e?.type||"fixed");return t==="continuous"||t==="revolute"}function Yv(e,t){const n=Xv(t,0);return Nj(e)?n*180/Math.PI:n}function Fse(e,t){const n=Xv(t,0);return Nj(e)?n*Math.PI/180:n}function zse(e,t){const n=Array.isArray(e?.joints)?e.joints:[],r=new Map(n.map(i=>[String(i?.name||""),i]).filter(([i])=>i)),o={};for(const[i,s]of Object.entries(t||{})){const a=String(i||"").trim(),l=r.get(a);a&&l&&(o[a]=Fse(l,s))}return o}function Yl(e,t=[0,0,0]){const n=Array.isArray(e)?e:t;return[0,1,2].map(r=>Xv(n[r],t[r]??0))}function Bse(e,t){const n=Yl(e),r=Yl(t);return Math.hypot(n[0]-r[0],n[1]-r[1],n[2]-r[2])}function TE(e,t,{native:n=!1}={}){if(!_E(t))throw new Error("MoveIt2 server response jointValuesByName must be an object");const r=Array.isArray(e?.joints)?e.joints:[],o=new Map(r.map(s=>[String(s?.name||""),s]).filter(([s])=>s)),i={};for(const[s,a]of Object.entries(t)){const l=String(s||"").trim();if(!l)throw new Error("MoveIt2 server response includes an empty joint name");const u=o.get(l);if(!u)throw new Error(`MoveIt2 server response references unknown joint ${l}`);const d=String(u?.type||"fixed");if(d==="fixed")throw new Error(`MoveIt2 server response cannot set fixed joint ${l}`);if(u?.mimic)throw new Error(`MoveIt2 server response cannot set mimic joint ${l}`);const m=Number(a);if(!Number.isFinite(m))throw new Error(`MoveIt2 server response joint ${l} must be a finite number`);const p=n?Yv(u,m):m,g=uc(u,p);if(d!=="continuous"&&Math.abs(g-p)>Lse)throw new Error(`MoveIt2 server response joint ${l} must stay within joint limits`);i[l]=p}return i}function Vse(e,t){if(!_E(t))throw new Error("MoveIt2 server response trajectory must be an object");const r=(Array.isArray(t.jointNames)?t.jointNames:[]).map(a=>String(a||"").trim()).filter(Boolean);if(!r.length)throw new Error("MoveIt2 server response trajectory.jointNames must be a non-empty array");const o=Array.isArray(t.points)?t.points:[];if(!o.length)throw new Error("MoveIt2 server response trajectory.points must be a non-empty array");let i=-Number.EPSILON;const s=o.map((a,l)=>{if(!_E(a))throw new Error(`MoveIt2 server response trajectory point ${l+1} must be an object`);const u=Number(a.timeFromStartSec);if(!Number.isFinite(u)||u<0||uNumber(x)):[];if(d&&(m.length!==r.length||m.some(x=>!Number.isFinite(x))))throw new Error("MoveIt2 server response trajectory positions must match trajectory.jointNames");const p=d?m.map((x,y)=>{const S=(Array.isArray(e?.joints)?e.joints:[]).find(b=>String(b?.name||"")===r[y]);return Yv(S,x)}):Array.isArray(a.positionsDeg)?a.positionsDeg.map(x=>Number(x)):[];if(p.length!==r.length||p.some(x=>!Number.isFinite(x)))throw new Error("MoveIt2 server response trajectory positions must match trajectory.jointNames");const g=Object.fromEntries(r.map((x,y)=>[x,p[y]]));return TE(e,g),{timeFromStartSec:u,positions:d?m:null,positionsDeg:p,positionsByName:d?Object.fromEntries(r.map((x,y)=>[x,m[y]])):null,positionsByNameDeg:g}});return{jointNames:r,points:s}}function $se(e,t,n,r){const o=EE(e,t,n?.link,n?.frame);return o?{actualPosition:o,positionError:Bse(o,r)}:{actualPosition:null,positionError:Number.POSITIVE_INFINITY}}function jr(e){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).map(([t,n])=>[String(t||"").trim(),Dr(n,0)]).filter(([t])=>t))}function _j(e,t){if(!t||typeof t!="object")return{};const n=Array.isArray(e?.joints)?e.joints:[],r=new Map(n.map(o=>[String(o?.name||""),o]).filter(([o])=>o));return Object.fromEntries(Object.entries(t).map(([o,i])=>{const s=String(o||"").trim(),a=r.get(s);return s&&a?[s,Yv(a,i)]:null}).filter(Boolean))}function Gse(e){return(Array.isArray(e?.srdf?.groupStates)?e.srdf.groupStates:Array.isArray(e?.motion?.groupStates)?e.motion.groupStates:[]).reduce((n,r)=>{if(String(r?.name||"").trim().toLowerCase()!=="home")return n;const o=_j(e,r?.jointValuesByName||r?.jointValuesByNameRad);return{...n,...o}},{})}function Use(e,t){const n=jr(t),r=Object.keys(n);if(!r.length)return!1;const o=Object.fromEntries(r.map(i=>[i,e?.[i]]));return Ip(o,n)}function Wse(e,t,n={}){const r=Array.isArray(e)?e:[],o=jr(t),i=jr(n),s=new Set([...Object.keys(o),...Object.keys(i)]);let a=null,l=0;for(const u of r){const d=jr(u?.jointValuesByName),m=Object.keys(d);if(!m.length||!Use(o,d))continue;const p=[...s].filter(y=>!Object.hasOwn(d,y)),g=Object.fromEntries(p.map(y=>[y,o[y]??0])),x=Object.fromEntries(p.map(y=>[y,i[y]??0]));Ip(g,x)&&m.length>l&&(a=u,l=m.length)}return a}function Hse(e,t,n={}){const r=Array.isArray(e?.points)?e.points:[];if(!r.length)return jr(n);const o=r[0];if(t<=Dr(o.timeFromStartSec,0))return{...jr(n),...jr(o.positionsByNameDeg)};for(let i=1;iu)continue;const d=Math.max(u-l,1e-6),m=Math.min(Math.max((t-l)/d,0),1),p=jr(s.positionsByNameDeg),g=jr(a.positionsByNameDeg),x={};for(const[y,S]of Object.entries(g)){const b=Object.hasOwn(p,y)?p[y]:S;x[y]=b+(S-b)*m}return{...jr(n),...x}}return{...jr(n),...jr(r[r.length-1].positionsByNameDeg)}}function Kse(e){const t=Dr(e,0),n=Math.round(t*1e3)/1e3;return Object.is(n,-0)?0:n}function db(){return{fileRef:"",originalPerspective:null}}function Xse(e){if(!Array.isArray(e)||e.length<3)return null;const t=[Number(e[0]),Number(e[1]),Number(e[2])];return t.every(Number.isFinite)?t:null}function Yse(e,t){const n=Array.isArray(e)?e:[];return JSON.stringify(Object.fromEntries(n.map(r=>{const o=String(r?.name||"").trim(),i=Kse(t?.[o]??r?.defaultValueDeg??0);return[o,i]}).filter(([r])=>r)),null,2)}const qv={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1},kT=6e4,qse="ws://127.0.0.1:8765/ws",Zse=1,rf=new Map;let ms=null,RE="";function Jse(){if(Tj())return!0;const e=typeof import.meta<"u"?qv:null;return e&&typeof e=="object"&&Object.hasOwn(e,"DEV")?!!e.DEV:!0}function wu({enabled:e=Jse()}={}){return!!e}function Qse(e){const t=String(e||"").trim();return t||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`moveit2-server-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`)}function DT({enabled:e=wu()}={}){if(!wu({enabled:e}))return"";const t=typeof import.meta<"u"?String(qv?.VIEWER_MOVEIT2_WS_URL||"").trim():"";return t||qse}function Tj(){const e=typeof import.meta<"u"?String(qv?.VIEWER_MOVEIT2_WS_URL||"").trim():"";if(e)return e;if(typeof window>"u")return"";try{return String(new URL(window.location.href).searchParams.get("moveit2Ws")||"").trim()}catch{return""}}function Rj({enabled:e=wu()}={}){if(!wu({enabled:e}))return"";if(typeof window>"u")return DT({enabled:e});const t=Tj();return String(t||"").trim()||DT({enabled:e})}function eae(e){for(const[t,n]of rf.entries())clearTimeout(n.timer),n.reject(new Error(e)),rf.delete(t)}function OS(e="MoveIt2 server connection closed."){eae(e),ms=null,RE=""}function tae(e,t){if(!t)throw new Error("MoveIt2 server requires browser WebSocket support.");return ms&&RE===e&&ms.readyState<=t.OPEN||(ms&&(ms.close(),OS("MoveIt2 server connection changed.")),ms=new t(e),RE=e,ms.addEventListener("message",n=>{let r;try{r=JSON.parse(String(n.data||""))}catch{return}const o=String(r?.id||"").trim(),i=rf.get(o);if(i){if(rf.delete(o),clearTimeout(i.timer),r?.ok===!1){i.reject(new Error(String(r?.error?.message||"MoveIt2 server request failed.")));return}i.resolve(r?.result??{})}}),ms.addEventListener("close",()=>OS("MoveIt2 server connection closed.")),ms.addEventListener("error",()=>{ms?.readyState!==t.OPEN&&OS(`Could not connect to MoveIt2 server at ${e}.`)})),ms}function nae(e,t,n,r){const o=e.constructor?.OPEN??1;if(e.readyState===o){e.send(t);return}const i=()=>{e.removeEventListener("open",i),e.send(t)};e.addEventListener("open",i)}function rae({timeoutMs:e=1e3,url:t=Rj(),WebSocketImpl:n=globalThis.WebSocket,enabled:r=wu()}={}){const o=Math.max(Number(e)||1e3,1);return new Promise(i=>{if(!r||!t||!n){i(!1);return}let s=!1,a=null,l=0;const u=d=>{s||(s=!0,clearTimeout(l),a&&d&&a.close(),i(!!d))};l=setTimeout(()=>u(!1),o);try{a=new n(t)}catch{u(!1);return}a.addEventListener("open",()=>u(!0)),a.addEventListener("error",()=>u(!1)),a.addEventListener("close",()=>u(!1))})}function oae(e,t,{timeoutMs:n=kT,url:r=Rj(),WebSocketImpl:o=globalThis.WebSocket,enabled:i=wu()}={}){const s=Qse(t?.id),a=Math.max(Number(n)||kT,1);return new Promise((l,u)=>{if(!i||!r){u(new Error("MoveIt2 server connections are not enabled for this viewer session."));return}let d;try{d=tae(r,o)}catch(g){u(g);return}const m=setTimeout(()=>{rf.delete(s),u(new Error(`MoveIt2 server request ${s} timed out.`))},a);rf.set(s,{resolve:l,reject:u,timer:m});const p=JSON.stringify({id:s,type:e,protocolVersion:Zse,payload:t});nae(d,p)})}function iae(e,t){const n=String(t||"").trim();if(!e||!n)return[];const r=String(e?.id||"").trim();if(n===r||n==="root")return[e];const o=[{node:e,path:[e]}];for(;o.length;){const{node:i,path:s}=o.pop();if(String(i?.id||"").trim()===n)return s;const a=Array.isArray(i?.children)?i.children:[];for(let l=a.length-1;l>=0;l-=1){const u=a[l];o.push({node:u,path:[...s,u]})}}return[]}function Jc(e,t,n){const r=String(t||"").trim(),o=String(n||"").trim();return!e||!r||!o?!1:iae(e,o).some(i=>String(i?.id||"").trim()===r)}function Fb(e,t,{rootId:n=""}={}){if(!e)return[];const r=String(n||e?.id||"").trim(),o=[],i=new Set;for(const a of Array.isArray(t)?t:[t]){const l=String(a||"").trim();!l||l===r||i.has(l)||!oc(e,l)||(i.add(l),o.push(l))}const s=[];for(const a of o)if(!s.some(l=>Jc(e,l,a))){for(let l=s.length-1;l>=0;l-=1)Jc(e,a,s[l])&&s.splice(l,1);s.push(a)}return s}function sae(e,t,n,{referencePartId:r=null}={}){const o=new Set((Array.isArray(n)?n:[n]).map(s=>String(s||"").trim()).filter(Boolean));if(!o.size)return Array.isArray(e)?e:[];const i=typeof r=="function"?r:s=>String(s?.partId||"").trim();return(Array.isArray(e)?e:[]).map(s=>String(s||"").trim()).filter(s=>{if(!s)return!1;const a=t?.get?.(s)||null,l=String(a?.selectorType||"").trim();if(l!=="shape"&&l!=="occurrence")return!0;const u=String(i(a)||"").trim();return!u||!o.has(u)})}function aae(e,t,{rootId:n="",isolatedNodeIds:r=[]}={}){if(!e)return[];const o=String(n||e?.id||"").trim(),i=new Set((Array.isArray(t)?t:[t]).map(p=>String(p||"").trim()).filter(Boolean)),s=Fb(e,r,{rootId:o}),a=s.length?s.map(p=>oc(e,p)).filter(Boolean):[e],l=[],u=new Set,d=p=>{const g=String(p||"").trim();!g||g===o||u.has(g)||(u.add(g),l.push(g))},m=(p,{forceChildren:g=!1}={})=>{if(!p)return;const x=String(p?.id||"").trim(),y=Array.isArray(p?.children)?p.children:[],S=x&&i.has(x);if(y.length&&(g||S||x===o)){for(const b of y)m(b);return}d(x)};for(const p of a)m(p,{forceChildren:!s.length||i.has(String(p?.id||"").trim())});return l}const lae={},cae="CAD Viewer",Pj="local-fs",fb=Object.freeze([]),uae=wu(),dae=Object.freeze([0,0,0]),Vl=150,yd=520,mb=CE,Uc=240,xd=448,fae=44,jT=36,LT=80,mae=220,FT=Object.freeze({selectableTopologyEnabled:!1});function pae(){return String(lae?.VIEWER_ASSET_BACKEND||Pj).trim().toLowerCase()}function pb(e={}){return{selectableTopologyEnabled:e?.selectableTopologyEnabled===!0}}function Af(){if(typeof window>"u")return 1600;const e=Number(window.innerWidth);return Number.isFinite(e)&&e>0?e:1600}function hae(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-color-scheme: dark)").matches===!0}function gae(){return zy(Af())}function Bd(e=Af()){return ij({defaultFileSheetWidthPx:Dv(e)})}function bae(){const e=Bd().fileSheetOpen;return typeof e=="boolean"?e:rB(Af())}function yae(){const e=Af();return Bd(e).fileSheetWidthPx||Dv(e)}function xae(){const e=Af();return Bd(e).fileSheetWidthPx!=null}function vi(e){return String(e?.id||e?.occurrenceId||"").trim()}const Sae=/^(?:o\d+(?:\.\d+)*(?:\.[sfev]\d+)?|[sfev]\d+|m\d+)$/i;function Qp(e){const t=String(e||"").trim();return Sae.test(t)?t:""}function Oj(e){const t=String(e||"").trim();return t.startsWith(Ap)?Qp(t.split(":").pop()):""}function Zv(e,{allowOpaque:t=!1}={}){const n=String(e||"").trim();if(!n)return"";if(n.startsWith("#"))return Gs(n);const r=Oj(n)||n;return!t&&!Qp(r)?"":`#${r}`}function Eae(e){for(const t of Array.isArray(e)?e:[]){const n=Zv(t?.value,{allowOpaque:t?.allowOpaque===!0});if(n)return n}return""}function wae(e){return[e?.displaySelector,e?.occurrenceId,e?.sourceOccurrenceId,e?.sourceRootTargetOccurrenceId,e?.id].map(Qp).find(Boolean)||""}function of(e,t){const n=String(t||"").trim();if(!e||!n)return null;const r=[e];for(;r.length;){const o=r.pop();if(vi(o)===n||wae(o)===n||String(o?.name||"").trim()===n||String(o?.label||"").trim()===n||String(o?.displayName||"").trim()===n)return o;const i=hr(o);for(let s=i.length-1;s>=0;s-=1)r.push(i[s])}return null}function vae(e){const t=[],n=e?[e]:[];for(;n.length;){const r=n.pop(),o=hr(r);for(let s=o.length-1;s>=0;s-=1)n.push(o[s]);const i=vi(r);i&&String(r?.nodeType||"").trim()==="part"&&o.length===0&&t.push(i)}return _n(t)}function hb({assemblyPartMap:e,displayStepTreeRoot:t,stepTreeRoot:n,nodeId:r}){const o=String(r||"").trim();return o&&(e.get(o)||of(t,o)||of(n,o)||oc(t,o)||oc(n,o))||null}function Cae(e,t){const r=[Qp(t),e?.displaySelector,e?.occurrenceId,e?.sourceOccurrenceId,e?.sourceRootTargetOccurrenceId,e?.id].map(Qp).find(Boolean)||"";return r?{...e||{},id:String(e?.id||r).trim(),displaySelector:r,occurrenceId:r,name:String(e?.name||e?.label||e?.displayName||r).trim()}:null}function zT(e,t){const n=Cae(e,t),r=String(n?.occurrenceId||n?.id||t||"").trim();return r?{id:`assembly-part:${String(n?.id||r).trim()}`,copyText:dc({selector:r})}:null}function $l(e,t="selector-ref"){const n=Zv(e);if(!n)return null;const r=n.slice(1);return{id:`${t}:${r}`,copyText:n}}function rp(e,t,n="step-tree"){const o=String(e?.nodeType||"").trim().startsWith("topology-"),i=Eae(o?[{value:e?.displaySelector,allowOpaque:!0},{value:e?.topologyReferenceId,allowOpaque:!0},{value:t,allowOpaque:!1},{value:e?.id,allowOpaque:!1}]:[{value:e?.displaySelector,allowOpaque:!0},{value:e?.occurrenceId,allowOpaque:!0},{value:e?.sourceOccurrenceId,allowOpaque:!0},{value:e?.sourceRootTargetOccurrenceId,allowOpaque:!0},{value:t,allowOpaque:!1},{value:e?.id,allowOpaque:!1}]);if(!i)return null;const s=i.slice(1);return{id:`${n}:${s}`,copyText:i}}function Os(e,t,n){const r=String(t||"").trim();!r||!n||e.has(r)||e.set(r,n)}function Mae(e){const t=new Map;if(!e)return t;const n=[e];for(;n.length;){const r=n.pop(),o=vi(r),i=rp(r,o);i&&(Os(t,o,i),Os(t,r?.id,i),Os(t,r?.topologyReferenceId,i),Os(t,r?.displaySelector,i),Os(t,r?.occurrenceId,i),Os(t,r?.name,i),Os(t,r?.label,i),Os(t,r?.displayName,i),Os(t,Oj(r?.id),i),Os(t,i.copyText,i),Os(t,i.copyText.slice(1),i));const s=hr(r);for(let a=s.length-1;a>=0;a-=1)n.push(s[a])}return t}function kS(e,t){const n=[],r=new Set;for(const o of Array.isArray(e)?e:[]){const i=String(o||"").trim(),s=Gs(t?.get(i)?.copyText)||Zv(i);!s||r.has(s)||(r.add(s),n.push(s))}return n}function Fm(e,{selectedReferenceIds:t=[],selectedPartIds:n=[],selectedMateIds:r=[],copyReferenceMap:o=null}={}){const i=Array.isArray(e?.lines)?e.lines.map(a=>Gs(a)).filter(Boolean):[];if(i.length)return{...e||{},lines:_n(i),copiedCount:e?.copiedCount||i.length};const s=_n([...kS(t,o),...kS(n,o),...kS(r,o)]);return{...e||{},lines:s,copiedCount:s.length||e?.copiedCount||0}}function BT(e,t){if(!(e instanceof Map)||!t)return;const n=[t?.id,t?.normalizedSelector,t?.displaySelector].map(o=>String(o||"").trim()).filter(Boolean),r=Gs(t?.copyText);if(r.startsWith("#")){n.push(r);for(const o of r.slice(1).split(",")){const i=String(o||"").trim();i&&n.push(i)}}for(const o of n)e.has(o)||e.set(o,t)}function kj(e,t){return hr(e).length>0&&(t||vi(e)===hs)}function Iae(e,{omitRoot:t=!1,expandedTreeNodeIds:n=[],loadableTreeNodeIds:r=[]}={}){if(!e)return[];const o=[],i=new Set,s=new Set((Array.isArray(r)?r:[]).map(l=>String(l||"").trim()).filter(Boolean)),a=Bb(e,n,{omitRoot:t,showAllRootChildren:!0});for(const l of a){const u=l?.node||l,d=String(l?.id||"").trim()||vi(u);!d||i.has(d)||(l?.hasChildren||hr(u).length||s.has(d))&&(i.add(d),o.push(d))}return o}function VT({root:e,isAssemblyView:t=!1,expandedTreeNodeIds:n=[],loadableTreeNodeIds:r=[],actionNodeIds:o=[]}={}){const i=new Set((Array.isArray(n)?n:[]).map(g=>String(g||"").trim()).filter(Boolean)),a=_n((Array.isArray(o)?o:[]).map(g=>String(g||"").trim()).filter(Boolean)).map(g=>of(e,g)).filter(Boolean),l=a.filter(g=>(hr(g).length||r.includes(vi(g)))&&!i.has(vi(g))).map(g=>vi(g)).filter(Boolean),u=a.filter(g=>(hr(g).length||r.includes(vi(g)))&&i.has(vi(g))).map(g=>vi(g)).filter(Boolean),d=Iae(e,{omitRoot:kj(e,t),expandedTreeNodeIds:n,loadableTreeNodeIds:r}),m=d.filter(g=>!i.has(g)),p=d.filter(g=>i.has(g));return{collapsedActionNodeIds:l,expandedActionNodeIds:u,collapsedExpandableTreeNodeIds:m,expandedExpandableTreeNodeIds:p,showExpandCollapse:!!(a.some(g=>hr(g).length)||d.length)}}function Aae(e,t,{isAssemblyView:n=!1}={}){return e?_n(Bb(e,t,{omitRoot:kj(e,n),showAllRootChildren:!0}).map(r=>String(r?.topologyReferenceId||"").trim()).filter(Boolean)):[]}function $T(e,t){const n=String(t||"").trim();if(!e||!n)return"";const r=[e];for(;r.length;){const o=r.pop();if(String(o?.topologyReferenceId||"").trim()===n)return vi(o);const i=hr(o);for(let s=i.length-1;s>=0;s-=1)r.push(i[s])}return""}function Nae(e,t){const n=String(t||"").trim(),r=Array.isArray(e?.children)?e.children:[];if(!n||!r.length)return"";for(const o of r){const i=String(o?.id||"").trim();if(i&&(i===n||Zp(o).includes(n)))return i}return""}function _ae(e){const t=[],n=[...hr(e)].reverse();for(;n.length;){const r=n.pop(),o=vi(r),i=String(r?.nodeType||"").trim(),s=hr(r);i.startsWith("topology-")&&o&&s.length&&r?.visualOnly!==!0&&t.push(o);for(let a=s.length-1;a>=0;a-=1)n.push(s[a])}return t}function Tae(e,t,{expandSelf:n=!1,includeVisualOnlyAncestors:r=!0}={}){const o=String(t||"").trim();if(!e||!o)return[];const i=of(e,o),s=F5(e,o).filter(a=>r?!0:of(e,a)?.visualOnly!==!0);return n&&i&&hr(i).length&&s.push(o,..._ae(i)),[...new Set(s.filter(Boolean))]}function DS(e,t){const n=String(t||"").trim(),r=of(e,n);if(!r)return n?[n]:[];const o=[],i=[r];for(;i.length;){const s=i.pop(),a=vi(s);a&&o.push(a);const l=hr(s);for(let u=l.length-1;u>=0;u-=1)i.push(l[u])}return o}function jS({definition:e,animation:t,elapsedSec:n,speed:r,parameterValues:o}){if(!e)return{};const i=wb(e,o);if(typeof t?.update!="function")return i;const s=Math.max(Number(t.duration)||1,.001),a=Ao(n,0,s),l=s>0?Ao(a/s,0,1):0,u={...i},d=(m,p)=>{const g=String(m||"").trim(),x=e.parameterMap?.[g];x&&(u[g]=bu(x,p))};try{t.update({elapsed:a,elapsedSec:a,duration:s,progress:l,cycle:s>0?a/s:0,loop:t.loop!==!1,params:i,set:d,speed:Ao(r,.1,5)})}catch(m){console.error("STEP animation update failed",m)}return u}function GT(e,t,n=""){const[r,o]=f.useState(e),i=f.useRef(e),s=f.useRef(n),a=f.useRef(0),l=f.useRef(0);return f.useEffect(()=>()=>{l.current&&(window.clearTimeout(l.current),l.current=0)},[]),f.useEffect(()=>{i.current=e;const u=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),d=Math.max(Number(t)||0,0);if(s.current!==n){s.current=n,l.current&&(window.clearTimeout(l.current),l.current=0),a.current=u,o(e);return}if(d<=0||typeof window>"u"){a.current=u,o(e);return}const m=u-a.current;if(m>=d){l.current&&(window.clearTimeout(l.current),l.current=0),a.current=u,o(e);return}l.current||(l.current=window.setTimeout(()=>{l.current=0,a.current=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),o(i.current)},d-m))},[t,n,e]),r}function UT(e,t,n,r){if(!e||typeof t?.update!="function")return n;const o=Math.max(Number(t.duration)||1,.001),i=Ao(r,0,o),s=o>0?Ao(i/o,0,1):0,a=qd(e,n),l={...a},u=(d,m)=>{const p=String(d||"").trim(),g=e.parameterMap?.[p];g&&(l[p]=bu(g,m))};return t.update({...a,elapsed:i,elapsedSec:i,duration:o,progress:s,cycle:o>0?i/o:0,t:i,loop:t.loop!==!1,params:a,set:u}),l}async function Rae(e,t){try{const n=await e.json();return String(n?.error||n?.message||t).trim()||t}catch{return t}}function Pae(e){const t=at(e),n=zt(e,"dxf");return t&&n?`${t}:${n}`:""}function WT(e,t){return Object.prototype.hasOwnProperty.call(e||{},t)}function Oae(e){return!!(vn(e,"implicit")&&zt(e,"implicit"))}function kae(e,t){if(!e||!t||typeof t!="object")return e;const n={...e};WT(t,"artifact")&&(t.artifact&&typeof t.artifact=="object"?n.artifact=t.artifact:delete n.artifact);const r=String(t.sourceKind||"").trim().toLowerCase();r&&(n.sourceKind=r);const o=String(t.sourcePath||"").trim();return r==="python"&&o?n.source={...e.source&&typeof e.source=="object"?e.source:{},file:o,sourcePath:o}:r==="step"&&WT(n,"source")&&delete n.source,n}function Dae(e){const t=new Set,n=[];for(const r of Array.isArray(e?.activeDirectories)?e.activeDirectories:[]){const o=String(r?.dir||"").trim(),i=String(r?.rootPath||"").trim(),s=i||o;!o||!s||t.has(s)||(t.add(s),n.push({dir:o,rootPath:i,rootName:String(r?.rootName||"").trim()}))}return n}function jae({manifestEntries:e=[],generationStatus:t=null,manifestRevision:n=0,catalogHydrated:r=!1,catalogRefreshing:o=!1,catalogError:i="",activeDir:s=""}){const a=Array.isArray(e)?e:[],l=a,u=kq(),d=Pb(),m=pae(),p=f.useMemo(()=>Object.entries(t?.files||{}).filter(([,h])=>h?.running===!0).map(([h])=>String(h||"").trim()).filter(Boolean),[t]),g=String(s||"").trim(),[x,y]=f.useState(""),S=f.useRef(null);if(!S.current){const h=Bd().fileViewerExpandedDirectoryIds;S.current={hasStoredState:Array.isArray(h),expandedDirectoryIds:Array.isArray(h)?h:[]}}const[b,I]=f.useState(()=>new Set(S.current.expandedDirectoryIds)),[A,N]=f.useState(()=>S.current.hasStoredState),[P,R]=f.useState([]),[v,C]=f.useState(null),T=String(v?.backend||"").trim().toLowerCase();g||Hp(m)||Hp(T);const[k,z]=f.useState(""),[Y,K]=f.useState(null),[J,G]=f.useState(0),[Q,D]=f.useState([]),[$,ie]=f.useState("2d"),[W,Z]=f.useState(!1),[Ee,re]=f.useState(null),[be,_e]=f.useState(!1),[Ie,oe]=f.useState(du),[me,se]=f.useState(""),[Ae,we]=f.useState([]),[ct,ut]=f.useState([]),[Tt,Ve]=f.useState(()=>pb(FT)),[St,wt]=f.useState(""),[Vn,De]=f.useState(""),[xe,yt]=f.useState(""),[Te,rt]=f.useState([]),[Re,Fe]=f.useState({}),[on,ht]=f.useState(""),[jt,qt]=f.useState([]),[sn,Mn]=f.useState(!1),[fn,Bt]=f.useState(""),[dt,qe]=f.useState([]),[Vt,We]=f.useState([]),[ze,Ze]=f.useState(null),[vt,Tn]=f.useState(()=>So()),[pe,Xe]=f.useState(""),[He,Rn]=f.useState(""),[xn,ue]=f.useState(""),[Rt,Zt]=f.useState(!1),[qn,fi]=f.useState({}),[Ct,wr]=f.useState({key:"",file:"",status:null,loading:!1,error:""}),[vr,Qt]=f.useState(""),[In,gr]=f.useState(""),[lo,Mt]=f.useState(""),[gt,Sn]=f.useState(""),[On,Kr]=f.useState(!1),[Xr,Co]=f.useState(gae),[br,j]=f.useState(()=>Bd().fileViewerOpen),[de,L]=f.useState(()=>Bd().fileViewerWidthPx||mb),[te,fe]=f.useState(Af),ae=Xr===Od.DESKTOP,[he,ot]=f.useState(bae),[It,Pt]=f.useState(!1),[Ke,en]=f.useState(null),[Ne,Et]=f.useState(so),[Pe,En]=f.useState(()=>rse(so())),Se=Pe.settings,Yr=Pe.presetId,Kt=f.useMemo(()=>uj(Ne),[Ne]),[X,At]=f.useState(hae),[ne,ye]=f.useState(G_),it=f.useMemo(()=>rD(ne,{prefersDark:X}),[ne,X]),ft=f.useMemo(()=>_2(Se,{prefersDark:it===qo}),[it,Se]),xt=f.useMemo(()=>a2(vt),[vt]),_r=f.useMemo(()=>T2(ft),[ft]),Ti=f.useCallback(h=>{Tn(E=>So(typeof h=="function"?h(E):h))},[]),Ra=f.useCallback(h=>{Ti(E=>({...So(E),mode:h}))},[Ti]),Pa=f.useCallback(h=>{Ti(E=>({...So(E),projection:h}))},[Ti]),Cr=f.useCallback(h=>{Nf(E=>Ms(typeof h=="function"?h(E):h))},[]),[Xt,os]=f.useState(!1),[kn,Tr]=f.useState(yae),[Ri,_u]=f.useState(xae),[Zn,qr]=f.useState(Jt.FREEHAND),[mi,Jn]=f.useState(null),[ar,Mr]=f.useState(oo.REFERENCES),[pi,co]=f.useState([]),[Qs,Lr]=f.useState([]),[ko,is]=f.useState([]),[Mo,uo]=f.useState({}),[wc,hl]=f.useState({}),[Pi,Do]=f.useState({}),[Ns,_s]=f.useState({url:"",status:"idle",error:"",definition:null}),[Qo,Dn]=f.useState({}),[$r,ea]=f.useState(!0),[tn,Zr]=f.useState({activeId:"",playing:!1,elapsedSec:0,speed:1}),Rr=f.useRef(Qo),Qn=f.useRef(tn),[ei,Oi]=f.useState({}),[Pr,ti]=f.useState({activeId:"",playing:!1,elapsedSec:0,speed:1}),jo=f.useRef(Pr),[Tu,Nf]=f.useState(()=>Ms()),[Ru,$e]=f.useState(!1),ki=f.useRef(0),[hi,Pu]=f.useState(db),_f=f.useRef(""),gl=f.useRef({frameId:0,token:0}),Di=f.useRef({frameId:0,token:0,mode:"",fileRef:"",currentValues:null,targetValues:null,smoothingMs:Pd,lastTimestampMs:0}),bl=f.useRef(new Map),w=f.useRef(""),V=f.useCallback(({key:h})=>{const E=String(h||"browser-storage");_f.current!==E&&(_f.current=E,Mt("Browser storage could not save the CAD Viewer session."))},[]),q=f.useMemo(()=>{const h=new Map;for(const E of l)h.set(at(E),E);return h},[l]),ce=f.useMemo(()=>Wv(g),[g]),{meshState:ge,setMeshState:et,meshLoadInProgress:Nt,meshLoadTargetFile:je,meshLoadStage:Je,status:Lt,setStatus:gn,error:lr,setError:cr,dxfState:wn,setDxfState:$n,dxfStatus:er,setDxfStatus:ur,dxfError:bn,setDxfError:nn,dxfLoadStage:Jr,gcodeState:Or,setGcodeState:kr,gcodeStatus:Gn,setGcodeStatus:Qr,gcodeError:Lo,setGcodeError:ta,gcodeLoadStage:Ou,implicitState:yl,setImplicitState:fo,implicitStatus:ni,setImplicitStatus:Oa,implicitError:ji,setImplicitError:na,implicitLoadStage:ss,urdfState:vc,setUrdfState:xl,urdfStatus:ka,setUrdfStatus:Sl,urdfError:Sh,setUrdfError:ku,urdfLoadStage:Jv,referenceState:Tf,setReferenceState:Eh,referenceStatus:Dj,setReferenceStatus:Rf,setReferenceError:Pf,referenceLoadStage:Qv,displayEdgeState:wh,setDisplayEdgeState:eC,setDisplayEdgeStatus:h0,setDisplayEdgeError:g0,getCachedMeshState:tC,getCachedReferenceState:nC,getCachedDxfState:rC,getCachedImplicitState:oC,getCachedUrdfState:iC,cancelMeshLoad:b0,cancelDxfLoad:vh,cancelGcodeLoad:Ch,cancelImplicitLoad:Mh,cancelUrdfLoad:Ih,cancelReferenceLoad:Ah,cancelDisplayEdgeLoad:y0,loadMeshForEntry:sC,loadDxfForEntry:aC,loadGcodeForEntry:lC,loadImplicitForEntry:cC,loadUrdfForEntry:uC,loadReferencesForEntry:dC,loadDisplayEdgesForEntry:fC}=iie({entryHasMesh:qc,entryHasReferences:Qx,entryHasDisplayEdges:YN,entryHasDxf:vm,entryHasGcode:Yg,buildNormalizedReferenceState:Sie}),x0=f.useMemo(()=>{const h=x.trim().toLowerCase();return h?l.filter(E=>dl(E).toLowerCase().includes(h)||String(E.kind||"").toLowerCase().includes(h)||at(E).toLowerCase().includes(h)):l},[l,x]),S0=f.useMemo(()=>n_(l),[l]),jj=f.useMemo(()=>n_(x0),[x0]),mC=f.useMemo(()=>rk(S0),[S0]),ra=q.get(k)??null,pC=d?G1(l,d):null,hC=Dq({explicitFileParam:d,matchingEntry:pC,selectedEntry:ra,catalogHydrated:r,catalogRefreshing:o}),gC=i?"":jq({explicitFileParam:d,matchingEntry:pC,selectedEntry:ra,catalogHydrated:r,catalogRefreshing:o}),Lj=or(ra),bC=f.useMemo(()=>{const h=Object.values(qn).filter(E=>E?.status==="loading"&&E?.file).map(E=>String(E.file).trim()).filter(Boolean);return[...new Set(h)]},[qn]),ri=!!(ra&&p.includes(at(ra))),El=Lj===B.STEP&&ra?at(ra):"",wl=El?[El,ra?.hash||"",n].join(":"):"",Of=!ri&&wl&&Ct.key===wl?Ct.status:null,ee=f.useMemo(()=>kae(ra,Of),[ra,Of]),mo=or(ee),_t=hA(ee),kf=f.useMemo(()=>Dae(v),[v]),Fj=Xp({assetBackend:m}),yC=g||Fj,xC=!u&&!yC,Cc=xC&&kf.length>1,E0=xC&&!String(d||"").trim()&&kf.length===1?kf[0].dir:"",w0=!Cc,Df=v?v.stepArtifactGenerationAvailable!==!1:m===Pj,v0=v?T||"local-fs":"",oa=v0==="local-fs",SC=v0==="local-fs"&&!!(v?.rootPath||v?.directoryRoot),vl=v0==="vercel-blob",mr=mo===B.STEP,Me=ee?.kind==="assembly",C0=Hi(mo),zj=!!(C0&&(Di.current?.frameId||gl.current?.frameId)),Bj=mo===B.GCODE,gi=mr?oq(ee):"",Nh=gi?iv(ee):"",$t=Ns.url===gi?Ns.definition:null,Vj=Array.isArray($t?.animations)&&$t.animations.length>0,_h=gi?Ns.url===gi?Ns.status:"loading":"idle",M0=Ns.url===gi?Ns.error:"",Th=!!(gi&&_h==="loading"),jf=qc(ee),Rh=Xg(ee),Fo=Qx(ee),EC=YN(ee),Lf=vm(ee),Ph=Yg(ee),Oh=Oae(ee),I0=by({entry:ee,activeGenerationFiles:p}),Mc=!jf&&fh(ee,mo,{generationAvailable:Df||I0})?at(ee):"",zo=Mc?[Mc,ee?.hash||"",ee?.artifact?.error||""].join(":"):"",Ff=zo?qn[zo]:null,Ic=Ff?.status||"idle",A0=tv(Ff),$j=by({entry:ee,generationState:Ff,activeGenerationFiles:p}),zf=!!(zo&&($j||Ic!=="error"&&Ic!=="ready")),Gj=HO(ee),bi=!!ge&&!!ee&&ge.file===at(ee)&&ge.meshHash===Gj,kh=ee?.kind==="assembly"&&bi&&!!ge?.assemblyStructureReady,Bf=ee?.kind==="assembly"&&bi&&!!ge?.assemblyInteractionReady,Dh=ee?.kind==="assembly"&&bi&&!!ge?.assemblyBackgroundError,jh=!!wn&&!!ee&&wn.file===at(ee)&&wn.dxfHash===zt(ee,"dxf"),Lh=!!Or&&!!ee&&Or.file===at(ee)&&Or.gcodeHash===zt(ee,"gcode"),Fh=!!yl&&!!ee&&yl.file===at(ee)&&yl.implicitHash===zt(ee,"implicit"),Vf=!!vc&&!!ee&&vc.file===at(ee)&&vc.urdfHash===Wp(ee),mt=Vf?vc.urdfData:null,N0=Vf?vc.meshesByUrl:null,tr=jh?wn.dxfData:null,ia=Lh?Or.gcodeData:null,$f=Fh?yl.model:null,Yt=$f?.definition||null,wC=mo===B.DXF?at(ee):"",Du=mo===B.GCODE?at(ee):"",ve=Hi(mo)?at(ee):"",Ac=f.useMemo(()=>({...goe(mt),...Gse(mt)}),[mt]),vC=f.useMemo(()=>{if(!ve)return{};const h=Mo?.[ve];return h&&typeof h=="object"?h:{}},[Mo,ve]),nr=f.useMemo(()=>({...Ac,...vC}),[Ac,vC]),_0=f.useMemo(()=>{const h=mt?.motion,E=Array.isArray(h?.endEffectors)?h.endEffectors:[];return E.length?{...h,endEffectors:E}:null},[mt]),Gf=f.useMemo(()=>{const h=Array.isArray(mt?.srdf?.groupStates)?mt.srdf.groupStates:Array.isArray(mt?.motion?.groupStates)?mt.motion.groupStates:[],M=h.map(_=>String(_?.name||"").trim()).filter(Boolean).reduce((_,O)=>_.set(O,(_.get(O)||0)+1),new Map);return h.map(_=>{const O=String(_?.name||"").trim(),F=String(_?.group||"").trim();if(!O||!F)return null;const U=_j(mt,_?.jointValuesByName||_?.jointValuesByNameRad);return{..._,id:`${F}/${O}`,label:M.get(O)>1?`${O} (${F})`:O,jointValuesByName:U}}).filter(Boolean)},[mt]),zh=f.useMemo(()=>new Set((Array.isArray(mt?.joints)?mt.joints:[]).filter(h=>String(h?.type||"").trim()==="continuous").map(h=>String(h?.name||"").trim()).filter(Boolean)),[mt]),CC=f.useMemo(()=>Wse(Gf,nr,Ac)?.id||"",[Ac,nr,Gf]),Bh=ve?String(wc?.[ve]||"").trim():"",Uj=f.useMemo(()=>Bh&&Gf.some(h=>String(h?.id||"").trim()===Bh)?Bh:CC,[CC,Gf,Bh]),MC=f.useMemo(()=>!uae||!ve||!_0?.srdf?"":`${ve}:${Wp(ee)||""}`,[ee,ve,_0]);f.useEffect(()=>{if(typeof window>"u")return;const h=new AbortController;let E=!0;const M=new URL("/__cad/server",window.location.href),_=Xp(),O=Pb();return _&&M.searchParams.set("dir",_),O&&M.searchParams.set("file",O),fetch(`${M.pathname}${M.search}`,{cache:"no-store",signal:h.signal}).then(async F=>{if(!F.ok)throw new Error(`Failed to read CAD Viewer server info: ${F.status} ${F.statusText}`);return F.json()}).then(F=>{E&&C(F&&typeof F=="object"?F:{})}).catch(F=>{E&&F?.name!=="AbortError"&&C({})}),()=>{E=!1,h.abort()}},[g,d]),f.useEffect(()=>{E0&&(e_(E0),Yp({markRefreshing:!0}).catch(h=>{}),vp())},[E0]),f.useEffect(()=>{let h=!0,E=0;const M=()=>{E&&(clearTimeout(E),E=0)};if(!MC)return Kr(!1),()=>{h=!1,M()};Kr(!1);const _=async()=>{const O=await rae({timeoutMs:750});h&&(Kr(O),E=setTimeout(_,O?5e3:2e3))};return _(),()=>{h=!1,M()}},[MC]),f.useEffect(()=>{let h=!1;return gi?(_s({url:gi,status:"loading",error:"",definition:null}),Dn({}),ea(!0),Zr(Lm(null)),Bl(),_4(gi,{cadPath:Nh}).then(E=>{if(h)return;const _=RS(ce,at(ee),ee)?.slices?.stepModule||null,O=Lm(E);_s({url:gi,status:"ready",error:"",definition:E});const F=wb(E,_?.parameterValues||E.defaultParameterValues),U=_?.animationState?{...O,..._.animationState,activeId:_.animationState.activeId||O.activeId,playing:!1}:O;Rr.current=F,Qn.current=U,Dn(F),ea(_?_.enabled!==!1:!0),Zr(U),Bl({elapsedSec:U.elapsedSec,parameterValues:F})}).catch(E=>{h||(_s({url:gi,status:"error",error:E instanceof Error?E.message:String(E),definition:null}),Dn({}),ea(!0),Zr(Lm(null)),Bl())}),()=>{h=!0}):(_s({url:"",status:"idle",error:"",definition:null}),Dn({}),ea(!0),Zr(Lm(null)),Bl(),()=>{h=!0})},[ce,ee,Nh,gi]),f.useEffect(()=>{if(!Yt||!ee||mo!==B.IMPLICIT){Oi({});const O=PS(null);jo.current=O,ti(O);return}const E=RS(ce,at(ee),ee)?.slices?.implicit||null,M=PS(Yt);Oi(qd(Yt,E?.parameterValues||Yt.defaultParameterValues));const _=E?.animationState?{...M,...E.animationState,activeId:E.animationState.activeId||M.activeId,playing:!1}:M;jo.current=_,ti(_)},[ce,ee,mo,Yt]);const Nc=_0,ju=!!(On&&Nc),Gr=f.useMemo(()=>{if(!ve)return{};const h=Pi?.[ve];return h&&typeof h=="object"?h:{}},[ve,Pi]),Vh=Nc?.planningGroups||fb,IC=f.useMemo(()=>{const h=String(Gr.activePlanningGroupName||"").trim();return h&&Vh.some(E=>String(E?.name||"").trim()===h)?h:String(Vh[0]?.name||"").trim()},[Vh,Gr.activePlanningGroupName]),Cl=Nc?.endEffectors||fb,mn=f.useMemo(()=>{const h=String(Gr.activeEndEffectorName||"").trim();return h&&Cl.some(E=>String(E?.name||"").trim()===h)?h:String(Cl[0]?.name||"").trim()},[Cl,Gr.activeEndEffectorName]),Li=f.useMemo(()=>Cl.find(h=>String(h?.name||"").trim()===mn)||null,[mn,Cl]),Uf=f.useMemo(()=>Array.isArray(mt?.links)?mt.links.map(h=>String(h?.name||"").trim()).filter(Boolean):[],[mt]),yi=f.useMemo(()=>{const h=String(Gr.targetFrame||"").trim();return h&&Uf.includes(h)?h:mt?.rootLink&&Uf.includes(mt.rootLink)?mt.rootLink:Uf[0]||""},[mt,Gr.targetFrame,Uf]),Bo=f.useMemo(()=>({planningGroup:IC,endEffector:mn,targetFrame:yi,ikTimeout:Math.max(Dr(Gr.ikTimeout,.05),.001),ikAttempts:Math.max(Math.round(Dr(Gr.ikAttempts,1)),1),ikTolerance:Math.max(Dr(Gr.ikTolerance,.002),1e-4),planningPipeline:String(Gr.planningPipeline||"ompl").trim()||"ompl",plannerId:String(Gr.plannerId||"RRTConnectkConfigDefault").trim()||"RRTConnectkConfigDefault",planningTime:Math.max(Dr(Gr.planningTime,1),.1),maxVelocityScalingFactor:Math.min(Math.max(Dr(Gr.maxVelocityScalingFactor,1),.01),1),maxAccelerationScalingFactor:Math.min(Math.max(Dr(Gr.maxAccelerationScalingFactor,1),.01),1)}),[mn,IC,Gr,yi]),Lu=f.useMemo(()=>!mt||!Li||!yi?null:EE(mt,nr,Li.link,yi),[mt,Li,nr,yi]),sa=f.useMemo(()=>{const h=Gr.targetsByEndEffector&&typeof Gr.targetsByEndEffector=="object"?Gr.targetsByEndEffector:{},E=mn?h[mn]:null;return Yl(E,Lu||[0,0,0])},[Lu,mn,Gr.targetsByEndEffector]),Wj=!!(mn&&Gr.solvingEndEffectorName===mn),$h=ve&&hi.fileRef===ve?hi:null,_c=!!(ve&&ju&&$h),Gh=f.useMemo(()=>{if(!mt||!N0)return{meshData:null,error:""};try{return{meshData:Noe(mt,N0,{lightweight:!0}),error:""}}catch(h){return{meshData:null,error:h instanceof Error?h.message:String(h)}}},[mt,N0]),Uh=f.useMemo(()=>Array.isArray(mt?.joints)?mt.joints.filter(h=>String(h?.type||"")!=="fixed"&&!h?.mimic):[],[mt]),AC=f.useMemo(()=>{if(!mt||!Gh.meshData)return{meshData:null,error:Gh.error,linkWorldTransforms:new Map};try{return{...Toe(mt,Gh.meshData,nr),error:""}}catch(h){return{meshData:null,error:h instanceof Error?h.message:String(h),linkWorldTransforms:new Map}}},[mt,nr,Gh]),Ml=Array.isArray(ia?.layers)?ia.layers.length:0,Wf=Ml>0?Math.min(Math.max(Number.isFinite(Number(Ee))?Math.trunc(Number(Ee)):Ml-1,0),Ml-1):0,NC=f.useMemo(()=>bk({showTravel:W,layerRange:[0,Wf],detailMode:be?"full":"adaptive",detailLevel:Ie},Ml),[be,Ie,W,Ml,Wf]),_C=f.useMemo(()=>{if(!ia)return{meshData:null,error:""};try{return{meshData:fJ(ia,NC),error:""}}catch(h){return{meshData:null,error:h instanceof Error?h.message:String(h)}}},[ia,NC]),TC=_C.meshData,RC=_C.error;f.useMemo(()=>!Du||!ia?Du:`${Du}:travel=${W?"1":"0"}:layer=${Wf}:detail=${be?"full":`adaptive-${Ie}`}`,[be,Ie,W,ia,Du,Wf]),f.useEffect(()=>{if(!Du||Ml<=0){re(null);return}re(Ml-1),_e(!1),oe(du)},[Du,Ml]);const Fr=Hi(mo)?AC.meshData:Bj?TC:bi?ge.meshData:null,Ts=f.useMemo(()=>np($t,tn.activeId),[$t,tn.activeId]),Wh=f.useMemo(()=>({...tn,activeId:Ts?.id||tn.activeId||"",duration:Ts?.duration||0,loop:Ts?.loop!==!1}),[Ts,tn]),PC=f.useMemo(()=>!$t||!$r?null:{definition:$t,parameterValues:wb($t,Qo),animationState:Wh,cadPath:$t.cadPath||Nh,sourceUrl:gi},[Wh,Nh,$t,gi,$r,Qo]),Hj=f.useCallback(()=>{},[]),Vo=!1,Kj="";f.useEffect(()=>{Rr.current=Qo},[Qo]),f.useEffect(()=>{Qn.current=tn},[tn]);const Xj=f.useCallback((h,E)=>{const M=String(h||"").trim(),_=$t?.parameterMap?.[M];_&&Dn(O=>({...O,[M]:bu(_,E)}))},[$t]),Yj=f.useCallback(async()=>{if(Qt(""),!$t?.parameters?.length){ue("No STEP parameters to copy");return}try{await ps(aee($t,Qo)),ue("Copied STEP parameters")}catch(h){ue(h instanceof Error?h.message:"Clipboard write failed")}},[$t,Qo]),qj=f.useCallback(async()=>{if(Qt(""),!$t?.parameters?.length){ue("No STEP parameters to paste");return}try{const h=await tI(),{values:E,count:M}=lee($t,h);Dn(_=>({..._,...E})),ue(`Pasted ${M} STEP param${M===1?"":"s"}`)}catch(h){ue(h instanceof Error?h.message:"Clipboard paste failed")}},[$t]),Zj=f.useCallback(()=>{if(!$t)return;const h=wb($t,$t.defaultParameterValues),E=Lm($t);Rr.current=h,Qn.current=E,Dn(h),Zr(E),Bl({elapsedSec:E.elapsedSec,parameterValues:h})},[$t]),Jj=f.useCallback(h=>{const E=np($t,h),M={...Qn.current,activeId:E?.id||"",playing:!1,elapsedSec:0};Qn.current=M,Bl({elapsedSec:0,parameterValues:Rr.current}),Zr(M)},[$t]),OC=f.useCallback(()=>{const h=Qn.current,E=np($t,h.activeId);if(!E)return;const M=Math.max(Number(E.duration)||0,.001);if(h.playing){const F=Ao(Zx(),0,M),U=_N(),le=U&&typeof U=="object"&&Object.keys(U).length?U:Rr.current;Rr.current=le,Dn(le),Yx({elapsedSec:F,parameterValues:le});const Ce={...h,activeId:E.id,elapsedSec:F,playing:!1};Qn.current=Ce,Zr(Ce);return}const _=h.elapsedSec>=M?0:Ao(h.elapsedSec,0,M);qx(_);const O={...h,activeId:E.id,elapsedSec:_,playing:!0};Qn.current=O,Zr(O)},[$t]),Qj=f.useCallback(()=>{const h=Qn.current,E=np($t,h.activeId),M=$t&&E?jS({definition:$t,animation:E,elapsedSec:0,speed:h.speed,parameterValues:Rr.current}):Rr.current;Rr.current=M,Dn(O=>bd(O,M)?O:M),Bl({elapsedSec:0,parameterValues:M});const _={...h,elapsedSec:0,playing:!1};Qn.current=_,Zr(_)},[$t]),eL=f.useCallback(h=>{const E=Math.max(Number(Ts?.duration)||1,.001),M=Ao(h,0,E);qx(M);const _={...Qn.current,elapsedSec:M};Qn.current=_,Zr(_)},[Ts]),tL=f.useCallback(h=>{const E={...Qn.current,speed:Ao(h,.1,5)};Qn.current=E,Zr(E)},[]),nL=f.useCallback(h=>{const E=h!==!1;if(ea(E),!E){const M={...Qn.current,playing:!1};Qn.current=M,Zr(M)}},[]);f.useEffect(()=>{if(!$t||!$r||!Ts||!tn.playing||typeof window>"u"||typeof window.requestAnimationFrame!="function")return;const h=$t,E=Ts,M=Math.max(Number(E.duration)||1,.001);let _=0,O=Ka();qx(Ao(Qn.current.elapsedSec,0,M));const F=U=>{const le=Qn.current;if(!le.playing||le.activeId!==E.id)return;const Ce=Math.max((U-O)/1e3,0);O=U;const st=Ao(le.speed,.1,5);let tt=Zx()+Ce*st,Ot=le.playing;E.loop!==!1?tt%=M:tt>=M&&(tt=M,Ot=!1);const Gt=jS({definition:h,animation:E,elapsedSec:tt,speed:st,parameterValues:Rr.current});if(Yx({elapsedSec:tt,parameterValues:Gt}),!Ot){Rr.current=Gt,Dn(Go=>bd(Go,Gt)?Go:Gt);const pn={...le,elapsedSec:tt,speed:st,playing:!1};Qn.current=pn,Zr(pn);return}_=window.requestAnimationFrame(F)};return _=window.requestAnimationFrame(F),()=>{window.cancelAnimationFrame(_)}},[Ts,$t,$r,tn.playing]),f.useEffect(()=>{const h=Ts;if(!$t||!$r||typeof h?.update!="function"){Bl({elapsedSec:0,parameterValues:Rr.current});return}if(tn.playing)return;const E=Math.max(Number(h.duration)||1,.001),M=Ao(tn.elapsedSec,0,E),_=jS({definition:$t,animation:h,elapsedSec:M,speed:tn.speed,parameterValues:Rr.current});Rr.current=_,Dn(O=>bd(O,_)?O:_),Yx({elapsedSec:M,parameterValues:_})},[Ts,$t,$r,tn.elapsedSec,tn.playing,tn.speed]);const xi=f.useMemo(()=>Lb(Yt,Pr.activeId),[Pr.activeId,Yt]),Hf=f.useMemo(()=>({...Pr,activeId:xi?.id||Pr.activeId||"",duration:xi?.duration||0,loop:xi?.loop!==!1}),[Pr,xi]),T0=GT(ei,jT,k),R0=GT(Hf,jT,k),kC=f.useMemo(()=>{if(!$f)return{model:null,error:""};if(!Yt?.buildModel)return{model:$f,error:""};try{return{model:Yt.buildModel(T0,R0),error:""}}catch(h){return{model:null,error:h instanceof Error?h.message:String(h)}}},[R0,T0,Yt,$f]),Tc=kC.model,Fu=kC.error;f.useEffect(()=>{jo.current=Pr},[Pr]);const Il=f.useCallback(()=>{typeof window>"u"||typeof window.setTimeout!="function"||(ki.current&&window.clearTimeout(ki.current),$e(!0),ki.current=window.setTimeout(()=>{ki.current=0,$e(!1)},mae))},[]);f.useEffect(()=>()=>{ki.current&&typeof window<"u"&&(window.clearTimeout(ki.current),ki.current=0)},[]);const rL=!bd(ei,T0)||Hf.elapsedSec!==R0.elapsedSec,oL=!!($f&&(Pr.playing||Ru||rL)),iL=f.useCallback((h,E)=>{const M=String(h||"").trim(),_=Yt?.parameterMap?.[M];if(!_)return;const O=bu(_,E);Il(),Oi(F=>F?.[M]===O?F:{...F,[M]:O})},[Il,Yt]),sL=f.useCallback(async()=>{if(Qt(""),!Yt?.parameters?.length){ue("No implicit parameters to copy");return}try{await ps(Hk(Yt,ei)),ue("Copied implicit parameters")}catch(h){ue(h instanceof Error?h.message:"Clipboard write failed")}},[ei,Yt]),aL=f.useCallback(async()=>{if(Qt(""),!Yt?.parameters?.length){ue("No implicit parameters to paste");return}try{const h=await tI(),{values:E,count:M}=Kk(Yt,h,{label:"implicit parameter",unknownLabel:"implicit parameter"});Il(),Oi(_=>({..._,...E})),ue(`Pasted ${M} implicit param${M===1?"":"s"}`)}catch(h){ue(h instanceof Error?h.message:"Clipboard paste failed")}},[Il,Yt]),lL=f.useCallback(()=>{if(!Yt)return;Il(),Oi(qd(Yt,Yt.defaultParameterValues));const h=PS(Yt);jo.current=h,ti(h)},[Il,Yt]),cL=f.useCallback(h=>{const E=Lb(Yt,h);ti(M=>{const _={...M,activeId:E?.id||"",playing:!1,elapsedSec:0};return jo.current=_,_})},[Yt]),uL=f.useCallback(()=>{ti(h=>{const E=Lb(Yt,h.activeId);if(!E)return h;const M=Math.max(Number(E.duration)||0,.001),_=h.elapsedSec>=M?0:h.elapsedSec,O={...h,activeId:E.id,elapsedSec:_,playing:!h.playing};return jo.current=O,O})},[Yt]),dL=f.useCallback(()=>{ti(h=>{const E={...h,elapsedSec:0,playing:!1};return jo.current=E,E})},[]),fL=f.useCallback(h=>{const E=Math.max(Number(xi?.duration)||1,.001);Il(),ti(M=>{const _={...M,elapsedSec:Ao(h,0,E)};return jo.current=_,_})},[Il,xi]),mL=f.useCallback(h=>{ti(E=>{const M={...E,speed:Ao(h,.1,5)};return jo.current=M,M})},[]);f.useEffect(()=>{if(!Yt||!xi||!Pr.playing||typeof window>"u"||typeof window.setTimeout!="function")return;let h=Ka(),E=0;const M=()=>{const _=Ka(),O=Math.min(Math.max((_-h)/1e3,0),.25);h=_;const F=jo.current;if(F.playing&&F.activeId===xi.id){const U=Math.max(Number(xi.duration)||1,.001),le=Ao(F.speed,.1,5);let Ce=F.elapsedSec+O*le,st=F.playing;xi.loop!==!1?Ce%=U:Ce>=U&&(Ce=U,st=!1);const tt={...F,elapsedSec:Ce,speed:le,playing:st};jo.current=tt,ti(tt),Oi(Ot=>{try{const Gt=UT(Yt,xi,Ot,Ce);return bd(Ot,Gt)?Ot:Gt}catch(Gt){return console.error("Implicit parameter animation update failed",Gt),Ot}})}E=window.setTimeout(M,LT)};return E=window.setTimeout(M,LT),()=>{window.clearTimeout(E)}},[Pr.playing,xi,Yt]),f.useEffect(()=>{const h=xi;!Yt||typeof h?.update!="function"||Oi(E=>{try{const M=UT(Yt,h,E,Pr.elapsedSec);return bd(E,M)?E:M}catch(M){return console.error("Implicit parameter animation update failed",M),E}})},[Pr.elapsedSec,xi,Yt]);const rn=kh&&Fr?.assemblyRoot||null,Hh=kh&&Array.isArray(Fr?.assemblyMates)?Fr.assemblyMates:[],Al=f.useMemo(()=>{const h=new Map;for(const E of Hh){const M=String(E?.id||"").trim();M&&h.set(M,E)}return h},[Hh]),An=f.useMemo(()=>mr?S5({selectedEntry:ee,assemblyRoot:rn,meshData:Fr}):null,[rn,mr,ee,Fr]),Kh=f.useMemo(()=>Array.isArray(Fr?.parts)?Fr.parts:Ov(rn),[rn,Fr?.parts]),Kf=f.useMemo(()=>Me?Kh:An?[{id:op,label:An.displayName||An.name||"STEP part",name:An.displayName||An.name||"STEP part",nodeType:"part",bounds:Fr?.bounds||null}]:[],[Kh,Me,Fr?.bounds,An]);f.useMemo(()=>hT(rn),[rn]);const Xh=f.useMemo(()=>hT(An),[An]),Xf=f.useMemo(()=>Xh.map(h=>String(h?.id||"").trim()).filter(Boolean),[Xh]),DC=f.useMemo(()=>new Set(Xf),[Xf]),Nl=f.useMemo(()=>koe(rn),[rn]),Nn=f.useMemo(()=>!Me||!rn||!Vt.length?[]:Fb(rn,Vt,{rootId:Nl}),[rn,Nl,Vt,Me]),Rc=f.useMemo(()=>mr&&Me&&Fo?vae(An):[],[Me,mr,Fo,An]),jC=f.useMemo(()=>new Set(Rc),[Rc]),_l=f.useMemo(()=>!mr||!Me||!Fo?[]:_n(jt.map(h=>String(h||"").trim()).filter(h=>h&&jC.has(h))),[jt,Me,mr,jC,Fo]),Pc=f.useMemo(()=>Me?aae(rn,jt,{rootId:Nl,isolatedNodeIds:Nn}):[],[rn,Nl,jt,Nn,Me,_l]),LC=f.useMemo(()=>new Set(Pc),[Pc]),Yh=f.useMemo(()=>Pc.length?Pc.map(h=>oc(rn,h)).filter(Boolean).map(h=>({...h,leafPartIds:Zp(h)})):[],[rn,Pc]),FC=f.useMemo(()=>Doe(Yh),[Yh]),P0=Me?kh:mr&&bi&&!!Fr,zC=mr&&P0&&Kf.length>0,as=f.useMemo(()=>{const h=new Map;for(const E of Xh)h.set(E.id,E);for(const E of Kf)h.set(E.id,E);return h},[Kf,Xh]);f.useEffect(()=>{if(!Me||!rn){We(h=>h.length?[]:h);return}We(h=>{const E=Fb(rn,h,{rootId:Nl});return pd(E,h)?h:E})},[rn,Nl,Me]);const aa=f.useMemo(()=>Kf.map(h=>String(h?.id||"").trim()).filter(Boolean),[Kf]),qh=f.useMemo(()=>new Set(aa),[aa]),la=f.useCallback(h=>joe(h,{pickPartIdMap:FC,validLeafPartIds:qh}),[FC,qh]),yn=f.useCallback((h,E="")=>String(h||"").trim()===hs?[op]:Loe(h,{assemblyPartMap:as,fallbackPartId:E,validLeafPartIds:qh}),[as,qh]),O0=f.useCallback((h,E="")=>yn(h,E)[0]||"",[yn]);f.useLayoutEffect(()=>{const h=new Set((Array.isArray(dt)?dt:[]).map(E=>String(E||"").trim()).filter(Boolean));h.size&&qt(E=>{let M=!1;const _=E.filter(O=>{const F=yn(O).map(le=>String(le||"").trim()).filter(Boolean);return F.length>0&&F.every(le=>h.has(le))?(M=!0,!1):!0});return M?_:E})},[dt,yn]);const BC=AC.error,pL=f.useMemo(()=>{if(!tr)return[];try{return VO(tr)}catch{return[]}},[tr]),Yf=f.useMemo(()=>{if(!tr)return[];try{return Rb(tr,Q)}catch{return[]}},[Q,tr]),qf=f.useMemo(()=>py(J,Dr(tr?.defaultThicknessMm,$p)),[J,tr]),VC=f.useMemo(()=>{if(!tr)return{meshData:null,error:""};try{return{meshData:CY(tr,qf,Yf),error:""}}catch(h){return{meshData:null,error:h instanceof Error?h.message:String(h)}}},[qf,Yf,tr]),hL=VC.meshData,$C=VC.error,gL=f.useMemo(()=>{const h=Pae(ee);if(!h||!tr)return h;const E=Yf.map(M=>`${Gp(M?.direction)}:${Up(M?.angleDeg).toFixed(1)}`).join("|");return`${h}:t=${qf.toFixed(2)}:b=${E}`},[qf,Yf,tr,ee]),Ye=mo,k0=!!ee&&er!==ke.ERROR&&(!jh||er===ke.LOADING),D0=!!ee&&Gn!==ke.ERROR&&(!Lh||Gn===ke.LOADING),j0=!!ee&&ni!==ke.ERROR&&(!Fh||ni===ke.LOADING),L0=!!ee&&ka!==ke.ERROR&&(!Vf||ka===ke.LOADING),bL=Ye===B.STEP&&ee?.artifact&&!ee.artifact.ok&&!jf&&!zf,F0=!!ee&&(zf||!bL)&&Lt!==ke.ERROR&&(!bi||Lt===ke.LOADING||Th),Da=Ye===B.DXF?k0:Ye===B.GCODE?D0:Ye===B.IMPLICIT?j0:Hi(Ye)?L0:F0,yL=Da||ri||hC,z0=Me&&bi&&!P0&&!Dh,GC=Me&&bi&&kh&&!Bf&&!Dh,ja=ri?"Generating file...":Ye===B.DXF?ee&&!Lf?"Generating DXF preview...":"Loading DXF preview...":Ye===B.GCODE?"Loading G-code preview...":Ye===B.IMPLICIT?"Loading implicit CAD...":Hi(Ye)?`Loading ${Ye===B.SDF?"SDF":"URDF"} robot...`:Ye===B.STL?"Loading STL...":Ye===B.THREE_MF?"Loading 3MF...":Ye===B.GLB?"Loading GLB...":Rt?"STEP changed. Updating/regenerating CAD...":zf?"Generating STEP GLB artifact...":Th?"Loading STEP module...":ee&&!jf?"Generating CAD assets...":"Loading CAD...",Tl=f.useMemo(()=>Ke?.blocking?Ke:!ee||Da||ri?null:Ye===B.DXF?bie(at(ee),!!tr,er===ke.ERROR?bn:"",$C):Ye===B.GCODE?NS(ee,!!Fr,Gn===ke.ERROR?Lo:RC)||Ke:Ye===B.IMPLICIT?yie(at(ee),!!Tc,ni===ke.ERROR?ji:Fu)||Ke:Hi(Ye)?NS(ee,!!Fr,ka===ke.ERROR?Sh:BC)||Ke:NS(ee,!!Fr,Lt===ke.ERROR?lr:"")||Ke,[bn,$C,er,Ye,lr,Lo,Gn,ji,ni,tr,ee,ri,RC,Fu,Tc,Fr,BC,Lt,Sh,ka,Da,Ke]),xL=Tl?[at(ee),Tl.severity,Tl.summary,Tl.title].join(":"):"";f.useEffect(()=>{mo!==B.DXF||!tr||J>0||G(py(tr.defaultThicknessMm,$p))},[J,tr,mo]),f.useEffect(()=>{if(!wC||!tr){D([]);return}D(h=>Rb(tr,h))},[tr,wC]);const UC=!!(Me&&_l.length>0&&Pc.length<1),ls=Me&&Pc.length>0,SL=ls?"assembly":"part",EL=mo===B.STEP&&ar===oo.DRAW,wL=Te.length+Ae.length+ct.length,jn=f.useRef(Ae),$o=f.useRef(ct),an=f.useRef(Te),B0=f.useRef({fileRef:"",stepHash:""}),La=f.useRef(pi),Zf=f.useRef(Qs),Jf=f.useRef(ko),Oc=f.useRef(null),V0=f.useRef(null),Zh=f.useRef(null),zu=f.useRef(0),WC=f.useRef(P),kc=f.useRef(null),Jh=f.useRef(null),Qh=f.useRef(""),vL=f.useRef(!1);f.useEffect(()=>{WC.current=P},[P]);const Fa=he,HC=f.useMemo(()=>[...b].sort((h,E)=>h.localeCompare(E,void 0,{numeric:!0,sensitivity:"base"})),[b]),Qf=f.useMemo(()=>Dv(te),[te]),po=f.useCallback(h=>{ot(E=>typeof h=="function"?h(E):h)},[]),KC=f.useMemo(()=>tse(Pe,Ne),[Ne,Pe]);f.useEffect(()=>{Vie({fileViewerOpen:br,fileViewerExpandedDirectoryIds:A?HC:null,fileViewerWidthPx:de,fileSheetOpen:Fa,fileSheetWidthPx:Ri?kn:Qf,theme:KC},{defaultFileSheetWidthPx:Qf,onWriteError:V})},[Qf,A,HC,Ri,V,br,de,Fa,kn,KC]),f.useEffect(()=>{Ri||Tr(Qf)},[Qf,Ri]);const Rs=ae&&Fa&&!!_t&&!Xt,em=w0&&br&&!Xt,cs=ae&&em&&!Xt,tm=f.useCallback(()=>{},[]),XC=f.useCallback(()=>Kc(so()),[]),CL=f.useCallback(h=>{const E=hh(h);ute(E,{onWriteError:V})&&ye(E)},[V]),eg=f.useCallback((h,E={})=>{const M=E.persistGlobal===!0,_=String(E.presetId||"").trim();if(M&&typeof h!="function"){const O=fr(h),F=_||Ry(O,Ne)||Yr||"";En({presetId:F,settings:O}),F&&ise(O,{presetId:F,customPresets:Ne,onWriteError:V});return}En(O=>{const F=typeof h=="function"?h(O.settings):h,U=fr(F);return{presetId:O.presetId||Ry(U,Ne)||"",settings:U}})},[Ne,V,Yr]),YC=f.useCallback(()=>{const h=Kt.find(E=>E.id===Yr);if(!h){En(XC());return}En({presetId:h.id,settings:fr(h.settings)})},[Kt,XC,Yr]),qC=f.useCallback(h=>{const E=Yie(h,Se,{customPresets:Ne,sourceThemeId:Yr,onWriteError:V});if(!E)return null;const M=E.preset;return Et(E.customPresets),En({presetId:M.id,settings:fr(M.settings)}),M},[Ne,V,Yr,Se]),ML=f.useCallback(h=>{const E=String(h||"").trim();if(!qie(E,{onWriteError:V}))return!1;const M=so();return Et(M),En(_=>_.presetId!==E?_:Kc(M)),!0},[V]),ZC=f.useCallback((h=Yr)=>{const E=String(h||"").trim();if(!E||!Zie(E,Se,{onWriteError:V}))return!1;const M=so();return Et(M),En(Kc(M)),!0},[V,Yr,Se]),IL=f.useCallback(h=>{const E=String(h||"").trim();if(!E||!Jie(E,{onWriteError:V}))return!1;const M=so();return Et(M),En(_=>_.presetId===E?Kc(M):_),!0},[V]),AL=f.useCallback(()=>{if(!Qie({onWriteError:V}))return!1;const h=so();return Et(h),En(Kc(h)),!0},[V]),NL=f.useCallback(h=>{en(h||null)},[]),_L=f.useCallback(()=>{document.querySelector("[data-slot='sidebar-wrapper']")?.removeAttribute("data-sidebar-resizing"),Zh.current=null,Jh.current||(document.body.style.cursor="",document.body.style.userSelect="")},[]),TL=f.useCallback(()=>{Jh.current=null,Zh.current||(document.body.style.cursor="",document.body.style.userSelect="")},[]),RL=f.useCallback(h=>{if(h.button!==0||!ae||!em)return;h.preventDefault();const E=md({viewportWidth:te,sidebarOpen:cs,sheetOpen:Rs,sidebarWidth:de,sheetWidth:kn,sidebarMinWidth:Vl,sheetMinWidth:Uc,sidebarMaxWidth:yd,sheetMaxWidth:xd}).sidebarWidth;document.querySelector("[data-slot='sidebar-wrapper']")?.setAttribute("data-sidebar-resizing","true"),Zh.current={startX:h.clientX,startWidth:E,latestWidth:E},document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[Rs,cs,em,ae,te,de,kn]),tg=f.useCallback(h=>{j(E=>{const M=typeof h=="function"?h(E):h;return M&&!ae&&po(!1),!E&&M&&L(_=>{const O=Number(_);return Number.isFinite(O)&&O>=Vl?_:mb}),M})},[ae,po]),Bu=f.useCallback(h=>{if(h.button!==0||!ae||!(!Xt&&Fa&&!!_t))return;h.preventDefault(),_u(!0);const M=md({viewportWidth:te,sidebarOpen:cs,sheetOpen:Rs,sidebarWidth:de,sheetWidth:kn,sidebarMinWidth:Vl,sheetMinWidth:Uc,sidebarMaxWidth:yd,sheetMaxWidth:xd}).sheetWidth;Jh.current={startX:h.clientX,startWidth:M},document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[ae,Rs,cs,te,Xt,de,_t,_u,Fa,kn]),JC=f.useCallback(()=>{an.current=[],jn.current=[],rt([]),we([]),Fe({}),ht(""),wt(""),De(""),Xe(""),Rn(""),ue("")},[]),ng=f.useCallback((h,E,M=null)=>{if(!E)return h;const _=M?Oy(M):null,O=h.findIndex(le=>le.key===E);if(O===-1)return _?[...h,Dm(E,_)]:[...h,Dm(E)];if(!_)return h;const F=h[O];if(fj(F,_))return h;const U=[...h];return U[O]={key:E,..._},U},[]),za=f.useMemo(()=>ri?[]:LZ({entry:ee,fileSheetKind:_t,stepSourceStatus:Of,gcodeData:ia,urdfData:mt,viewerAlert:Tl,stepArtifactGenerationAvailable:Df,stepArtifactGenerationState:Ff,activeGenerationFiles:p,viewerServerInfo:v}),[p,ee,_t,ia,ri,Ff,Df,Of,mt,Tl,v]),QC=f.useMemo(()=>uk(za),[za]),eM=vZ(za),rg=f.useMemo(()=>({hasStepModulePanel:!!($t||_h==="loading"||M0),hasImplicitParameterPanel:!!(ni===ke.LOADING||Fu||Yt?.parameters?.length||Yt?.animations?.length),hasFileStatus:eM,isSdf:_t==="sdf",motionEnabled:_t==="srdf"&&On&&Cl.length>0,showJoints:_t==="urdf"||_t==="srdf"||_t==="sdf"}),[ni,Yt,Fu,_t,eM,$t,M0,_h,On,Cl]),eo=f.useMemo(()=>YY(_t,rg),[rg,_t]),Dc=f.useMemo(()=>qY(_t,rg),[rg,_t]),ca=f.useMemo(()=>ma(Array.isArray(Y)?Y:Dc,eo),[Dc,Y,eo]),Vu=f.useCallback(h=>{K(ma(h,eo))},[eo]),og=f.useCallback((h,{openSheet:E=!0}={})=>{const M=String(h||"").trim();return!M||!eo.includes(M)?!1:(E&&po(!0),K(_=>{const O=ma(Array.isArray(_)?_:ca,eo);return O.includes(M)?O:ma([...O,M],eo)}),!0)},[ca,eo,po]),PL=f.useCallback(h=>{const E=Kt.find(M=>M.id===h);return E?(eg(E.settings,{persistGlobal:!0,presetId:E.id}),og(bt.THEME_APPEARANCE)&&typeof window<"u"&&window.requestAnimationFrame(()=>{window.requestAnimationFrame(()=>{document.querySelector("[data-cad-theme-appearance-section='true']")?.scrollIntoView({block:"start",behavior:"instant"})})}),!0):!1},[Kt,og,eg]);f.useEffect(()=>{if(!Array.isArray(Y))return;const h=ma(Y,eo);pd(h,Y)||K(h)},[Y,eo]),f.useEffect(()=>{QC===Xn.ERROR&&K(h=>{const E=ma(Array.isArray(h)?h:Dc,eo),M=ZY(E,eo,bt.FILE_STATUS);return pd(M,E)?h:M})},[Dc,eo,QC,k]),f.useEffect(()=>{if(_t!==B.IMPLICIT)return;const h=bt.STEP_PARAMETERS,E=bt.IMPLICIT_GRAPHICS,M=eo.includes(h),_=eo.includes(E);!M&&!_||K(O=>{const F=ma(Array.isArray(O)?O:Dc,eo).filter(le=>le!==E),U=M&&!F.includes(h)?[...F,h]:F;return pd(U,ma(Array.isArray(O)?O:Dc,eo))?O:ma(U,eo)})},[Dc,eo,_t,k]);const nm=f.useCallback(()=>Oy({dxfThicknessMm:J,referenceQuery:me,selectedReferenceIds:Ae,selectedPartIds:Te,inspectedAssemblyNodeId:"",expandedStepTreeNodeIds:jt,stepTreeRootShowMore:sn,fileSheetOpenSectionIds:ca,hiddenPartIds:dt,camera:kc.current,drawingTool:Zn,tabToolMode:ar,drawingStrokes:pi,drawingUndoStack:Qs,drawingRedoStack:ko}),[J,Zn,ko,pi,Qs,ca,jt,dt,me,Te,Ae,sn,ar]),rm=f.useCallback((h,E=null)=>{const M=String(h||"").trim();return M?RS(ce,M,E||q.get(M)):null},[q,ce]),tM=f.useCallback(h=>{const E=h||ee,M=at(E),_=M&&Mo?.[M]?Mo[M]:{},O=M&&Pi?.[M]?Pi[M]:{},F=tn.playing?{...tn,elapsedSec:Zx()}:tn,U=tn.playing?_N():Qo;return Ase({fileKey:M,entry:E,slices:{...or(E)===B.STEP?{display:vt}:{},tab:nm(),dxf:{thicknessMm:J,bendSettings:Q},stepModule:{enabled:$r,parameterValues:U,animationState:F},implicit:{parameterValues:ei,animationState:Pr},urdf:{jointValues:_,motionState:O},largeFile:{selectableTopologyEnabled:Tt.selectableTopologyEnabled}}})},[nm,vt,Q,J,Pr,ei,Mo,Tt,ee,tn,$r,Qo,Pi]),$u=f.useCallback(()=>{if(!zu.current||typeof window>"u"){zu.current=0;return}window.clearTimeout(zu.current),zu.current=0},[]),ig=f.useCallback(h=>{const E=at(h);return E?Nse(ce,E,tM(h),{onWriteError:V}):!0},[tM,ce,V]),sg=f.useCallback(()=>($u(),ee?ig(ee):!0),[$u,ee,ig]),ag=f.useCallback(()=>{!ee||typeof window>"u"||($u(),zu.current=window.setTimeout(()=>{zu.current=0,ig(ee)},180))},[$u,ee,ig]),$0=f.useCallback((h,E=null)=>{const M=String(h||"").trim();if(!M)return;const _=E||rm(M),O=$v(Kt);O&&En(O),Ve(pb(_?.slices?.largeFile));const F=q.get(M);Tn(or(F)===B.STEP?So(_?.slices?.display):So());const U=_?.slices?.dxf||null;D(U?.bendSettings||[]),U?.thicknessMm>0&&G(U.thicknessMm);const le=_?.slices?.stepModule||null;le&&(ea(le.enabled!==!1),Dn(le.parameterValues||{}),Zr({activeId:String(le.animationState?.activeId||""),playing:!1,elapsedSec:Math.max(Number(le.animationState?.elapsedSec)||0,0),speed:Ao(le.animationState?.speed,.1,5)}));const Ce=_?.slices?.implicit||null;if(Ce){Oi(Ce.parameterValues||{});const tt={activeId:String(Ce.animationState?.activeId||""),playing:!1,elapsedSec:Math.max(Number(Ce.animationState?.elapsedSec)||0,0),speed:Ao(Ce.animationState?.speed,.1,5)};jo.current=tt,ti(tt)}const st=_?.slices?.urdf||null;st?(uo(tt=>({...tt,[M]:st.jointValues||{}})),Do(tt=>({...tt,[M]:st.motionState||{}}))):(uo(tt=>{if(!tt?.[M])return tt;const Ot={...tt};return delete Ot[M],Ot}),Do(tt=>{if(!tt?.[M])return tt;const Ot={...tt};return delete Ot[M],Ot}))},[Kt,q,rm]),OL=f.useCallback((h,E)=>{D(M=>{if(!tr)return M;const _=Rb(tr,M).map(O=>({...O}));return h<0||h>=_.length||(Object.prototype.hasOwnProperty.call(E||{},"direction")&&(_[h].direction=Gp(E.direction)),Object.prototype.hasOwnProperty.call(E||{},"angleDeg")&&(_[h].angleDeg=Up(E.angleDeg))),_})},[tr]),nM=f.useCallback(h=>{const E=String(h||"").trim(),M=hA(q.get(E));return E&&M?`${E}:${M}`:""},[q]),G0=f.useCallback(h=>{const E=Dm(h?.key||"",h||{}),M=Bs(E.camera);Qh.current=nM(E.key),G(E.dxfThicknessMm),se(E.referenceQuery),jn.current=E.selectedReferenceIds,we(E.selectedReferenceIds),$o.current=[],ut([]),an.current=E.selectedPartIds,rt(E.selectedPartIds),Fe({}),ht(""),qt(E.expandedStepTreeNodeIds),Mn(E.stepTreeRootShowMore),K(E.fileSheetOpenSectionIds),qe(E.hiddenPartIds),We([]),wt(""),De(""),yt(""),Xe(""),Rn(""),ue(""),Qt(""),Mr(E.tabToolMode),qr(E.drawingTool),kc.current=M,Jn(M),co(E.drawingStrokes),Lr(E.drawingUndoStack),is(E.drawingRedoStack),z(E.key)},[nM]),om=f.useCallback(()=>{jn.current=[],$o.current=[],an.current=[],ht(""),G(0),D([]),se(""),we([]),ut([]),rt([]),Fe({}),qt([]),Mn(!1),K(null),qe([]),We([]),Tn(So()),Ve(pb(FT)),wt(""),De(""),yt(""),Xe(""),Rn(""),ue(""),Qt(""),po(!1),Mr(oo.REFERENCES),qr(Jt.FREEHAND),kc.current=null,Jn(null),co([]),Lr([]),is([]),z("")},[po]);f.useEffect(()=>{Cc&&k&&om()},[om,k,Cc]);const im=f.useCallback(h=>{if(!h||!q.has(h)||h===k)return;k&&sg();const E=WC.current,M=q.get(h),_=rm(h,M),O=_?.slices?.tab||null,F=E.find(Gt=>Gt.key===h)||Dm(h,{drawingTool:k?Zn:Jt.FREEHAND,tabToolMode:k?ar:oo.REFERENCES,...O||{}}),U=M?tC(M):null,le=M?nC(M):null,Ce=M?rC(M):null,st=M?iC(M):null,tt=M?oC(M):null,Ot=k?nm():null;R(Gt=>{let pn=Gt;return k&&(pn=ng(pn,k,Ot)),pn=ng(pn,h,F),pn}),qc(M)?U&&(et(U),gn(ke.READY),cr("")):(gn(ke.PENDING),cr("")),Qx(M)?le&&(Eh(le),Rf(le.disabledReason?Wn.DISABLED:Wn.READY),Pf(le.disabledReason||"")):(Eh(null),Rf(Wn.DISABLED),Pf("")),vm(M)?Ce&&($n(Ce),ur(ke.READY),nn("")):($n(null),ur(ke.PENDING),nn("")),or(M)!==B.IMPLICIT?(fo(null),Oa(ke.PENDING),na("")):tt?(fo(tt),Oa(ke.READY),na("")):(fo(null),Oa(ke.PENDING),na("")),Xg(M)?st&&(xl(st),Sl(ke.READY),ku("")):(xl(null),Sl(ke.PENDING),ku("")),G0(F),$0(h,_)},[$0,G0,nm,Zn,q,sg,rC,oC,tC,nC,iC,rm,k,nn,$n,ur,na,fo,Oa,ku,xl,Sl,ar,ng]),kL=f.useCallback(h=>Ep(h),[]);fie({manifestEntries:a,cadFileParamForEntry:kL,cadDirectorySessionBootstrappedRef:vL,setOpenTabs:R,applyTabRecord:G0,selectedEntryKeyFromUrl:Lq,createTabRecord:Dm,initialSelectedTabSnapshot:{drawingTool:Jt.FREEHAND,tabToolMode:oo.REFERENCES},upsertTabRecord:ng,selectedEntry:ee,defaultDocumentTitle:cae,selectedKey:k,entryMap:q,buildActiveTabSnapshot:nm,catalogEntries:l,manifestRevision:n,readCadParam:Pb,activateEntryTab:im,resetActiveDirectory:om,writeCadParam:Cm,readEntrySessionState:rm,applyEntrySessionState:$0}),f.useEffect(()=>{if(!(tn.playing||Pr.playing))return ag(),()=>{$u()}},[$u,Pr.playing,ag,tn.playing]),f.useEffect(()=>{if(typeof window>"u")return;const h=()=>{sg()};return window.addEventListener("pagehide",h),()=>{window.removeEventListener("pagehide",h)}},[sg]),f.useEffect(()=>{const h=typeof window<"u"?window.matchMedia?.("(prefers-color-scheme: dark)"):null;if(!h)return;const E=()=>{At(h.matches===!0)};return E(),h.addEventListener?.("change",E),()=>{h.removeEventListener?.("change",E)}},[]),f.useEffect(()=>{const h=Se.colorMode===Ht.SYSTEM?ne:Se.colorMode;dte(h,document.documentElement,{prefersDark:X})},[ne,X,Se.colorMode]),f.useEffect(()=>{Kie(Ne,{onWriteError:V})},[Ne,V]),f.useEffect(()=>(document.documentElement.dataset.glassTone=_r,()=>{delete document.documentElement.dataset.glassTone}),[_r]),f.useEffect(()=>{const h=E=>{const M=Tse(E.key);if(M!==Rd.IGNORE){if(M===Rd.COLOR_SCHEME){ye(G_());return}try{const _=so();Et(_),En(O=>O.presetId?Kc(_):O)}catch(_){console.warn("Failed to sync theme from another tab",_)}}};return window.addEventListener("storage",h),()=>{window.removeEventListener("storage",h)}},[]),f.useEffect(()=>{jn.current=Ae},[Ae]),f.useEffect(()=>{$o.current=ct},[ct]),f.useEffect(()=>{an.current=Te},[Te]),f.useEffect(()=>{if(!Nn.length||!Te.length)return;const h=new Set(Nn),E=Te.filter(M=>!h.has(String(M||"").trim()));E.length!==Te.length&&(an.current=E,rt(E),Fe(M=>{const _=new Set(E),O={};for(const[F,U]of Object.entries(M||{}))_.has(F)&&(O[F]=U);return O}),ue(""))},[Nn,Te]),f.useEffect(()=>{const h=k&&_t?`${k}:${_t}`:"";if(!h){Qh.current="";return}Qh.current!==h&&(Qh.current=h)},[_t,k]),f.useEffect(()=>{const h=at(ee),E=String(ee?.hash||zt(ee,"topology")||"").trim();if(!h){B0.current={fileRef:"",stepHash:""},Zt(!1);return}const M=B0.current,_=M.fileRef===h;_&&!!M.stepHash&&!!E&&M.stepHash!==E?(JC(),Zt(!0)):_||Zt(!1),B0.current={fileRef:h,stepHash:E}},[JC,ee]),f.useEffect(()=>{if(Rt){if(!ee){Zt(!1);return}bi&&Lt!==ke.LOADING&&Zt(!1)}},[ee,bi,Lt,Rt]),f.useEffect(()=>{La.current=pi},[pi]),f.useEffect(()=>{Zf.current=Qs},[Qs]),f.useEffect(()=>{Jf.current=ko},[ko]),f.useEffect(()=>{Ye!==B.STEP||!Fo||Mr(h=>h!==oo.DRAW||La.current.length?h:oo.REFERENCES)},[Ye,k,Fo]),f.useEffect(()=>{Pt(!1)},[xL]),f.useEffect(()=>{en(null)},[k]);const rM=f.useMemo(()=>md({viewportWidth:te,sidebarOpen:cs,sheetOpen:Rs,sidebarWidth:de,sheetWidth:kn,sidebarMinWidth:Vl,sheetMinWidth:Uc,sidebarMaxWidth:yd,sheetMaxWidth:xd}),[Rs,cs,te,de,kn]),DL=f.useCallback(h=>md({viewportWidth:te,sidebarOpen:cs,sheetOpen:Rs,sidebarWidth:h,sheetWidth:kn,sidebarMinWidth:Vl,sheetMinWidth:Uc,sidebarMaxWidth:yd,sheetMaxWidth:xd}).sidebarWidth,[Rs,cs,te,kn]),jL=f.useCallback(h=>md({viewportWidth:te,sidebarOpen:cs,sheetOpen:Rs,sidebarWidth:de,sheetWidth:h,sidebarMinWidth:Vl,sheetMinWidth:Uc,sidebarMaxWidth:yd,sheetMaxWidth:xd}).sheetWidth,[Rs,cs,te,de]);lie({isDesktop:ae,setLayoutMode:Co,setSidebarOpen:j,setTabToolsOpen:po,setLayoutViewportWidth:fe,clampSidebarWidth:DL,clampTabToolsWidth:jL,setSidebarWidth:L,setTabToolsWidth:Tr,panelResizeStateRef:Zh,tabToolsResizeStateRef:Jh,defaultSidebarWidth:mb,sidebarMinWidth:Vl,tabToolsMinWidth:Uc,endPanelResize:_L,endTabToolsResize:TL}),f.useEffect(()=>{!r||!l.length||_se(ce,l.map(h=>at(h)),{onWriteError:V})},[l,r,ce,V]),f.useEffect(()=>{R(h=>{const E=h.filter(M=>q.has(M.key));return E.length===h.length?h:E})},[q]);const lg=f.useCallback(h=>{const E=lv(h);if(!E)return;const M=$q(E);M.length&&I(_=>{let O=!1;const F=new Set(_);for(const U of M)F.has(U)||(F.add(U),O=!0);return O?F:_})},[]);f.useEffect(()=>{!r&&!l.length||I(h=>{const E=new Set(h),M=new Set(mC);let _=!1;for(const O of h)M.has(O)||(E.delete(O),_=!0);return _?E:h})},[mC,l.length,r]),f.useEffect(()=>{S.current.hasStoredState||S.current.initialRevealDone||!ee||(S.current.initialRevealDone=!0,N(!0),lg(ee))},[lg,ee]),f.useEffect(()=>{w.current=zo},[zo]),f.useEffect(()=>{if(!zo||!Mc||I0||Ic==="ready"||Ic==="error"&&A0>=ev||bl.current.has(zo))return;const h={key:zo,file:Mc};bl.current.set(zo,h),gn(ke.LOADING),cr(""),fq({key:zo,file:Mc,initialFailureCount:A0,generate:OJ,isCurrent:()=>bl.current.get(zo)===h,onState:M=>{fi(_=>({..._,[zo]:M}))},onFinalError:M=>{w.current===zo&&(gn(ke.ERROR),cr(M))},validatePayload:M=>dq(M,{file:Mc})}).finally(()=>{bl.current.get(zo)===h&&bl.current.delete(zo)})},[Mc,zo,I0,A0,Ic,cr,gn]),f.useEffect(()=>{if(!wl||!El){wr(F=>F.status===null&&!F.loading?F:{key:"",file:"",status:null,loading:!1,error:""});return}let h=!1,E=0,M=0;const _=new AbortController,O=()=>{wr(F=>({key:wl,file:El,status:F.key===wl?F.status:null,loading:!0,error:""})),kJ(El,{signal:_.signal}).then(F=>{if(h||_.signal.aborted)return;wr({key:wl,file:El,status:F,loading:!1,error:""});const U=String(F?.step?.status||"").trim();Ic==="ready"&&(U==="missing"||U==="stale")&&M<6&&(M+=1,E=window.setTimeout(O,1500))}).catch(F=>{h||_.signal.aborted||wr({key:wl,file:El,status:null,loading:!1,error:F instanceof Error?F.message:String(F)})})};return O(),()=>{h=!0,_.abort(),E&&window.clearTimeout(E)}},[Ic,El,wl]),f.useEffect(()=>{if(!ee){b0();return}if(![B.STEP,B.STL,B.THREE_MF,B.GLB].includes(Ye)){b0();return}Nt&&je===at(ee)||bi&&(!Me||Bf||Dh)||sC(ee).catch(h=>{gn(ke.ERROR),cr(h instanceof Error?h.message:String(h))})},[b0,Ye,Me,sC,Nt,je,Dh,Bf,ee,bi]),f.useEffect(()=>{if(!ee){vh();return}if(Ye!==B.DXF){vh();return}if(!Lf){vh(),$n(null),ur(ke.PENDING),nn("");return}jh||aC(ee).catch(h=>{ur(ke.ERROR),nn(h instanceof Error?h.message:String(h))})},[vh,Ye,aC,jh,ee,Lf,nn,$n,ur]),f.useEffect(()=>{if(!ee){Ch();return}if(Ye!==B.GCODE){Ch();return}if(!Ph){Ch(),kr(null),Qr(ke.PENDING),ta("");return}Lh||lC(ee).catch(h=>{Qr(ke.ERROR),ta(h instanceof Error?h.message:String(h))})},[Ch,Ye,lC,ee,Ph,Lh,ta,kr,Qr]),f.useEffect(()=>{if(!ee){Mh();return}if(Ye!==B.IMPLICIT){Mh();return}if(!Oh){Mh(),fo(null),Oa(ke.PENDING),na("");return}Fh||cC(ee).catch(h=>{Oa(ke.ERROR),na(h instanceof Error?h.message:String(h))})},[Mh,Ye,cC,ee,Oh,Fh,na,fo,Oa]),f.useEffect(()=>{if(!ee){Ih();return}if(!Hi(Ye)){Ih();return}if(!Rh){Ih(),xl(null),Sl(ke.PENDING),ku("");return}Vf||uC(ee).catch(h=>{Sl(ke.ERROR),ku(h instanceof Error?h.message:String(h))})},[Ih,Ye,uC,ee,Rh,Vf,ku,xl,Sl]);const Gu=!!Tf&&!!ee&&Fo&&Tf.fileRef===at(ee)&&Tf.referenceHash===HD(ee),LL=Gu&&Tf?.selectorRuntime||null,U0=!!wh&&!!ee&&EC&&wh.fileRef===at(ee)&&wh.displayEdgeHash===zt(ee,"displayEdgeTopology"),FL=U0&&wh?.displayEdgeRuntime||null,W0=!Me&&Te.includes(hs),cg=Ye===B.STEP&&Fo&&!Me,zL=Ye===B.STEP&&Fo&&Me&&_l.length>0,oM=Ye===B.STEP&&EC&&!ml(vt.mode)&&($y(vt.mode)||xt.enabled!==!1),BL=Tt.selectableTopologyEnabled===!0,VL=!!($D(ee)||bi&&Joe(Fr)),$L=!!(cg&&!Yoe(ee)&&!bi),sm=!!(cg&&VL&&!BL&&!W0),GL=W0||cg,iM=W0||zL||cg&&!sm&&!$L;f.useEffect(()=>{if(!ee){Ah();return}if(!Fo){Ah(),Eh(null),Rf(Wn.DISABLED),Pf("");return}if(!iM){Ah(),Eh(null),Rf(Wn.IDLE),Pf("");return}Gu||dC(ee).catch(h=>{Rf(Wn.ERROR),Pf(h instanceof Error?h.message:String(h))})},[Ah,Me,dC,iM,ee,Fo,Gu]),f.useEffect(()=>{if(!ee){y0();return}if(!oM){y0(),eC(null),h0(Wn.IDLE),g0("");return}U0||fC(ee).catch(h=>{h0(Wn.ERROR),g0(h instanceof Error?h.message:String(h))})},[y0,fC,U0,ee,oM,g0,eC,h0]),f.useEffect(()=>{Ye!==B.DXF||!Xt||(V0.current=null,os(!1))},[Ye,Xt]);const{currentReferences:ug,activeReferenceMap:sM,hoveredReferenceId:UL,hoveredPartId:Uu,visibleReferences:aM}=pie({selectedReferencesMatch:Gu,referenceState:Tf,isAssemblyView:Me,supportsPartSelection:zC,assemblyParts:Yh,assemblyPartMap:as,inspectedAssemblyNodeId:"",inspectedAssemblyPartTopologyReferences:[],selectedReferenceIds:Ae,selectedPartIds:Te,hoveredListReferenceId:St,hoveredModelReferenceId:Vn,hoveredListPartId:pe,hoveredModelPartId:He});cie({isAssemblyView:Me,supportsPartSelection:zC,assemblyPartsLoaded:P0,selectedEntryHasReferences:Fo,setSelectedReferenceIds:we,selectedReferenceIdsRef:jn,setHoveredListReferenceId:wt,setHoveredModelReferenceId:De,assemblyParts:Yh,validAssemblyPartIds:Xf,validHiddenPartIds:aa,selectedPartIdsRef:an,setSelectedPartIds:rt,parseAssemblyPartReferenceSelectionId:CT,setHiddenPartIds:qe,setHoveredListPartId:Xe,setHoveredModelPartId:Rn}),f.useEffect(()=>{const h=String(An?.id||"").trim();if(!h){qt(M=>M.length?[]:M);return}const E=new Set(Xf);qt(M=>{const _=M.filter(O=>E.has(O));return _.length===1&&_[0]===h&&!an.current.length&&!jn.current.length?[]:pd(_,M)?M:_})},[k,An,Xf]);const dg=f.useCallback(h=>String(h?.selectorType||"").trim()==="face",[]),fg=f.useCallback(h=>String(h?.selectorType||"").trim()==="edge",[]),lM=f.useCallback(h=>String(h?.selectorType||"").trim()==="vertex",[]),Rl=f.useCallback(h=>dg(h)||fg(h)||lM(h),[fg,dg,lM]),cM=f.useCallback(h=>{const E=String(h?.selectorType||"").trim();return E==="occurrence"||E==="shape"||E==="face"||E==="edge"||E==="vertex"},[]),Fi=f.useCallback(h=>{const E=String(h?.partId||"").trim();return E||CT(h?.id)?.partId||""},[]),Wu=f.useMemo(()=>!mr||!Me||!Gu?[]:k5(An,ug),[ug,Me,mr,Gu,An]),am=f.useMemo(()=>!Me||!Nn.length?[]:_n(Nn.flatMap(h=>[h,...yn(h)]).map(h=>String(h||"").trim()).filter(Boolean)),[Nn,Me,yn]),uM=f.useMemo(()=>{if(!Me||!am.length)return[];const h=new Set(am);return Wu.filter(E=>h.has(Fi(E))&&cM(E))},[Wu,am,Me,cM,Fi]),mg=f.useMemo(()=>Me&&UC?uM:aM,[uM,UC,Me,aM]),dM=f.useMemo(()=>mr?Me?_l.length?Wu:[]:ug:[],[Wu,ug,Me,mr,_l]),Un=f.useMemo(()=>j5({root:An,references:dM,fallbackPartId:Me?"":hs,topologyPartIds:Me?_l:null}),[Me,_l,An,dM]),WL=f.useMemo(()=>{if(!Me||!Nn.length)return null;const h=Un||An;return _n(Nn.flatMap(E=>DS(h,E)))},[Un,Nn,Me,An]),fM=f.useMemo(()=>mr&&Me?Aae(Un,jt,{isAssemblyView:Me}):[],[Un,jt,Me,mr]),H0=f.useMemo(()=>new Set(fM),[fM]),Io=f.useMemo(()=>Mae(Un),[Un]),K0=LL,rr=f.useMemo(()=>{const h=new Map(sM);for(const E of Array.from(h.values()))BT(h,E);for(const E of mg)BT(h,E);return h},[sM,mg]);f.useEffect(()=>{if(!Me||!Nn.length||!Ae.length)return;const h=sae(Ae,rr,Nn,{referencePartId:Fi});pd(h,Ae)||(jn.current=h,we(h),ue(""))},[rr,Nn,Me,Fi,Ae]);const pg=f.useCallback(h=>{const E=String(h||"").trim();if(!E)return[];const M=rr.get(E),_=String(M?.selectorType||"").trim();if(_!=="occurrence"&&_!=="shape")return[];const O=Fi(M);if(Me)return O?yn(O):[];const F=O&&O!==hs?O:op;return F?[F]:[]},[rr,Me,Fi,yn]),hg=f.useMemo(()=>Me?H0.size?Wu.filter(h=>H0.has(String(h?.id||"").trim())):[]:mg,[Wu,mg,Me,Vo,H0]),mM=f.useMemo(()=>hg.filter(h=>dg(h)),[dg,hg]),pM=f.useMemo(()=>hg.filter(h=>fg(h)),[fg,hg]),hM=fb,jc=Dj,HL=!!(mM.length||pM.length||hM.length),gM=Me&&_l.length>0||GL,X0=Ye===B.STEP&&Fo&&gM&&!ls&&!sm&&(jc===Wn.DISABLED||jc===Wn.ERROR||jc===Wn.READY&&!!K0&&!HL),gg=Ye===B.STEP&&Fo&&gM&&!ls&&!sm&&!X0&&(Rt||jc===Wn.IDLE||jc===Wn.LOADING||!K0),KL=f.useMemo(()=>{if(!ee)return null;if(ri)return{loading:!0,label:"generating",title:"Generator script is running"};if(Ye===B.DXF&&k0)return{loading:!0,label:Lf?Jr||"loading DXF":"building",title:ja};if(Ye===B.GCODE&&D0)return{loading:!0,label:Ph?Ou||"loading G-code":"building",title:ja};if(Ye===B.IMPLICIT&&j0)return{loading:!0,label:Oh?ss||"loading implicit CAD":"loading",title:ja};if(Hi(Ye)&&L0)return{loading:!0,label:Rh?Jv||(Ye===B.SDF?"loading SDF":"loading URDF"):"building",title:ja};if(Ye===B.STEP&&Rt)return{loading:!0,label:"building",title:ja};if(Ye===B.STEP&&zf)return{loading:!0,label:"generating GLB",title:ja};if(Ye===B.STEP&&Th)return{loading:!0,label:"loading STEP module",title:ja};if([B.STEP,B.STL,B.THREE_MF,B.GLB].includes(Ye)&&F0){const h=je===at(ee)?Je:"";return{loading:!0,label:jf?h||"loading mesh":"building",title:ja}}return Ye===B.STEP&&GC?{loading:!0,label:(je===at(ee)?Je:"")||"loading meshes",title:"Loading assembly meshes"}:Ye===B.STEP&&jc===Wn.LOADING?{loading:!0,label:Qv||"loading topology",title:"Loading selectable topology"}:Ye===B.STEP&&gg?{loading:!0,label:"building topology",title:"Preparing selectable topology"}:z0?{loading:!0,label:"building assembly",title:"Preparing assembly parts"}:null},[GC,z0,Jr,k0,Ye,Ou,D0,ss,j0,Je,je,Qv,gg,jc,ee,Lf,Ph,Oh,jf,Rh,ri,zf,Th,Rt,F0,Jv,L0,ja]),Y0=f.useMemo(()=>_n(Ae.flatMap(h=>pg(h))),[pg,Ae]),q0=f.useMemo(()=>_n([St,Vn].flatMap(h=>pg(h))),[St,Vn,pg]),XL=f.useMemo(()=>{if(!Me)return Y0;const h=new Set(Nn);return _n([...Te.flatMap(E=>{const M=String(E||"").trim();return h.has(M)?[]:yn(M,Re[M])}),...Y0])},[Nn,Me,yn,Te,Re,Y0]),YL=f.useMemo(()=>{const h=String(ze?.nodeId||"").trim();if(Me&&h){const F=String(ze?.renderPartId||"").trim(),U=yn(h,F);return U.length?U:h}if(q0.length)return q0;if(!Me||!Uu)return Uu;const E=String(pe||"").trim();if(E){const F=yn(E);return F.length?F:E}const M=String(He||Uu||"").trim(),_=la(M),O=yn(_,M);return O.length?O:Uu},[Uu,pe,He,q0,Me,yn,la,ze]),bM=String(ze?.referenceId||"").trim()||UL,qL=f.useMemo(()=>am,[am]),ZL=f.useMemo(()=>dt,[dt]),JL=f.useMemo(()=>!Me||!Bf?fb:Kh,[Kh,Me,Bf]),Hu=f.useCallback(h=>{h&&Do(E=>{const M=E?.[h];return M?.statusesByEndEffector?{...E,[h]:{...M,statusesByEndEffector:{}}}:E})},[]),Ku=f.useCallback(h=>{const E=String(h||"").trim();E&&hl(M=>{if(!M?.[E])return M;const _={...M};return delete _[E],_})},[]),bg=f.useCallback(()=>{const h=gl.current;h.token+=1,h.frameId&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(h.frameId),h.frameId=0},[]),lm=f.useCallback(()=>{const h=Di.current;h.token+=1,h.frameId&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(h.frameId),h.frameId=0,h.mode="",h.fileRef="",h.targetValues=null,h.currentValues=null,h.lastTimestampMs=0},[]),us=f.useCallback(()=>{bg(),lm()},[lm,bg]),Pl=f.useCallback((h,E,M,_={})=>{const O=String(h||"").trim();if(!O)return;const F=jr(E),U=jr(M);if(us(),typeof requestAnimationFrame!="function"||Ip(F,U)){uo(Gt=>({...Gt,[O]:U}));return}const le=Di.current,Ce=le.token+1;le.token=Ce;const st=Ka(),tt=Math.max(Dr(_?.durationMs,Rse),1),Ot=Gt=>{if(Di.current.token!==Ce)return;const pn=Math.max(Dr(Gt,Ka())-st,0),Go=Math.min(pn/tt,1),da=Dse(F,U,Go,void 0,zh),Uo=da.done||Go>=1?U:{...F,...da.values};if(uo(fa=>({...fa,[O]:Uo})),da.done||Go>=1){Di.current.frameId=0;return}Di.current.frameId=requestAnimationFrame(Ot)};le.frameId=requestAnimationFrame(Ot)},[us,zh]),yM=f.useCallback((h,E,M,_={})=>{const O=String(h||"").trim();if(!O)return;const F=jr(E),U=jr(M),le=Math.max(Dr(_?.durationMs,Pd),1);if(bg(),typeof requestAnimationFrame!="function"||Ip(F,U)){lm(),uo(Gt=>({...Gt,[O]:U}));return}const Ce=Di.current;if(Ce.frameId&&Ce.mode==="follow"&&Ce.fileRef===O){Ce.targetValues=U,Ce.smoothingMs=le;return}lm();const st=Di.current,tt=st.token+1;st.token=tt,st.mode="follow",st.fileRef=O,st.currentValues=F,st.targetValues=U,st.smoothingMs=le,st.lastTimestampMs=Ka();const Ot=Gt=>{const pn=Di.current;if(pn.token!==tt)return;const Go=Dr(Gt,Ka()),da=Math.max(Go-Dr(pn.lastTimestampMs,Go),0);pn.lastTimestampMs=Go;const Uo=jr(pn.currentValues),fa=jr(pn.targetValues),dm=jse(Uo,fa,da,pn.smoothingMs,void 0,zh),oi=dm.done?fa:{...Uo,...dm.values};if(pn.currentValues=oi,uo(nx=>({...nx,[O]:oi})),dm.done||Ip(oi,fa)){pn.frameId=0,pn.mode="",pn.fileRef="",pn.currentValues=null,pn.targetValues=null,pn.lastTimestampMs=0;return}pn.frameId=requestAnimationFrame(Ot)};st.frameId=requestAnimationFrame(Ot)},[lm,bg,zh]),xM=f.useCallback((h,E,M,_)=>{const O=String(h||"").trim();if(!O)return;us();const F=Array.isArray(M?.points)?M.points:[],U=F.length?Dr(F[F.length-1].timeFromStartSec,0):0;if(!F.length||U<=0||typeof requestAnimationFrame!="function"){uo(pn=>({...pn,[O]:jr(_)}));return}const le=gl.current,Ce=le.token+1;le.token=Ce;const st=jr(E),tt=jr(_),Ot=Ka(),Gt=pn=>{if(gl.current.token!==Ce)return;const Go=Math.max((Dr(pn,Ka())-Ot)/1e3,0),da=Go>=U,Uo=da?tt:Hse(M,Go,st);if(uo(fa=>({...fa,[O]:Uo})),da){gl.current.frameId=0;return}gl.current.frameId=requestAnimationFrame(Gt)};le.frameId=requestAnimationFrame(Gt)},[us]);f.useEffect(()=>()=>{us()},[us]);const Xu=f.useCallback((h,E)=>{const M=String(h||"").trim();if(!M||!mt||!Li||!mn||!yi||!E||typeof E!="object")return;const _=EE(mt,E,Li.link,yi);if(!_)return;const O=Yl(_);Do(F=>{const U=F?.[M]&&typeof F[M]=="object"?F[M]:{},le=U.targetsByEndEffector&&typeof U.targetsByEndEffector=="object"?U.targetsByEndEffector:{},Ce=U.statusesByEndEffector&&typeof U.statusesByEndEffector=="object"?{...U.statusesByEndEffector}:{};return delete Ce[mn],{...F,[M]:{...U,targetsByEndEffector:{...le,[mn]:O},statusesByEndEffector:Ce}}})},[mt,Li,mn,yi]),QL=f.useCallback((h,E,M={})=>{const _=String(h?.name||"").trim();if(!ve||!_)return;const O=uc(h,E),F=Dr(nr?.[_],h?.defaultValueDeg??0);if(Math.abs(O-F)<=p0)return;const U={...nr,[_]:O};M?.scrub?yM(ve,nr,U,{durationMs:Pd}):Pl(ve,nr,U,{durationMs:Pd}),Ku(ve),Xu(ve,U),Hu(ve)},[Pl,Hu,Ku,yM,ve,nr,Xu]),eF=f.useCallback(()=>{ve&&(us(),Ku(ve),Pl(ve,nr,Ac),Xu(ve,Ac),Hu(ve))},[Pl,us,Hu,Ku,Ac,ve,nr,Xu]),tF=f.useCallback(h=>{if(!ve||!h?.jointValuesByName||typeof h.jointValuesByName!="object")return;us();const E=jr(h.jointValuesByName);if(!Object.keys(E).length)return;const M={...nr,...E},_=String(h?.id||"").trim();_&&hl(O=>({...O,[ve]:_})),Pl(ve,nr,M),Xu(ve,M),Hu(ve)},[Pl,us,Hu,ve,nr,Xu]),nF=f.useCallback(h=>{if(!ve)return;const E=String(h||"").trim();f.startTransition(()=>{Do(M=>({...M,[ve]:{...M?.[ve]&&typeof M[ve]=="object"?M[ve]:{},activeEndEffectorName:E}}))})},[ve]),rF=f.useCallback((h,E)=>{if(!ve)return;const M=String(h||"").trim();M&&f.startTransition(()=>{Do(_=>({..._,[ve]:{..._?.[ve]&&typeof _[ve]=="object"?_[ve]:{},[M]:E}}))})},[ve]),oF=f.useCallback((h,E)=>{if(!ve||!mn)return;const M=Number(h);if(!Number.isInteger(M)||M<0||M>2)return;const _=Dr(E,sa[M]??0);f.startTransition(()=>{Do(O=>{const F=O?.[ve]&&typeof O[ve]=="object"?O[ve]:{},U=F.targetsByEndEffector&&typeof F.targetsByEndEffector=="object"?F.targetsByEndEffector:{},le=Yl(U[mn],sa);le[M]=_;const Ce=F.statusesByEndEffector&&typeof F.statusesByEndEffector=="object"?{...F.statusesByEndEffector}:{};return delete Ce[mn],{...O,[ve]:{...F,targetsByEndEffector:{...U,[mn]:le},statusesByEndEffector:Ce}}})})},[ve,mn,sa]),iF=f.useCallback(()=>{if(!ve||!mn||!Lu)return;const h=Yl(Lu);f.startTransition(()=>{Do(E=>{const M=E?.[ve]&&typeof E[ve]=="object"?E[ve]:{},_=M.targetsByEndEffector&&typeof M.targetsByEndEffector=="object"?M.targetsByEndEffector:{},O=M.statusesByEndEffector&&typeof M.statusesByEndEffector=="object"?{...M.statusesByEndEffector}:{};return delete O[mn],{...E,[ve]:{...M,targetsByEndEffector:{..._,[mn]:h},statusesByEndEffector:O}}})})},[ve,Lu,mn]),Yu=f.useCallback(async(h="srdf.solvePose",E=sa)=>{if(!ve||!mt||!Li||!mn||!yi)return;const M=h==="srdf.planToPose"?"srdf.planToPose":"srdf.solvePose",_=Yl(E),O=F=>{const U=String(F||"Motion request failed.");if(Sn(""),typeof window>"u"){Sn(U);return}window.setTimeout(()=>{Sn(U)},0)};if(Sn(""),!Nc?.srdf){O("SRDF data is not loaded for this file.");return}if(!On){O("MoveIt2 server is offline.");return}us(),Do(F=>{const U=F?.[ve]&&typeof F[ve]=="object"?F[ve]:{};return{...F,[ve]:{...U,solvingEndEffectorName:mn}}});try{const F=await oae(M,{dir:g,file:ve,startJointValuesByName:zse(mt,nr),startJointValuesByNameDeg:nr,target:{endEffector:mn,frame:yi,targetLink:Li.link,xyz:_},moveit2:{planningGroup:Bo.planningGroup,endEffector:Bo.endEffector,targetLink:Li.link,targetFrame:Bo.targetFrame,ik:{positionOnly:!0,timeout:Bo.ikTimeout,attempts:Bo.ikAttempts,tolerance:Bo.ikTolerance},planning:{pipeline:Bo.planningPipeline,plannerId:Bo.plannerId,planningTime:Bo.planningTime,maxVelocityScalingFactor:Bo.maxVelocityScalingFactor,maxAccelerationScalingFactor:Bo.maxAccelerationScalingFactor}}});if(F?.ok===!1){O(String(F.message||"MoveIt2 server request failed."));return}const U=F?.trajectory?Vse(mt,F.trajectory):null,le=U?.points?.length?U.points[U.points.length-1].positionsByName:null,Ce=U?.points?.length?U.points[U.points.length-1].positionsByNameDeg:null,st=F?.jointValuesByName||le,tt=st?TE(mt,st,{native:!0}):TE(mt,F?.jointValuesByNameDeg||Ce),Ot={...nr,...tt},Gt=$se(mt,Ot,{...Li,frame:yi},_),pn=Bo.ikTolerance;Ku(ve),U?xM(ve,nr,U,Ot):Pl(ve,nr,Ot),Gt.positionError>pn&&O("Motion applied, but FK residual is outside tolerance.")}catch(F){O(F instanceof Error?F.message:String(F))}finally{Do(F=>{const U=F?.[ve]&&typeof F[ve]=="object"?F[ve]:{};if(U.solvingEndEffectorName!==mn)return F;const le={...U};return delete le.solvingEndEffectorName,{...F,[ve]:le}})}},[Pl,us,g,Ku,On,xM,mt,ve,Nc,Li,mn,yi,sa,Bo,nr]),sF=f.useCallback(async()=>{await Yu("srdf.solvePose",sa)},[Yu,sa]),aF=f.useCallback(async()=>{await Yu("srdf.planToPose",sa)},[Yu,sa]),qu=f.useCallback(h=>{const E=Bs(h);return E?(Oc.current?.setPerspective?.(E,{animate:!0}),kc.current=E,Jn(E),!0):!1},[]),SM=f.useCallback(()=>{if(!ve||!ju)return;const h=Bs(Oc.current?.getPerspective?.()||kc.current);Pu({fileRef:ve,originalPerspective:h})},[ve,ju]),Zu=f.useCallback(()=>{const h=hi.fileRef?hi.originalPerspective:null;Pu(db()),qu(h)},[qu,hi.fileRef,hi.originalPerspective]),EM=f.useCallback(()=>{if(_c){Zu();return}SM()},[SM,Zu,_c]);f.useEffect(()=>{if(!_c||typeof window>"u")return;const h=E=>{E.defaultPrevented||E.key!=="Escape"&&E.key!=="Esc"&&E.code!=="Escape"||(E.preventDefault(),E.stopPropagation(),Zu())};return window.addEventListener("keydown",h,!0),()=>{window.removeEventListener("keydown",h,!0)}},[Zu,_c]);const wM=f.useCallback(h=>{!ve||!mn||Do(E=>{const M=E?.[ve]&&typeof E[ve]=="object"?E[ve]:{},_=M.targetsByEndEffector&&typeof M.targetsByEndEffector=="object"?M.targetsByEndEffector:{},O=M.statusesByEndEffector&&typeof M.statusesByEndEffector=="object"?{...M.statusesByEndEffector}:{};return delete O[mn],{...E,[ve]:{...M,targetsByEndEffector:{..._,[mn]:h},statusesByEndEffector:O}}})},[ve,mn]),lF=f.useCallback(async({point:h}={})=>{if(!ve||!mt||!Li||!mn)return;const E=Xse(h);if(!E||!$h)return;const M=Eoe(mt,nr,E,yi);if(!M)return;const _=Yl(M),O=$h.originalPerspective;Pu(db()),qu(O),wM(_),await Yu("srdf.solvePose",_)},[wM,Yu,qu,mt,ve,Li,mn,yi,nr,$h]),cF=f.useCallback(async()=>{if(Qt(""),!Uh.length){ue("No movable joints are available");return}try{await ps(Yse(Uh,nr)),ue(mo===B.SDF?"Copied joint values":"Copied joint angles")}catch(h){ue(h instanceof Error?h.message:"Clipboard write failed")}},[Uh,mo,nr]);f.useEffect(()=>{if(hi.fileRef&&hi.fileRef!==ve){const h=hi.originalPerspective;Pu(db()),qu(h)}},[qu,ve,hi.fileRef,hi.originalPerspective]);const yg=f.useMemo(()=>{const h=Ae.map(_=>Io.get(_)||rr.get(_)||$l(_,"topology")).filter(Boolean);if(!Me&&Te.includes(hs)){const _=_S(ee);_&&h.push(_)}const E=Te.map(_=>$l(_,"assembly-part")||Io.get(_)||rp(hb({assemblyPartMap:as,displayStepTreeRoot:Un,stepTreeRoot:An,nodeId:_}),_,"assembly-part")).filter(Boolean),M=ct.map(_=>Al.get(_)).filter(Boolean);return Fm(km({references:[...h,...E],parts:[],mates:M,entry:ee}),{selectedReferenceIds:Ae,selectedPartIds:Te,selectedMateIds:ct,copyReferenceMap:Io})},[as,Un,rr,Al,ee,ct,Te,Ae,Io,An]),vM=f.useMemo(()=>yg.lines.map(h=>Gs(h)).filter(Boolean),[yg.lines]),uF=f.useMemo(()=>Iie(vM,{count:yg.copiedCount}),[vM,yg.copiedCount]),CM=f.useCallback((h,{expandSelf:E=!1,includeVisualOnlyAncestors:M=!0}={})=>{const _=String(h||"").trim(),O=Un||An;if(!_||!O)return;const F=Tae(O,_,{expandSelf:E,includeVisualOnlyAncestors:M});F.length&&qt(U=>_n([...U,...F]))},[Un,An]),ua=f.useCallback((h,{expandSelf:E=!1,expandAncestors:M=!1,source:_="viewer"}={})=>{const O=String(h||"").trim();!O||_t!=="step"||(Bt(_==="viewer"?`${Date.now()}:${O}`:""),og(bt.STEP_TREE,{openSheet:JY({isDesktop:ae,source:_})}),(M||E)&&CM(O,{expandSelf:E}))},[CM,ae,og,_t]),Lc=f.useCallback((h,{multiSelect:E=!1,source:M="viewer"}={})=>{if(Rt||Vo)return;M!=="viewer"&&Bt("");const _=String(h||"").trim(),O=rr.get(_),F=String(O?.selectorType||"").trim(),U=Fi(O);if(Me&&(F==="shape"||F==="occurrence")&&U&&Nn.includes(U)){const Ce=jn.current.filter(st=>String(st||"").trim()!==_);Ce.length!==jn.current.length&&(jn.current=Ce,we(Ce),ue(""));return}const le=!E&&(an.current.length||$o.current.length)?_?[_]:[]:TS(jn.current,_,{multiSelect:E});if(le.length&&!ae&&j(!1),ht(""),!E&&an.current.length&&(an.current=[],rt([]),Fe({})),!E&&$o.current.length&&($o.current=[],ut([])),jn.current=le,we(le),le.includes(_)){const Ce=$T(Un,_);ua(Ce||U,{source:M})}},[Un,rr,Nn,ae,Me,Fi,ua,Vo,Rt]),MM=f.useCallback(()=>{jn.current=[],$o.current=[],ht(""),we([]),ut([]),ue("")},[]);f.useCallback(()=>{jn.current=[],$o.current=[],ht(""),we([]),ut([]),wt(""),De(""),yt(""),ue("")},[]);const dF=f.useCallback(async()=>{if(Qt(""),Rt){ue("STEP update in progress. Please wait.");return}const h=jn.current.map(U=>Io.get(U)||rr.get(U)||$l(U,"topology")).filter(Boolean);if(!Me&&an.current.includes(hs)){const U=_S(ee);U&&h.push(U)}const E=an.current.map(U=>$l(U,"assembly-part")||Io.get(U)||rp(hb({assemblyPartMap:as,displayStepTreeRoot:Un,stepTreeRoot:An,nodeId:U}),U,"assembly-part")).filter(Boolean),M=$o.current.map(U=>Al.get(U)).filter(Boolean);if(!h.length&&!E.length&&!M.length){ue("Nothing selected");return}const _=Fm(km({references:[...h,...E],parts:[],mates:M,entry:ee}),{selectedReferenceIds:jn.current,selectedPartIds:an.current,selectedMateIds:$o.current,copyReferenceMap:Io}),{lines:O,missingPartNames:F=[]}=_;if(!O.length){ue(F.length===1?`No selector ref is available for ${F[0]}`:"No selector refs are available for the selection");return}try{await ps(O.map(Ce=>Gs(Ce)).filter(Boolean).join(` `));const U=_.copiedCount||h.length+E.length+M.length-F.length,le=F.length?` (${F.length} unavailable)`:"";ue(`Copied ${U} ref${U===1?"":"s"}${le}`)}catch(U){ue(U instanceof Error?U.message:"Clipboard write failed")}},[as,Un,rr,Al,ee,Qt,Io,An,Rt]),Ba=f.useCallback(h=>{const E=String(h||"").trim();if(!E)return;const _=jt.includes(E)&&Me&&rn&&Nn.some(F=>Jc(rn,E,F)),O=_?new Set(DS(Un||An,E)):null;qt(F=>F.includes(E)?F.filter(U=>O?!O.has(U):U!==E):_n([...F,E])),_&&We(F=>{const U=F.filter(le=>!Jc(rn,E,le));return U.length===F.length?F:U})},[rn,Un,jt,Nn,Me,An]),cm=f.useCallback(h=>{const E=String(h||"").trim();if(!E)return an.current;const M=an.current.filter(_=>String(_||"").trim()!==E);return M.length===an.current.length?an.current:(an.current=M,rt(M),Fe(_=>{const O={..._};return delete O[E],O}),M)},[]),Ju=f.useCallback((h,{multiSelect:E=!1,renderPartId:M="",source:_="viewer"}={})=>{if(Rt||Vo)return an.current;_!=="viewer"&&Bt("");const O=String(h||"").trim();if(Me&&Nn.includes(O))return cm(O);const F=an.current.includes(O);if(Me&&!(_==="viewer"?LC:DC).has(O)&&!F)return an.current;const le=!E&&(jn.current.length||$o.current.length)?O?[O]:[]:TS(an.current,h,{multiSelect:E});return le.length&&!ae&&j(!1),ht(""),!E&&jn.current.length&&(jn.current=[],we([])),!E&&$o.current.length&&($o.current=[],ut([])),an.current=le,rt(le),le.includes(O)&&ua(O,{source:_}),Fe(Ce=>{const st={};for(const tt of le){const Ot=String(tt||"").trim();if(!Ot)continue;const Gt=Ot===O?O0(Ot,M):O0(Ot,Ce[Ot]);Gt&&(st[Ot]=Gt)}return st}),le},[ae,Me,Nn,cm,ua,O0,DC,LC,Vo,Rt]),fF=f.useCallback((h,{multiSelect:E=!1}={})=>{const M=String(h||"").trim();Ju(M,{multiSelect:E,source:"tree"})},[Ju]),mF=f.useCallback((h,{multiSelect:E=!1}={})=>{const M=String(h||"").trim();M&&Lc(M,{multiSelect:E,source:"tree"})},[Lc]),IM=f.useCallback((h,{multiSelect:E=!1}={})=>{if(Rt||Vo)return;Bt("");const M=String(h||"").trim();if(!M||!Al.has(M))return;const _=!E&&(an.current.length||jn.current.length)?[M]:TS($o.current,M,{multiSelect:E});_.length&&!ae&&j(!1),ht(""),!E&&an.current.length&&(an.current=[],rt([]),Fe({})),!E&&jn.current.length&&(jn.current=[],we([])),$o.current=_,ut(_),ue("")},[ae,Al,Vo,Rt]),pF=f.useCallback((h,{multiSelect:E=!1}={})=>{IM(h,{multiSelect:E})},[IM]),ds=f.useCallback(()=>{Bt(""),an.current=[],jn.current=[],$o.current=[],ht(""),rt([]),Fe({}),we([]),ut([]),Xe(""),Rn(""),wt(""),De(""),yt(""),Ze(null),ue("")},[]),Ol=f.useCallback(h=>{const E=String(h||"").trim(),M=Un||An,_=new Set(DS(M,E));_.size&&qt(O=>O.filter(F=>!_.has(F)))},[Un,An]),um=f.useCallback(h=>{if(!Me||!rn)return;const E=_n((Array.isArray(h)?h:[h]).map(U=>String(U||"").trim()).filter(Boolean)),M=Fb(rn,E,{rootId:Nl}),_=M.map(U=>({id:U,node:oc(rn,U)})).filter(({node:U})=>!!U);if(!_.length){We(U=>U.length?[]:U);return}const O=_.flatMap(({node:U})=>Zp(U)).map(U=>String(U||"").trim()).filter(Boolean),F=new Set(O);ds(),We(M),qt(U=>_n([...U,...M])),qe(U=>{if(!F.size)return U;const le=U.filter(Ce=>!F.has(String(Ce||"").trim()));return le.length===U.length?U:le});for(const U of M)ua(U,{expandSelf:!0,source:"tree"})},[rn,Nl,ds,Me,ua]),Fc=f.useCallback(()=>{for(const h of Nn)Ol(h);We(h=>h.length?[]:h)},[Ol,Nn]),Z0=f.useCallback(h=>{const E=String(h||"").trim();if(!E){Fc();return}Ol(E),We(M=>{const _=M.filter(O=>String(O||"").trim()!==E);return _.length===M.length?M:_})},[Ol,Fc]),Va=f.useCallback(()=>{ds()},[ds]);f.useEffect(()=>{},[Va,on,Vo]);const Qu=f.useCallback((h,E="")=>{const M=new Set((Array.isArray(h)?h:[]).map(Ce=>String(Ce||"").trim()).filter(Boolean));if(!M.size)return;const _=String(E||"").trim(),O=an.current.filter(Ce=>{const st=String(Ce||"").trim();return!st||_&&Jc(rn,_,st)?!1:!yn(st).some(Ot=>M.has(String(Ot||"").trim()))}),F=O.length!==an.current.length;F&&(an.current=O,rt(O),Fe(Ce=>{const st=new Set(O),tt={};for(const[Ot,Gt]of Object.entries(Ce||{}))st.has(Ot)&&(tt[Ot]=Gt);return tt}));const U=jn.current.filter(Ce=>{const st=rr.get(Ce),tt=Fi(st);return!yn(tt,tt).some(Gt=>M.has(String(Gt||"").trim()))}),le=U.length!==jn.current.length;le&&(jn.current=U,we(U)),(F||le)&&(ht(""),ue(""))},[rn,rr,Fi,yn]);f.useEffect(()=>{Qu(dt)},[Qu,dt]);const AM=f.useCallback(h=>{const E=String(h||"").trim(),M=yn(h);M.length&&(Ol(h),Qu(M,E),We(_=>{const O=_.filter(F=>!Jc(rn,E,F));return O.length===_.length?_:O}),qe(_=>{const O=new Set(_);let F=!1;for(const U of M)!U||O.has(U)||(O.add(U),F=!0);return F?[...O]:_}))},[rn,Ol,Qu,yn]),NM=f.useCallback(h=>{const E=yn(h);if(!E.length)return;const M=new Set(E);qe(_=>_.filter(O=>!M.has(O))),ua(h,{source:"viewer"})},[yn,ua]),hF=f.useCallback(h=>{const E=yn(h);if(!E.length)return;const M=new Set(dt);E.every(O=>M.has(O))||(Ol(h),Qu(E,h),We(O=>{const F=O.filter(U=>!Jc(rn,h,U));return F.length===O.length?O:F})),qe(O=>{const F=new Set(O);if(E.every(le=>F.has(le)))return O.filter(le=>!E.includes(le));for(const le of E)F.add(le);return[...F]})},[rn,Ol,Qu,dt,yn]),_M=f.useCallback(()=>{const h=[...new Set(an.current.map(E=>String(E||"").trim()).filter(Boolean))];h.length<1||(We(E=>E.length?[]:E),qe(E=>{const M=[...E],_=new Set(E);let O=!1;for(const F of h.flatMap(U=>yn(U)))!F||_.has(F)||(_.add(F),M.push(F),O=!0);return O?M:E}),ds())},[ds,yn]),gF=f.useCallback(()=>{const h=[...new Set(an.current.map(M=>String(M||"").trim()).filter(Boolean).flatMap(M=>yn(M)).map(M=>String(M||"").trim()).filter(Boolean))];if(!h.length)return;const E=new Set(h);We(M=>M.length?[]:M),qe(aa.filter(M=>!E.has(M))),ds()},[ds,yn,aa]),J0=f.useCallback(h=>{const E=_n((Array.isArray(h)?h:[h]).map(O=>String(O||"").trim()).filter(Boolean));if(!E.length)return;const M=[...new Set(E.flatMap(O=>yn(O)).map(O=>String(O||"").trim()).filter(Boolean))];if(!M.length)return;const _=new Set(M);We(O=>O.length?[]:O),qe(aa.filter(O=>!_.has(O))),ds();for(const O of E)ua(O,{source:"tree"})},[ds,yn,ua,aa]),Q0=f.useCallback(()=>{aa.length&&(We(h=>h.length?[]:h),qe(aa),ds())},[ds,aa]),ex=f.useCallback(()=>{qe(h=>h.length?[]:h)},[]),bF=f.useCallback(h=>{const E=String(h||"").trim(),M=rr.get(E)||null;if(M&&Rl(M)){De(E),Rn("");return}if(ls){const _=E;if(!_){De(""),Rn("");return}De(""),Rn(la(_));return}De(E)},[rr,Rl,ls,la,Vo]),yF=f.useCallback((h,{multiSelect:E=!1}={})=>{if(Rt||Vo)return;const M=String(h||"").trim();if(!M){Va();return}const _=rr.get(M)||null;if(_&&Rl(_)){Lc(M,{multiSelect:E});return}if(ls){const O=M,F=la(O);if(!F){Va();return}Ju(F,{multiSelect:E,renderPartId:O});return}rr.has(M)&&Lc(M,{multiSelect:E})},[Va,rr,Rl,la,Rt,Lc,Ju,ls,Vo]),xF=f.useCallback(h=>{if(Rt||Vo||!Me)return;const E=String(h||"").trim();if(!E){Fc(),Va();return}if(!ls)return;const M=rr.get(E)||null;if(M&&Rl(M))return;const _=la(E);if(_){um(_);const O=oc(rn,_),F=Nae(O,E);De(""),Rn(F||_)}},[rn,Va,um,Fc,rr,Rl,ls,Me,la,Vo,Rt]),SF=f.useCallback(()=>{Ze(null)},[]);f.useEffect(()=>{Ze(null)},[k]);const xg=f.useCallback(({clientX:h=0,clientY:E=0}={})=>{if(!mr){Ze(null);return}const M=VT({root:Un,isAssemblyView:Me,expandedTreeNodeIds:jt,loadableTreeNodeIds:Rc,actionNodeIds:[]});Ze({x:Number(h)||0,y:Number(E)||0,global:!0,label:"Viewer",hidden:!0,showShowAll:dt.length>0,showCameraActions:!0,showExpandCollapse:M.showExpandCollapse||jt.length>0,collapsedExpandableTreeNodeIds:M.collapsedExpandableTreeNodeIds,expandedExpandableTreeNodeIds:jt,expandAllDisabled:M.collapsedExpandableTreeNodeIds.length<1,collapseAllDisabled:jt.length<1})},[Un,jt,dt.length,Me,mr,Rc]),EF=f.useCallback((h,{clientX:E=0,clientY:M=0}={})=>{if(Rt||Vo){Ze(null);return}const _=String(h||"").trim();if(!_){xg({clientX:E,clientY:M});return}const O=rr.get(_)||null;if(O&&Rl(O)){const oi=jn.current.includes(_),nx=_n(jn.current.map(zi=>String(zi||"").trim()).filter(Boolean)),fm=_n([...nx,_]),$M=fm.map(zi=>Io.get(zi)||rr.get(zi)||$l(zi,"topology")).filter(Boolean),rx=fm,tz=_n(an.current.map(zi=>String(zi||"").trim()).filter(Boolean).flatMap(zi=>yn(zi,zi))),GM=_n([...tz,...rx.map(zi=>Fi(rr.get(zi)||(zi===_?O:null))).filter(Boolean)]),nz=rx.length>0||GM.length>0,{lines:rz}=Fm(km({references:$M.length?$M:[O],parts:[],entry:ee}),{selectedReferenceIds:fm,copyReferenceMap:Io});Ze({x:Number(E)||0,y:Number(M)||0,referenceId:_,referenceIds:fm,label:String(O?.label||O?.displayName||_).trim(),selected:oi,hidden:!1,focused:!1,actionCount:fm.length||1,copyText:rz.join(` `),showIsolate:!1,showHideOther:!1,showVisibility:!1,showHideAll:!1,showCameraActions:!0,zoomToFitDisabled:!nz,fitReferenceIds:rx,fitPartIds:GM});return}if(!ls){xg({clientX:E,clientY:M});return}const F=la(_);if(!F){xg({clientX:E,clientY:M});return}const U=as.get(F)||oc(rn,F)||null,le=String(U?.displayName||U?.name||U?.label||F).trim(),Ce=yn(F,_),st=Ce.length>0&&Ce.every(oi=>dt.includes(oi)),tt=Nn.includes(F),Ot=an.current.includes(F),Gt=_n([...an.current.map(oi=>String(oi||"").trim()).filter(Boolean),F]),pn=_n(jn.current.map(oi=>String(oi||"").trim()).filter(Boolean)),Go=_n([...Gt.flatMap(oi=>yn(oi,oi===F?_:oi))]),da=pn.length>0||Go.length>0,Uo=VT({root:Un,isAssemblyView:Me,expandedTreeNodeIds:jt,loadableTreeNodeIds:Rc,actionNodeIds:Gt}),fa=Io.get(F)||rp(U,F,"assembly-part")||zT(U,F)||$l(F,"assembly-part"),{lines:dm}=Fm(km({references:fa?[fa]:[],parts:[],entry:ee}),{selectedPartIds:Gt,copyReferenceMap:Io});Ze({x:Number(E)||0,y:Number(M)||0,nodeId:F,renderPartId:_,label:le,selected:Ot,hidden:st,focused:tt,actionNodeIds:Gt,actionCount:Gt.length||1,copyText:dm[0]||"",selectDisabled:tt||!Ot&&st,showIsolate:!0,isolateDisabled:!1,showExitAllIsolate:Nn.length>1,exitAllIsolateDisabled:Nn.length<2,showHideOther:!0,hideOtherDisabled:st,showVisibility:!tt,visibilityDisabled:tt,showHideAll:!1,hideAllDisabled:!1,hideAllLabel:"Show all",showCameraActions:!0,zoomToFitDisabled:!da,fitPartIds:Go,fitReferenceIds:pn,showExpandCollapse:Uo.showExpandCollapse,collapsedActionNodeIds:Uo.collapsedActionNodeIds,expandedActionNodeIds:Uo.expandedActionNodeIds,collapsedExpandableTreeNodeIds:Uo.collapsedExpandableTreeNodeIds,expandedExpandableTreeNodeIds:Uo.expandedExpandableTreeNodeIds,expandSelectedDisabled:Uo.collapsedActionNodeIds.length<1,collapseSelectedDisabled:Uo.expandedActionNodeIds.length<1,expandAllDisabled:Uo.collapsedExpandableTreeNodeIds.length<1,collapseAllDisabled:Uo.expandedExpandableTreeNodeIds.length<1})},[as,rn,Un,Nn,rr,dt,Me,Rl,Rc,yn,xg,la,ee,Io,jt,Vo,Rt,ls]),wF=f.useCallback(async h=>{const E=String(h?.copyText||"").split(` `).map(M=>Gs(M)).filter(Boolean).join(` `);if(!E){ue("No selector ref is available for this node");return}try{await ps(E),ue("Copied reference")}catch(M){ue(M instanceof Error?M.message:"Failed to copy reference")}},[]),vF=f.useCallback(async(h,{topology:E=!1}={})=>{const M=String(h||"").trim();if(!M){ue("No selector ref is available for this node");return}const _=!E&&!Me&&M===hs?_S(ee):null,O=E&&(Io.get(M)||rr.get(M)||$l(M,"topology"))||null,F=!E&&!_?Io.get(M)||rp(hb({assemblyPartMap:as,displayStepTreeRoot:Un,stepTreeRoot:An,nodeId:M}),M,"assembly-part")||zT(hb({assemblyPartMap:as,displayStepTreeRoot:Un,stepTreeRoot:An,nodeId:M}),M)||$l(M,"assembly-part"):null,{lines:U}=Fm(km({references:[..._?[_]:[],...O?[O]:[],...F?[F]:[]],parts:[],entry:ee}),{selectedReferenceIds:E?[M]:[],selectedPartIds:E?[]:[M],copyReferenceMap:Io}),le=Gs(U[0]);if(!le){ue("No selector ref is available for this node");return}try{await ps(le),ue("Copied reference")}catch(Ce){ue(Ce instanceof Error?Ce.message:"Failed to copy reference")}},[as,Un,rr,Me,ee,Io,An]),CF=f.useCallback(async h=>{const E=String(h||"").trim(),M=E&&Al.get(E)||null;if(!M){ue("No selector ref is available for this mate");return}const _=KD(M);if(!_){ue("No selector ref is available for this mate");return}try{await ps(_),ue("Copied reference")}catch(O){ue(O instanceof Error?O.message:"Failed to copy reference")}},[Al,ee]),MF=f.useCallback(h=>{const E=String(h?.referenceId||"").trim();if(E){const O=_n((Array.isArray(h?.referenceIds)?h.referenceIds:[E]).map(F=>String(F||"").trim()).filter(Boolean));if(h?.selected===!0&&O.length>1){MM();return}Lc(E,{multiSelect:!1});return}const M=String(h?.nodeId||"").trim();if(!M)return;if(Nn.includes(M)){cm(M);return}const _=_n((Array.isArray(h?.actionNodeIds)?h.actionNodeIds:[M]).map(O=>String(O||"").trim()).filter(Boolean));if(h?.selected===!0){if(_.length>1){Va();return}cm(M);return}Ju(M,{renderPartId:String(h?.renderPartId||"").trim(),source:"viewer"})},[Va,MM,cm,Nn,Ju,Lc]),IF=f.useCallback(h=>{const E=String(h?.nodeId||"").trim();if(!E)return;if(h?.focused===!0){Z0(E);return}const M=_n((Array.isArray(h?.actionNodeIds)?h.actionNodeIds:[E]).map(_=>String(_||"").trim()).filter(Boolean));um(M)},[um,Z0]),AF=f.useCallback(h=>{const E=String(h?.nodeId||"").trim();if(!E)return;const M=_n((Array.isArray(h?.actionNodeIds)?h.actionNodeIds:[E]).map(_=>String(_||"").trim()).filter(Boolean));if(h?.selected===!0&&M.length>1){_M();return}for(const _ of M)AM(_)},[_M,AM]),NF=f.useCallback(h=>{const E=String(h?.nodeId||"").trim();if(!E)return;const M=_n((Array.isArray(h?.actionNodeIds)?h.actionNodeIds:[E]).map(_=>String(_||"").trim()).filter(Boolean));for(const _ of M)NM(_)},[NM]),_F=f.useCallback(h=>{const E=String(h?.nodeId||"").trim();if(!E)return;const M=_n((Array.isArray(h?.actionNodeIds)?h.actionNodeIds:[E]).map(_=>String(_||"").trim()).filter(Boolean));J0(M)},[J0]),TF=f.useCallback(h=>{if(h?.hidden===!0){ex();return}Q0()},[Q0,ex]),RF=f.useCallback(()=>{Oc.current?.resetZoom?.()||ue("CAD Viewer camera not ready")},[]),PF=f.useCallback(h=>{const E=_n((Array.isArray(h?.fitPartIds)?h.fitPartIds:[]).map(_=>String(_||"").trim()).filter(Boolean)),M=_n((Array.isArray(h?.fitReferenceIds)?h.fitReferenceIds:[]).map(_=>String(_||"").trim()).filter(Boolean));if(!E.length&&!M.length){ue("No geometry to fit");return}Oc.current?.zoomToFitSelection?.({partIds:E,referenceIds:M,animate:!0})||ue("No geometry to fit")},[]),OF=f.useCallback(h=>{for(const E of Array.isArray(h?.collapsedActionNodeIds)?h.collapsedActionNodeIds:[])Ba(E)},[Ba]),kF=f.useCallback(h=>{for(const E of Array.isArray(h?.expandedActionNodeIds)?h.expandedActionNodeIds:[])Ba(E)},[Ba]),DF=f.useCallback(h=>{for(const E of Array.isArray(h?.collapsedExpandableTreeNodeIds)?h.collapsedExpandableTreeNodeIds:[])Ba(E)},[Ba]),jF=f.useCallback(h=>{for(const E of Array.isArray(h?.expandedExpandableTreeNodeIds)?h.expandedExpandableTreeNodeIds:[])Ba(E)},[Ba]),tx=f.useCallback(h=>{const E=h?q.get(h):null;E&&Cm(Ep(E),{history:"push"}),im(h),ae||j(!1)},[im,q,ae,Cm]),TM=f.useCallback(h=>{const E=String(h||"").trim();E&&(om(),y(""),e_(E,{history:"push",preserveFile:!!(Cc&&d)}),Yp({markRefreshing:!0}).catch(M=>{}),vp())},[d,om,Cc]),RM=f.useCallback(h=>{const E=at(h);!E||!q.has(E)||(y(""),N(!0),lg(h),E!==k&&(Cm(Ep(h),{history:"push"}),im(E)),tg(!0))},[im,q,lg,tg,k,Cm]),LF=f.useCallback(h=>{Pt(!1);const E=h===oo.DRAW?oo.DRAW:oo.REFERENCES;Mr(E),E===oo.DRAW&&Zn===Jt.SURFACE_LINE&&qr(Jt.FREEHAND)},[Zn]);f.useCallback(()=>{!ee||!Fo||(Ve(h=>{const E=pb(h);return E.selectableTopologyEnabled?E:{...E,selectableTopologyEnabled:!0}}),Pt(!1),Mr(oo.REFERENCES))},[ee,Fo]);const FF=f.useCallback(()=>{_t&&(tm(!1),Pt(!1),po(h=>{const E=!h;return E&&!ae&&j(!1),E}))},[ae,_t,tm,po]),PM=f.useCallback((h,E="output",M=null)=>{const _=h?at(h):"",O=String(E||"output").trim()||"output";if(!_||typeof window>"u")return;const U=String(M?.downloadUrl||"").trim()||U1(_,O);ue(""),Qt("");const le=String(M?.filename||"").trim();try{const Ce=$S(U,{filename:le});ue(Ce.message)}catch(Ce){ue(Ce instanceof Error?Ce.message:"Download failed")}},[]),OM=f.useCallback(async(h,E="output",M=null,_="path")=>{const O=h?at(h):"",F=String(E||"output").trim()||"output",U=String(_||"").trim();if(O){ue(""),Qt("");try{let le="",Ce="Copied file reference";if(U==="link")le=String(M?.downloadUrl||"").trim()||U1(O,F,typeof window>"u"?v?.url:window.location.href),Ce="Copied link";else{const tt=rZ(M,v);U==="relativePath"?(le=tt.relativePath,Ce="Copied relative path"):(le=tt.path,Ce="Copied path")}if(!le)throw new Error("No file reference is available to copy");await ps(le);const st=String(M?.filename||"").trim();ue(st?`${Ce} for ${st}`:Ce)}catch(le){ue(le instanceof Error?le.message:"Failed to copy file reference")}}},[v]),kl=f.useCallback(async(h,E="output",M=null)=>{const _=h?at(h):"",O=String(E||"output").trim()||"output";if(!_||!oa||typeof window>"u")return;const F=sk(_,O),U=`${_}:${O}`;ue(""),Qt(""),gr(U);try{const le=await fetch(F,{method:"POST",cache:"no-store"});if(!le.ok)throw new Error(await Rae(le,`Failed to reveal file: ${le.status} ${le.statusText}`))}catch(le){ue(le instanceof Error?le.message:"Failed to reveal file")}finally{gr(le=>le===U?"":le)}},[oa]),kM=f.useCallback(async(h,E)=>{const M=h?at(h):"",_=String(E||"").trim().toLowerCase();if(!M||!_||typeof window>"u")return;const O=`${M}:export:${_}`,F=M===k?ei:null,U=M===k?Hf:null;ue(""),Qt(""),gr(O);try{ue(`Exporting ${_.toUpperCase()}...`);const le=await FJ({file:M,format:_,parameterValues:F,animationState:U,resolution:vk}),Ce=String(le?.filename||le?.result?.filename||"").trim(),st=String(le?.downloadUrl||"").trim();if(st){const tt=$S(st,{filename:Ce});ue(tt.message)}else ue(Ce?`Exported ${Ce}`:`Exported ${_.toUpperCase()}`)}catch(le){ue(le instanceof Error?le.message:"Implicit CAD export failed")}finally{gr(le=>le===O?"":le)}},[ei,Hf,k]),zF=f.useCallback(h=>{const E=pa(h),M=La.current;jv(M,E)||(Lr(_=>[..._,pa(M)]),is([]),co(E))},[]),BF=f.useCallback(h=>{Mr(oo.DRAW),qr(h===Jt.SURFACE_LINE?Jt.FREEHAND:h)},[]),DM=f.useCallback(()=>{const h=Zf.current;if(!h.length)return;const E=pa(h[h.length-1]),M=pa(La.current);Lr(h.slice(0,-1)),is(_=>[..._,M]),co(E)},[]),jM=f.useCallback(()=>{const h=Jf.current;if(!h.length)return;const E=pa(h[h.length-1]),M=pa(La.current);is(h.slice(0,-1)),Lr(_=>[..._,M]),co(E)},[]),VF=f.useCallback(()=>{La.current.length&&(Lr(h=>[...h,pa(La.current)]),is([]),co([]))},[]),$F=f.useCallback(h=>{const E=Bs(h);E&&(kc.current=E,ag()),(La.current.length>0||Zf.current.some(_=>_.length>0)||Jf.current.some(_=>_.length>0))&&(La.current=[],Zf.current=[],Jf.current=[],co([]),Lr([]),is([]))},[ag]);hie({copyStatus:xn,screenshotStatus:vr,setCopyStatus:ue,setScreenshotStatus:Qt,previewMode:Xt,viewerAlertOpen:It,themeSheetOpen:!1,tabToolsOpen:Fa,isDesktop:ae,sidebarOpen:br,previewUiStateRef:V0,tabToolMode:ar,drawingUndoStackRef:Zf,drawingRedoStackRef:Jf,handleUndoDrawing:DM,handleRedoDrawing:jM,setPreviewMode:os,setViewerAlertOpen:Pt,setThemeMenuOpen:tm,setTabToolsOpen:po,setSidebarOpen:j,setTabToolMode:Mr});const LM=f.useCallback(async()=>{if(ee)try{const h=`${at(ee).replace(/[^a-zA-Z0-9._-]+/g,"-")}.png`;if(!Oc.current?.captureScreenshot)throw new Error("CAD Viewer not ready");await Oc.current.captureScreenshot({filename:h,mode:"clipboard"}),ue(""),Qt("Copied screenshot to clipboard")}catch(h){ue(""),Qt(h instanceof Error?h.message:"Clipboard copy failed")}},[ee]),GF=f.useCallback(()=>{const h=Ye===B.IMPLICIT?!!Tc:!!Fr;Ye===B.DXF||Da||!h||Xt||(V0.current={sidebarOpen:br,tabToolsOpen:Fa,tabToolMode:ar,themeMenuOpen:!1,viewerAlertOpen:It},ue(""),Qt(""),co([]),Lr([]),is([]),Pt(!1),tm(!1),j(!1),po(!1),os(!0))},[Ye,Xt,br,tm,po,Tc,Fr,ar,Fa,It,Da]),UF=h=>{N(!0),I(E=>{const M=new Set(E);return M.has(h)?M.delete(h):M.add(h),M})},WF=Ye===B.STEP&&ar===oo.REFERENCES,FM=EL,HF=wL,ed=String(Ae[Ae.length-1]||"").trim(),zM=f.useMemo(()=>ed?Fi(rr.get(ed)):"",[ed,rr,Fi]),KF=f.useMemo(()=>ed?$T(Un,ed)||zM:"",[ed,zM,Un]),XF=Te[Te.length-1]||KF,YF=Qs.length>0,qF=ko.length>0,zc=!!_t&&Fa&&!Xt,BM=cs?rM.sidebarWidth:0,Bc=Rs?rM.sheetWidth:0,ZF=ae&&cs?BM:ae?md({viewportWidth:te,sidebarOpen:!0,sheetOpen:!1,sidebarWidth:de,sheetWidth:0,sidebarMinWidth:Vl,sheetMinWidth:Uc,sidebarMaxWidth:yd,sheetMaxWidth:xd}).sidebarWidth:mb,VM={top:Xt?0:fae,right:Bc,bottom:0,left:BM},JF={top:"14px",right:"14px"},QF=[{id:Jt.FREEHAND,label:"Freehand",Icon:uR},{id:Jt.LINE,label:"Line",Icon:PE},{id:Jt.ARROW,label:"Arrow",Icon:$3},{id:Jt.DOUBLE_ARROW,label:"Expand",Icon:G3},{id:Jt.RECTANGLE,label:"Rectangle",Icon:U3},{id:Jt.CIRCLE,label:"Circle",Icon:W3},{id:Jt.FILL,label:"Fill",Icon:H3},{id:Jt.ERASE,label:"Erase",Icon:K3}],ez=mr?vt:null,td=c.jsxs(c.Fragment,{children:[mr?c.jsx(WQ,{displaySettings:vt,updateDisplaySettings:Ti,clipBounds:Fr?.bounds||null,showClip:!0}):null,c.jsx(HQ,{themePresets:Kt,themeSettings:Se,themePresetId:Yr,resolvedColorSchemeMode:it,updateThemeSettings:eg,handleResetThemeSettings:YC,handleSaveCustomThemePreset:qC,handleUpdateThemePresetSettings:ZC})]});return c.jsxs(QB,{open:em,onOpenChange:tg,mobileOpen:em,onMobileOpenChange:tg,"data-glass-tone":_r,style:{"--sidebar-width":`${ZF}px`},className:"relative h-svh overflow-hidden bg-transparent",children:[c.jsx("div",{className:"fixed inset-0 z-0",children:c.jsx(UX,{viewerRef:Oc,renderFormat:Ye,renderPartsIndividually:C0||!!PC,stepParameters:PC,selectedMeshData:Fr,selectedDxfData:tr,selectedDxfMeshData:hL,dxfViewMode:$,onDxfViewModeChange:ie,selectedImplicitModel:Tc,implicitDynamicRenderActive:oL,implicitGraphicsSettings:Tu,selectedKey:k,selectedDxfKey:gL,missingFileRef:gC,viewerPerspective:mi,viewerPerspectiveRef:kc,themeSettings:ft,displaySettings:ez,onProjectionChange:mr?Pa:void 0,onDisplayModeChange:mr?Ra:void 0,previewMode:Xt,viewportFrameInsets:VM,viewerLoading:Da,viewerAlert:Tl,stepUpdateInProgress:Ye===B.STEP&&Rt,referenceSelectionPending:gg,referenceSelectionUnavailable:X0,referenceSelectionDeferred:sm,viewPlaneOffsetRight:VM.right+16,viewerMode:SL,assemblyPickingActive:ls,assemblyParts:JL,hiddenPartIds:ZL,selectedPartIds:XL,hoveredPartId:YL,assemblyMates:Hh,selectedMateIds:ct,hoveredMateId:xe,hoveredReferenceId:bM,selectedReferenceIds:Ae,selectorRuntime:K0,displayEdgeRuntime:FL,pickableFaces:mM,pickableEdges:pM,pickableVertices:hM,focusedPartIds:qL,boundsAnimationActive:zj,drawToolActive:FM,drawingTool:Zn,drawingStrokes:pi,handleDrawingStrokesChange:zF,handlePerspectiveChange:$F,handleModelHoverChange:bF,handleModelReferenceActivate:yF,handleModelReferenceDoubleActivate:xF,handleModelReferenceContext:EF,viewerContextMenu:ze,onViewerContextMenuClose:SF,onViewerContextMenuCopyReference:wF,onViewerContextMenuSelect:MF,onViewerContextMenuFocus:IF,onViewerContextMenuExitAllIsolate:Fc,onViewerContextMenuHideOther:_F,onViewerContextMenuHideAll:TF,onViewerContextMenuHide:AF,onViewerContextMenuReveal:NF,onViewerContextMenuResetZoom:RF,onViewerContextMenuZoomToFit:PF,onViewerContextMenuExpandSelected:OF,onViewerContextMenuCollapseSelected:kF,onViewerContextMenuExpandAll:DF,onViewerContextMenuCollapseAll:jF,handleViewerAlertChange:NL,handleStepModuleTransformDetectedChange:Hj,selectionCount:HF,copyButtonLabel:uF,handleCopySelection:dF,handleScreenshotCopy:LM,urdfPosePicker:C0&&ju?{active:_c,center:dae,onPickPoint:lF,onCancel:Zu}:null})}),c.jsxs(t5,{className:"pointer-events-none relative z-10 h-svh min-w-0 overflow-hidden bg-transparent",children:[c.jsx(Dte,{previewMode:Xt,sidebarLabelForEntry:dl,directoryTree:S0,selectedKey:k,selectedEntry:ee,onSelectEntry:tx,entrySourceFormat:or,entryHasMesh:qc,entryHasDxf:vm,entryHasGcode:Yg,entryHasUrdf:Xg,activeGenerationFiles:p,activeStepArtifactGenerationFile:bC,stepArtifactGenerationAvailable:Df,themePresets:Kt,themeSettings:Se,themePresetId:Yr,resolvedColorSchemeMode:it,onColorSchemePreferenceChange:CL,updateThemeSettings:eg,handleResetThemeSettings:YC,handleSaveCustomThemePreset:qC,handleUpdateThemePresetSettings:ZC,handleDeleteCustomThemePreset:ML,handleEditThemePreset:PL,handleResetThemePresetToDefault:IL,handleRestoreDefaultThemePresets:AL,filenameLoadActivity:KL,selectedStepSourceStatus:Of,canRevealFileAssets:oa,canCopyFileAssetLinks:vl,canCopyFileAssetPaths:SC,fileAccessBusyKey:In,onDownloadFileAsset:PM,onExportImplicitFile:kM,onRevealFileAsset:kl,onRevealInExplorerView:RM,onCopyFileAssetReference:OM,fileSheetKind:_t,fileSheetOpen:zc,onToggleFileSheet:FF,navigationAvailable:w0}),c.jsx("div",{className:"pointer-events-none relative min-h-0 flex-1 overflow-hidden",children:c.jsxs("div",{className:"flex h-full min-w-0",children:[w0?c.jsx(XJ,{previewMode:Xt,query:x,onQueryChange:y,filteredEntries:x0,catalogEntries:l,filteredEntriesTree:jj,selectedKey:k,expandedDirectoryIds:b,onToggleDirectory:UF,onSelectEntry:tx,entrySourceFormat:or,entryHasMesh:qc,entryHasDxf:vm,entryHasGcode:Yg,entryHasUrdf:Xg,activeGenerationFiles:p,activeStepArtifactGenerationFile:bC,stepArtifactGenerationAvailable:Df,canRevealFileAssets:oa,canCopyFileAssetLinks:vl,canCopyFileAssetPaths:SC,fileAccessBusyKey:In,onDownloadFileAsset:PM,onExportImplicitFile:kM,onRevealFileAsset:kl,onRevealInExplorerView:RM,onCopyFileAssetReference:OM,catalogHydrated:r,catalogRefreshing:o,catalogError:i,directoryOptions:kf,activeDirectory:yC||u||"",onSelectDirectory:TM,resizable:ae,onStartResize:RL}):null,c.jsxs("div",{className:"pointer-events-none relative min-w-0 flex-1 overflow-hidden",children:[c.jsx(ote,{previewMode:Xt,selectedEntry:ee,renderFormat:Ye,floatingCadToolbarPosition:JF,selectionToolActive:WF,referenceSelectionPending:gg,referenceSelectionUnavailable:X0,referenceSelectionDeferred:sm,urdfPosePickerAvailable:ju,urdfPosePickerActive:_c,handleToggleUrdfPosePicker:EM,stepAnimationAvailable:Vj,stepAnimationPlaying:Wh.playing,stepAnimationDisabled:!$r,handleStepAnimationPlayToggle:OC,drawToolActive:FM,handleSelectTabToolMode:LF,displayMode:mr?vt.mode:void 0,onDisplayModeChange:mr?Ra:void 0,projection:mr?vt.projection:void 0,onProjectionChange:mr?Pa:void 0,viewerLoading:Da,selectedMeshData:Fr,selectedDxfData:tr,selectedImplicitModel:Tc,drawingToolOptions:QF,drawingTool:Zn,handleSelectDrawingTool:BF,handleUndoDrawing:DM,handleRedoDrawing:jM,handleClearDrawings:VF,canUndoDrawing:YF,canRedoDrawing:qF,drawingStrokes:pi,handleEnterPreviewMode:GF,handleScreenshotCopy:LM}),!Xt&&(Cc||!ee&&!gC&&!hC)?c.jsx(Wte,{entries:l,onSelectEntry:tx,catalogHydrated:r,catalogRefreshing:o,catalogError:i,directorySelectionActive:Cc,directoryOptions:kf,onSelectDirectory:TM}):null,c.jsx(Yee,{viewerLoading:yL,previewMode:Xt})]}),_t==="dxf"?c.jsx(VZ,{open:zc,isDesktop:ae,width:Bc||kn,onOpenChange:po,selectedEntry:ee,onStartResize:Bu,valueMm:qf,bendLines:pL,bendSettings:Yf,hasDxfData:!!tr,viewerLoading:Da,onThicknessChange:G,onBendChange:OL,fileDownloadAvailable:vl,viewerServerInfo:v,localFileOpenAvailable:oa,fileAccessBusyKey:In,onOpenFileAsset:kl,suppressDynamicMetadataStatus:ri,statusItems:za,themeSections:td,openSectionIds:ca,onOpenSectionIdsChange:Vu},`dxf:${k}`):null,_t==="gcode"?c.jsx(SJ,{open:zc,isDesktop:ae,width:Bc||kn,onOpenChange:po,selectedEntry:ee,onStartResize:Bu,gcodeData:ia,previewMetadata:TC?.metadata||null,maxLayer:Wf,showTravel:W,fullDetail:be,previewDetailLevel:Ie,onMaxLayerChange:re,onShowTravelChange:Z,onFullDetailChange:_e,onPreviewDetailLevelChange:oe,fileDownloadAvailable:vl,viewerServerInfo:v,localFileOpenAvailable:oa,fileAccessBusyKey:In,onOpenFileAsset:kl,suppressDynamicMetadataStatus:ri,statusItems:za,themeSections:td,openSectionIds:ca,onOpenSectionIdsChange:Vu},`gcode:${k}`):null,_t==="step"?c.jsx(Oee,{open:zc,isDesktop:ae,width:Bc||kn,onOpenChange:po,onStartResize:Bu,selectedEntry:ee,viewerLoading:Da||z0,isAssemblyView:Me,stepTreeRoot:Un,assemblyMates:Hh,expandedTreeNodeIds:jt,stepTreeRootShowMore:sn,onStepTreeRootShowMoreChange:Mn,loadableTreeNodeIds:Rc,selectedPartIds:Te,selectedReferenceIds:Ae,selectedMateIds:ct,selectableNodeIds:WL,activeTreeNodeId:XF,activeTreeNodeScrollKey:fn,hoveredPartId:Uu,hoveredReferenceId:bM,hoveredMateId:xe,hiddenPartIds:dt,focusedNodeIds:Nn,onSelectTreeNode:fF,onSelectReferenceNode:mF,onSelectMateNode:pF,onCopyTreeNodeReference:vF,onCopyMateNodeReference:CF,onFocusTreeNode:um,onUnfocusTreeNode:Z0,onExitAllIsolate:Fc,onHideOtherTreeNode:J0,onToggleTreeNode:Ba,onClearSelection:Va,onHoverTreeNode:Xe,onHoverReferenceNode:wt,onHoverMateNode:yt,treeSelectionDisabled:Vo,treeSelectionDisabledReason:Kj,onTogglePartVisibility:hF,hideOtherSelectedParts:gF,hideAllParts:Q0,showAllHiddenParts:ex,exitIsolate:Fc,stepModule:{status:_h,error:M0,definition:$t,enabled:$r,parameterValues:Qo,animationState:Wh,onParameterChange:Xj,onResetParameters:Zj,onAnimationSelect:Jj,onAnimationPlayToggle:OC,onAnimationReset:Qj,onAnimationScrub:eL,onAnimationSpeedChange:tL,onEnabledChange:nL,onCopyParams:Yj,onPasteParams:qj},fileDownloadAvailable:vl,viewerServerInfo:v,localFileOpenAvailable:oa,fileAccessBusyKey:In,onOpenFileAsset:kl,suppressDynamicMetadataStatus:ri,statusItems:za,themeSections:td,openSectionIds:ca,onOpenSectionIdsChange:Vu},`step:${k}`):null,_t==="urdf"||_t==="srdf"||_t==="sdf"?c.jsx(Hee,{open:zc,title:_t==="srdf"?"SRDF":_t==="sdf"?"SDF":"URDF",sourceFormat:_t,showJoints:_t==="urdf"||_t==="srdf"||_t==="sdf",showMotion:_t==="srdf",isDesktop:ae,width:Bc||kn,selectedEntry:ee,onOpenChange:po,onStartResize:Bu,joints:Uh,groupStates:Gf,activeGroupStateId:Uj,jointValues:nr,onJointValueChange:QL,onGroupStateSelect:tF,onCopyJointAngles:cF,onResetPose:eF,motion:_t==="srdf"&&Nc?{srdf:Nc.srdf,endEffectors:Cl,planningGroups:Vh,targetFrames:Uf,activeEndEffectorName:mn,activePlanningGroupName:Bo.planningGroup,activeTargetFrameName:Bo.targetFrame,targetPosition:sa,currentPosition:Lu,solving:Wj,serverLive:On,actionsEnabled:ju,moveit2:Bo,selectPoseActive:_c,onEndEffectorChange:nF,onMoveIt2SettingChange:rF,onTargetPositionChange:oF,onUseCurrentPosition:iF,onSolve:sF,onPlan:aF,onSelectPose:EM,onCancelSelectPose:Zu}:null,sdf:_t==="sdf"?{info:mt?.sdf||null}:null,fileDownloadAvailable:vl,viewerServerInfo:v,localFileOpenAvailable:oa,fileAccessBusyKey:In,onOpenFileAsset:kl,suppressDynamicMetadataStatus:ri,statusItems:za,themeSections:td,openSectionIds:ca,onOpenSectionIdsChange:Vu},`${_t}:${k}`):null,_t==="mesh"?c.jsx(KQ,{open:zc,title:mo===B.THREE_MF?"3MF":mo===B.GLB?"GLB":"STL",isDesktop:ae,width:Bc||kn,selectedEntry:ee,onOpenChange:po,onStartResize:Bu,fileDownloadAvailable:vl,viewerServerInfo:v,localFileOpenAvailable:oa,fileAccessBusyKey:In,onOpenFileAsset:kl,suppressDynamicMetadataStatus:ri,statusItems:za,themeSections:td,openSectionIds:ca,onOpenSectionIdsChange:Vu},`mesh:${k}`):null,_t==="implicit"?c.jsx(iee,{open:zc,title:"Implicit CAD",isDesktop:ae,width:Bc||kn,selectedEntry:ee,onOpenChange:po,onStartResize:Bu,parameterRuntime:{status:ni===ke.LOADING?"loading":Fu?"error":Yt?"ready":"idle",error:Fu,definition:Yt,parameterValues:ei,animationState:Hf,onParameterChange:iL,onResetParameters:lL,onAnimationSelect:cL,onAnimationPlayToggle:uL,onAnimationReset:dL,onAnimationScrub:fL,onAnimationSpeedChange:mL,onCopyParams:sL,onPasteParams:aL},graphicsRuntime:{model:Tc,settings:Tu,onSettingsChange:Cr},fileDownloadAvailable:vl,viewerServerInfo:v,localFileOpenAvailable:oa,fileAccessBusyKey:In,onOpenFileAsset:kl,suppressDynamicMetadataStatus:ri,statusItems:za,themeSections:td,openSectionIds:ca,onOpenSectionIdsChange:Vu},`implicit:${k}`):null]})}),c.jsx(Fee,{copyStatus:xn,screenshotStatus:vr,persistenceStatus:lo,motionErrorStatus:gt,previewMode:Xt,onClear:()=>{ue(""),Qt(""),Mt(""),Sn(""),_f.current=""}}),c.jsx(Xee,{viewerAlertOpen:It,viewerAlert:Tl,previewMode:Xt,setViewerAlertOpen:Pt})]})]})}const Lae="/assets/favicon-DLqji3p4.ico",HT="root",KT="__cadViewerRoot";function Fae(){if(typeof document>"u")return;let e=document.querySelector('link[rel="icon"]');e||(e=document.createElement("link"),e.rel="icon",document.head.appendChild(e)),e.type="image/x-icon",e.href=`${Lae}?v=planetary-gear-workbench`}function zae(){const e=document.getElementById(HT);if(!e)throw new Error(`Missing #${HT} mount point.`);Fae(),document.title="CAD Viewer";const t=globalThis[KT],n=t?.element===e&&t?.root?t.root:oz.createRoot(e);globalThis[KT]={element:e,root:n},n.render(c.jsx(f.StrictMode,{children:c.jsx(Bae,{})}))}function Bae(){const{manifest:e,generationStatus:t,revision:n,catalogHydrated:r,catalogRefreshing:o,catalogError:i,activeDir:s}=f.useSyncExternalStore(DJ,S_,S_);return c.jsx(jae,{manifestRevision:n,manifestEntries:e.entries,generationStatus:t,catalogHydrated:r,catalogRefreshing:o,catalogError:i,activeDir:s})}zae();export{OD as i,Fd as m,Hae as p}; //# sourceMappingURL=index-BkFzql5p.js.map