import { replaceDraft } from './native-workspace-tools.mjs';
import { readPegPlan } from './peg-plan.mjs';
const dialog = document.createElement('dialog');
dialog.id = 'graphicDraftDialog';
dialog.innerHTML = `
Graphical Draft
`;
document.body.append(dialog);
const $ = id => document.getElementById(id);
const pageSize = 12;
let state, draft, shafts, revision, pending;
let sequence = 1500000;
function offset(id,total) {
const input = $(id);
input.max = Math.ceil(total / pageSize);
input.value = Math.min(Number(input.max),Math.max(1,Math.trunc(Number(input.value)) || 1));
return (Number(input.value)-1)*pageSize;
}
function header(row,label) {
const cell = document.createElement('th');
cell.textContent = label;
row.append(cell);
}
function draw() {
const firstEnd = offset('draftEndPage',draft.length);
const lastEnd = Math.min(firstEnd + pageSize,draft.length);
const firstShaft = offset('draftShaftPage',shafts) + 1;
const grid = $('draftGraphGrid');
grid.replaceChildren();
const row = grid.insertRow();
header(row,'Shaft / End');
for (let end=firstEnd;end=firstShaft;shaft--) {
const line = grid.insertRow();
header(line,shaft);
for (let end=firstEnd;end {
if (draft[end] === shaft) return;
const updated = [...draft];
updated[end] = shaft;
commitDraft(updated);
grid.querySelector(`[aria-label="End ${end+1}, shaft ${shaft}"]`)?.focus();
};
line.insertCell().append(button);
}
}
}
window.addEventListener('cad:document',event => {state=event.detail;});
window.addEventListener('cad:draft-graphical',() => {
const plan = readPegPlan(state.project);
draft = plan.draft;
shafts = plan.lifting[0].length;
revision = state.revision;
$('draftEndPage').value = $('draftShaftPage').value = 1;
$('draftGraphInfo').textContent = `${draft.length} ends · ${shafts} shafts`;
$('draftGraphStatus').textContent = '';
draw();
dialog.showModal();
});
$('draftEndPage').onchange = $('draftShaftPage').onchange = draw;
$('draftGraphClose').onclick = () => dialog.close();
function commitDraft(updated) {
try {
if (state.revision !== revision || state.raster) throw Error('Design changed. Reopen Draft.');
const project = replaceDraft(state.project,updated);
pending = ++sequence;
window.dispatchEvent(new CustomEvent('cad:edit',{detail:{id:pending,revision,type:'replace-project',project}}));
} catch (error) {
$('draftGraphStatus').textContent = error.message;
}
}
window.addEventListener('cad:edit-result',event => {
if (event.detail.id !== pending) return;
pending = undefined;
if (event.detail.ok) {
revision=state.revision;
draft=readPegPlan(state.project).draft;
$('draftGraphStatus').textContent='';
draw();
}
else $('draftGraphStatus').textContent = event.detail.error;
});
window.dispatchEvent(new CustomEvent('cad:request-state'));