UNPKG

@wayrisignals/kicad-webview

Version:

Interactive KiCad schematic, PCB and 3D viewer for the web, with Gerber, Excellon, linked views and offline HTML exports

83 lines (81 loc) • 39.2 kB
/* Copyright (c) 2026 wayri. SPDX-License-Identifier: MPL-2.0 */ import {parseWayriCADResults,classifyWayriCADSource,wayriCADSurface,wayriCADFrame,probeWayriCADPlot,wayriCADPointHistory} from './wayricad-results.mjs'; import {rasterizeWayriCADSurface,waveformWindow} from './wayricad-plot.mjs'; import {createWayriCADBoardLayer} from './wayricad-board-layer.mjs'; import {fieldColorRange,fieldPalette} from '../engine/spike/fieldColors.mjs'; import {analysisSourceHash} from './analysis-results.mjs'; import {fetchText} from './source-loader.mjs'; import {getWayriCADSourceLinks} from './wayricad-links.mjs'; import {viewerOwners} from './viewer-host.mjs'; const format=v=>Number.isFinite(v)?Number(v.toPrecision(6)).toString():'missing'; const previewText=(value,max=500)=>typeof value==='string'?value.slice(0,max)+(value.length>max?' … [full text retained]':''):value===null||typeof value==='number'||typeof value==='boolean'?value:'[structured data retained]'; function metadataPreview(model){const portable=model.metadata.portable,producer=portable?Object.fromEntries(['schema','tool','version','source_state','coordinate_frame','zBasis'].map(k=>[k,previewText(portable[k])])):null;if(producer&&portable.units&&typeof portable.units==='object'){producer.units={};let count=0;for(const key in portable.units){if(++count>32)break;Object.defineProperty(producer.units,key.slice(0,80),{enumerable:true,value:previewText(portable.units[key],80)});}}return{producer,projectRecord:model.metadata.library?{schema:previewText(model.metadata.library.schema),plugin:previewText(model.metadata.library.plugin),identity:'unverified; original record retained'}:null,sourceBindings:model.sourceBindings.slice(0,32).map(b=>({path:previewText(b.path,200),sha256:b.sha256})),notes:model.report.warnings.slice(0,24).map(v=>previewText(v)),display:'No solver execution. Missing values stay missing. Grid cells follow saved center spacing and are not clipped to board/copper boundaries. Full source data remains downloadable.'};} const colors=['#58d8de','#f2c66d','#b59af5','#ff8f9b','#87cc8f','#9cbeff']; const STYLE=`.kw-results{--bg:#14212c;--panel:#1b2d3b;--ink:#edf4f8;--muted:#b8c8d5;--line:#3d5668;--accent:#69dce3;color:var(--ink);background:var(--bg);border:1px solid var(--line);border-radius:10px;padding:12px;font:13px/1.5 system-ui;min-width:0;color-scheme:dark}.kw-results[data-theme=light]{--bg:#fff;--panel:#eef4f8;--ink:#152534;--muted:#40566a;--line:#aebdca;--accent:#00727d;color-scheme:light}.kw-results *{box-sizing:border-box}.kw-results button,.kw-results select,.kw-results input{font:inherit;color:var(--ink);background:var(--panel);border:1px solid var(--line);border-radius:5px;padding:7px;min-width:0;max-width:100%;min-height:38px}.kw-results button{cursor:pointer}.kw-results button:disabled{opacity:.55;cursor:default}.kw-results :focus-visible{outline:2px solid var(--accent);outline-offset:2px}.kw-results label{display:flex;align-items:center;gap:6px;min-width:0}.kw-result-tools{display:flex;flex-wrap:wrap;gap:8px;align-items:center}.kw-result-tools>select{flex:1 1 220px}.kw-results p{margin:7px 0;overflow-wrap:anywhere}.kw-result-status{color:var(--accent);font-weight:650}.kw-result-small{color:var(--muted);font-size:12px}.kw-result-viewport{position:relative;height:clamp(260px,48vh,500px);min-height:240px;margin:10px 0;overflow:hidden;border:1px solid var(--line);border-radius:6px;background:var(--panel)}.kw-result-viewport>canvas,.kw-result-viewport>.kw-result-three{position:absolute;inset:0;width:100%;height:100%}.kw-result-series{display:flex;flex-wrap:wrap;gap:6px 14px;max-height:160px;overflow:auto}.kw-result-series label{min-height:38px;overflow-wrap:anywhere;white-space:normal}.kw-result-series input{min-height:0}.kw-results details{border-top:1px solid var(--line);padding-top:8px;margin-top:10px}.kw-results summary{cursor:pointer;padding:6px 0;font-weight:600}.kw-results pre{white-space:pre-wrap;overflow-wrap:anywhere;max-height:240px;overflow:auto;background:var(--panel);padding:8px}.kw-result-data{display:grid;gap:4px;max-height:260px;overflow:auto;margin-top:8px}.kw-result-data button{text-align:left;white-space:normal;overflow-wrap:anywhere}.kw-result-data-path{overflow-wrap:anywhere}.kw-result-controls{display:flex;flex-wrap:wrap;gap:8px;align-items:center}.kw-result-controls input[type=range]{flex:1 1 140px}.kw-results [hidden]{display:none!important}@media(pointer:coarse){.kw-results button,.kw-results select,.kw-result-series label{min-height:44px}}`; /** Read-only WayriCAD PI, SI and thermal results. Never runs a solver or loads producer paths. */ export class WayriCADResultsViewer extends EventTarget{ constructor(target,{theme='dark',boardViewer=null,palette='wayricad'}={}){ super();fieldPalette(palette);if(!['light','dark'].includes(theme))throw new TypeError('Choose light or dark theme.');const host=typeof target==='string'?globalThis.document?.querySelector(target):target;if(!host?.ownerDocument)throw new TypeError('Choose a results mount element.');if(viewerOwners.has(host))throw new Error('This container already has a viewer.'); this.host=host;this.doc=host.ownerDocument;this.theme=theme;this.ticket=0;this.plotTicket=0;this.model=null;this.mode='2d';this.palette=palette;this.opacity=.65;this.overlayWanted=false;this.sourceState='unverified';this.sourceSnapshot=null;this.selected=new Set();this.stops=[];this.make=(tag,text)=>{const n=this.doc.createElement(tag);if(text!==undefined)n.textContent=String(text);return n;}; const make=this.make;this.root=make('section');this.root.className='kw-results';this.root.dataset.theme=theme;this.root.setAttribute('aria-label','WayriCAD saved results');const style=make('style',STYLE),title=make('strong','WayriCAD · saved results'),tools=make('div');tools.className='kw-result-tools';this.plotSelect=make('select');this.plotSelect.setAttribute('aria-label','Saved result plot');this.viewSelect=make('select');this.viewSelect.setAttribute('aria-label','Result view');for(const [value,text]of [['2d','2D field / graph'],['3d','3D saved field']]){const option=make('option',text);option.value=value;this.viewSelect.append(option);}this.sourceButton=this.button('Highlight saved net',()=>this.highlightSource());this.routeButton=this.button('Locate saved route',()=>this.locateSource());this.sourceButton.disabled=this.routeButton.disabled=true;this.fitButton=this.button('Fit result',()=>this.scene?.fit());this.downloadButton=this.button('Download full JSON',()=>this.download());this.layerSelect=make('select');this.layerSelect.setAttribute('aria-label','Saved result layer');this.layerSelect.disabled=true;this.paletteSelect=make('select');this.paletteSelect.setAttribute('aria-label','Saved field palette');for(const [value,label]of [['wayricad','WayriCAD'],['viridis','Viridis (4 stops)'],['inferno','Inferno (4 stops)'],['grayscale','Grayscale']]){const option=make('option',label);option.value=value;this.paletteSelect.append(option);}this.paletteSelect.value=palette;this.paletteSelect.disabled=true;this.paletteSelect.onchange=()=>{try{this.setPalette(this.paletteSelect.value);}catch(error){this.paletteSelect.value=this.palette;this.fail(error);}};tools.append(this.plotSelect,this.layerSelect,this.viewSelect,this.paletteSelect,this.fitButton,this.sourceButton,this.routeButton,this.downloadButton); this.status=make('p','Open a saved WayriCAD result JSON.');this.status.className='kw-result-status';this.status.setAttribute('role','status');this.sourceNote=make('p','No PCB registration. Independent result plots do not establish engineering validity.');this.sourceNote.className='kw-result-small';this.viewport=make('div');this.viewport.className='kw-result-viewport';this.canvas=make('canvas');this.canvas.setAttribute('role','img');this.canvas.setAttribute('aria-label','Saved numerical result plot; use the probe readout for values');this.threeHost=make('div');this.threeHost.className='kw-result-three';this.threeHost.hidden=true;this.viewport.append(this.canvas,this.threeHost); this.legend=make('p');this.legend.className='kw-result-small';this.colorBar=make('div');this.colorBar.setAttribute('role','img');this.colorBar.style.cssText='height:12px;max-width:480px;border:1px solid var(--line);border-radius:4px;margin-block:8px';this.colorBar.hidden=true;this.boardStatus=make('p');this.boardStatus.className='kw-result-small';this.boardStatus.setAttribute('role','status');this.probe=make('output','Click the plot to probe retained values.');this.probe.setAttribute('aria-live','polite');this.historyButton=this.button('Plot probe history',()=>this.showHistory());this.historyButton.hidden=true;this.frameRow=make('label','Saved frame');this.frameRow.className='kw-result-controls';this.frame=make('input');this.frame.type='range';this.frame.min='0';this.frame.step='1';this.frame.setAttribute('aria-label','Saved thermal frame');this.frameTime=make('span');this.frameRow.append(this.frame,this.frameTime);this.frameRow.hidden=true; this.series=make('div');this.series.className='kw-result-series';this.series.setAttribute('aria-label','Visible saved series');this.seriesMore=this.button('More series',()=>{this.seriesPage=(this.seriesPage||0)+1;this.updateSeries();});const overlayRow=make('div');overlayRow.className='kw-result-controls';this.overlayInput=make('input');this.overlayInput.type='checkbox';this.overlayInput.setAttribute('aria-label','Show result on matching PCB');const overlayLabel=make('label');overlayLabel.append(this.overlayInput,make('span','Show on matching PCB'));this.alpha=make('input');this.alpha.type='range';this.alpha.min='0';this.alpha.max='100';this.alpha.value='65';this.alpha.setAttribute('aria-label','Saved field opacity');overlayRow.append(overlayLabel,this.alpha); const details=make('details'),summary=make('summary','Producer, assumptions & display limits');this.metadata=make('pre');details.append(summary,this.metadata);const raw=make('details');raw.append(make('summary','Complete numerical data'));this.dataPath=make('p');this.dataPath.className='kw-result-data-path';this.dataList=make('div');this.dataList.className='kw-result-data';raw.append(this.dataPath,this.dataList);this.root.append(style,title,tools,this.status,this.sourceNote,this.viewport,this.colorBar,this.legend,this.probe,this.historyButton,this.frameRow,this.series,this.seriesMore,overlayRow,details,raw);host.append(this.root);viewerOwners.set(host,this); this.plotSelect.onchange=()=>this.setPlot(Number(this.plotSelect.value));this.viewSelect.onchange=()=>{void this.setView(this.viewSelect.value).catch(e=>this.fail(e));};this.frame.oninput=()=>{try{this.setFrame(Number(this.frame.value));}catch(e){this.frame.value=String(this.plot?.frameIndex||0);this.fail(e);}};this.alpha.oninput=()=>this.setOpacity(Number(this.alpha.value)/100);this.layerSelect.onchange=()=>this.setLayer(this.layerSelect.value);this.overlayInput.onchange=()=>this.setBoardOverlay(this.overlayInput.checked);this.canvas.onpointerup=e=>this.probeAt(e); this.plotSelect.disabled=this.viewSelect.disabled=this.downloadButton.disabled=this.fitButton.disabled=this.overlayInput.disabled=this.alpha.disabled=true;this.seriesMore.hidden=true; this.observer=typeof ResizeObserver==='function'?new ResizeObserver(()=>this.invalidate()):null;this.observer?.observe(this.viewport);this.visible=true;this.intersection=typeof IntersectionObserver==='function'?new IntersectionObserver(entries=>{this.visible=entries.some(e=>e.isIntersecting);if(this.visible)this.invalidate();}):null;this.intersection?.observe(this.root);this.visibility=()=>{if(!this.doc.hidden)this.invalidate();};this.doc.addEventListener?.('visibilitychange',this.visibility);this.root.append(this.boardStatus);this.attachBoard(boardViewer); } button(text,action){const b=this.make('button',text);b.type='button';b.onclick=()=>{try{action();}catch(e){this.fail(e);}};return b;} assertActive(){if(this.disposed)throw new Error('Results viewer is disposed.');} emit(name,detail){this.dispatchEvent(new CustomEvent(name,{detail}));} fail(error){if(this.disposed)return;this.status.textContent=error.message;this.emit('error',{message:error.message});} beginLoad(signal){this.assertActive();signal?.throwIfAborted();this.downloadController?.abort();const controller=this.downloadController=new AbortController(),ticket=++this.ticket,abort=()=>controller.abort(signal.reason);signal?.addEventListener('abort',abort,{once:true});return{ticket,controller,current:()=>!this.disposed&&this.ticket===ticket,check:()=>{signal?.throwIfAborted();controller.signal.throwIfAborted();},cleanup:()=>signal?.removeEventListener('abort',abort)};} async commitResult(input,path,op){op.check();const model=parseWayriCADResults(input,{path}),assessment=await this.assessSource(model);if(!op.current())return false;op.check();this.scene?.dispose();this.scene=null;this.boardLayer?.dispose();this.boardLayer=null;this.model=model;this.downloadButton.disabled=false;this.mode='2d';this.plotSelect.replaceChildren();this.sourceLinks=getWayriCADSourceLinks(model);model.report.plots.forEach((p,i)=>{const o=this.make('option',p.title);o.value=String(i);this.plotSelect.append(o);});this.metadata.textContent=JSON.stringify(metadataPreview(model),null,2);this.rawPath=[];this.rawPage=0;this.showRaw();this.setPlot(0);this.applyAssessment(assessment);this.emit('ready',{path,plots:model.report.plots.length,sourceState:this.sourceState});return true;} async load(input,{path='wayricad-results.json',signal}={}){const op=this.beginLoad(signal);try{return await this.commitResult(input,path,op);}catch(error){if(!op.current()&&!signal?.aborted)return false;throw error;}finally{op.cleanup();}} async loadURL(input,{signal,credentials='omit',path}={}){const op=this.beginLoad(signal);try{const url=new URL(input,this.doc.baseURI),source=await fetchText(url.href,{signal:op.controller.signal,credentials,limit:64*1024*1024});if(!op.current())return false;return await this.commitResult(source,path||url.pathname.split('/').at(-1)||'wayricad-results.json',op);}catch(error){if(!op.current()&&!signal?.aborted)return false;throw error;}finally{op.cleanup();}} getResults(){this.assertActive();return this.model;} getSourceState(){this.assertActive();return this.sourceState;} getView(){this.assertActive();return this.mode;} getPalette(){this.assertActive();return this.palette;} setPalette(name){this.assertActive();fieldPalette(name);if(this.palette===name)return name;if(this.scene){if(typeof this.scene.setPalette!=='function')throw new Error('Use a matching library distribution to change 3D palettes.');this.scene.setPalette(name);this.scene.setProbes?.(this.probePins());}this.palette=name;this.paletteSelect.value=name;this.cache=null;this.updateColorBar();this.boardLayer?.sync();this.invalidate();this.emit('palettechange',{palette:name});return name;} updateColorBar(){const range=this.colorRange;this.colorBar.hidden=!this.surface||!range;if(!range)return;this.colorBar.style.background='linear-gradient(to right,'+fieldPalette(this.palette).map(rgb=>'rgb('+rgb.join(',')+')').join(',')+')';this.colorBar.setAttribute('aria-label',this.palette+' palette, '+format(range[0])+' to '+format(range[1])+' '+(this.plot?.unit||'')+'. Missing values are transparent.');} getResultLayers(){this.assertActive();return [...new Set((this.model?.report.plots||[]).map(p=>p.layerName).filter(Boolean))];} setLayer(layer){this.assertActive();const plots=this.model?.report.plots||[],base=this.plot?.title?.replace(/ · [^·]+$/,'');const matches=plots.map((p,i)=>({p,i})).filter(({p})=>p.layerName===layer);const target=matches.find(({p})=>p.type===this.plot?.type&&p.title.replace(/ · [^·]+$/,'')===base)||matches[0];if(!target)throw new RangeError('Choose a saved result layer.');return this.setPlot(target.i);} setBoardOverlay(enabled){this.assertActive();if(typeof enabled!=='boolean')throw new TypeError('Choose true or false for the board overlay.');this.overlayWanted=enabled&&this.sourceReady()&&Boolean(this.surface)&&this.model?.metadata.portable?.coordinate_frame==='KiCad PCB XY in mm';this.overlayInput.checked=this.overlayWanted;this.boardLayer?.sync();return this.overlayWanted;} getBoardOverlayState(){this.assertActive();return this.boardLayer?.getState()||{placed:false,reason:'No matching board overlay.'};} getRenderStats(){this.assertActive();return {view:this.mode,palette:this.palette,sourceState:this.sourceState,preview:this.cache?{width:this.cache.width,height:this.cache.height,pixelTests:this.cache.pixelTests,range:[...this.cache.range],drawn:this.cache.drawn,omitted:this.cache.omitted}:null,scene:this.scene?.getRenderStats()||null,boardOverlay:this.getBoardOverlayState()};} setPlot(index){this.assertActive();if(!this.model)return false;const plot=this.model.report.plots[index];if(!plot){if(this.model.report.plots.length)throw new RangeError('Choose a saved plot.');this.plot=null;this.surface=null;this.paletteSelect.disabled=true;this.colorBar.hidden=true;this.plotSelect.disabled=this.viewSelect.disabled=this.fitButton.disabled=true;this.series.replaceChildren();this.legend.textContent='';this.frameRow.hidden=true;this.historyButton.hidden=true;this.status.textContent='No supported plot; complete numerical data is available below.';this.invalidate();return false;}this.plotSelect.disabled=this.viewSelect.disabled=false;this.plotTicket++;this.scene?.dispose();this.scene=null;this.mode='2d';this.plotIndex=index;this.plot=plot;this.plotSelect.value=String(index);this.viewSelect.value='2d';this.cache=null;this.lastProbe=null;this.historyButton.hidden=true;this.historyButton.textContent='Plot probe history';this.historySource=null;this.seriesPage=0;this.colorRange=this.rangeForPlot(plot);this.selected=new Set((plot.series||[]).slice(0,/eye/i.test(plot.title)?32:4).map((_,i)=>i));this.updatePlot();this.updateSeries();this.status.textContent=plot.title;this.emit('plotchange',{index,title:plot.title});return true;} updatePlot(surface){const layers=this.getResultLayers();this.layerSelect.replaceChildren(...layers.map(layer=>{const option=this.make('option',layer);option.value=layer;return option;}));this.layerSelect.disabled=!layers.length;this.layerSelect.value=this.plot?.layerName||'';this.fitButton.disabled=this.mode!=='3d';this.viewSelect.value=this.mode;this.surface=surface===undefined?wayriCADSurface(this.plot):surface;this.paletteSelect.disabled=!this.surface;this.updateColorBar();this.frameRow.hidden=!this.plot?.frames;this.frame.max=String(Math.max(0,(this.plot?.frames?.length||1)-1));this.frame.value=String(this.plot?.frameIndex||0);this.frameTime.textContent=this.plot?.frames?format(this.plot.frames[this.plot.frameIndex||0]?.time_s)+' s · '+(Number(this.frame.value)+1)+'/'+this.plot.frames.length:'';this.viewSelect.options[1].disabled=!this.surface?.zKnown;this.alpha.disabled=!this.surface;this.threeHost.hidden=this.mode!=='3d';this.canvas.hidden=this.mode==='3d';this.overlayInput.disabled=this.sourceState!=='matching'||!this.surface||this.model?.metadata.portable?.coordinate_frame!=='KiCad PCB XY in mm';this.overlayInput.checked=!this.overlayInput.disabled&&this.overlayWanted;this.invalidate();this.boardLayer?.sync();} rangeForPlot(plot){if(plot?.frames&&plot.cells&&Number.isSafeInteger(plot.layerIndex)){const count=plot.cells.length,start=plot.layerIndex*count;function* values(){for(const frame of plot.frames)for(let i=0;i<count;i++)yield frame.temperatures_c?.[start+i];}return fieldColorRange(values());}if(plot?.type==='mesh-field')return fieldColorRange(plot.values);if(plot?.type==='heatmap'){function* values(){for(const row of plot.values)yield* row;}return fieldColorRange(values());}return null;} setFrame(index){this.assertActive();if(!this.plot?.frames||!Number.isSafeInteger(index)||index<0||index>=this.plot.frames.length)throw new RangeError('Choose a saved thermal frame.');const next={...this.plot,frameIndex:index,values:wayriCADFrame(this.plot,index)},surface=wayriCADSurface(next);if(this.scene){try{this.scene.setSurface(surface);}catch(error){if(!['NO_SAVED_FIELD_VALUES','SAVED_Z_REQUIRED'].includes(error.code))throw error;this.scene.dispose();this.scene=null;this.mode='2d';this.status.textContent='Saved frame has no supported 3D field; showing its 2D data.';}}this.plot=next;this.cache=null;this.updatePlot(surface);if(this.lastProbe)this.showProbe(probeWayriCADPlot(this.plot,this.lastProbe.x,this.lastProbe.y));this.emit('framechange',{index,time:this.plot.frames[index].time_s});} async setView(mode){this.assertActive();if(!['2d','3d'].includes(mode))throw new TypeError('Choose 2d or 3d results.');const ticket=++this.plotTicket;if(mode==='2d'){this.scene?.dispose();this.scene=null;this.mode=mode;this.viewSelect.value=mode;this.updatePlot();return mode;}if(!this.surface?.zKnown)throw new Error('This field has no explicit saved elevation. Use its 2D plot.');const surface=this.surface,runtime=await import('./three-runtime.mjs'),engine=await runtime.loadThree();if(this.disposed||ticket!==this.plotTicket||surface!==this.surface)return false;if(typeof engine.mountSavedResult3D!=='function')throw new Error('This renderer does not support saved-result 3D. Use the matching library distribution.');const scene=engine.mountSavedResult3D(this.threeHost,surface,{dark:this.theme==='dark',palette:this.palette,range:this.colorRange||undefined,coordinateUnit:this.model.metadata.portable?.coordinate_frame==='KiCad PCB XY in mm'?'mm':'source units',onProbe:p=>this.showProbe(p),onDiagnostics:notes=>{if(!this.disposed)this.legend.textContent=notes.join(' ');}});if(this.disposed||ticket!==this.plotTicket){scene.dispose();return false;}if(scene.unavailable){scene.dispose();throw new Error(scene.diagnostic?.message||scene.diagnostic||'Saved field 3D is unavailable.');}this.scene?.dispose();this.scene=scene;scene.setOpacity(this.opacity);scene.setProbes?.(this.probePins());this.mode='3d';this.viewSelect.value='3d';this.updatePlot();return mode;} setTheme(theme){this.assertActive();if(!['light','dark'].includes(theme))throw new TypeError('Choose light or dark theme.');this.theme=theme;this.root.dataset.theme=theme;this.scene?.setTheme(theme==='dark');this.invalidate();} setOpacity(value){this.assertActive();if(!Number.isFinite(value)||value<0||value>1)throw new RangeError('Opacity must be 0–1.');this.opacity=value;this.alpha.value=String(Math.round(value*100));this.scene?.setOpacity(value);this.boardLayer?.sync();this.invalidate();return value;} attachBoard(viewer){this.assertActive();this.boardLayer?.dispose();this.boardLayer=null;this.stopBoard?.();this.boardViewer=viewer;this.sourceHashCache=null;this.sourceSnapshot=null;this.sourceState='unverified';if(viewer){const refresh=()=>{void this.checkSource().catch(e=>this.fail(e));};viewer.addEventListener('ready',refresh);const select=event=>this.receiveSourceSelection(event.detail),probe=event=>{const p=event.detail?.probe;if(this.sourceReady()&&this.overlayInput.checked&&this.boardLayer?.ownsProbe(p)&&[p.x,p.y,p.z,p.value].every(Number.isFinite)){const {overlayOwner,...saved}=p;this.showProbe(saved);}};viewer.addEventListener('select',select);viewer.addEventListener('analysisprobe',probe);this.stopBoard=()=>{viewer.removeEventListener('ready',refresh);viewer.removeEventListener('select',select);viewer.removeEventListener('analysisprobe',probe);};}else this.stopBoard=null;if(this.model)void this.checkSource().catch(e=>this.fail(e));} sourceReady(){return this.sourceState==='matching'&&this.boardViewer?.source===this.sourceSnapshot&&!this.boardViewer?.disposed;} highlightSource(){this.assertActive();if(!this.sourceReady()||!this.sourceLinks?.netName)return false;const nets=this.boardViewer.getNets().filter(net=>net.name===this.sourceLinks.netName);return nets.length===1?this.boardViewer.selectNet(nets[0].id,{locate:true}):false;} locateSource(){this.assertActive();if(!this.sourceReady())return false;for(const id of this.sourceLinks?.objectIds||[])if(this.boardViewer.selectObject(id,{locate:true}))return true;return false;} probeSourcePoint(x,y){if(!this.sourceReady()||!this.surface)return;this.showProbe(probeWayriCADPlot(this.plot,x,y));} receiveSourceSelection(detail){if(!this.sourceReady()||!this.model)return;const point=this.boardViewer?.getSelectionPosition?.();if(point){if(!this.overlayInput.checked&&point.layer&&point.layer!==this.plot?.layerName&&this.getResultLayers().includes(point.layer))this.setLayer(point.layer);this.probeSourcePoint(point.x,point.y);}const item=detail?.item||{},match=Boolean(this.sourceLinks?.objectIds.includes(item.uuid||item.id)||this.sourceLinks?.netName&&item.netName===this.sourceLinks.netName);this.viewport.style.outline=match?'2px solid var(--accent)':'';if(match){this.status.textContent=(this.plot?.title||'Saved result')+' · source selection matched';this.emit('sourceselection',{matched:true,netName:item.netName||null,objectId:item.uuid||item.id||null});}} async assessSource(model){const viewer=this.boardViewer,source=viewer?.source;if(!model||viewer?.kind!=='pcb'||typeof source!=='string')return{state:'unverified',source:null,viewer};if(!globalThis.crypto?.subtle)return{state:'unverified',source,viewer,reason:'PCB registration requires HTTPS or localhost; independent saved results remain available.'};if(this.sourceHashCache?.viewer!==viewer||this.sourceHashCache?.source!==source)this.sourceHashCache={viewer,source,promise:analysisSourceHash(source)};const hash=await this.sourceHashCache.promise;return{state:viewer.source===source?classifyWayriCADSource(model,hash):'unverified',source,viewer};} applyAssessment(assessment){this.boardLayer?.dispose();this.boardLayer=null;this.overlayInput.checked=this.overlayWanted;this.sourceState=assessment.viewer===this.boardViewer&&assessment.viewer?.source===assessment.source?assessment.state:'unverified';this.sourceSnapshot=this.sourceState==='matching'?assessment.source:null;this.sourceButton.disabled=this.sourceState!=='matching'||!this.sourceLinks?.netName;this.routeButton.disabled=this.sourceState!=='matching'||!this.sourceLinks?.objectIds?.length;this.sourceNote.textContent=this.sourceState==='matching'?'Matching saved PCB bytes · result provenance and solver applicability remain producer claims.':this.sourceState==='stale'?'Stale result · loaded PCB hash differs. Board overlay is disabled.':(assessment.reason||'Unverified PCB association · board overlay is disabled.');if(this.sourceState==='matching'){this.boardLayer=createWayriCADBoardLayer(this.boardViewer,{surface:()=>this.surface,range:()=>this.colorRange,palette:()=>this.palette,probe:()=>this.lastProbe,onProbe:(x,y)=>this.probeSourcePoint(x,y),onState:state=>{this.boardStatus.textContent=state.placed?(state.view==='3d'?'Registered on 3D PCB · '+(state.layer||'saved elevation')+' · visible through board and components':'Registered on PCB · '+(state.layer||'saved XY field')):state.reason;},raster:()=>{try{return this.getRaster();}catch(e){this.fail(e);return null;}},allowed:()=>!this.disposed&&this.overlayInput.checked&&this.model?.metadata.portable?.coordinate_frame==='KiCad PCB XY in mm'&&this.boardViewer?.source===this.sourceSnapshot&&this.sourceState==='matching',layer:()=>this.plot?.layerName,opacity:()=>this.opacity});}this.updatePlotIfLoaded();this.emit('sourcechange',{state:this.sourceState});} async checkSource(){const model=this.model,ticket=this.ticket,sourceTicket=this.sourceTicket=(this.sourceTicket||0)+1;if(this.boardViewer?.source!==this.sourceSnapshot)this.overlayWanted=false;this.sourceState='unverified';this.sourceSnapshot=null;this.boardLayer?.dispose();this.boardLayer=null;this.overlayInput.checked=false;this.overlayInput.disabled=true;this.sourceButton.disabled=this.routeButton.disabled=true;this.sourceNote.textContent='Unverified PCB association · independent saved results only.';const assessment=await this.assessSource(model);if(this.disposed||this.model!==model||this.ticket!==ticket||this.sourceTicket!==sourceTicket)return 'unverified';this.applyAssessment(assessment);return this.sourceState;} updatePlotIfLoaded(){if(this.plot)this.updatePlot(this.surface);} getRaster(){if(!this.surface)return null;if(this.cache)return this.cache;const result=rasterizeWayriCADSurface(this.surface,{range:this.colorRange||undefined,palette:this.palette});if(!result)return null;const canvas=this.make('canvas');canvas.width=result.width;canvas.height=result.height;const ctx=canvas.getContext('2d'),image=ctx.createImageData(result.width,result.height);image.data.set(result.pixels);ctx.putImageData(image,0,0);this.cache={...result,canvas};return this.cache;} invalidate(){if(this.disposed||this.frameRequest!==undefined||!this.visible||this.doc.hidden)return;this.frameRequest=requestAnimationFrame(()=>{this.frameRequest=undefined;try{if(!this.disposed&&this.visible&&!this.doc.hidden)this.draw();}catch(e){this.fail(e);}});} draw(){if(this.mode==='3d')return;const box=this.viewport.getBoundingClientRect(),w=Math.max(1,box.width),h=Math.max(1,box.height),dpr=Math.min(2,globalThis.devicePixelRatio||1);this.canvas.width=Math.max(1,Math.round(w*dpr));this.canvas.height=Math.max(1,Math.round(h*dpr));const ctx=this.canvas.getContext('2d');ctx.setTransform(dpr,0,0,dpr,0,0);ctx.fillStyle=this.theme==='dark'?'#1b2d3b':'#eef4f8';ctx.fillRect(0,0,w,h);this.mapping=null;if(!this.plot)return; if(this.surface){const raster=this.getRaster();if(!raster){this.legend.textContent='No finite saved field coverage.';return;}const b=raster.bounds,scale=Math.min((w-44)/(b.x1-b.x0),(h-44)/(b.y1-b.y0)),width=(b.x1-b.x0)*scale,height=(b.y1-b.y0)*scale,x=(w-width)/2,y=(h-height)/2;ctx.globalAlpha=this.opacity;ctx.drawImage(raster.canvas,x,y,width,height);ctx.globalAlpha=1;if(this.lastProbe&&Number.isFinite(this.lastProbe.x)&&Number.isFinite(this.lastProbe.y)){const px=x+(this.lastProbe.x-b.x0)*scale,py=y+(this.lastProbe.y-b.y0)*scale;ctx.beginPath();ctx.arc(px,py,6,0,Math.PI*2);ctx.strokeStyle='#fff';ctx.lineWidth=3;ctx.stroke();ctx.strokeStyle='#073e49';ctx.lineWidth=1;ctx.stroke();}this.mapping={x,y,width,height,bounds:b,field:true};this.legend.textContent=format(raster.range[0])+' – '+format(raster.range[1])+' '+(this.plot.unit||'')+' · '+raster.drawn+' supplied triangles · '+raster.omitted+' missing/degenerate triangles omitted. Transparent areas have no drawn data. Grid boundary cells are not clipped to board cutouts.';return;} if(!this.plot.series){this.legend.textContent='No supported spatial geometry. Inspect complete numerical data.';return;}const data=waveformWindow(this.plot,this.selected);this.chartData=data;if(!data.bounds){this.legend.textContent='No finite selected samples.';return;}const {x:[x0,x1],y:[y0,y1]}=data.bounds,left=60,top=18,width=Math.max(1,w-78),height=Math.max(1,h-62);ctx.strokeStyle=this.theme==='dark'?'#7891a3':'#5a7083';ctx.beginPath();ctx.moveTo(left,top);ctx.lineTo(left,top+height);ctx.lineTo(left+width,top+height);ctx.stroke();for(const series of data.series){ctx.strokeStyle=colors[series.index%colors.length];ctx.lineWidth=1.4;ctx.beginPath();let started=false;for(const p of series.points){if(!Number.isFinite(p.x)||!Number.isFinite(p.y)){started=false;continue;}const x=left+(p.x-x0)/(x1-x0)*width,y=top+height-(p.y-y0)/(y1-y0)*height;if(started)ctx.lineTo(x,y);else{ctx.moveTo(x,y);started=true;}}ctx.stroke();if(series.points.length===1&&Number.isFinite(series.points[0].y)){const p=series.points[0];ctx.fillStyle=ctx.strokeStyle;ctx.fillRect(left+(p.x-x0)/(x1-x0)*width-2,top+height-(p.y-y0)/(y1-y0)*height-2,4,4);}} ctx.fillStyle=this.theme==='dark'?'#edf4f8':'#152534';ctx.font='11px system-ui';ctx.fillText(format(y1),4,top+10);ctx.fillText(format(y0),4,top+height);ctx.fillText(format(x0),left,top+height+17);ctx.textAlign='right';ctx.fillText(format(x1),left+width,top+height+17);ctx.textAlign='center';ctx.fillText(this.plot.xLabel||'Saved axis',left+width/2,h-7);ctx.textAlign='left';this.mapping={x:left,y:top,width,height,bounds:{x0,x1,y0,y1},field:false};this.legend.textContent=data.series.length+' of '+this.plot.series.length+' saved series selected · '+data.shown+' of '+data.total+' selected saved samples shown'+(data.limited?' · DISPLAY LIMIT: remaining samples are retained in the full JSON.':' · missing values break curves; repeated timestamps are retained.'); } updateSeries(){this.series.replaceChildren();const list=this.plot?.series||[],start=(this.seriesPage||0)*20;for(let i=start;i<Math.min(list.length,start+20);i++){const label=this.make('label'),check=this.make('input');check.type='checkbox';check.checked=this.selected.has(i);check.onchange=()=>{if(check.checked)this.selected.add(i);else this.selected.delete(i);this.invalidate();};label.append(check,this.make('span',list[i].name));label.style.borderBottom='2px solid '+colors[i%colors.length];this.series.append(label);}if(start>0){const previous=this.button('Previous series',()=>{this.seriesPage--;this.updateSeries();});this.series.append(previous);}this.seriesMore.hidden=start+20>=list.length;} probeAt(event){if(!this.mapping||!this.plot)return;const box=this.canvas.getBoundingClientRect(),m=this.mapping,x=event.clientX-box.left,y=event.clientY-box.top;if(x<m.x||x>m.x+m.width||y<m.y||y>m.y+m.height)return;const px=m.bounds.x0+(x-m.x)/m.width*(m.bounds.x1-m.bounds.x0),py=m.field?m.bounds.y0+(y-m.y)/m.height*(m.bounds.y1-m.bounds.y0):m.bounds.y1-(y-m.y)/m.height*(m.bounds.y1-m.bounds.y0);const series=[...this.selected][0];this.showProbe(probeWayriCADPlot(this.plot,px,py,this.plot.series?.[series]?.name));if(this.sourceReady()&&this.sourceLinks?.netName){const nets=this.boardViewer.getNets().filter(n=>n.name===this.sourceLinks.netName);if(nets.length===1)this.boardViewer.selectNet(nets[0].id,{locate:false});}} probePins(){const p=this.lastProbe;if(!p||!this.surface||!Number.isFinite(p.x)||!Number.isFinite(p.y))return[];const z=Number.isFinite(p.z)?p.z:this.surface.points[0]?.[2];return Number.isFinite(z)?[{x:p.x,y:p.y,z}]:[];} showProbe(value){this.lastProbe=value;this.scene?.setProbes?.(this.probePins());this.boardLayer?.sync();this.invalidate();this.probe.textContent=value?(value.name||this.plot?.title||'Saved field')+' · '+format(value.value)+' '+(value.unit||'')+' · x '+format(value.x)+(value.y!==undefined?', y '+format(value.y):'')+' · '+(value.method||'Saved field'):'No saved value at this position.';this.historyButton.hidden=!value||!this.plot?.frames||!Number.isFinite(value.y);this.emit('probe',{...value});} showHistory(){if(this.historySource){this.plot=this.historySource;this.historySource=null;this.cache=null;this.colorRange=this.rangeForPlot(this.plot);this.lastProbe=null;this.historyButton.hidden=true;this.historyButton.textContent='Plot probe history';this.selected=new Set();this.updatePlot();this.updateSeries();this.status.textContent=this.plot.title;return;}if(!this.lastProbe)return;const history=wayriCADPointHistory(this.plot,this.lastProbe.x,this.lastProbe.y);if(!history)return;this.scene?.dispose();this.scene=null;this.historySource=this.plot;this.mode='2d';this.viewSelect.value='2d';this.plot=history;this.surface=null;this.colorRange=null;this.cache=null;this.selected=new Set([0]);this.updatePlot();this.updateSeries();this.historyButton.hidden=false;this.historyButton.textContent='Return to saved field';this.status.textContent=history.title;} showRaw(){this.dataList.replaceChildren();if(!this.model)return;let value=this.model.raw;for(const key of this.rawPath)value=value?.[key];this.dataPath.textContent='root'+this.rawPath.map(k=>'['+JSON.stringify(String(k).slice(0,120))+']').join('');if(this.rawPath.length)this.dataList.append(this.button('Up one level',()=>{this.rawPath.pop();this.rawPage=0;this.showRaw();}));if(value===null||typeof value!=='object'){if(typeof value==='string'){const start=(this.rawPage||0)*4096;this.dataList.append(this.make('pre',value.slice(start,start+4096)));if(start)this.dataList.append(this.button('Previous text block',()=>{this.rawPage--;this.showRaw();}));if(start+4096<value.length)this.dataList.append(this.button('Next text block',()=>{this.rawPage++;this.showRaw();}));this.dataList.append(this.make('small',Math.min(start+4096,value.length)+' of '+value.length+' characters'));}else this.dataList.append(this.make('pre',JSON.stringify(value)));return;}const array=Array.isArray(value),keys=array?null:Object.keys(value),total=array?value.length:keys.length,start=(this.rawPage||0)*100;for(let i=start;i<Math.min(total,start+100);i++){const key=array?String(i):keys[i],child=value[key],label=String(key).slice(0,120)+': '+(child&&typeof child==='object'?(Array.isArray(child)?'['+child.length+' saved entries]':'{structured fields}'):typeof child==='string'?JSON.stringify(child.slice(0,180))+(child.length>180?' …':''):JSON.stringify(child));this.dataList.append(this.button(label,()=>{this.rawPath.push(key);this.rawPage=0;this.showRaw();}));}if(start)this.dataList.append(this.button('Previous entries',()=>{this.rawPage--;this.showRaw();}));if(start+100<total)this.dataList.append(this.button('Next entries',()=>{this.rawPage++;this.showRaw();}));this.dataList.append(this.make('small',Math.min(start+100,total)+' of '+total+' entries · full arrays retained.'));} download(){this.assertActive();if(!this.model)return;const url=URL.createObjectURL(new Blob([JSON.stringify(this.model.raw)+'\n'],{type:'application/json'})),link=this.make('a');link.href=url;link.download='wayricad-results.json';link.click();setTimeout(()=>URL.revokeObjectURL(url),0);} clear(){this.assertActive();this.ticket++;this.plotTicket++;this.downloadController?.abort();this.scene?.dispose();this.scene=null;this.boardLayer?.dispose();this.boardLayer=null;this.model=this.plot=this.surface=this.cache=this.sourceSnapshot=this.historySource=this.sourceHashCache=null;this.paletteSelect.disabled=true;this.colorBar.hidden=true;this.plotSelect.disabled=this.viewSelect.disabled=this.downloadButton.disabled=this.fitButton.disabled=true;this.plotSelect.replaceChildren();this.series.replaceChildren();this.dataList.replaceChildren();this.metadata.textContent='';this.status.textContent='No saved result loaded.';this.sourceState='unverified';this.sourceLinks=null;this.sourceButton.disabled=this.routeButton.disabled=true;this.sourceNote.textContent='No PCB registration. Independent saved results only.';this.threeHost.hidden=true;this.canvas.hidden=false;this.frameRow.hidden=true;this.historyButton.hidden=true;this.legend.textContent='';this.probe.textContent='';this.overlayWanted=false;this.overlayInput.checked=false;this.overlayInput.disabled=true;this.boardStatus.textContent='';this.layerSelect.replaceChildren();this.layerSelect.disabled=true;this.mode='2d';this.invalidate();} dispose(){if(this.disposed)return;this.clear();this.disposed=true;if(this.frameRequest!==undefined)cancelAnimationFrame(this.frameRequest);this.observer?.disconnect();this.intersection?.disconnect();this.doc.removeEventListener?.('visibilitychange',this.visibility);this.stopBoard?.();this.paletteSelect.onchange=null;this.canvas.width=this.canvas.height=1;this.root.remove();if(viewerOwners.get(this.host)===this)viewerOwners.delete(this.host);this.boardViewer=null;} }