import { LandscapeRenderer, KIND } from './renderer.js'; import { layoutCity, squarifiedLayout, spatialIndex, pickRay } from './city.js'; import { apiFetch, progressEvents } from './api.mjs'; const configuredBackend=window.CODENAVIGATOR_CONFIG?.backendUrl?.trim()||''; const API_BASE=configuredBackend.replace(/\/+$/,''); const apiUrl=path=>`${API_BASE}${path}`; const $ = selector => document.querySelector(selector); const $$ = selector => [...document.querySelectorAll(selector)]; document.addEventListener('pointerdown',()=>{document.documentElement.dataset.inputMethod='pointer';},true); document.addEventListener('keydown',()=>{document.documentElement.dataset.inputMethod='keyboard';},true); const glCanvas = $('#glCanvas'); const overlay = $('#overlayCanvas'); const overlayCtx = overlay.getContext('2d'); const viewport = $('#viewport'); const MAX_2D_ZOOM=260; const MIN_3D_DISTANCE=.52; let renderer; try { renderer = new LandscapeRenderer(glCanvas); } catch (error) { $('#emptyState').hidden=false; $('#emptyState strong').textContent='WebGL2 is unavailable'; $('#emptyState span').textContent=error.message; throw error; } const palettes = [ { application:'#1fbf8c', library:'#28aa8b', test:'#c7a62e', generated:'#cc7741', vendor:'#4e83bc', platform:'#d05492', docs:'#8d9561', unknown:'#65706a' }, { application:'#48a9e6', library:'#7874db', test:'#e6a04b', generated:'#d6627c', vendor:'#45b39d', platform:'#b781d4', docs:'#9ca35c', unknown:'#697277' }, { application:'#87b95d', library:'#39a5a0', test:'#e2bf52', generated:'#e37d52', vendor:'#527ac2', platform:'#c76699', docs:'#a4a4a4', unknown:'#6b706d' }, ]; let paletteIndex=0; let files=[]; let edges=[]; let layoutItems=[]; let directoryRects=[]; let fileById=new Map(); let layoutById=new Map(); let referenceDegree=new Map(); let edgesByFile=new Map(); let sceneStats={definitions:0,totalLines:0,known:0,inferred:0,layers:new Map()}; let spatialGrid=new Map(); let visibleScreenItems=[]; let overviewCanvas=null,overviewContext=null,overviewIndex=0,overviewUploaded=-1,overviewUploadedAt=0; let codeTextureBytes=0; const codeTextureLru=new Map(),codeTextureBudget=192*1024*1024,overviewScale=3; let selected=null; let history=[]; let searchHits=[]; let expandedCoverageLayer=null; let coverageActiveIndex=-1; let cameraAnimation=null; let cityModel=null,cityEntries=[],cityIndex=null,cityFitted=false; let currentSnapshot=null; let currentName=''; let currentMetric='lines'; let showCode=true; let showLegend=false; let dirty=true; let pointer={down:false,x:0,y:0,startX:0,startY:0,action:'orbit',id:null}; let lastFrame=performance.now(), frameSamples=[]; const layerLabels = { application:'Application',library:'Libraries',test:'Tests',generated:'Generated',vendor:'Vendor',platform:'Platform',docs:'Documentation',unknown:'Other' }; function toRgb(hex){const value=parseInt(hex.slice(1),16);return[((value>>16)&255)/255,((value>>8)&255)/255,(value&255)/255];} function fileWeight(file){ if(currentMetric==='references'){ const degree=referenceDegree.get(file.id)||0; return Math.max(1,degree*55+(file.symbolCount??file.symbols?.length??0)*7); } return Math.max(1,file.lines); } function makeTree(list){ // Repositories frequently keep source files at their root. Root participates // in the same layout contract as every child directory. const root={name:currentName,path:'',children:new Map(),files:[],weight:0,depth:0}; for(const file of list){ const parts=file.path.split('/'), filename=parts.pop(); let node=root; for(const part of parts){ if(!node.children.has(part)) node.children.set(part,{name:part,path:node.path?`${node.path}/${part}`:part,children:new Map(),files:[],weight:0,depth:node.depth+1}); node=node.children.get(part); } node.files.push({name:filename,file,weight:fileWeight(file)}); } function weigh(node){ let weight=0;const layers=new Map(); for(const item of node.files||[]){weight+=item.weight;const layer=item.file.layer in layerLabels?item.file.layer:'unknown';layers.set(layer,(layers.get(layer)||0)+item.weight);} for(const child of node.children.values()){const childWeight=weigh(child);weight+=childWeight;layers.set(child.layer,(layers.get(child.layer)||0)+childWeight);} node.weight=weight;node.layer=[...layers.entries()].sort((a,b)=>b[1]-a[1])[0]?.[0]||'unknown';return weight; } weigh(root); return root; } function computeLayout(){ const root=makeTree(files); layoutItems=[];directoryRects=[]; function visit(node,x,y,w,h,depth){ directoryRects.push({node,x,y,w,h,depth}); const pad=Math.min(3.2,1.2+depth*.35,w*.07,h*.07),header=Math.min(8,Math.max(0,h*.05)),ix=x+pad,iy=y+pad+header,iw=Math.max(.01,w-pad*2),ih=Math.max(.01,h-pad*2-header); const values=[...node.children.values(),...(node.files||[])],total=values.reduce((sum,value)=>sum+value.weight,0); // A file should be compared with its siblings, not visually erased by the // aggregate weight of a huge neighboring subtree. The local floor keeps // every entry readable while leaving at least 87.5% of each region fully // proportional to the selected metric. const floor=total/Math.max(1,values.length*8); const entries=values.map(value=>({value,weight:Math.max(value.weight,floor)})).sort((a,b)=>b.weight-a.weight); squarifiedLayout(entries,ix,iy,iw,ih,depth,(wrapped,rx,ry,rw,rh)=>{ const entry=wrapped.value; if(entry.file){ const inset=Math.min(1,Math.min(rw,rh)*.08),layer=entry.file.layer in palettes[paletteIndex]?entry.file.layer:'unknown'; layoutItems.push({...entry.file,x:rx+inset,y:ry+inset,w:Math.max(.1,rw-inset*2),h:Math.max(.1,rh-inset*2),color:toRgb(palettes[paletteIndex][layer]),height:4+Math.log2(entry.file.lines+entry.file.complexity*5)*5}); }else visit(entry,rx,ry,rw,rh,depth+1); }); } visit(root,0,0,1000,680,0); layoutById=new Map(layoutItems.map(item=>[item.id,item]));buildSpatialGrid();resetCodeCaches(); renderer.setData(layoutItems);computeCity();renderer.setSelected(selected?.id||0);dirty=true; } // The city shares files, colours and the code overview atlas with the landscape but has its own // street layout in metres. Each layout item keeps its building as item.city. function computeCity(){ cityModel=layoutCity(files,currentName); const instances=[{x:-80,y:-80,w:cityModel.width+160,h:cityModel.height+160,height:.02,color:[0,0,0],kind:KIND.ground}]; for(const block of cityModel.blocks)if(block.depth>0)instances.push({x:block.x,y:block.y,w:block.w,h:block.h,height:.1+.06*Math.min(block.depth,4),color:[.55,.6,.9],kind:KIND.block}); cityEntries=[]; for(const item of layoutItems){ const building=cityModel.buildings.get(item.id);if(!building)continue; item.city={...building,file:item};cityEntries.push(item.city); instances.push({...building,color:item.color,atlas:[item.x/1000,item.y/680,item.w/1000,item.h/680],kind:KIND.building,id:item.id}); } cityIndex=spatialIndex(cityEntries); renderer.setCity(instances,{width:cityModel.width,height:cityModel.height}); } function fitCity(){ if(!cityModel)return; Object.assign(renderer.city,{view:'heli',x:cityModel.width/2,y:cityModel.height/2,yaw:-.35,pitch:.72,distance:Math.max(cityModel.width,cityModel.height)*1.05}); cityFitted=true;dirty=true; } function resetCodeCaches(){ overviewUploaded=-1;overviewCanvas=document.createElement('canvas');overviewCanvas.width=1000*overviewScale;overviewCanvas.height=680*overviewScale;overviewContext=overviewCanvas.getContext('2d',{alpha:true});overviewIndex=0;codeTextureBytes=0;codeTextureLru.clear(); } const spatialCell=50; function buildSpatialGrid(){ spatialGrid=new Map(); for(const item of layoutItems){ const x0=Math.floor(item.x/spatialCell),x1=Math.floor((item.x+item.w)/spatialCell),y0=Math.floor(item.y/spatialCell),y1=Math.floor((item.y+item.h)/spatialCell); for(let y=y0;y<=y1;y++)for(let x=x0;x<=x1;x++){const key=`${x}:${y}`,cell=spatialGrid.get(key);if(cell)cell.push(item);else spatialGrid.set(key,[item]);} } } function visibleLayout(w,h){ let candidates=layoutItems; if(renderer.mode==='2d'&&renderer.camera.zoom>1){ const halfW=w/(2*renderer.camera.zoom),halfH=h/(2*renderer.camera.zoom),x0=Math.floor((renderer.camera.x-halfW)/spatialCell),x1=Math.floor((renderer.camera.x+halfW)/spatialCell),y0=Math.floor((renderer.camera.y-halfH)/spatialCell),y1=Math.floor((renderer.camera.y+halfH)/spatialCell),seen=new Set(),near=[]; for(let y=y0;y<=y1;y++)for(let x=x0;x<=x1;x++)for(const item of spatialGrid.get(`${x}:${y}`)||[])if(!seen.has(item.id)){seen.add(item.id);near.push(item);} candidates=near; } const visible=[]; for(const item of candidates){const rect=renderer.screenRect(item);if(rect.x>w||rect.y>h||rect.x+rect.w<0||rect.y+rect.h<0)continue;visible.push({item,rect});} return visible; } function applySnapshot(snapshot){ sourceQueue.length=0;queuedSources.clear(); files=snapshot.files||[];for(const file of files)file.symbols||=[];edges=snapshot.edges||[];currentName=snapshot.name||'codebase';currentSnapshot=snapshot.id||null;selected=null;history=[];searchHits=[];expandedCoverageLayer=null;coverageActiveIndex=-1;cameraAnimation=null; fileById=new Map(files.map(file=>[file.id,file]));referenceDegree=new Map();edgesByFile=new Map();let known=0,inferred=0;for(const edge of edges){referenceDegree.set(edge.from,(referenceDegree.get(edge.from)||0)+1);referenceDegree.set(edge.to,(referenceDegree.get(edge.to)||0)+1);for(const id of [edge.from,edge.to]){const list=edgesByFile.get(id);if(list)list.push(edge);else edgesByFile.set(id,[edge]);}if(edge.confidence==='known')known++;else inferred++;} const layers=new Map();for(const file of files){const layer=file.layer in layerLabels?file.layer:'unknown';layers.set(layer,(layers.get(layer)||0)+1);}sceneStats={definitions:snapshot.definitions??files.reduce((n,file)=>n+(file.symbolCount||0),0),totalLines:snapshot.totalLines??files.reduce((n,file)=>n+file.lines,0),known,inferred,layers}; computeLayout();fitScene();fitCity();updateStats(snapshot);renderInspector();renderResults([]);renderHistory(); $('#breadcrumbText').textContent=currentName;$('#emptyState').hidden=files.length>0;$('#welcome').hidden=true; } function fitScene(){ cameraAnimation=null; if(renderer.mode==='city'){fitCity();return;} renderer.camera.x=500;renderer.camera.y=340; renderer.camera.zoom=Math.min((viewport.clientWidth-24)/1000,(viewport.clientHeight-24)/680); renderer.camera.distance=3.5;renderer.camera.yaw=-.12;renderer.camera.pitch=.76;dirty=true; } function pan3d(dx,dy){ const {yaw,distance}=renderer.camera; const scale=Math.max(.18,distance*.29); const cy=Math.cos(yaw),sy=Math.sin(yaw); // Keep the grabbed ground point beneath the pointer in screen space. renderer.camera.x+=(-dx*cy-dy*sy)*scale; renderer.camera.y+=( dx*sy-dy*cy)*scale; } function dragCity(dx,dy,action){ const c=renderer.city;if(c.view!=='heli')return; if(action==='pan'){const scale=c.distance*.0016,cy=Math.cos(c.yaw),sy=Math.sin(c.yaw);c.x+=(-dx*cy-dy*sy)*scale;c.y+=(dx*sy-dy*cy)*scale;} else{c.yaw-=dx*.007;c.pitch=Math.max(.08,Math.min(1.5,c.pitch+dy*.006));} } function dollyCity(amount){ const c=renderer.city,size=Math.max(cityModel?.width||1000,cityModel?.height||1000); if(c.view==='heli')c.distance=Math.max(12,Math.min(size*3,c.distance*Math.exp(amount))); } function dolly3d(amount){ renderer.camera.distance=Math.max(MIN_3D_DISTANCE,Math.min(14,renderer.camera.distance*Math.exp(amount))); } function updateStats(snapshot={}){ const definitions=snapshot.definitions??files.reduce((n,file)=>n+file.symbols.length,0); const references=snapshot.references??edges.length; $('#headlineStats').textContent=`${format(definitions)} definitions · ${format(references)} references`; $('#fileStats').textContent=`${format(files.length)} files · ${format(snapshot.totalLines??files.reduce((n,f)=>n+f.lines,0))} lines`; } function format(value){return Number(value||0).toLocaleString();} function escapeHtml(value=''){return String(value).replace(/[&<>"]/g,char=>({'&':'&','<':'<','>':'>','"':'"'}[char]));} const syntaxPalette={plain:'#b6bfd0',comment:'#5c667a',string:'#8fd694',number:'#f5a97f',keyword:'#c69cff',type:'#6ec6ff',function:'#7aa7ff',property:'#5fd3c6',operator:'#8f9ab0',constant:'#ff8fa3',tag:'#5fd3c6'}; // Matches the renderer's tile top so code drawn over a 3D roof blends with the WebGL face. const TILE_TOP='#0e1118'; const syntaxKeywords=new Set(`abstract as async await break case catch class const continue crate def default defer delete do else enum export extends extern false final finally fn for from func function get go if impl import in instanceof interface is lambda let loop match mod module mut namespace new nil None null of override package private protected pub public raise readonly require return self set static struct super switch this throw trait true try type typeof undefined union unsafe use using var virtual void where while with yield`.split(' ')); const syntaxConstants=new Set('true false null nil none undefined nan infinity self this super'.split(' ')); const tokenPattern=/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`|\b0x[\da-f]+\b|\b0b[01]+\b|#[\da-f]{3,8}\b|\b\d+(?:\.\d+)?(?:e[+-]?\d+)?\b|[A-Za-z_$][\w$-]*|\s+|./gi; function syntaxKind(file={}){ const ext=(file.extension||file.name?.split('.').pop()||'').toLowerCase(),language=(file.language||'').toLowerCase(); if(['html','htm','xml','svg','vue','svelte'].includes(ext))return'markup'; if(['css','scss','sass','less'].includes(ext))return'css'; if(['json','jsonc','toml','yaml','yml'].includes(ext))return'data'; if(['md','mdx','rst','txt'].includes(ext)||language==='docs')return'docs'; if(['py','pyi','rb','r','pl','sh','bash','zsh','fish'].includes(ext))return'hash-comment'; if(['sql','lua','hs'].includes(ext))return'dash-comment'; return language==='other'?'plain':'code'; } function commentStart(line,kind){ const markers=kind==='markup'?['