@wayrisignals/kicad-webview
Version:
Interactive KiCad schematic, PCB and 3D viewer for the web, with Gerber, Excellon, linked views and offline HTML exports
89 lines (88 loc) • 19.1 kB
JavaScript
/* Copyright (c) 2026 wayri. SPDX-License-Identifier: MPL-2.0 */
import {buildProjectHierarchy} from './project-hierarchy.mjs';
import {loadProjectHierarchy} from './hierarchy-loader.mjs';
import {safeRelativePath} from './source-types.mjs';
import {viewerOwners} from './viewer-host.mjs';
export {buildProjectHierarchy,loadProjectHierarchy};
const statuses=new Set(['ok','missing','invalid','cycle','truncated','error']);
function hierarchyRows(model){
if(model?.schema!=='kicad-webview.hierarchy/v1'||!Array.isArray(model.roots)||model.roots.length>4096||!Array.isArray(model.warnings)||model.warnings.length>1024||model.warnings.some(w=>typeof w!=='string'||w.length>8192)||!Array.isArray(model.files)||model.files.length>256)throw new TypeError('Choose a generated project hierarchy.');
const paths=new Set(model.files.map(file=>file.path));if(paths.size!==model.files.length||model.rootPath!==null&&!paths.has(model.rootPath))throw new TypeError('Hierarchy paths must be unique and root must be listed.');for(const path of paths)if(!safeRelativePath(path)||!/\.kicad_sch$/i.test(path))throw new TypeError('Hierarchy files need safe schematic paths.');
const rows=[],seen=new Set(),ids=new Set(),stack=model.roots.map(node=>({node,depth:0,parent:null})).reverse();
while(stack.length){const row=stack.pop(),node=row.node;if(rows.length>=4096||row.depth>33||!node||seen.has(node)||typeof node.id!=='string'||node.id.length>2048||ids.has(node.id)||!statuses.has(node.status)||!Array.isArray(node.children)||rows.length+stack.length+node.children.length+1>4096||node.path!==null&&!paths.has(node.path))throw new TypeError('Hierarchy contains invalid, recursive or excessive nodes.');
if(node.instancePath!==undefined&&node.instancePath!==null&&(typeof node.instancePath!=='string'||node.instancePath.length>8192||!/^\/[^\x00-\x1f\x7f]+$/.test(node.instancePath)))throw new TypeError('Invalid saved sheet instance path.');
for(const field of ['name','file'])if(typeof node[field]!=='string'||node[field].length>8192)throw new TypeError('Hierarchy labels exceed their limit.');
seen.add(node);ids.add(node.id);row.index=rows.length;rows.push(row);for(let i=node.children.length-1;i>=0;i--)stack.push({node:node.children[i],depth:row.depth+1,parent:row.index});
}
return rows;
}
const label=node=>String(node.name||node.file||node.path||'Unnamed sheet').replace(/\s+/g,' ').slice(0,160);
const escape=text=>String(text).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\ufffe\uffff]/g,'').replace(/[&<>"']/g,ch=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[ch]));
/** Portable, script-free SVG. The export explicitly discloses its size cap. */
export function hierarchyToSVG(model,{theme='dark'}={}){
if(!['light','dark'].includes(theme))throw new TypeError('Choose light or dark theme.');
const all=hierarchyRows(model),rows=all.slice(0,512),maxDepth=Math.max(0,...rows.map(row=>row.depth)),width=Math.max(440,Math.min(1600,maxDepth*28+410)),height=72+rows.length*64+(all.length>rows.length?32:0),dark=theme==='dark',bg=dark?'#101b28':'#f5f8fc',ink=dark?'#e8f1fa':'#203347',muted=dark?'#9fb5ca':'#52697e',border=dark?'#3c566d':'#b8cad9',accent=dark?'#7de3d4':'#126d70';
const svg=['<svg xmlns="http://www.w3.org/2000/svg" width="'+width+'" height="'+height+'" viewBox="0 0 '+width+' '+height+'" role="img" aria-label="Project schematic hierarchy"><rect width="100%" height="100%" fill="'+bg+'"/><g font-family="system-ui,sans-serif"><text x="20" y="30" font-size="18" font-weight="700" fill="'+ink+'">Project schematic hierarchy</text>'];
for(const row of rows){const x=20+row.depth*28,y=48+row.index*64,w=Math.min(350,width-x-20),node=row.node;if(row.parent!==null){const parent=rows[row.parent],px=20+parent.depth*28+10,py=48+parent.index*64+48;svg.push('<path d="M '+px+' '+py+' V '+(y+23)+' H '+x+'" fill="none" stroke="'+border+'"/>');}
svg.push('<rect x="'+x+'" y="'+y+'" width="'+w+'" height="48" rx="7" fill="'+(dark?'#192a3a':'#fff')+'" stroke="'+(node.status==='ok'?border:'#bd794f')+'"/><text x="'+(x+10)+'" y="'+(y+20)+'" font-size="13" font-weight="600" fill="'+ink+'">'+escape(label(node).slice(0,42))+'</text><text x="'+(x+10)+'" y="'+(y+37)+'" font-size="10" fill="'+(node.status==='ok'?muted:accent)+'">'+escape((node.path||node.file||'No saved Sheetfile').slice(0,48))+' · '+escape(node.status)+'</text>');
}
if(all.length>rows.length)svg.push('<text x="20" y="'+(height-14)+'" font-size="12" fill="'+ink+'">Export limited to512 of '+all.length+' sheet instances. Use the interactive tree for the full hierarchy.</text>');
return svg.join('')+'</g></svg>';
}
const STYLE=':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}';
/** Independent read-only diagram. Selecting a node emits data; the host owns navigation. */
export class ProjectTree extends EventTarget{
constructor(target,{theme='dark',onSelect}={}){
super();const host=typeof target==='string'?document.querySelector(target):target;if(!host?.ownerDocument||!host.append)throw new TypeError('Choose a tree container.');if(viewerOwners.has(host))throw new Error('This container already has a viewer.');if(onSelect!==undefined&&typeof onSelect!=='function')throw new TypeError('onSelect must be a function.');
this.host=host;this.doc=host.ownerDocument;this.onSelect=onSelect;this.disposed=false;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;
const make=(tag,text)=>{const n=this.doc.createElement(tag);if(text)n.textContent=text;return n;};this.make=make;const style=make('style');style.textContent=STYLE;this.tools=make('div');this.tools.className='tools';this.tools.append(make('strong','Project tree'));this.toolButtons=[];
for(const [text,action]of [['Expand all',()=>this.expandAll()],['Collapse all',()=>this.collapseAll()]]){const button=make('button',text);button.type='button';button.onclick=action;this.tools.append(button);this.toolButtons.push(button);}
for(const [text,action]of [['Zoom out',()=>this.zoomBy(1/1.25)],['Zoom in',()=>this.zoomBy(1.25)],['Fit',()=>this.fit()],['Reset view',()=>this.resetView()]]){const button=make('button',text);button.type='button';button.onclick=action;this.tools.append(button);this.toolButtons.push(button);}
this.camera={zoom:1,x:0,y:0};this.drag=null;
this.status=make('p','Load a project to see its saved schematic hierarchy.');this.status.className='status';this.status.setAttribute('role','status');this.diagram=make('nav');this.diagram.className='diagram';this.diagram.setAttribute('aria-label','Project schematic hierarchy');this.diagram.tabIndex=0;this.content=make('div');this.content.className='tree-content';this.diagram.append(this.content);this._installNavigation();this.warnings=make('div');this.warnings.className='warnings';this.warnings.hidden=true;this.surface.append(style,this.tools,this.status,this.diagram,this.warnings);this.setTheme(theme);host.append(this.root);viewerOwners.set(host,this);
}
assertActive(){if(this.disposed)throw new Error('The project tree has been disposed.');}
setTheme(theme){this.assertActive();if(!['light','dark'].includes(theme))throw new TypeError('Choose light or dark theme.');this.theme=theme;this.root.setAttribute('data-theme',theme);}
_installNavigation(){
const down=event=>{if(this.disposed||event.pointerType==='touch'||event.button!==0||(!event.altKey&&event.target!==this.diagram&&event.target!==this.content&&event.target?.tagName!=='UL'&&event.target?.tagName!=='LI')||event.composedPath?.().some(node=>node?.tagName==='BUTTON'))return;this.drag={id:event.pointerId,x:event.clientX,y:event.clientY,left:this.diagram.scrollLeft||0,top:this.diagram.scrollTop||0};this.diagram.setPointerCapture?.(event.pointerId);this.diagram.setAttribute('data-panning','true');event.preventDefault();};
const move=event=>{if(!this.drag||event.pointerId!==this.drag.id)return;this.diagram.scrollLeft=this.drag.left-(event.clientX-this.drag.x);this.diagram.scrollTop=this.drag.top-(event.clientY-this.drag.y);this._rememberScroll();event.preventDefault();};
const up=event=>{if(!this.drag||event.pointerId!==this.drag.id)return;this.diagram.releasePointerCapture?.(event.pointerId);this.drag=null;this.diagram.setAttribute('data-panning','false');};
const scroll=()=>this._rememberScroll();
for(const [name,fn] of [['pointerdown',down],['pointermove',move],['pointerup',up],['pointercancel',up],['scroll',scroll]]){this.diagram.addEventListener(name,fn);this.listeners.push([name,fn]);}
}
_rememberScroll(){if(!this.disposed&&this.model){this.camera.x=Math.max(0,Math.min(1000000,this.diagram.scrollLeft||0));this.camera.y=Math.max(0,Math.min(1000000,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(){this.assertActive();this._rememberScroll();return {...this.camera};}
setCamera(camera){this.assertActive();if(!camera||![camera.zoom,camera.x,camera.y].every(Number.isFinite)||camera.zoom<.35||camera.zoom>2||camera.x<0||camera.x>1000000||camera.y<0||camera.y>1000000)throw new TypeError('Camera needs zoom 0.35–2 and scroll offsets 0–1000000.');this.camera={zoom:camera.zoom,x:camera.x,y:camera.y};this._applyCamera();return this.getCamera();}
zoomBy(factor){this.assertActive();if(!Number.isFinite(factor)||factor<=0)throw new TypeError('Zoom factor must be positive.');const camera=this.getCamera(),zoom=Math.max(.35,Math.min(2,camera.zoom*factor));return this.setCamera({...camera,zoom});}
fit(){this.assertActive();const w=this.diagram.clientWidth,h=this.diagram.clientHeight,cw=this.content.offsetWidth,ch=this.content.offsetHeight;if(!this.model||![w,h,cw,ch].every(n=>Number.isFinite(n)&&n>0))return false;this.setCamera({zoom:Math.max(.35,Math.min(2,w/cw,h/ch)),x:0,y:0});return true;}
resetView(){this.assertActive();return this.setCamera({zoom:1,x:0,y:0});}
_error(error){if(this.disposed)return;this.status.textContent=error.message||String(error);this.dispatchEvent(new CustomEvent('error',{detail:{error}}));}
async load(input,options={}){
this.assertActive();this.pending?.abort();const controller=new AbortController(),ticket=++this.ticket;this.pending=controller;const abort=()=>controller.abort();options.signal?.addEventListener('abort',abort,{once:true});if(options.signal?.aborted)abort();this.status.textContent='Reading saved sheet links…';
try{const model=await loadProjectHierarchy(input,{...options,signal:controller.signal});if(this.disposed||ticket!==this.ticket||controller.signal.aborted)return false;this._setHierarchy(model);this.dispatchEvent(new CustomEvent('ready',{detail:{hierarchy:this.getHierarchy()}}));return true;}
catch(error){if(this.disposed||ticket!==this.ticket||controller.signal.aborted&&!options.signal?.aborted)return false;this._error(error);throw error;}
finally{options.signal?.removeEventListener('abort',abort);if(ticket===this.ticket)this.pending=null;}
}
loadFiles(files,options={}){return this.load(files,options);}
loadArchive(bytes,options={}){return this.load(bytes,options);}
setHierarchy(model){this.assertActive();hierarchyRows(model);this.pending?.abort();this.pending=null;++this.ticket;this._setHierarchy(model);return this;}
setFiles(files,options={}){return this.setHierarchy(buildProjectHierarchy(files,options));}
_setHierarchy(model){const rows=hierarchyRows(model);this.model=structuredClone(model);this.rows=hierarchyRows(this.model);this.expanded=new Set(rows.filter(row=>row.depth<2).map(row=>row.node.id));this.selectedId=null;this._render();this.status.textContent=this.model.files.length+' schematic files · '+this.rows.length+' sheet instances · '+(this.model.rootPath?'Root: '+this.model.rootPath:'Multiple roots / no unambiguous root');this.warnings.textContent=(this.model.warnings||[]).slice(0,256).map(String).join('\n');this.warnings.hidden=!this.warnings.textContent;}
_render(){
if(this.content.children.length)this._rememberScroll();
for(const button of this.buttons.values())button.onclick=null;for(const branch of this.branches.values())branch.toggle.onclick=null;this.buttons.clear();this.branches.clear();const root=this.make('ul');root.className='tree-list';const lists=new Map([[null,root]]);
for(const row of this.rows){const node=row.node,li=this.make('li'),line=this.make('div');line.className='node-row';let children;
if(node.children.length){const toggle=this.make('button',this.expanded.has(node.id)?'−':'+');toggle.type='button';toggle.className='branch-toggle';toggle.setAttribute('aria-label','Toggle subsheets of '+label(node));toggle.setAttribute('aria-expanded',String(this.expanded.has(node.id)));children=this.make('ul');children.className='tree-list';children.hidden=!this.expanded.has(node.id);toggle.onclick=()=>{if(this.expanded.has(node.id))this.expanded.delete(node.id);else this.expanded.add(node.id);children.hidden=!this.expanded.has(node.id);toggle.textContent=children.hidden?'+':'−';toggle.setAttribute('aria-expanded',String(!children.hidden));};line.append(toggle);this.branches.set(node.id,{toggle,children});lists.set(row.index,children);}else{const spacer=this.make('span');spacer.className='branch-spacer';line.append(spacer);}
const button=this.make('button');button.type='button';button.className='node-button';button.setAttribute('aria-pressed',String(node.id===this.selectedId));button.setAttribute('aria-label','Open schematic '+(node.path||node.file||label(node)));button.title=node.path||node.file||label(node);button.disabled=node.status!=='ok'||!node.path;button.append(this.make('strong',label(node)),this.make('small',node.path||node.file||'No saved Sheetfile'));const state=this.make('span',node.status==='ok'?(node.role==='unlinked'?'Unlinked / separate root':row.depth===0?'Root sheet':'Subsheet'):node.status);state.className='node-state';button.append(state);button.onclick=()=>this.select(node.id);line.append(button);li.append(line);if(children)li.append(children);lists.get(row.parent).append(li);this.buttons.set(node.id,button);
}
this.content.replaceChildren(root);this._applyCamera();
}
expandAll(){this.assertActive();for(const [id,branch]of this.branches){this.expanded.add(id);branch.children.hidden=false;branch.toggle.textContent='−';branch.toggle.setAttribute('aria-expanded','true');}}
collapseAll(){this.assertActive();this.expanded.clear();for(const branch of this.branches.values()){branch.children.hidden=true;branch.toggle.textContent='+';branch.toggle.setAttribute('aria-expanded','false');}}
select(id){this.assertActive();const node=this.rows?.find(row=>row.node.id===id)?.node;if(!node||node.status!=='ok'||!node.path)return false;this.selectedId=id;for(const [key,button]of this.buttons)button.setAttribute('aria-pressed',String(key===id));const selected={id:node.id,path:node.path,file:node.file,name:node.name,uuid:node.uuid,status:node.status,...(node.instancePath?{instancePath:node.instancePath}:{})};this.dispatchEvent(new CustomEvent('select',{detail:{node:{...selected}}}));const ticket=this.ticket;try{Promise.resolve(this.onSelect?.({...selected})).catch(error=>{if(ticket===this.ticket)this._error(error);});}catch(error){this._error(error);}return true;}
clear(){this.assertActive();this._rememberScroll();this.pending?.abort();this.pending=null;++this.ticket;for(const button of this.buttons.values())button.onclick=null;for(const branch of this.branches.values())branch.toggle.onclick=null;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=true;return this;}
getHierarchy(){this.assertActive();return this.model?structuredClone(this.model):null;}
toSVG(options={}){this.assertActive();if(!this.model)throw new Error('Load a hierarchy before exporting.');return hierarchyToSVG(this.model,{theme:this.theme,...options});}
dispose(){if(this.disposed)return;this.disposed=true;++this.ticket;this.pending?.abort();this.pending=null;for(const [name,fn] of this.listeners)this.diagram.removeEventListener(name,fn);this.listeners=[];if(this.drag)this.diagram.releasePointerCapture?.(this.drag.id);this.drag=null;for(const button of this.toolButtons)button.onclick=null;for(const button of this.buttons.values())button.onclick=null;for(const branch of this.branches.values())branch.toggle.onclick=null;this.buttons.clear();this.branches.clear();this.root.remove();if(viewerOwners.get(this.host)===this)viewerOwners.delete(this.host);this.model=null;this.rows=[];this.onSelect=null;}
}