Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

36.8 KB
Raw Blame
import { validateProject, planProject, footprint, history, clone, ASSUMPTIONS } from './project.mjs';
import { bounds, distance, parseGeoJSON, flightRegion, pointIn, toLonLat } from './geo.mjs';
import { parseCSV, importFlight, analyzeFlight, verifyFlightSource } from './log.mjs';
import { geoJSON, photoCSV, routeCSV, flightCSV, kml, report as createReport, reportHTML, mapSVG, escapeHTML as esc, slug } from './formats.mjs';
import { zipFiles } from './archive.mjs';

const originalHTML = '<!doctype html>' + document.documentElement.outerHTML;
const payload = JSON.parse(document.getElementById('vector-data').textContent);
const $ = id => document.getElementById(id), $$ = selector => [...document.querySelectorAll(selector)];
const num = (n, digits=0) => n.toLocaleString(undefined,{maximumFractionDigits:digits,minimumFractionDigits:digits});
const uid = prefix => prefix + '-' + crypto.randomUUID().slice(0,8);
const notify = message => { $('status').textContent=message; };
const download = (name,body,type='application/octet-stream') => { const url=URL.createObjectURL(body instanceof Blob?body:new Blob([body],{type})),a=document.createElement('a');a.href=url;a.download=name;a.click();setTimeout(()=>URL.revokeObjectURL(url),10000); };
let project=validateProject(payload.project), revision=project.revision, journal=history(project), plan=null, evidence=null, selected=null, selectedSortie=null, selectedPhoto=null, logSample=null, tool='select', drawn=[], view=null, logInput=null;
let connected=false,dirty=false,saving=false,pendingSource=null,pollEpoch=0,drag=null;
const draftKey='vector-draft:'+location.pathname+':'+location.port;
function guard(fn) { return async (...args) => { try { $$('.dialog-error').forEach(e=>e.remove()); await fn(...args); } catch(error) { notify(error.message); const dialog=document.querySelector('dialog[open]'); if(dialog){const message=document.createElement('p');message.className='dialog-error';message.setAttribute('role','alert');message.textContent=error.message;dialog.append(message);}else{$('plan-error').textContent=error.message;$('plan-error').hidden=false;} } }; }
function stash() { try { localStorage.setItem(draftKey,JSON.stringify({project,revision})); } catch { notify('Draft storage is full. Save a project file or save to the workspace.'); } }
function status() {
  $('save-state').textContent=dirty?'Unsaved draft':connected?'Saved in workspace':'Editable offline project';
  $('save-source').hidden=!connected;$('save-source').disabled=!dirty||saving||Boolean(pendingSource);
  $('undo').disabled=!journal.canUndo;$('redo').disabled=!journal.canRedo;$('deliver').disabled=!plan;
}
function change(edit,message='Plan updated') {
  const next=clone(project);edit(next);project=journal.push(next);dirty=true;rebuild();stash();notify(message);
}
async function open(next,message='Project opened as a draft') { const checked=validateProject(next);await verifyFlightSource(checked);project=journal.push(checked);selected=null;selectedSortie=null;view=null;dirty=true;rebuild();stash();notify(message); }
function resetSource(next) {project=validateProject(next);revision=project.revision;journal=history(project);dirty=false;selected=null;selectedSortie=null;view=null;try{localStorage.removeItem(draftKey);}catch{}rebuild();}
const input = (label,key,value,step=1,group='settings') => `<label>${esc(label)}<input type="number" data-field="${key}" data-group="${group}" value="${value}" step="${step}"></label>`;
function renderSettings() {
  const s=project.settings,c=project.camera;
  $('settings-panel').innerHTML=`<section><div class="section-title">CAPTURE GEOMETRY</div><div class="two">${input('Height above takeoff · m','height',s.height,1)}${input('Survey speed · m/s','speed',s.speed,.1)}</div><div class="two">${input('Front overlap · %','frontOverlap',s.frontOverlap*100,1)}${input('Side overlap · %','sideOverlap',s.sideOverlap*100,1)}</div><div class="two">${input('Line angle · degrees','angle',s.angle,1)}${input('Horizontal margin · m','margin',s.margin,.5)}</div><p>0° is east; 90° is north. Margins inset boundaries and expand exclusions. Image coverage can extend beyond the flight region.</p></section><section><div class="section-title">TIME PER SORTIE</div><div class="two">${input('Measured usable · min','usableMinutes',s.usableMinutes,.5)}${input('Reserve · %','reservePercent',s.reservePercent,1)}</div><div class="two">${input('Climb · m/s','climbSpeed',s.climbSpeed,.1)}${input('Descent · m/s','descentSpeed',s.descentSpeed,.1)}</div>${input('Allowance per capture run · s','turnSeconds',s.turnSeconds,.5)}<p>Return, climb and descent are included. A fixed turn allowance is not an aircraft dynamics model.</p></section><section><div class="section-title">YOUR CAMERA</div><label>Camera name<input id="camera-name" value="${esc(c.name)}" maxlength="120"></label><div class="two">${input('Sensor width · mm','sensorWidth',c.sensorWidth,.1,'camera')}${input('Sensor height · mm','sensorHeight',c.sensorHeight,.1,'camera')}</div><div class="two">${input('Focal length · mm','focalLength',c.focalLength,.1,'camera')}${input('Min. interval · s','minInterval',c.minInterval,.1,'camera')}</div><details><summary>Image dimensions</summary><div class="two">${input('Width · pixels','imageWidth',c.imageWidth,1,'camera')}${input('Height · pixels','imageHeight',c.imageHeight,1,'camera')}</div></details></section>`;
  $$('[data-field]').forEach(el=>el.onchange=guard(()=>change(p=>{let value=Number(el.value);if(!el.value.trim())throw new Error('Enter a value.');if(['frontOverlap','sideOverlap'].includes(el.dataset.field))value/=100;p[el.dataset.group][el.dataset.field]=value;})));
  $('camera-name').onchange=guard(e=>change(p=>{p.camera.name=e.target.value;}));
  const compare=document.createElement('button');compare.id='compare-angles';compare.textContent='Compare line directions ↗';compare.style.width='100%';compare.onclick=guard(compareAngles);$('settings-panel').querySelector('section').append(compare);
}
function renderMetrics() {
  const items=plan?[['Target area',num(plan.area/10000,2),'ha'],['Ground sampling',num(plan.camera.gsdX,2),'cm/px'],['Planned captures',num(plan.photos.length),'photos'],['Nominal coverage',num(plan.coverage*100,1),'%'],['Sorties',num(plan.sorties.length),'returns included'],['Nominal time',num(plan.totalSeconds/60,1),'min']]:[['Target area','—',''],['Ground sampling','—',''],['Planned captures','—',''],['Nominal coverage','—',''],['Sorties','—',''],['Nominal time','—','']];
  $('metrics').innerHTML=items.map(([label,value,unit])=>`<div class="metric"><small>${label}</small><b>${value}<em>${unit}</em></b></div>`).join('');
}
function renderAreas() {
  if(!project.areas.some(a=>a.id===selected))selected=null;
  $('area-count').textContent=project.areas.length;
  $('area-list').innerHTML=project.areas.map(a=>`<button class="area-row ${a.id===selected?'active':''}" data-area="${esc(a.id)}"><i style="background:${a.kind==='boundary'?'#829f72':'#cb8e7d'}"></i><span>${esc(a.name)}</span><small>${a.locked?'Locked':a.ring.length+' pts'}</small></button>`).join('');
  $$('[data-area]').forEach(el=>el.onclick=()=>{selected=el.dataset.area;renderAreas();renderMap();});
  const area=project.areas.find(a=>a.id===selected);
  $('area-editor').innerHTML=area?`<label>Layer name<input id="area-name" value="${esc(area.name)}" ${area.locked?'disabled':''}></label><div class="row-actions"><button id="lock-area">${area.locked?'Unlock geometry':'Lock geometry'}</button><button id="delete-area" ${area.locked?'disabled':''}>Remove</button></div><details><summary>Vertices · east, north meters</summary><textarea id="vertices" rows="6" ${area.locked?'disabled':''}>${area.ring.map(p=>p.map(n=>num(n,2).replaceAll(',','')).join(', ')).join('\n')}</textarea><button id="apply-vertices" ${area.locked?'disabled':''}>Apply vertices</button></details><p>${area.locked?'Unlock to change this geometry.':'Drag its corner handles on the map. Enter coordinates for precise edits.'}</p>`:'';
  if(area){$('area-name').onchange=guard(e=>change(p=>{p.areas.find(a=>a.id===selected).name=e.target.value;}));$('lock-area').onclick=guard(()=>change(p=>{const a=p.areas.find(a=>a.id===selected);a.locked=!a.locked;}));$('delete-area').onclick=guard(()=>change(p=>{p.areas=p.areas.filter(a=>a.id!==selected);}));$('apply-vertices').onclick=guard(()=>{const points=$('vertices').value.trim().split(/\n/).map(row=>row.split(',').map(v=>Number(v.trim())));change(p=>{p.areas.find(a=>a.id===selected).ring=points;});});}
}
function renderSorties() {
  if(selectedSortie&&!plan?.sorties.some(s=>s.id===selectedSortie))selectedSortie=null;
  $('sortie-list').innerHTML=plan?plan.sorties.map(s=>`<button class="sortie ${selectedSortie===s.id?'active':''}" data-sortie="${s.id}"><span class="row"><b>Sortie ${String(s.id).padStart(2,'0')}</b><span>${num(s.seconds/60,1)} min</span></span><small>${s.photos.length} captures · ${num(s.distance)} m · ${num(s.remainingSeconds)} s unused</small><div class="bar"><i style="width:${Math.min(100,s.seconds/plan.budgetSeconds*100)}%"></i></div></button>`).join(''):'<p>Resolve the planning issue to generate sorties.</p>';
  $$('[data-sortie]').forEach(el=>el.onclick=()=>{selectedSortie=Number(el.dataset.sortie);selectedPhoto=plan.sorties.find(s=>s.id===selectedSortie).photos[0].id;renderSorties();renderMap();});
  if(plan&&selectedSortie){const sortie=plan.sorties.find(s=>s.id===selectedSortie);if(!sortie.photos.some(p=>p.id===selectedPhoto))selectedPhoto=sortie.photos[0].id;const i=sortie.photos.findIndex(p=>p.id===selectedPhoto),p=sortie.photos[i],inspector=document.createElement('div');inspector.className='hint';inspector.innerHTML=`<label>Inspect planned capture<input id="inspect-photo" type="range" min="0" max="${sortie.photos.length-1}" value="${i}"></label><span id="photo-details">Photo ${p.id} · ${num(p.time/60,1)} min after takeoff</span><p>Outlined rectangle = ideal image footprint. Drag the slider to inspect each capture.</p>`;$('sortie-list').append(inspector);$('inspect-photo').oninput=e=>{const p=sortie.photos[Number(e.target.value)];selectedPhoto=p.id;$('photo-details').textContent=`Photo ${p.id} · ${num(p.time/60,1)} min after takeoff`;renderMap();};}
}
function renderEvidence() {
  const log=project.log;
  if(!log){$('evidence-panel').innerHTML='<section><div class="section-title">FROM PLAN TO EVIDENCE</div><p>Bring a flight CSV to inspect recorded positions, capture events, timing and gaps against this plan.</p><button id="import-log" class="primary">Import flight CSV…</button><p>Choose the columns and units yourself. The original CSV stays in your editable project and exported kit.</p><div class="hint">No flight has been recorded in this example.</div></section>';}
  else{const e=evidence;$('evidence-panel').innerHTML=`<section><div class="section-title">RECORDED SOURCE</div><strong style="font-size:12px;word-break:break-word">${esc(log.name)}</strong><p>${log.records.length} coordinate samples · ${log.sourceRows} source rows<br>${log.startTime?esc(log.startTime):'Elapsed time from first source row'}</p><div class="row-actions"><button id="import-log">Replace log</button><button id="remove-log">Remove</button></div><label>Compare nearest route<select id="compare-sortie"><option value="">All planned routes</option>${(plan?.sorties??[]).map(s=>`<option value="${s.id}" ${log.comparisonSortie===s.id?'selected':''}>Sortie ${s.id}</option>`).join('')}</select></label><label>Break track after a gap · seconds<input id="gap-limit" type="number" min=".1" max="120" step=".5" value="${log.maxGap??10}"></label>${e?`<div class="evidence-metrics"><div><b>${e.captureEvents}</b>Recorded capture events</div><div><b>${e.coverage===null?'—':num(e.coverage*100,1)+'%'}</b>Estimated event coverage</div><div><b>${num(e.deviationP95,1)} m</b>P95 nearest-route distance</div><div><b>${e.outsideSamples}</b>Positions outside flight area</div></div><p>${e.modeledCaptures} event footprints modeled; ${e.unmodeledCaptures} events lack height or heading. ${e.unknownCaptureSamples} samples have unknown capture state.</p><p>${e.discontinuities} track breaks · ${e.missingCoordinates} rows without coordinates · ${num(e.measuredDistance)} m connected track.</p><p>Recorded span ${num(e.elapsedSeconds/60,1)} min. Battery: ${e.startBattery===null?'unknown':num(e.startBattery)+'%'} → ${e.endBattery===null?'unknown':num(e.endBattery)+'%'}.</p><div class="hint">Event coverage is an estimate of the whole target. Images, camera orientation and mapping quality have not been verified.</div>`:'<p>Resolve the plan or comparison selection to analyze this log.</p>'}</section><details><summary>Column mapping &amp; source hash</summary><pre style="font-size:9px;white-space:pre-wrap;word-break:break-word">${esc(JSON.stringify(log.mapping,null,2))}\nSHA-256 ${esc(log.sha256)}</pre></details>`;
    $('remove-log').onclick=guard(()=>change(p=>{delete p.log;},'Recorded log removed from draft'));
    $('compare-sortie').onchange=guard(e=>change(p=>{p.log.comparisonSortie=e.target.value?Number(e.target.value):null;}));
    $('gap-limit').onchange=guard(e=>change(p=>{const n=Number(e.target.value);if(n<.1||n>120)throw new Error('Use a gap threshold between 0.1 and 120 seconds.');p.log.maxGap=n;}));
  }
  $('import-log').onclick=()=>{$('log-file').value='';$('log-file').click();};
  if(log&&evidence){const inspector=document.createElement('section');logSample=Math.min(logSample??0,log.records.length-1);inspector.innerHTML=`<div class="section-title">INSPECT A LOG SAMPLE</div><input id="inspect-log" aria-label="Recorded sample" type="range" min="0" max="${log.records.length-1}" value="${logSample}"><p id="sample-details"></p>`;$('evidence-panel').append(inspector);const detail=()=>{const row=log.records[logSample];$('sample-details').textContent=`Row ${row.sourceRow} · ${num(row.time,1)} s · height ${row.altitude===null?'unknown':num(row.altitude,1)+' m'} · capture ${row.capture===null?'unknown':row.capture?'recorded':'no event'}`;};detail();$('inspect-log').oninput=e=>{logSample=Number(e.target.value);detail();renderMap();};}
  $('log-legend').hidden=!log;
}
function fit() {
  const b=bounds(project.areas.map(a=>a.ring)),rect=$('map').getBoundingClientRect(),aspect=Math.max(.5,rect.width/rect.height);
  const width=Math.max(b.size[0]*1.45,b.size[1]*1.75*aspect,60);view={center:b.min.map((n,i)=>(n+b.max[i])/2),width};
}
function renderMap() {
  if(!view)fit();const rect=$('map').getBoundingClientRect(),aspect=Math.max(.5,rect.width/rect.height),height=view.width/aspect,unit=view.width/Math.max(1,rect.width),v=view.center;
  $('map').setAttribute('viewBox',`${v[0]-view.width/2} ${-v[1]-height/2} ${view.width} ${height}`);
  const path=points=>points.map((p,i)=>(i?'L':'M')+p[0].toFixed(3)+' '+(-p[1]).toFixed(3)).join(' '),polygon=ring=>path(ring)+'Z';
  const grid=Math.pow(10,Math.floor(Math.log10(view.width/10))),gridSize=grid*(view.width/grid>25?5:1);
  let html=`<defs><pattern id="grid" width="${gridSize}" height="${gridSize}" patternUnits="userSpaceOnUse"><path d="M ${gridSize} 0 H 0 V ${gridSize}" fill="none" stroke="#d7decd" stroke-width="${unit*.55}"/></pattern><pattern id="hatch" width="${unit*7}" height="${unit*7}" patternUnits="userSpaceOnUse" patternTransform="rotate(40)"><line x1="0" x2="0" y2="${unit*7}" stroke="#c58870" stroke-width="${unit*1}" opacity=".35"/></pattern></defs><rect x="${v[0]-view.width/2}" y="${-v[1]-height/2}" width="${view.width}" height="${height}" fill="url(#grid)"/>`;
  for(const a of project.areas){const active=a.id===selected,exclude=a.kind==='exclusion';html+=`<path class="area" data-map-area="${esc(a.id)}" d="${polygon(a.ring)}" fill="${exclude?'#e9d7c6':'#d7e1c7'}" stroke="${active?'#48623c':exclude?'#b6806b':'#94a77f'}" stroke-width="${active?2:1.3}"/>`;if(exclude)html+=`<path pointer-events="none" d="${polygon(a.ring)}" fill="url(#hatch)"/>`;}
  if(plan){
    html+=`<path d="${plan.region.map(polygon).join(' ')}" fill="none" stroke="#91a278" stroke-width="1" stroke-dasharray="4 4" vector-effect="non-scaling-stroke" pointer-events="none"/>`;
    if($('show-coverage').checked)html+=`<path d="${plan.covered.map(polygon).join(' ')}" fill="#75a895" fill-rule="evenodd" opacity=".3" pointer-events="none"/>`;
    if($('show-gaps').checked)html+=`<path d="${plan.gaps.map(polygon).join(' ')}" fill="#df9138" fill-rule="evenodd" opacity=".5" pointer-events="none"/>`;
    for(const s of plan.sorties){const visible=!selectedSortie||selectedSortie===s.id;html+=`<path d="${path(s.path)}" fill="none" stroke="${visible?'#c66537':'#aeb99d'}" stroke-width="${selectedSortie===s.id?2:1.2}" opacity="${visible?.85:.25}" vector-effect="non-scaling-stroke" pointer-events="none"/>`;if(visible)for(const photo of s.photos)html+=`<circle cx="${photo.point[0]}" cy="${-photo.point[1]}" r="${unit*(selectedSortie?2:1.4)}" fill="#a74f2b" pointer-events="none"/>`;}
    const shot=selectedSortie&&plan.photos.find(p=>p.id===selectedPhoto);if(shot)html+=`<path d="${polygon(footprint(shot.point,shot.heading,plan.camera.width,plan.camera.along))}" fill="#c65a32" fill-opacity=".12" stroke="#b45632" stroke-width="2" vector-effect="non-scaling-stroke" pointer-events="none"/><circle cx="${shot.point[0]}" cy="${-shot.point[1]}" r="${unit*4}" fill="#9a4024"/>`;
  }
  if(evidence){if($('show-coverage').checked)html+=`<path d="${evidence.covered.map(polygon).join(' ')}" fill="#328f97" fill-rule="evenodd" opacity=".22" pointer-events="none"/>`;for(const points of evidence.paths)html+=`<path d="${path(points)}" fill="none" stroke="#267d81" stroke-width="2.7" vector-effect="non-scaling-stroke" pointer-events="none"/>`;}
  if(evidence&&logSample!==null&&!$('evidence-panel').hidden){const row=project.log.records[logSample];html+=`<circle cx="${row.point[0]}" cy="${-row.point[1]}" r="${unit*6}" fill="#267d81" stroke="#fff" stroke-width="${unit*2}" pointer-events="none"/>`;}
  for(const a of project.areas){const b=bounds([a.ring]),mid=[(b.min[0]+b.max[0])/2,(b.min[1]+b.max[1])/2];if(a.kind==='exclusion')html+=`<text x="${mid[0]}" y="${-mid[1]}" fill="#976a55" text-anchor="middle" font-size="${unit*9}" font-family="system-ui" pointer-events="none" paint-order="stroke" stroke="#e9d7c6" stroke-width="${unit*3}">${esc(a.name)}</text>`;if(a.id===selected&&!a.locked)for(const [i,p] of a.ring.entries())html+=`<circle class="handle" data-handle="${i}" cx="${p[0]}" cy="${-p[1]}" r="${unit*5}" fill="#fffdf3" stroke="#526d42" stroke-width="1.5"/>`;}
  const [hx,hy]=project.home;html+=`<g data-home="true"><circle cx="${hx}" cy="${-hy}" r="${unit*9}" fill="#263d30" stroke="#fffdf3" stroke-width="${unit*2}"/><text x="${hx}" y="${-hy+unit*3.2}" text-anchor="middle" fill="#fffdf3" font-size="${unit*9}" font-family="system-ui">H</text></g><text x="${hx+unit*14}" y="${-hy+unit*3}" fill="#425d36" font-size="${unit*9}" font-family="system-ui" pointer-events="none" paint-order="stroke" stroke="#eef2e6" stroke-width="${unit*3}">TAKEOFF</text>`;
  if(drawn.length){html+=`<path d="${path(drawn)}" fill="none" stroke="#344f31" stroke-width="2" stroke-dasharray="5 4" vector-effect="non-scaling-stroke" pointer-events="none"/>`;for(const point of drawn)html+=`<circle cx="${point[0]}" cy="${-point[1]}" r="${unit*4}" fill="#344f31"/>`;}
  $('map').innerHTML=html;$('scale').textContent='Grid '+num(gridSize)+' m';
  $('map').style.cursor=tool==='select'?'default':'crosshair';
}
function rebuild() {
  let error='';try{plan=planProject(project);}catch(e){plan=null;error=e.message;}
  evidence=null;if(plan&&project.log)try{evidence=analyzeFlight(plan);}catch(e){error=e.message;}
  $('plan-error').hidden=!error;$('plan-error').textContent=error;
  $('project-title').textContent=project.title;$('map-title').textContent=project.title;
  $('map-subtitle').textContent=plan?`${plan.runs.length} survey runs · ${num(project.settings.height)} m above takeoff · ${num(project.settings.frontOverlap*100)} / ${num(project.settings.sideOverlap*100)}% overlap`:'Edit your boundary and planning settings';
  $('map-origin').textContent=`WGS 84 · ${project.origin[1].toFixed(5)}, ${project.origin[0].toFixed(5)}`;
  document.title=project.title+' · Vector';renderMetrics();renderSettings();renderAreas();renderSorties();renderEvidence();renderMap();status();
}
function point(event) { const p=new DOMPoint(event.clientX,event.clientY).matrixTransform($('map').getScreenCTM().inverse());return [Math.round(p.x*10)/10,Math.round(-p.y*10)/10]; }
function setTool(next) {tool=next;drawn=[];$$('[data-tool]').forEach(b=>b.classList.toggle('active',b.dataset.tool===tool));$('draw-help').hidden=!['boundary','exclusion'].includes(tool);renderMap();}
function finishDrawing(){if(drawn.length<3)throw new Error('Draw at least three different corners.');const id=uid(tool),ring=drawn.map(p=>[...p]);change(p=>{p.areas.push({id,name:tool==='boundary'?'New survey area':'New exclusion',kind:tool,locked:false,ring});},'Polygon added; drag its vertices or enter precise coordinates');selected=id;setTool('select');renderAreas();renderMap();}
$$('[data-tool]').forEach(b=>b.onclick=()=>setTool(b.dataset.tool));
$('finish-draw').onclick=guard(finishDrawing);$('cancel-draw').onclick=()=>setTool('select');
$('map').onpointerdown=event=>{
  if(event.button!==0)return;const p=point(event),handle=event.target.closest('[data-handle]'),home=event.target.closest('[data-home]'),area=event.target.closest('[data-map-area]');
  if(tool==='home'){guard(()=>change(next=>{next.home=p;},'Takeoff moved'))();setTool('select');return;}
  if(tool!=='select'){if(!drawn.length||distance(drawn.at(-1),p)>.2)drawn.push(p);renderMap();return;}
  if(handle){drag={kind:'vertex',index:Number(handle.dataset.handle),start:p,ring:clone(project.areas.find(a=>a.id===selected).ring),pointer:event.pointerId};}
  else if(home){drag={kind:'home',start:p,home:[...project.home],pointer:event.pointerId};}
  else if(area){selected=area.dataset.mapArea;renderAreas();renderMap();return;}
  else{drag={kind:'pan',start:p,center:[...view.center],pointer:event.pointerId};}
  $('map').setPointerCapture(event.pointerId);
};
$('map').onpointermove=event=>{if(!drag)return;const p=point(event);if(drag.kind==='pan'){view.center=view.center.map((n,i)=>n+drag.start[i]-p[i]);renderMap();}else{if(drag.kind==='home')project.home=p;else project.areas.find(a=>a.id===selected).ring[drag.index]=p;renderMap();}};
function endDrag(event,cancel=false){if(!drag)return;const d=drag;drag=null;if($('map').hasPointerCapture(d.pointer))$('map').releasePointerCapture(d.pointer);if(d.kind==='pan')return;const edited=clone(project);if(d.kind==='home')project.home=d.home;else project.areas.find(a=>a.id===selected).ring=d.ring;if(cancel){renderMap();return;}try{project=journal.push(edited);dirty=true;rebuild();stash();notify('Map geometry updated');}catch(error){renderMap();notify(error.message);}}
$('map').onpointerup=event=>endDrag(event);$('map').onpointercancel=event=>endDrag(event,true);
$('map').ondblclick=guard(()=>{if(['boundary','exclusion'].includes(tool))finishDrawing();});
$('map').addEventListener('wheel',event=>{event.preventDefault();if(!view)fit();view.width=Math.max(20,Math.min(15000,view.width*Math.exp(event.deltaY*.001)));renderMap();},{passive:false});
$('zoom-in').onclick=()=>{view.width=Math.max(20,view.width*.8);renderMap();};$('zoom-out').onclick=()=>{view.width=Math.min(15000,view.width/ .8);renderMap();};$('frame-site').onclick=()=>{fit();renderMap();};
$('undo').onclick=()=>{project=journal.undo();dirty=true;rebuild();stash();notify('Edit undone');};$('redo').onclick=()=>{project=journal.redo();dirty=true;rebuild();stash();notify('Edit restored');};
$('show-all').onclick=()=>{selectedSortie=null;renderSorties();renderMap();};$('show-coverage').onchange=renderMap;$('show-gaps').onchange=renderMap;
function tab(evidenceTab){$('plan-tab').classList.toggle('active',!evidenceTab);$('evidence-tab').classList.toggle('active',evidenceTab);$('settings-panel').hidden=evidenceTab;$('evidence-panel').hidden=!evidenceTab;renderMap();}
$('plan-tab').onclick=()=>tab(false);$('evidence-tab').onclick=()=>tab(true);
$$('[data-close]').forEach(b=>b.onclick=()=>b.closest('dialog').close());
$('model-details').onclick=()=>$('model-dialog').showModal();
$('project-details').onclick=()=>{$('title-input').value=project.title;$('brief-input').value=project.brief;$('origin-lon').value=project.origin[0];$('origin-lat').value=project.origin[1];$('project-dialog').showModal();};
$('apply-project').onclick=guard(()=>{const origin=[Number($('origin-lon').value),Number($('origin-lat').value)];if(project.log&&distance(origin,project.origin)>1e-10)throw new Error('Remove the recorded log before relocating this project.');change(p=>{p.title=$('title-input').value;p.brief=$('brief-input').value;p.origin=origin;});$('project-dialog').close();});
async function readFile(input,max=8000000){const file=input.files[0];if(!file)return null;if(file.size>max)throw new Error('Choose a file smaller than '+max/1000000+' MB.');let raw;try{raw=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(await file.arrayBuffer());}catch{throw new Error('Save this file as UTF-8 text before importing.');}return {name:file.name,raw};}
$('choose-project').onclick=()=>{$('project-file').value='';$('project-file').click();};
$('project-file').onchange=guard(async()=>{const file=await readFile($('project-file'));if(file){await open(JSON.parse(file.raw.replace(/^\uFEFF/,'')));$('open-dialog').close();}});
$('open-project').onclick=guard(async()=>{$('native-open').hidden=!connected;$('open-dialog').showModal();if(connected){const response=await fetch('/api/files'),result=await response.json();$('recent-projects').replaceChildren();for(const file of result.files??[]){const b=document.createElement('button');b.textContent=file.name+' · '+file.folder;b.onclick=guard(()=>openPath(file.path));$('recent-projects').append(b);}}});
async function openPath(path){const response=await fetch('/api/open',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({path})}),result=await response.json();if(!response.ok)throw new Error(result.error||'Could not open project.');await open(result.project);$('open-dialog').close();}
$('open-path').onclick=guard(()=>openPath($('project-path').value));
$('save-project').onclick=()=>download(slug(project.title)+'.vector.json',JSON.stringify(project,null,2),'application/json');
$('import-geo').onclick=()=>$('geo-dialog').showModal();$('choose-geo').onclick=()=>{$('geo-file').value='';$('geo-file').click();};
$('geo-file').onchange=guard(async()=>{
  const file=await readFile($('geo-file'),3000000);if(!file)return;const replace=$('geo-mode').value==='replace',kind=$('geo-kind').value;
  if(replace&&kind==='exclusion')throw new Error('Start a site with boundaries, then add exclusions.');
  const source=parseGeoJSON(JSON.parse(file.raw.replace(/^\uFEFF/,'')),replace?undefined:project.origin);if(!source.areas.length)throw new Error('Choose a file containing polygon boundaries.');
  const next=clone(project);if(replace){next.origin=source.origin;next.areas=[];next.id=uid('site');next.title=file.name.replace(/\.(geojson|json)$/i,'');next.brief='Site geometry imported from '+file.name+'. Review takeoff, exclusions, camera specifications and model assumptions.';delete next.log;}
  for(const area of source.areas){const areaKind=area.kind||kind;next.areas.push({id:uid(areaKind),name:area.name,kind:areaKind,locked:false,ring:area.boundary});for(const hole of area.holes)next.areas.push({id:uid('exclusion'),name:area.name+' interior',kind:'exclusion',locked:false,ring:hole});}
  const region=flightRegion(next.areas.filter(a=>a.kind==='boundary').map(a=>a.ring),next.areas.filter(a=>a.kind==='exclusion').map(a=>a.ring),next.settings.margin);
  if(replace||!pointIn(region,next.home)){let found=source.points.find(p=>pointIn(region,p.point))?.point;const b=bounds(region);for(let y=1;y<20&&!found;y++)for(let x=1;x<20&&!found;x++){const point=b.min.map((n,i)=>n+b.size[i]*(i?y:x)/20);if(pointIn(region,point))found=point;}if(!found)throw new Error('No takeoff position fits the current margin. Reduce the margin before importing.');next.home=found;}
  await open(next,'Site imported; review the proposed takeoff and capture settings');$('geo-dialog').close();
});
$('log-file').onchange=guard(async()=>{
  const file=await readFile($('log-file'),3000000);if(!file)return;const table=parseCSV(file.raw);logInput=file;$('log-name').textContent=file.name+' · '+table.rows.length+' source rows';
  const options=optional=>(optional?'<option value="">Not supplied</option>':'<option value="">Choose column…</option>')+table.headers.map(name=>`<option value="${esc(name)}">${esc(name)}</option>`).join('');
  $('log-mapping').innerHTML=['time','latitude','longitude','altitude','heading','battery','capture'].map(field=>`<label>${field[0].toUpperCase()+field.slice(1)} column<select data-map="${field}">${options(!['time','latitude','longitude'].includes(field))}</select></label>`).join('')+`<label>Time format<select data-map="timeUnit"><option value="seconds">Elapsed seconds</option><option value="milliseconds">Elapsed milliseconds</option><option value="iso">ISO 8601 with timezone</option></select></label><label>Altitude units<select data-map="altitudeUnit"><option value="meters">Meters</option><option value="feet">Feet</option></select></label><label>Altitude reference<select data-map="altitudeReference"><option value="takeoff">Height above takeoff</option><option value="amsl">AMSL elevation</option></select></label><label>Takeoff elevation · meters AMSL<input data-map="homeElevation" type="number" step="any" placeholder="Required for AMSL data"></label>`;
  $('log-dialog').showModal();
});
$('apply-log').onclick=guard(async()=>{const mapping=Object.fromEntries($$('[data-map]').map(el=>[el.dataset.map,el.dataset.map==='homeElevation'?(el.value.trim()?Number(el.value):null):el.value]));const log=await importFlight(logInput.raw,logInput.name,mapping,project.origin);change(p=>{p.log=log;},'Recorded flight imported with original CSV and column mapping');tab(true);$('log-dialog').close();});
function portable(){return originalHTML.replace(/(<script id="vector-data" type="application\/json">)[\s\S]*?(<\/script>)/,(_,a,b)=>a+JSON.stringify({project,licenses:payload.licenses}).replace(/</g,'\\u003c')+b);}
function requirePlan(){if(!plan)throw new Error('Resolve the planning issue before exporting.');if(project.log&&!evidence)throw new Error('Resolve the recorded-flight comparison before exporting.');return plan;}
async function compareAngles(){
  const baseline=clone(project),signature=JSON.stringify(project);let dialog=$('angles-dialog');if(!dialog){dialog=document.createElement('dialog');dialog.id='angles-dialog';document.body.append(dialog);}
  dialog.innerHTML='<h2>Compare line directions</h2><p>Same site, camera, overlaps and time budget. Comparing 12 directions in 15° steps, plus your current angle. These are sampled alternatives, not a global optimum.</p><p id="angle-progress" role="status">Calculating…</p><div id="angle-results"></div><div class="dialog-actions"><button id="close-angles">Close</button></div>';dialog.showModal();$('close-angles').onclick=()=>dialog.close();
  const results=[],angles=[...new Set([baseline.settings.angle,...Array.from({length:12},(_,i)=>i*15)])];
  for(const angle of angles){await new Promise(r=>setTimeout(r,15));if(!dialog.open||JSON.stringify(project)!==signature)return;const candidate=clone(baseline);candidate.settings.angle=angle;try{const p=planProject(candidate);results.push({angle,minutes:p.totalSeconds/60,sorties:p.sorties.length,photos:p.photos.length,coverage:p.coverage});}catch(error){results.push({angle,error:error.message});}$('angle-progress').textContent=`Compared ${results.length} of ${angles.length} directions`;}results.sort((a,b)=>(a.error?Infinity:a.minutes)-(b.error?Infinity:b.minutes));
  $('angle-progress').textContent='Sorted by nominal total time. Compare coverage before applying a direction.';
  $('angle-results').innerHTML=results.map(r=>r.error?`<p>${r.angle}° · ${esc(r.error)}</p>`:`<button data-angle="${r.angle}" style="display:flex;width:100%;justify-content:space-between;margin:7px 0;font-size:11px"><b>${r.angle}°${r.angle===baseline.settings.angle?' · current':''}</b><span>${num(r.minutes,1)} min · ${r.sorties} sorties · ${num(r.coverage*100,1)}% coverage</span></button>`).join('');
  $$('[data-angle]').forEach(b=>b.onclick=guard(()=>{if(JSON.stringify(project)!==signature)throw new Error('The source changed during comparison. Run the comparison again.');change(p=>{p.settings.angle=Number(b.dataset.angle);},'Compared direction applied; other requirements preserved');dialog.close();}));
}
$('deliver').onclick=guard(()=>{const p=requirePlan();$('export-summary').textContent=`${project.title} · ${p.photos.length} planned captures · ${p.sorties.length} sorties · ${num(p.area/10000,2)} hectares`;$('export-dialog').showModal();});
$('export-geo').onclick=guard(()=>download(slug(project.title)+'.geojson',JSON.stringify(geoJSON(requirePlan()),null,2),'application/geo+json'));
$('export-kml').onclick=guard(()=>download(slug(project.title)+'.kml',kml(requirePlan()),'application/vnd.google-earth.kml+xml'));
$('export-report').onclick=guard(()=>download(slug(project.title)+'-report.html',reportHTML(requirePlan()),'text/html'));
$('export-kit').onclick=guard(()=>{
  const p=requirePlan(),files=[[slug(project.title)+'.vector.json',JSON.stringify(project,null,2)],['planner.html',portable()],['survey.geojson',JSON.stringify(geoJSON(p),null,2)],['overlay.kml',kml(p)],['site-map.svg',mapSVG(p)],['planned-photos.csv',photoCSV(p)],['planned-route.csv',routeCSV(p)],['report.json',JSON.stringify(createReport(p),null,2)],['report.html',reportHTML(p)],['LICENSES.txt',payload.licenses||'See the embedded upstream licenses in planner.html.'],['README.md',`# ${project.title}\n\n${project.brief}\n\nOpen planner.html to edit offline. Keep the .vector.json source. Load survey.geojson in GIS or overlay.kml in a map viewer; KML is ground-clamped. CSV coordinates are longitude/latitude degrees, with explicit height above takeoff and nominal timing. These files are for planning and review, not aircraft upload. Print report.html to PDF.\n\n${ASSUMPTIONS}\n\nA recorded CSV, if supplied, is retained unchanged with SHA-256 and explicit column/unit mapping. Event footprints do not prove image existence or quality.\n`]];
  if(project.log){files.push(['recorded-source.csv',project.log.raw],['recorded-normalized.csv',flightCSV(p)]);}
  download(slug(project.title)+'-field-kit.zip',zipFiles(files));notify('Field kit exported with editable source and review files');
});
function sourceNotice(next,message){pendingSource=next;$('source-notice').hidden=false;document.querySelector('#source-notice span').textContent=message;status();}
$('draft-keep').onclick=()=>download(slug(project.title)+'-draft.vector.json',JSON.stringify(project,null,2),'application/json');
$('source-load').onclick=()=>{if(!pendingSource)return;download(slug(project.title)+'-before-restore.vector.json',JSON.stringify(project,null,2),'application/json');const next=pendingSource;pendingSource=null;$('source-notice').hidden=true;resetSource(next);notify('Draft downloaded; source version restored');};
$('save-source').onclick=guard(async()=>{if(!connected||pendingSource)return;saving=true;pollEpoch++;status();try{const response=await fetch('/api/project',{method:'PUT',headers:{'content-type':'application/json','if-match':revision},body:JSON.stringify(project)}),result=await response.json();if(response.status===409){sourceNotice(result.project,'The source changed. Keep your draft before switching versions.');return;}if(!response.ok)throw new Error(result.error||'Save failed.');resetSource(result.project);notify('Saved to workspace; previous source retained in history.');}finally{saving=false;status();}});
async function poll(){if(location.protocol==='file:'||saving||drag)return;const epoch=++pollEpoch;try{const response=await fetch('/api/project');if(!response.ok)return;const result=await response.json();if(epoch!==pollEpoch||saving||drag||!result.project)return;connected=true;const next=validateProject(result.project);if(next.revision!==revision){if(dirty)sourceNotice(next,'Your agent changed the source. Keep your draft before switching versions.');else{resetSource(next);notify('Agent changes loaded from source');}}status();}catch{}}
document.addEventListener('keydown',event=>{if(event.target.closest('input,textarea,select'))return;if((event.metaKey||event.ctrlKey)&&event.key.toLowerCase()==='z'){event.preventDefault();(event.shiftKey?$('redo'):$('undo')).click();}if(event.key==='Escape')setTool('select');if(event.key==='Enter'&&['boundary','exclusion'].includes(tool))guard(finishDrawing)();});
new ResizeObserver(()=>{if(project)renderMap();}).observe($('map'));
try{const saved=JSON.parse(localStorage.getItem(draftKey));if(saved?.project){project=validateProject(saved.project);revision=saved.revision;journal=history(project);dirty=true;notify('Recovered your unsaved draft');}}catch{}
rebuild();poll();setInterval(poll,1800);
window.vector={get project(){return clone(project);},get plan(){return plan;},get evidence(){return evidence;},get connected(){return connected;},get dirty(){return dirty;},screenPoint(point){const q=new DOMPoint(point[0],-point[1]).matrixTransform($('map').getScreenCTM());return {x:q.x,y:q.y};},portable};