@wayrisignals/kicad-webview
Version:
Interactive KiCad schematic, PCB and 3D viewer for the web, with Gerber, Excellon, linked views and offline HTML exports
4 lines (3 loc) • 42.7 kB
JavaScript
/*! KiCad WebView 1.2.1 | Copyright (c) 2026 wayri | SPDX-License-Identifier: MPL-2.0 | Source: https://github.com/wayri/kicad-webview/tree/v1.2.1 | Keep LICENSE and THIRD-PARTY-NOTICES.md; bundled dependencies retain their licenses. */
import{b as Le}from"./chunks/chunk-V2ND4NUF.js";import{a as De,b as X,c as J,d as Z,e as ge,f as we,g as Q,h as be,i as ze}from"./chunks/chunk-T357SPI3.js";import{a as ye}from"./chunks/chunk-KOT5IEJZ.js";import"./chunks/chunk-JQFHUX53.js";import{f as B}from"./chunks/chunk-AXOGACE7.js";import{b as Be}from"./chunks/chunk-LCG4X7QG.js";import"./chunks/chunk-FHIEKW7H.js";import"./chunks/chunk-FPOLRSV2.js";import"./chunks/chunk-TZWR7E27.js";var je="1.0";var se=class extends EventTarget{constructor(t,{viewer:r,slides:n,interval:c=5e3}={}){super();let s=typeof t=="string"?document.querySelector(t):t;if(!s?.ownerDocument||!s.append)throw new TypeError("Choose a carousel controls container.");if(!r||typeof r.setView!="function")throw new TypeError("Supply an existing KiCadViewer.");if(!Array.isArray(n)||n.length<1||n.length>100)throw new TypeError("Choose 1 to 100 presentation slides.");if(!Number.isFinite(c)||c<1e3||c>36e5)throw new TypeError("Choose an interval from 1000 to 3600000 milliseconds.");this.slides=n.map((a,g)=>{if(!a||typeof a!="object"||typeof a.label!="string"||!a.label.trim()||a.label.length>500)throw new TypeError("Each slide needs a label of 1 to 500 characters.");if(a.view!==void 0&&!["pcb","schematic","3d","manufacturing"].includes(a.view))throw new TypeError("Choose a supported slide view.");if("source"in a&&("input"in a||typeof a.source!="string"))throw new TypeError("Choose either source text or a load input.");if(a.camera&&a.view==="3d")throw new TypeError("Programmable cameras require a 2D drawing view.");if(a.camera3D!==void 0&&!["top","bottom","front","back","left","right","isometric"].includes(a.camera3D))throw new TypeError("Choose a named 3D camera preset.");if(a.camera3D!==void 0&&(a.camera||a.view!==void 0&&a.view!=="3d"))throw new TypeError("3D camera presets require a 3D view without a 2D camera.");if(a.net!==void 0&&(typeof a.net!="string"||!a.net||a.net.length>1e3))throw new TypeError("Choose a saved net name.");return{...a,options:{...a.options},camera:a.camera?{...a.camera,center:{...a.camera.center}}:void 0}}),this.viewer=r,this.host=s,this.doc=s.ownerDocument,this.interval=c,this.index=-1,this.requestedIndex=-1,this.ticket=0,this.disposed=!1,this.playing=!1,this.queue=Promise.resolve(),this.listeners=[];let i=(a,g)=>{let b=this.doc.createElement(a);return g!==void 0&&(b.textContent=g),b};this.root=i("section"),this.root.setAttribute("aria-label","Drawing presentation"),this.root.style.cssText="display:flex;align-items:center;flex-wrap:wrap;gap:8px;font:inherit";let o=(a,g)=>{let b=i("button",a);return b.type="button",b.setAttribute("aria-label",a),b.onclick=()=>{this.pause(),Promise.resolve().then(g).catch(()=>{})},b};this.previousButton=o("Previous slide",()=>this.previous()),this.nextButton=o("Next slide",()=>this.next()),this.playButton=o("Play presentation",()=>this.play()),this.playButton.onclick=()=>{this.playing?this.pause():this.play()},this.label=i("span","Choose a slide"),this.label.setAttribute("role","status"),this.label.setAttribute("aria-live","polite"),this.label.setAttribute("aria-atomic","true"),this.root.append(this.previousButton,this.label,this.nextButton,this.playButton),s.append(this.root),this.motion=this.doc.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)");let d=(a,g,b)=>{a?.addEventListener?.(g,b),this.listeners.push(()=>a?.removeEventListener?.(g,b))};d(this.motion,"change",()=>{this.motion.matches&&this.pause(),this.refresh()}),d(this.doc,"visibilitychange",()=>{this.doc.hidden&&this.pause()}),d(this.root,"focusin",()=>this.pause()),this.refresh()}assertActive(){if(this.disposed)throw new Error("Carousel has been disposed.")}emit(t,r){this.dispatchEvent(new CustomEvent(t,{detail:r}))}refresh(){this.previousButton.disabled=this.requestedIndex<=0,this.nextButton.disabled=this.requestedIndex>=this.slides.length-1,this.playButton.disabled=this.slides.length<2||!!this.motion?.matches,this.playButton.textContent=this.playing?"Pause presentation":"Play presentation",this.playButton.setAttribute("aria-label",this.playButton.textContent),this.playButton.setAttribute("aria-pressed",String(this.playing))}show(t){if(this.assertActive(),!Number.isInteger(t)||t<0||t>=this.slides.length)throw new RangeError("Choose a slide index in the presentation.");let r=++this.ticket;this.requestedIndex=t,this.pending?.abort(),clearTimeout(this.timer),this.refresh();let n=()=>!this.disposed&&r===this.ticket,c=async()=>{if(!n())return!1;let i=this.slides[t],o=new AbortController;this.pending=o,this.root.setAttribute("aria-busy","true");try{let d;if("input"in i?d=await this.viewer.load(i.input,{...i.options,view:i.view,signal:o.signal}):"source"in i&&(d=await this.viewer.loadSource(i.source,{...i.options,view:i.view,signal:o.signal})),!n()||d===!1||i.view!==void 0&&this.viewer.view!==i.view&&(d=await this.viewer.setView(i.view),!n()||d===!1))return!1;if(i.camera&&this.viewer.setCamera(i.camera),i.camera3D!==void 0&&this.viewer.setCamera3D(i.camera3D),i.clearSelection&&this.viewer.clearSelection(),i.net!==void 0&&!this.viewer.selectNet(i.net))throw new Error("Saved net is absent from this drawing: "+i.net);return n()?(this.index=t,this.label.textContent=t+1+" / "+this.slides.length+" \xB7 "+i.label,this.emit("slidechange",{index:t,label:i.label}),!0):!1}catch(d){if(!n()||o.signal.aborted)return!1;throw this.pause(),this.label.textContent="Unable to show "+i.label+": "+d.message,this.emit("error",{index:t,error:d}),d}finally{n()&&(this.pending=null,this.root.setAttribute("aria-busy","false"),this.schedule())}},s=this.queue.then(c);return this.queue=s.catch(()=>{}),s}next(){return this.assertActive(),this.show(Math.min(this.slides.length-1,this.requestedIndex+1))}previous(){return this.assertActive(),this.show(Math.max(0,this.requestedIndex-1))}play(){return this.assertActive(),this.motion?.matches||this.doc.hidden||this.slides.length<2?!1:(this.playing=!0,this.refresh(),this.requestedIndex<0?this.show(0).catch(()=>{}):this.queue.then(()=>this.schedule()),!0)}schedule(){clearTimeout(this.timer),!this.disposed&&this.playing&&(this.timer=setTimeout(()=>{!this.disposed&&this.playing&&this.show((this.requestedIndex+1)%this.slides.length).catch(()=>{})},this.interval))}pause(){this.disposed||(this.playing=!1,clearTimeout(this.timer),this.refresh())}dispose(){this.disposed||(this.pause(),this.disposed=!0,++this.ticket,this.pending?.abort(),this.listeners.forEach(t=>t()),this.listeners=[],this.previousButton.onclick=this.nextButton.onclick=this.playButton.onclick=null,this.root.remove())}};var ne="kicad-webview.views/v1",oe=16384,ve=8,S=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function H(e,t,r){if(!e||typeof e!="object"||Array.isArray(e)||![Object.prototype,null].includes(Object.getPrototypeOf(e)))throw new TypeError("Invalid "+r+".");if(Object.keys(e).some(n=>!t.includes(n)))throw new TypeError("Unsupported field in "+r+".");return e}function U(e,t,r,n=!1){if(typeof e!="string"||e.length>t||!n&&!e.length||/[\x00-\x1f\x7f]/.test(e))throw new TypeError("Invalid "+r+".");return e}function $(e,t,r,n){if(typeof e!="number"||!Number.isFinite(e)||e<t||e>r)throw new TypeError("Invalid "+n+".");return e}function Ve(e){if(U(e,1024,"drawing path",!0),e&&(e.startsWith("/")||e.includes("%")||/[\?#:]/.test(e)||e.split("/").some(t=>!t||t==="."||t==="..")))throw new TypeError("Choose a project-relative drawing path.");return e}function Ue(e){if(H(e,["center","zoom","flipped"],"2D camera"),H(e.center,["x","y"],"2D camera center"),typeof e.flipped!="boolean")throw new TypeError("Invalid flipped camera state.");return{center:{x:$(e.center.x,-1e6,1e6,"camera x"),y:$(e.center.y,-1e6,1e6,"camera y")},zoom:$(e.zoom,.001,1e4,"camera zoom"),flipped:e.flipped}}function He(e){return H(e,["position","target","up"],"3D camera"),ye(e)}function Re(e){if(e===null)return null;H(e,["kind","uuid","ownerUuid","id","netName","pinNumber"],"selection");let t={kind:U(e.kind,64,"selection kind")};for(let r of["uuid","ownerUuid","id","netName"])S(e,r)&&(t[r]=U(e[r],r==="id"?2048:1024,"selection "+r));if(S(e,"pinNumber")&&(t.pinNumber=typeof e.pinNumber=="number"?$(e.pinNumber,-1e6,1e6,"pin number"):U(e.pinNumber,64,"pin number")),t.kind==="net"?!t.id&&!t.netName:!t.uuid&&!t.id&&!t.ownerUuid)throw new TypeError("Selection needs a saved identity.");return t}function K(e){if(H(e,["schema","views","theme","layout","activePane","linkedSelection"],"view state"),e.schema!==ne)throw new TypeError("Unsupported view-state schema.");if(!Array.isArray(e.views)||e.views.length<1||e.views.length>ve)throw new TypeError("Choose 1 to 8 linked views.");let t={schema:ne,views:e.views.map(r=>{if(H(r,["path","sha256","view","camera","camera3D","layers","selection","instancePath","expand"],"saved view"),!["pcb","schematic","3d"].includes(r.view))throw new TypeError("View links support native KiCad views only.");if(typeof r.sha256!="string"||!/^[a-f0-9]{64}$/.test(r.sha256))throw new TypeError("Invalid source SHA-256.");let n={path:Ve(r.path),sha256:r.sha256,view:r.view};if(S(r,"instancePath")){if(r.view!=="schematic")throw new TypeError("Sheet occurrence requires a schematic view.");if(n.instancePath=r.instancePath===null?null:U(r.instancePath,8192,"sheet instance path"),n.instancePath!==null&&!n.instancePath.startsWith("/"))throw new TypeError("Choose a saved UUID instance path.")}if(S(r,"expand")){if(r.view!=="3d")throw new TypeError("Expansion requires a 3D view.");n.expand=$(r.expand,0,100,"expansion")}if(S(r,"camera")){if(r.view==="3d")throw new TypeError("Use a 3D camera for the 3D view.");n.camera=Ue(r.camera)}if(S(r,"camera3D")){if(r.view!=="3d")throw new TypeError("A 3D camera requires the 3D view.");n.camera3D=He(r.camera3D)}if(S(r,"layers")){if(r.view!=="pcb"||!Array.isArray(r.layers)||r.layers.length>128)throw new TypeError("Layer state requires a bounded PCB layer list.");if(n.layers=r.layers.map(c=>U(c,128,"saved layer")),new Set(n.layers).size!==n.layers.length)throw new TypeError("Duplicate saved layers.")}return S(r,"selection")&&(n.selection=Re(r.selection)),n})};if(S(e,"theme")){if(!["light","dark"].includes(e.theme))throw new TypeError("Invalid view theme.");t.theme=e.theme}if(S(e,"layout")){if(!["single","split"].includes(e.layout))throw new TypeError("Invalid view layout.");t.layout=e.layout}if(S(e,"activePane")){if(!Number.isInteger(e.activePane)||e.activePane<0||e.activePane>=t.views.length)throw new TypeError("Invalid active view.");t.activePane=e.activePane}if(S(e,"linkedSelection")){if(typeof e.linkedSelection!="boolean")throw new TypeError("Invalid selection linkage.");t.linkedSelection=e.linkedSelection}if(encodeURIComponent(JSON.stringify(t)).length+11>oe)throw new TypeError("View state is too large for a link.");return t}async function ke(e){if(!globalThis.crypto?.subtle)throw new Error("View links require Web Crypto on HTTPS or localhost.");return[...new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)))].map(t=>t.toString(16).padStart(2,"0")).join("")}function Ee(e){if(!Array.isArray(e)||!e.length||e.length>ve||new Set(e).size!==e.length)throw new TypeError("Supply 1 to 8 distinct viewers.");for(let t of e)if(t.assertActive?.(),typeof t.source!="string"||!["pcb","schematic"].includes(t.kind)||!["pcb","schematic","3d"].includes(t.view))throw new TypeError("Load native KiCad drawings before using view links.");return e}function qe(e){if(!e)return null;let t={kind:e.kind};for(let r of["uuid","ownerUuid","id","netName","pinNumber"])e[r]!==void 0&&e[r]!==""&&(t[r]=e[r]);return t}async function Oe(e,t={}){Ee(e);let r=e.map(i=>({source:i.source,path:i.path||"",view:i.view,renderer:i.renderer,generation:i.generation,instancePath:i.textInstancePath??null})),n=e.map((i,o)=>{let d={path:r[o].path,view:i.view,selection:qe(i.getSelection?.())};i.view==="schematic"&&(d.instancePath=i.textInstancePath??null),i.view==="3d"&&typeof i.getExpand=="function"&&(d.expand=i.getExpand());let a=i.view==="3d"?i.getCamera3D?.():i.getCamera?.();return a&&(d[i.view==="3d"?"camera3D":"camera"]=JSON.parse(JSON.stringify(a))),i.view==="pcb"&&i.renderer?.visibleLayers instanceof Set&&(d.layers=[...i.renderer.visibleLayers].filter(g=>i.getLayers().includes(g))),d}),c=await Promise.all(r.map(i=>ke(i.source)));if(e.some((i,o)=>i.disposed||i.source!==r[o].source||(i.path||"")!==r[o].path||i.view!==r[o].view||i.renderer!==r[o].renderer||i.generation!==r[o].generation||(i.textInstancePath??null)!==r[o].instancePath))throw new Error("A drawing changed while creating its view link. Try again.");let s={schema:ne,views:n.map((i,o)=>({...i,sha256:c[o]}))};for(let i of["theme","layout","activePane","linkedSelection"])t[i]!==void 0&&(s[i]=t[i]);return K(s)}function xe(){return new DOMException("View restoration was aborted.","AbortError")}async function Fe(e,t,{signal:r,openFile:n,current:c}={}){let s=K(t);if(Ee(e),s.views.length!==e.length)throw new TypeError("View link count does not match the supplied viewers.");let i=()=>{if(r?.aborted)throw xe();return!e.some(l=>l.disposed)&&(!c||c())},o=l=>new Promise((p,u)=>{let m=()=>u(xe());if(Promise.resolve(l).then(p,u).finally(()=>r?.removeEventListener("abort",m)),r?.aborted){m();return}r?.addEventListener("abort",m,{once:!0})});if(!i())return!1;let d=l=>({source:l.source,path:l.path||"",renderer:l.renderer,generation:l.generation,instancePath:l.textInstancePath??null}),a=e.map(d),g=(l,p)=>l.source===a[p].source&&(l.path||"")===a[p].path&&(l.textInstancePath??null)===a[p].instancePath,b=(l,p)=>g(l,p)&&l.renderer===a[p].renderer&&l.generation===a[p].generation,x=()=>e.every(b);for(let l=0;l<e.length;l++){if(!i()||!x())return!1;let p=s.views[l],u=S(p,"instancePath")&&(e[l].textInstancePath??null)!==p.instancePath;if((e[l].path||"")!==p.path||u){if(typeof n!="function")throw new Error("Load the linked drawing first: "+s.views[l].path);let m=e[l].generation,y=await o(n(l,p.path,r,{instancePath:p.instancePath??void 0}));if(!i()||y===!1||!e.every((v,T)=>T===l||b(v,T))||Number.isInteger(m)&&e[l].generation!==m+1)return!1;if((e[l].path||"")!==s.views[l].path)throw new Error("The host did not open the linked drawing: "+s.views[l].path);if(S(p,"instancePath")&&(e[l].textInstancePath??null)!==p.instancePath)throw new Error("The host did not open the linked sheet occurrence.");a[l]=d(e[l])}}let C=await o(Promise.all(a.map(l=>ke(l.source))));if(!i()||!x())return!1;for(let l=0;l<e.length;l++){let p=e[l],u=s.views[l];if(u.path!==a[l].path||u.sha256!==C[l])throw new Error("View link source SHA-256 does not match "+u.path+".");if(!["pcb","schematic"].includes(p.kind))throw new TypeError("View links require native KiCad drawings.");if(p.kind==="schematic"?u.view!=="schematic":!["pcb","3d"].includes(u.view))throw new TypeError("Linked view does not match the drawing kind.");if(u.layers?.some(m=>!p.getLayers().includes(m)))throw new TypeError("View link refers to an absent saved layer.")}for(let l=0;l<e.length;l++){let p=e[l],u=s.views[l];if(!i()||!x())return!1;if(p.view!==u.view){let m=p.generation,y=p.setView(u.view,{signal:r}),v=Number.isInteger(m)?m+1:p.generation,T=await o(y);if(!i()||T===!1||p.generation!==v||!e.every((P,O)=>O===l?g(P,O):b(P,O)))return!1;a[l].renderer=p.renderer,a[l].generation=p.generation}}if(e.some((l,p)=>l.view!==s.views[p].view))return!1;for(let l=0;l<e.length;l++){if(!i()||!x()||e.some((v,T)=>v.view!==s.views[T].view))return!1;let p=e[l],u=s.views[l];if(s.theme&&(p.setTheme(s.theme),!i()||!x()))return!1;if(S(u,"expand")){if(typeof p.setExpand!="function")throw new Error("The viewer cannot restore expansion.");if(p.setExpand(u.expand,{animate:!1}),!i()||!x())return!1}if(u.camera&&(p.setCamera(u.camera),!i()||!x())||u.camera3D&&(p.setCamera3D(u.camera3D),!i()||!x())||u.layers&&(p.setLayers(u.layers),!i()||!x())||(p.clearSelection(),!i()||!x()))return!1;let m=u.selection;if(!m)continue;let y=m.kind==="net"?p.selectNet(m.id||m.netName,{locate:!1}):p.selectObject(m.kind==="pin"&&m.ownerUuid?m.ownerUuid:m.uuid||m.id||m.ownerUuid,{locate:!1,...m.pinNumber!==void 0?{pinNumber:m.pinNumber}:{}});if(!i()||!x()||e.some((v,T)=>v.view!==s.views[T].view))return!1;if(!y)throw new Error("The linked selection is absent or ambiguous in "+u.path+".")}return!(!i()||!x()||e.some((l,p)=>l.view!==s.views[p].view))}function Ae(e){let t=new URL(e);if(!["http:","https:"].includes(t.protocol)||t.username||t.password)throw new TypeError("Choose an HTTP(S) view URL without credentials.");if(t.href.length>32768)throw new TypeError("View URL is too large.");return t}function Xe(e,t){let r=Ae(e);if(r.hash="kicad-view="+encodeURIComponent(JSON.stringify(K(t))),r.hash.length>oe)throw new TypeError("View link fragment is too large.");return r.href}function $e(e){let t=Ae(e);if(!t.hash.startsWith("#kicad-view="))return null;if(t.hash.length>oe)throw new TypeError("View link fragment is too large.");let r;try{r=JSON.parse(decodeURIComponent(t.hash.slice(12)))}catch{throw new TypeError("Malformed view-state link.")}return K(r)}var Ke=256,Te=J,We=Z,Se=4096,Ye=32,Ge=128,L=e=>e&&typeof e=="object"&&!Array.isArray(e)?e.quoted:e,ae=e=>Array.isArray(e)?L(e[0]):null,Ce=(e,t)=>e.filter(r=>ae(r)===t),R=(e,t)=>Ce(e,t)[0],ee=e=>/\.kicad_sch$/i.test(e),te=e=>e.split("/").at(-1),Je=e=>te(e).replace(/\.kicad_sch$/i,"")||te(e),N=(e,t)=>String(e??"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,"\uFFFD").slice(0,t);function W(e,{root:t,entry:r}={}){if(!Array.isArray(e)||e.length>Ke)throw new TypeError("Choose at most 256 project file entries.");for(let[h,f]of[["root",t],["entry",r]])if(f!==void 0&&!B(f))throw new TypeError("Choose a safe project-relative "+h+" path.");let n=[],c=new Set,s=!1,i=h=>{h=N(h,1600),!c.has(h)&&(n.length<Ge-1?(c.add(h),n.push(h)):s||(n.push("Additional hierarchy diagnostics were omitted."),s=!0))},o=(h,f,w)=>(h.length>f&&i(w+" was shortened for display."),h.slice(0,f)),d=new Set,a=new Map,g=new TextEncoder,b=0;for(let h of e){if(!h||typeof h!="object"||!B(h.path))throw new TypeError("Project files need safe relative paths.");let f=h.path.normalize("NFC").toLowerCase();if(d.has(f))throw new Error("Project paths must be unique, including Unicode/case variants.");if(d.add(f),!ee(h.path))continue;let w={path:h.path,title:o(Je(h.path),512,h.path+" title"),uuid:null,links:[],targets:new Set,sheetCount:0,error:null};if(h.error!==void 0){if(typeof h.error!="string")throw new TypeError("A schematic read error must be text.");w.error=N(h.error||"The schematic could not be read.",512)}else{if(typeof h.source!="string")throw new TypeError("A schematic needs source text or an explicit read error.");if(h.source.length>Te)throw new RangeError("Schematic hierarchy sources exceed 256 MiB per file or 512 MiB per project.");let E=g.encode(h.source).length;if(b+=E,E>Te||b>We)throw new RangeError("Schematic hierarchy sources exceed 256 MiB per file or 512 MiB per project.");w.source=h.source}a.set(h.path,w)}let x=(h,f)=>{if(typeof f!="string"||!f||f.length>1e3||f.startsWith("/")||/[\\\x00-\x1f\x7f%?#:]/.test(f)||/\$\{|\$\(/.test(f))return{path:null,status:"invalid"};let w=h.split("/").slice(0,-1);for(let A of f.split("/")){if(!A)return{path:null,status:"invalid"};if(A!==".")if(A===".."){if(!w.length)return{path:null,status:"invalid"};w.pop()}else w.push(A)}let E=w.join("/");return!B(E)||!ee(E)?{path:null,status:"invalid"}:a.has(E)?{path:E,status:"ok"}:{path:null,status:"missing"}},C=0,l=!1;for(let h of a.values()){if(h.error){i(h.path+": "+h.error);continue}try{let f=globalThis.KiCadDesignDiff.parse(h.source);if(ae(f)!=="kicad_sch")throw new TypeError("Expected a saved kicad_sch document.");let w=L(R(f,"uuid")?.[1]??R(f,"tstamp")?.[1]);typeof w=="string"&&w.length<=128&&w&&!/[\x00-\x1f\x7f]/.test(w)&&(h.uuid=w);let E=L(R(R(f,"title_block")||[],"title")?.[1]);typeof E=="string"&&E&&(h.title=o(E,512,h.path+" title"));for(let A of f){if(ae(A)!=="sheet")continue;let G=h.sheetCount++,V=_e=>Ce(A,"property").filter(me=>typeof L(me[1])=="string"&&L(me[1]).replaceAll(" ","").toLowerCase()===_e),k=V("sheetfile"),M=V("sheetname"),I=k.length===1?L(k[0][2]):null,_=M.length===1?L(M[0][2]):null,D=k.length===1?x(h.path,I):{path:null,status:"invalid"};if(D.path&&h.targets.add(D.path),D.status!=="ok"&&i(h.path+": "+(D.status==="missing"?"Missing listed child schematic: ":"Invalid saved sheet reference: ")+N(I||"(absent or ambiguous Sheetfile)",1e3)),C>=Se){l=!0;continue}C++;let z=L(R(A,"uuid")?.[1]??R(A,"tstamp")?.[1]);typeof z=="string"&&z.length>128&&i(h.path+": an oversized sheet UUID was omitted."),h.links.push({...D,ordinal:G,file:typeof I=="string"?N(N(o(I,1e3,h.path+" Sheetfile"),1e3),1e3):"",name:typeof _=="string"&&_?N(N(o(_,512,h.path+" Sheetname"),512),512):typeof I=="string"&&I?N(N(o(I,512,h.path+" sheet label"),512),512):"Unnamed sheet",uuid:typeof z=="string"&&z&&z.length<=128&&!/[\x00-\x1f\x7f]/.test(z)?z:null})}}catch(f){h.error=N(f?.message||"The schematic could not be parsed.",512),h.links=[],h.targets.clear(),h.sheetCount=0,i(h.path+": "+h.error)}delete h.source}let p=[...a.keys()],u=new Set;for(let h of a.values())for(let f of h.targets)u.add(f);let m=p.filter(h=>!u.has(h)),y=null,v="forest";if(t!==void 0){if(!a.has(t))throw new Error("The explicit hierarchy root is not a listed schematic.");y=t,v="explicit"}else if(r!==void 0&&ee(r)&&a.has(r))y=r,v="entry";else if(r!==void 0&&/\.kicad_pcb$/i.test(r)){let h=te(r).replace(/\.kicad_pcb$/i,""),f=r.split("/").slice(0,-1).join("/"),w=p.filter(A=>te(A).replace(/\.kicad_sch$/i,"")===h),E=w.filter(A=>A.split("/").slice(0,-1).join("/")===f);E.length===1?(y=E[0],v="matching-entry"):w.length===1&&(y=w[0],v="matching-entry")}y===null&&m.length===1&&(y=m[0],v="unique-root"),r!==void 0&&ee(r)&&!a.has(r)&&i("The entry schematic is not listed; hierarchy root selection used the saved project graph.");let T=new Set,P=[],O=h=>{let f=[h];for(;f.length;){let w=f.pop();if(!T.has(w)){T.add(w);for(let E of a.get(w).targets)T.has(E)||f.push(E)}}},ie=(h,f)=>{P.push({path:h,role:f}),O(h)};if(y!==null)ie(y,"root");else for(let h of m)T.has(h)||ie(h,"root");for(let h of[...m,...p])T.has(h)||ie(h,"unlinked");let j=0,pe=l,F=()=>{pe=!0,i("Hierarchy expansion was truncated at 4096 instances, 32 levels or the bounded saved-sheet descriptor budget.")},fe=(h,f,w,E,A,G,V=null)=>{if(j>=A)return F(),null;j++;let k={id:f,path:h.path,file:h.file,name:h.name,uuid:h.uuid,instancePath:V,status:h.status,children:[]};if(G&&(k.role=G),k.status!=="ok")return k;let M=a.get(k.path);if(M.error)return k.status="error",k;if(E.has(k.path))return k.status="cycle",i("Recursive sheet cycle at "+k.path+"."),k;if(w>=Ye&&M.sheetCount>0)return k.status="truncated",F(),k;let I=new Set(E);I.add(k.path);for(let _ of M.links){if(j>=A){F(),k.status="truncated";break}let D=fe(_,f+"/s"+_.ordinal,w+1,I,A,void 0,V&&_.uuid?V+"/"+_.uuid:null);D&&k.children.push(D)}return M.links.length<M.sheetCount&&(F(),j<A?(j++,k.children.push({id:f+"/more",path:null,file:"",name:"Additional saved sheets omitted",uuid:null,status:"truncated",children:[]})):k.status="truncated"),k},ue=[];for(let h=0;h<P.length;h++){let f=a.get(P[h].path),w=fe({path:f.path,file:f.path,name:f.title,uuid:f.uuid,status:"ok"},"r"+h,0,new Set,Se-(P.length-h-1),P[h].role,f.uuid?"/"+f.uuid:null);w&&ue.push(w)}return l&&F(),{schema:"kicad-webview.hierarchy/v1",rootPath:y,rootReason:v,roots:ue,files:p.map(h=>{let f=a.get(h);return{path:h,sheetCount:f.sheetCount,...f.error?{error:f.error}:{}}}),warnings:n,stats:{files:p.length,instances:j,truncated:pe}}}var q=J,Pe=Z,Ie=e=>typeof e=="string"&&/\.kicad_sch$/i.test(e),Ne=e=>new TextEncoder().encode(e).byteLength;async function he(e,t){if(!e||!Number.isSafeInteger(e.length)||e.length<1||e.length>256)throw new Error("Choose between 1 and 256 project files.");let r=[],n=0;for(let c of Array.from(e)){t?.throwIfAborted();let s=c?.path||c?.webkitRelativePath||c?.name;if(!B(s))throw new TypeError("Project files need safe relative names.");if(!Ie(s))continue;let i;if(typeof c.source=="string"){if(c.source.length>q)throw new Error("Schematic exceeds 256 MiB.");i=c.source}else{let d=c.bytes;if(d instanceof ArrayBuffer&&(d=new Uint8Array(d)),!(d instanceof Uint8Array)){if(typeof c.arrayBuffer!="function"||!Number.isSafeInteger(c.size)||c.size<0||c.size>q)throw new TypeError("A schematic needs bounded source text, bytes or a browser File.");if(d=new Uint8Array(await c.arrayBuffer()),d.byteLength!==c.size)throw new Error("File size changed while reading.")}if(d.byteLength>q)throw new Error("Schematic exceeds 256 MiB.");i=new TextDecoder("utf-8",{fatal:!0}).decode(d)}t?.throwIfAborted();let o=Ne(i);if(n+=o,o>q||n>Pe)throw new Error("Hierarchy exceeds 256 MiB per schematic or 512 MiB total.");r.push({path:s,source:i})}return r}async function ce(e,t={}){let{signal:r,root:n,credentials:c="omit"}=t;r?.throwIfAborted();let s,i=t.entry;if(e instanceof Uint8Array||e instanceof ArrayBuffer)s=await he(await Q(e,{signal:r}),r);else if(e&&typeof e=="object"&&Number.isSafeInteger(e.length))s=await he(e,r);else{let o=await we(e,{...t,metadataOnly:!0,file:t.file||n,baseURL:t.baseURL??globalThis.document?.baseURI});if(r?.throwIfAborted(),i??=o.project?.entry||o.path,o.archive)s=await he(await Q(o.archive,{signal:r}),r);else{let d=o.project?.files||[{path:o.path}],a=d.filter(p=>Ie(p.path));s=[];let g=0;if(a.length>256)throw new Error("Hierarchy exceeds 256 schematic files.");s=new Array(a.length);let b=0,x=new AbortController,C=()=>x.abort(r?.reason);r?.addEventListener("abort",C,{once:!0}),r?.aborted&&C();async function l(){for(;b<a.length;){x.signal.throwIfAborted();let p=b++,u=a[p],m;try{m=u.path===o.path&&typeof o.source=="string"?o.source:await ge(u.url,{signal:x.signal,credentials:c,limit:q})}catch(v){if(x.signal.throwIfAborted(),v?.name==="AbortError")throw v;s[p]={path:u.path,error:String(v.message||v).slice(0,512)};continue}x.signal.throwIfAborted();let y=Ne(m);if(g+=y,y>q||g>Pe)throw new Error("Hierarchy exceeds 256 MiB per schematic or 512 MiB total.");s[p]={path:u.path,source:m}}}try{await Promise.all(Array.from({length:Math.min(3,a.length)},()=>l().catch(p=>{throw x.abort(p),p})))}finally{r?.removeEventListener("abort",C)}}}return r?.throwIfAborted(),W(s,{root:n,entry:i})}var Ze=new Set(["ok","missing","invalid","cycle","truncated","error"]);function re(e){if(e?.schema!=="kicad-webview.hierarchy/v1"||!Array.isArray(e.roots)||e.roots.length>4096||!Array.isArray(e.warnings)||e.warnings.length>1024||e.warnings.some(i=>typeof i!="string"||i.length>8192)||!Array.isArray(e.files)||e.files.length>256)throw new TypeError("Choose a generated project hierarchy.");let t=new Set(e.files.map(i=>i.path));if(t.size!==e.files.length||e.rootPath!==null&&!t.has(e.rootPath))throw new TypeError("Hierarchy paths must be unique and root must be listed.");for(let i of t)if(!B(i)||!/\.kicad_sch$/i.test(i))throw new TypeError("Hierarchy files need safe schematic paths.");let r=[],n=new Set,c=new Set,s=e.roots.map(i=>({node:i,depth:0,parent:null})).reverse();for(;s.length;){let i=s.pop(),o=i.node;if(r.length>=4096||i.depth>33||!o||n.has(o)||typeof o.id!="string"||o.id.length>2048||c.has(o.id)||!Ze.has(o.status)||!Array.isArray(o.children)||r.length+s.length+o.children.length+1>4096||o.path!==null&&!t.has(o.path))throw new TypeError("Hierarchy contains invalid, recursive or excessive nodes.");if(o.instancePath!==void 0&&o.instancePath!==null&&(typeof o.instancePath!="string"||o.instancePath.length>8192||!/^\/[^\x00-\x1f\x7f]+$/.test(o.instancePath)))throw new TypeError("Invalid saved sheet instance path.");for(let d of["name","file"])if(typeof o[d]!="string"||o[d].length>8192)throw new TypeError("Hierarchy labels exceed their limit.");n.add(o),c.add(o.id),i.index=r.length,r.push(i);for(let d=o.children.length-1;d>=0;d--)s.push({node:o.children[d],depth:i.depth+1,parent:i.index})}return r}var Y=e=>String(e.name||e.file||e.path||"Unnamed sheet").replace(/\s+/g," ").slice(0,160),le=e=>String(e).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\ufffe\uffff]/g,"").replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]);function Me(e,{theme:t="dark"}={}){if(!["light","dark"].includes(t))throw new TypeError("Choose light or dark theme.");let r=re(e),n=r.slice(0,512),c=Math.max(0,...n.map(l=>l.depth)),s=Math.max(440,Math.min(1600,c*28+410)),i=72+n.length*64+(r.length>n.length?32:0),o=t==="dark",d=o?"#101b28":"#f5f8fc",a=o?"#e8f1fa":"#203347",g=o?"#9fb5ca":"#52697e",b=o?"#3c566d":"#b8cad9",x=o?"#7de3d4":"#126d70",C=['<svg xmlns="http://www.w3.org/2000/svg" width="'+s+'" height="'+i+'" viewBox="0 0 '+s+" "+i+'" role="img" aria-label="Project schematic hierarchy"><rect width="100%" height="100%" fill="'+d+'"/><g font-family="system-ui,sans-serif"><text x="20" y="30" font-size="18" font-weight="700" fill="'+a+'">Project schematic hierarchy</text>'];for(let l of n){let p=20+l.depth*28,u=48+l.index*64,m=Math.min(350,s-p-20),y=l.node;if(l.parent!==null){let v=n[l.parent],T=20+v.depth*28+10,P=48+v.index*64+48;C.push('<path d="M '+T+" "+P+" V "+(u+23)+" H "+p+'" fill="none" stroke="'+b+'"/>')}C.push('<rect x="'+p+'" y="'+u+'" width="'+m+'" height="48" rx="7" fill="'+(o?"#192a3a":"#fff")+'" stroke="'+(y.status==="ok"?b:"#bd794f")+'"/><text x="'+(p+10)+'" y="'+(u+20)+'" font-size="13" font-weight="600" fill="'+a+'">'+le(Y(y).slice(0,42))+'</text><text x="'+(p+10)+'" y="'+(u+37)+'" font-size="10" fill="'+(y.status==="ok"?g:x)+'">'+le((y.path||y.file||"No saved Sheetfile").slice(0,48))+" \xB7 "+le(y.status)+"</text>")}return r.length>n.length&&C.push('<text x="20" y="'+(i-14)+'" font-size="12" fill="'+a+'">Export limited to512 of '+r.length+" sheet instances. Use the interactive tree for the full hierarchy.</text>"),C.join("")+"</g></svg>"}var Qe=':host{display:flex;flex-direction:column;min-height:0;height:100%;font:13px/1.4 system-ui;--bg:#f6f9fc;--card:#fff;--ink:#24384a;--muted:#5e7489;--line:#cbd9e6;--accent:#126f79;color:var(--ink);background:var(--bg)}:host([data-theme="dark"]){--bg:#101b28;--card:#192a3a;--ink:#e8f1fa;--muted:#a1b5c8;--line:#375169;--accent:#7de3d4;color-scheme:dark}*{box-sizing:border-box}[hidden]{display:none!important}.tools{display:flex;align-items:center;gap:6px;flex-wrap:wrap;padding:12px;border-bottom:1px solid var(--line)}.tools strong{margin-right:auto}.tools button,.node-button,.branch-toggle{font:inherit;color:var(--ink);border:1px solid var(--line);background:var(--card);border-radius:6px;padding:6px 8px;cursor:pointer}button:focus-visible{outline:2px solid var(--accent);outline-offset:2px}button:hover{border-color:var(--accent)}button:disabled{cursor:default}.status{margin:0;padding:9px 14px;color:var(--muted);font-size:12px;overflow-wrap:anywhere}.diagram{overflow:auto;flex:1;min-height:0;padding:8px 16px 24px}.tree-content{display:inline-block;min-width:100%;vertical-align:top}.diagram[data-panning="true"]{cursor:grabbing;user-select:none}.tree-list{list-style:none;margin:0;padding:0}.tree-list .tree-list{margin-left:13px;padding-left:22px;border-left:1px solid var(--line)}li{position:relative;padding:6px 0}.tree-list .tree-list>li:before{content:"";position:absolute;left:-22px;top:28px;width:22px;border-top:1px solid var(--line)}.node-row{display:flex;align-items:center;gap:5px;min-width:200px;max-width:480px}.branch-toggle{width:27px;flex:0 0 27px;padding:5px 0}.branch-spacer{width:27px;flex:0 0 27px}.node-button{display:grid;gap:3px;min-width:0;text-align:left;flex:1;padding:8px 10px;overflow-wrap:anywhere}.node-button[aria-pressed="true"]{border-color:var(--accent);box-shadow:inset 3px 0 var(--accent)}.node-button small{font-size:11px;color:var(--muted)}.node-state{font-size:10px;color:var(--accent);text-transform:uppercase;letter-spacing:.05em}.warnings{padding:8px 14px;border-top:1px solid var(--line);color:var(--muted);font-size:12px;max-height:120px;overflow:auto;white-space:pre-line}',de=class extends EventTarget{constructor(t,{theme:r="dark",onSelect:n}={}){super();let c=typeof t=="string"?document.querySelector(t):t;if(!c?.ownerDocument||!c.append)throw new TypeError("Choose a tree container.");if(X.has(c))throw new Error("This container already has a viewer.");if(n!==void 0&&typeof n!="function")throw new TypeError("onSelect must be a function.");this.host=c,this.doc=c.ownerDocument,this.onSelect=n,this.disposed=!1,this.ticket=0,this.model=null,this.expanded=new Set,this.buttons=new Map,this.branches=new Map,this.listeners=[],this.root=this.doc.createElement("div"),this.root.style.cssText="height:100%;min-height:0;display:flex;flex-direction:column",this.surface=this.root.attachShadow?this.root.attachShadow({mode:"open"}):this.root;let s=(o,d)=>{let a=this.doc.createElement(o);return d&&(a.textContent=d),a};this.make=s;let i=s("style");i.textContent=Qe,this.tools=s("div"),this.tools.className="tools",this.tools.append(s("strong","Project tree")),this.toolButtons=[];for(let[o,d]of[["Expand all",()=>this.expandAll()],["Collapse all",()=>this.collapseAll()]]){let a=s("button",o);a.type="button",a.onclick=d,this.tools.append(a),this.toolButtons.push(a)}for(let[o,d]of[["Zoom out",()=>this.zoomBy(1/1.25)],["Zoom in",()=>this.zoomBy(1.25)],["Fit",()=>this.fit()],["Reset view",()=>this.resetView()]]){let a=s("button",o);a.type="button",a.onclick=d,this.tools.append(a),this.toolButtons.push(a)}this.camera={zoom:1,x:0,y:0},this.drag=null,this.status=s("p","Load a project to see its saved schematic hierarchy."),this.status.className="status",this.status.setAttribute("role","status"),this.diagram=s("nav"),this.diagram.className="diagram",this.diagram.setAttribute("aria-label","Project schematic hierarchy"),this.diagram.tabIndex=0,this.content=s("div"),this.content.className="tree-content",this.diagram.append(this.content),this._installNavigation(),this.warnings=s("div"),this.warnings.className="warnings",this.warnings.hidden=!0,this.surface.append(i,this.tools,this.status,this.diagram,this.warnings),this.setTheme(r),c.append(this.root),X.set(c,this)}assertActive(){if(this.disposed)throw new Error("The project tree has been disposed.")}setTheme(t){if(this.assertActive(),!["light","dark"].includes(t))throw new TypeError("Choose light or dark theme.");this.theme=t,this.root.setAttribute("data-theme",t)}_installNavigation(){let t=s=>{this.disposed||s.pointerType==="touch"||s.button!==0||!s.altKey&&s.target!==this.diagram&&s.target!==this.content&&s.target?.tagName!=="UL"&&s.target?.tagName!=="LI"||s.composedPath?.().some(i=>i?.tagName==="BUTTON")||(this.drag={id:s.pointerId,x:s.clientX,y:s.clientY,left:this.diagram.scrollLeft||0,top:this.diagram.scrollTop||0},this.diagram.setPointerCapture?.(s.pointerId),this.diagram.setAttribute("data-panning","true"),s.preventDefault())},r=s=>{!this.drag||s.pointerId!==this.drag.id||(this.diagram.scrollLeft=this.drag.left-(s.clientX-this.drag.x),this.diagram.scrollTop=this.drag.top-(s.clientY-this.drag.y),this._rememberScroll(),s.preventDefault())},n=s=>{!this.drag||s.pointerId!==this.drag.id||(this.diagram.releasePointerCapture?.(s.pointerId),this.drag=null,this.diagram.setAttribute("data-panning","false"))},c=()=>this._rememberScroll();for(let[s,i]of[["pointerdown",t],["pointermove",r],["pointerup",n],["pointercancel",n],["scroll",c]])this.diagram.addEventListener(s,i),this.listeners.push([s,i])}_rememberScroll(){!this.disposed&&this.model&&(this.camera.x=Math.max(0,Math.min(1e6,this.diagram.scrollLeft||0)),this.camera.y=Math.max(0,Math.min(1e6,this.diagram.scrollTop||0)))}_applyCamera(){this.content.style.zoom=String(this.camera.zoom),this.diagram.scrollLeft=this.camera.x,this.diagram.scrollTop=this.camera.y}getCamera(){return this.assertActive(),this._rememberScroll(),{...this.camera}}setCamera(t){if(this.assertActive(),!t||![t.zoom,t.x,t.y].every(Number.isFinite)||t.zoom<.35||t.zoom>2||t.x<0||t.x>1e6||t.y<0||t.y>1e6)throw new TypeError("Camera needs zoom 0.35\u20132 and scroll offsets 0\u20131000000.");return this.camera={zoom:t.zoom,x:t.x,y:t.y},this._applyCamera(),this.getCamera()}zoomBy(t){if(this.assertActive(),!Number.isFinite(t)||t<=0)throw new TypeError("Zoom factor must be positive.");let r=this.getCamera(),n=Math.max(.35,Math.min(2,r.zoom*t));return this.setCamera({...r,zoom:n})}fit(){this.assertActive();let t=this.diagram.clientWidth,r=this.diagram.clientHeight,n=this.content.offsetWidth,c=this.content.offsetHeight;return!this.model||![t,r,n,c].every(s=>Number.isFinite(s)&&s>0)?!1:(this.setCamera({zoom:Math.max(.35,Math.min(2,t/n,r/c)),x:0,y:0}),!0)}resetView(){return this.assertActive(),this.setCamera({zoom:1,x:0,y:0})}_error(t){this.disposed||(this.status.textContent=t.message||String(t),this.dispatchEvent(new CustomEvent("error",{detail:{error:t}})))}async load(t,r={}){this.assertActive(),this.pending?.abort();let n=new AbortController,c=++this.ticket;this.pending=n;let s=()=>n.abort();r.signal?.addEventListener("abort",s,{once:!0}),r.signal?.aborted&&s(),this.status.textContent="Reading saved sheet links\u2026";try{let i=await ce(t,{...r,signal:n.signal});return this.disposed||c!==this.ticket||n.signal.aborted?!1:(this._setHierarchy(i),this.dispatchEvent(new CustomEvent("ready",{detail:{hierarchy:this.getHierarchy()}})),!0)}catch(i){if(this.disposed||c!==this.ticket||n.signal.aborted&&!r.signal?.aborted)return!1;throw this._error(i),i}finally{r.signal?.removeEventListener("abort",s),c===this.ticket&&(this.pending=null)}}loadFiles(t,r={}){return this.load(t,r)}loadArchive(t,r={}){return this.load(t,r)}setHierarchy(t){return this.assertActive(),re(t),this.pending?.abort(),this.pending=null,++this.ticket,this._setHierarchy(t),this}setFiles(t,r={}){return this.setHierarchy(W(t,r))}_setHierarchy(t){let r=re(t);this.model=structuredClone(t),this.rows=re(this.model),this.expanded=new Set(r.filter(n=>n.depth<2).map(n=>n.node.id)),this.selectedId=null,this._render(),this.status.textContent=this.model.files.length+" schematic files \xB7 "+this.rows.length+" sheet instances \xB7 "+(this.model.rootPath?"Root: "+this.model.rootPath:"Multiple roots / no unambiguous root"),this.warnings.textContent=(this.model.warnings||[]).slice(0,256).map(String).join(`
`),this.warnings.hidden=!this.warnings.textContent}_render(){this.content.children.length&&this._rememberScroll();for(let n of this.buttons.values())n.onclick=null;for(let n of this.branches.values())n.toggle.onclick=null;this.buttons.clear(),this.branches.clear();let t=this.make("ul");t.className="tree-list";let r=new Map([[null,t]]);for(let n of this.rows){let c=n.node,s=this.make("li"),i=this.make("div");i.className="node-row";let o;if(c.children.length){let g=this.make("button",this.expanded.has(c.id)?"\u2212":"+");g.type="button",g.className="branch-toggle",g.setAttribute("aria-label","Toggle subsheets of "+Y(c)),g.setAttribute("aria-expanded",String(this.expanded.has(c.id))),o=this.make("ul"),o.className="tree-list",o.hidden=!this.expanded.has(c.id),g.onclick=()=>{this.expanded.has(c.id)?this.expanded.delete(c.id):this.expanded.add(c.id),o.hidden=!this.expanded.has(c.id),g.textContent=o.hidden?"+":"\u2212",g.setAttribute("aria-expanded",String(!o.hidden))},i.append(g),this.branches.set(c.id,{toggle:g,children:o}),r.set(n.index,o)}else{let g=this.make("span");g.className="branch-spacer",i.append(g)}let d=this.make("button");d.type="button",d.className="node-button",d.setAttribute("aria-pressed",String(c.id===this.selectedId)),d.setAttribute("aria-label","Open schematic "+(c.path||c.file||Y(c))),d.title=c.path||c.file||Y(c),d.disabled=c.status!=="ok"||!c.path,d.append(this.make("strong",Y(c)),this.make("small",c.path||c.file||"No saved Sheetfile"));let a=this.make("span",c.status==="ok"?c.role==="unlinked"?"Unlinked / separate root":n.depth===0?"Root sheet":"Subsheet":c.status);a.className="node-state",d.append(a),d.onclick=()=>this.select(c.id),i.append(d),s.append(i),o&&s.append(o),r.get(n.parent).append(s),this.buttons.set(c.id,d)}this.content.replaceChildren(t),this._applyCamera()}expandAll(){this.assertActive();for(let[t,r]of this.branches)this.expanded.add(t),r.children.hidden=!1,r.toggle.textContent="\u2212",r.toggle.setAttribute("aria-expanded","true")}collapseAll(){this.assertActive(),this.expanded.clear();for(let t of this.branches.values())t.children.hidden=!0,t.toggle.textContent="+",t.toggle.setAttribute("aria-expanded","false")}select(t){this.assertActive();let r=this.rows?.find(s=>s.node.id===t)?.node;if(!r||r.status!=="ok"||!r.path)return!1;this.selectedId=t;for(let[s,i]of this.buttons)i.setAttribute("aria-pressed",String(s===t));let n={id:r.id,path:r.path,file:r.file,name:r.name,uuid:r.uuid,status:r.status,...r.instancePath?{instancePath:r.instancePath}:{}};this.dispatchEvent(new CustomEvent("select",{detail:{node:{...n}}}));let c=this.ticket;try{Promise.resolve(this.onSelect?.({...n})).catch(s=>{c===this.ticket&&this._error(s)})}catch(s){this._error(s)}return!0}clear(){this.assertActive(),this._rememberScroll(),this.pending?.abort(),this.pending=null,++this.ticket;for(let t of this.buttons.values())t.onclick=null;for(let t of this.branches.values())t.toggle.onclick=null;return this.buttons.clear(),this.branches.clear(),this.model=null,this.rows=[],this.selectedId=null,this.expanded.clear(),this.content.replaceChildren(),this.status.textContent="Load a project to see its saved schematic hierarchy.",this.warnings.textContent="",this.warnings.hidden=!0,this}getHierarchy(){return this.assertActive(),this.model?structuredClone(this.model):null}toSVG(t={}){if(this.assertActive(),!this.model)throw new Error("Load a hierarchy before exporting.");return Me(this.model,{theme:this.theme,...t})}dispose(){if(!this.disposed){this.disposed=!0,++this.ticket,this.pending?.abort(),this.pending=null;for(let[t,r]of this.listeners)this.diagram.removeEventListener(t,r);this.listeners=[],this.drag&&this.diagram.releasePointerCapture?.(this.drag.id),this.drag=null;for(let t of this.toolButtons)t.onclick=null;for(let t of this.buttons.values())t.onclick=null;for(let t of this.branches.values())t.toggle.onclick=null;this.buttons.clear(),this.branches.clear(),this.root.remove(),X.get(this.host)===this&&X.delete(this.host),this.model=null,this.rows=[],this.onSelect=null}}};export{De as DemoController,je as EMBED_API_VERSION,be as KiCadViewer,de as ProjectTree,be as Viewer,se as ViewerCarousel,W as buildProjectHierarchy,Oe as captureViewState,Xe as createViewLink,Me as hierarchyToSVG,Le as linkViewers,ce as loadProjectHierarchy,Be as parseManufacturing,$e as parseViewLink,Q as readZip,ze as registerKiCadViewer,Fe as restoreViewState,K as validateViewState};